Salome HOME
0023478: EDF15356 - Viscous layer
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "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.6;
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 _LayerEdge::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                   UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
437                   MARKED          = 0x0000200, // local usage
438                   MULTI_NORMAL    = 0x0000400, // a normal is invisible by some of surrounding faces
439                   NEAR_BOUNDARY   = 0x0000800, // is near FACE boundary forcing smooth
440                   SMOOTHED_C1     = 0x0001000, // is on _eosC1
441                   DISTORTED       = 0x0002000, // was bad before smoothing
442                   RISKY_SWOL      = 0x0004000, // SWOL is parallel to a source FACE
443                   SHRUNK          = 0x0008000, // target node reached a tgt position while shrink()
444                   UNUSED_FLAG     = 0x0100000  // to add user flags after
445     };
446     bool Is   ( int flag ) const { return _flags & flag; }
447     void Set  ( int flag ) { _flags |= flag; }
448     void Unset( int flag ) { _flags &= ~flag; }
449     std::string DumpFlags() const; // debug
450
451     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
452     bool SetNewLength2d( Handle(Geom_Surface)& surface,
453                          const TopoDS_Face&    F,
454                          _EdgesOnShape&        eos,
455                          SMESH_MesherHelper&   helper );
456     void SetDataByNeighbors( const SMDS_MeshNode* n1,
457                              const SMDS_MeshNode* n2,
458                              const _EdgesOnShape& eos,
459                              SMESH_MesherHelper&  helper);
460     void Block( _SolidData& data );
461     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
462     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
463                             const TNode2Edge&     n2eMap);
464     void SmoothPos( const vector< double >& segLen, const double tol );
465     int  GetSmoothedPos( const double tol );
466     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
467     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
468     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
469     void SmoothWoCheck();
470     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
471                       const TopoDS_Face&             F,
472                       SMESH_MesherHelper&            helper);
473     void MoveNearConcaVer( const _EdgesOnShape*    eov,
474                            const _EdgesOnShape*    eos,
475                            const int               step,
476                            vector< _LayerEdge* > & badSmooEdges);
477     bool FindIntersection( SMESH_ElementSearcher&   searcher,
478                            double &                 distance,
479                            const double&            epsilon,
480                            _EdgesOnShape&           eos,
481                            const SMDS_MeshElement** face = 0);
482     bool SegTriaInter( const gp_Ax1&        lastSegment,
483                        const gp_XYZ&        p0,
484                        const gp_XYZ&        p1,
485                        const gp_XYZ&        p2,
486                        double&              dist,
487                        const double&        epsilon) const;
488     bool SegTriaInter( const gp_Ax1&        lastSegment,
489                        const SMDS_MeshNode* n0,
490                        const SMDS_MeshNode* n1,
491                        const SMDS_MeshNode* n2,
492                        double&              dist,
493                        const double&        epsilon) const
494     { return SegTriaInter( lastSegment,
495                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
496                            dist, epsilon );
497     }
498     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
499     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
500     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
501     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
502     bool   IsOnEdge() const { return _2neibors; }
503     bool   IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
504     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
505     void   SetCosin( double cosin );
506     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
507     void   SetMaxLen( double l ) { _maxLen = l; }
508     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
509     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
510     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
511       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
512     }
513     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
514
515     gp_XYZ smoothLaplacian();
516     gp_XYZ smoothAngular();
517     gp_XYZ smoothLengthWeighted();
518     gp_XYZ smoothCentroidal();
519     gp_XYZ smoothNefPolygon();
520
521     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
522     static const int theNbSmooFuns = FUN_NB;
523     static PSmooFun _funs[theNbSmooFuns];
524     static const char* _funNames[theNbSmooFuns+1];
525     int smooFunID( PSmooFun fun=0) const;
526   };
527   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
528                                                             &_LayerEdge::smoothLengthWeighted,
529                                                             &_LayerEdge::smoothCentroidal,
530                                                             &_LayerEdge::smoothNefPolygon,
531                                                             &_LayerEdge::smoothAngular };
532   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
533                                                          "LengthWeighted",
534                                                          "Centroidal",
535                                                          "NefPolygon",
536                                                          "Angular",
537                                                          "None"};
538   struct _LayerEdgeCmp
539   {
540     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
541     {
542       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
543       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
544     }
545   };
546   //--------------------------------------------------------------------------------
547   /*!
548    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
549    */
550   struct _halfPlane
551   {
552     gp_XY _pos, _dir, _inNorm;
553     bool IsOut( const gp_XY p, const double tol ) const
554     {
555       return _inNorm * ( p - _pos ) < -tol;
556     }
557     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
558     {
559       //const double eps = 1e-10;
560       double D = _dir.Crossed( hp._dir );
561       if ( fabs(D) < std::numeric_limits<double>::min())
562         return false;
563       gp_XY vec21 = _pos - hp._pos; 
564       double u = hp._dir.Crossed( vec21 ) / D; 
565       intPnt = _pos + _dir * u;
566       return true;
567     }
568   };
569   //--------------------------------------------------------------------------------
570   /*!
571    * Structure used to smooth a _LayerEdge based on an EDGE.
572    */
573   struct _2NearEdges
574   {
575     double               _wgt  [2]; // weights of _nodes
576     _LayerEdge*          _edges[2];
577
578      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
579     gp_XYZ*              _plnNorm;
580
581     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
582     const SMDS_MeshNode* tgtNode(bool is2nd) {
583       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
584     }
585     const SMDS_MeshNode* srcNode(bool is2nd) {
586       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
587     }
588     void reverse() {
589       std::swap( _wgt  [0], _wgt  [1] );
590       std::swap( _edges[0], _edges[1] );
591     }
592     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
593       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
594     }
595     bool include( const _LayerEdge* e ) {
596       return ( _edges[0] == e || _edges[1] == e );
597     }
598   };
599
600
601   //--------------------------------------------------------------------------------
602   /*!
603    * \brief Layers parameters got by averaging several hypotheses
604    */
605   struct AverageHyp
606   {
607     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
608       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
609     {
610       Add( hyp );
611     }
612     void Add( const StdMeshers_ViscousLayers* hyp )
613     {
614       if ( hyp )
615       {
616         _nbHyps++;
617         _nbLayers       = hyp->GetNumberLayers();
618         //_thickness     += hyp->GetTotalThickness();
619         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
620         _stretchFactor += hyp->GetStretchFactor();
621         _method         = hyp->GetMethod();
622       }
623     }
624     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
625     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
626     int    GetNumberLayers()   const { return _nbLayers; }
627     int    GetMethod()         const { return _method; }
628
629     bool   UseSurfaceNormal()  const
630     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
631     bool   ToSmooth()          const
632     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
633     bool   IsOffsetMethod()    const
634     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
635
636   private:
637     int     _nbLayers, _nbHyps, _method;
638     double  _thickness, _stretchFactor;
639   };
640
641   //--------------------------------------------------------------------------------
642   /*!
643    * \brief _LayerEdge's on a shape and other shape data
644    */
645   struct _EdgesOnShape
646   {
647     vector< _LayerEdge* > _edges;
648
649     TopoDS_Shape          _shape;
650     TGeomID               _shapeID;
651     SMESH_subMesh *       _subMesh;
652     // face or edge w/o layer along or near which _edges are inflated
653     TopoDS_Shape          _sWOL;
654     bool                  _isRegularSWOL; // w/o singularities
655     // averaged StdMeshers_ViscousLayers parameters
656     AverageHyp            _hyp;
657     bool                  _toSmooth;
658     _Smoother1D*          _edgeSmoother;
659     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
660     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
661
662     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
663     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
664
665     Handle(ShapeAnalysis_Surface) _offsetSurf;
666     _LayerEdge*                   _edgeForOffset;
667
668     _SolidData*            _data; // parent SOLID
669
670     _LayerEdge*      operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
671     size_t           size() const { return _edges.size(); }
672     TopAbs_ShapeEnum ShapeType() const
673     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
674     TopAbs_ShapeEnum SWOLType() const
675     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
676     bool             HasC1( const _EdgesOnShape* other ) const
677     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
678     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
679     _SolidData&      GetData() const { return *_data; }
680
681     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
682   };
683
684   //--------------------------------------------------------------------------------
685   /*!
686    * \brief Convex FACE whose radius of curvature is less than the thickness of
687    *        layers. It is used to detect distortion of prisms based on a convex
688    *        FACE and to update normals to enable further increasing the thickness
689    */
690   struct _ConvexFace
691   {
692     TopoDS_Face                     _face;
693
694     // edges whose _simplices are used to detect prism distortion
695     vector< _LayerEdge* >           _simplexTestEdges;
696
697     // map a sub-shape to _SolidData::_edgesOnShape
698     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
699
700     bool                            _isTooCurved;
701     bool                            _normalsFixed;
702     bool                            _normalsFixedOnBorders; // used in putOnOffsetSurface()
703
704     double GetMaxCurvature( _SolidData&         data,
705                             _EdgesOnShape&      eof,
706                             BRepLProp_SLProps&  surfProp,
707                             SMESH_MesherHelper& helper);
708
709     bool GetCenterOfCurvature( _LayerEdge*         ledge,
710                                BRepLProp_SLProps&  surfProp,
711                                SMESH_MesherHelper& helper,
712                                gp_Pnt &            center ) const;
713     bool CheckPrisms() const;
714   };
715
716   //--------------------------------------------------------------------------------
717   /*!
718    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
719    *        at inflation up to the full thickness. A detected collision
720    *        is fixed in updateNormals()
721    */
722   struct _CollisionEdges
723   {
724     _LayerEdge*           _edge;
725     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
726     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
727     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
728   };
729
730   //--------------------------------------------------------------------------------
731   /*!
732    * \brief Data of a SOLID
733    */
734   struct _SolidData
735   {
736     typedef const StdMeshers_ViscousLayers* THyp;
737     TopoDS_Shape                    _solid;
738     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
739     TGeomID                         _index; // SOLID id
740     _MeshOfSolid*                   _proxyMesh;
741     list< THyp >                    _hyps;
742     list< TopoDS_Shape >            _hypShapes;
743     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
744     set< TGeomID >                  _reversedFaceIds;
745     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
746
747     double                          _stepSize, _stepSizeCoeff, _geomSize;
748     const SMDS_MeshNode*            _stepSizeNodes[2];
749
750     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
751
752     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
753     map< TGeomID, TNode2Edge* >     _s2neMap;
754     // _LayerEdge's with underlying shapes
755     vector< _EdgesOnShape >         _edgesOnShape;
756
757     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
758     //        layers and a FACE w/o layers
759     // value: the shape (FACE or EDGE) to shrink mesh on.
760     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
761     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
762
763     // Convex FACEs whose radius of curvature is less than the thickness of layers
764     map< TGeomID, _ConvexFace >      _convexFaces;
765
766     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
767     // the adjacent SOLID
768     set< TGeomID >                   _noShrinkShapes;
769
770     int                              _nbShapesToSmooth;
771
772     vector< _CollisionEdges >        _collisionEdges;
773     set< TGeomID >                   _concaveFaces;
774
775     double                           _maxThickness; // of all _hyps
776     double                           _minThickness; // of all _hyps
777
778     double                           _epsilon; // precision for SegTriaInter()
779
780     SMESH_MesherHelper*              _helper;
781
782     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
783                _MeshOfSolid*       m=0)
784       :_solid(s), _proxyMesh(m), _helper(0) {}
785     ~_SolidData();
786
787     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
788     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
789
790     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
791       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
792       return id2face == _convexFaces.end() ? 0 : & id2face->second;
793     }
794     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
795     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
796     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
797     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
798
799     SMESH_MesherHelper& GetHelper() const { return *_helper; }
800
801     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
802       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
803         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
804           _edgesOnShape[i]._edges[j]->Unset( flag );
805     }
806     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
807                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
808
809     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
810   };
811   //--------------------------------------------------------------------------------
812   /*!
813    * \brief Offset plane used in getNormalByOffset()
814    */
815   struct _OffsetPlane
816   {
817     gp_Pln _plane;
818     int    _faceIndex;
819     int    _faceIndexNext[2];
820     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
821     bool   _isLineOK[2];
822     _OffsetPlane() {
823       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
824     }
825     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
826                                     const TopoDS_Edge&   E,
827                                     const TopoDS_Vertex& V );
828     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
829     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
830   };
831   //--------------------------------------------------------------------------------
832   /*!
833    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
834    */
835   struct _CentralCurveOnEdge
836   {
837     bool                  _isDegenerated;
838     vector< gp_Pnt >      _curvaCenters;
839     vector< _LayerEdge* > _ledges;
840     vector< gp_XYZ >      _normals; // new normal for each of _ledges
841     vector< double >      _segLength2;
842
843     TopoDS_Edge           _edge;
844     TopoDS_Face           _adjFace;
845     bool                  _adjFaceToSmooth;
846
847     void Append( const gp_Pnt& center, _LayerEdge* ledge )
848     {
849       if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
850         return;
851       if ( _curvaCenters.size() > 0 )
852         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
853       _curvaCenters.push_back( center );
854       _ledges.push_back( ledge );
855       _normals.push_back( ledge->_normal );
856     }
857     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
858     void SetShapes( const TopoDS_Edge&  edge,
859                     const _ConvexFace&  convFace,
860                     _SolidData&         data,
861                     SMESH_MesherHelper& helper);
862   };
863   //--------------------------------------------------------------------------------
864   /*!
865    * \brief Data of node on a shrinked FACE
866    */
867   struct _SmoothNode
868   {
869     const SMDS_MeshNode*         _node;
870     vector<_Simplex>             _simplices; // for quality check
871
872     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
873
874     bool Smooth(int&                  badNb,
875                 Handle(Geom_Surface)& surface,
876                 SMESH_MesherHelper&   helper,
877                 const double          refSign,
878                 SmoothType            how,
879                 bool                  set3D);
880
881     gp_XY computeAngularPos(vector<gp_XY>& uv,
882                             const gp_XY&   uvToFix,
883                             const double   refSign );
884   };
885   struct PyDump;
886   //--------------------------------------------------------------------------------
887   /*!
888    * \brief Builder of viscous layers
889    */
890   class _ViscousBuilder
891   {
892   public:
893     _ViscousBuilder();
894     // does it's job
895     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
896                                   const TopoDS_Shape& shape);
897     // check validity of hypotheses
898     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
899                                            const TopoDS_Shape& shape );
900
901     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
902     void RestoreListeners();
903
904     // computes SMESH_ProxyMesh::SubMesh::_n2n;
905     bool MakeN2NMap( _MeshOfSolid* pm );
906
907   private:
908
909     bool findSolidsWithLayers();
910     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
911     bool findFacesWithLayers(const bool onlyWith=false);
912     void getIgnoreFaces(const TopoDS_Shape&             solid,
913                         const StdMeshers_ViscousLayers* hyp,
914                         const TopoDS_Shape&             hypShape,
915                         set<TGeomID>&                   ignoreFaces);
916     bool makeLayer(_SolidData& data);
917     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
918     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
919                       SMESH_MesherHelper& helper, _SolidData& data);
920     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
921                          const TopoDS_Face&   face,
922                          SMESH_MesherHelper&  helper,
923                          bool&                isOK,
924                          bool                 shiftInside=false);
925     bool getFaceNormalAtSingularity(const gp_XY&        uv,
926                                     const TopoDS_Face&  face,
927                                     SMESH_MesherHelper& helper,
928                                     gp_Dir&             normal );
929     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
930     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
931                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
932                               int                              nbFaces,
933                               bool                             lastNoOffset = false);
934     bool findNeiborsOnEdge(const _LayerEdge*     edge,
935                            const SMDS_MeshNode*& n1,
936                            const SMDS_MeshNode*& n2,
937                            _EdgesOnShape&        eos,
938                            _SolidData&           data);
939     void findSimplexTestEdges( _SolidData&                    data,
940                                vector< vector<_LayerEdge*> >& edgesByGeom);
941     void computeGeomSize( _SolidData& data );
942     bool findShapesToSmooth( _SolidData& data);
943     void limitStepSizeByCurvature( _SolidData&  data );
944     void limitStepSize( _SolidData&             data,
945                         const SMDS_MeshElement* face,
946                         const _LayerEdge*       maxCosinEdge );
947     void limitStepSize( _SolidData& data, const double minSize);
948     bool inflate(_SolidData& data);
949     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
950     int  invalidateBadSmooth( _SolidData&               data,
951                               SMESH_MesherHelper&       helper,
952                               vector< _LayerEdge* >&    badSmooEdges,
953                               vector< _EdgesOnShape* >& eosC1,
954                               const int                 infStep );
955     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
956     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
957                              vector< _EdgesOnShape* >& eosC1,
958                              int smooStep=0, int moveAll=false );
959     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
960     void findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
961                                                 _SolidData&         data,
962                                                 SMESH_MesherHelper& helper );
963     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
964     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
965                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
966                                  const bool isSmoothable );
967     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
968     bool updateNormalsOfConvexFaces( _SolidData&         data,
969                                      SMESH_MesherHelper& helper,
970                                      int                 stepNb );
971     void updateNormalsOfC1Vertices( _SolidData& data );
972     bool updateNormalsOfSmoothed( _SolidData&         data,
973                                   SMESH_MesherHelper& helper,
974                                   const int           nbSteps,
975                                   const double        stepSize );
976     bool isNewNormalOk( _SolidData&   data,
977                         _LayerEdge&   edge,
978                         const gp_XYZ& newNormal);
979     bool refine(_SolidData& data);
980     bool shrink(_SolidData& data);
981     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
982                               SMESH_MesherHelper& helper,
983                               const SMESHDS_SubMesh* faceSubMesh );
984     void restoreNoShrink( _LayerEdge& edge ) const;
985     void fixBadFaces(const TopoDS_Face&          F,
986                      SMESH_MesherHelper&         helper,
987                      const bool                  is2D,
988                      const int                   step,
989                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
990     bool addBoundaryElements(_SolidData& data);
991
992     bool error( const string& text, int solidID=-1 );
993     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
994
995     // debug
996     void makeGroupOfLE();
997
998     SMESH_Mesh*                _mesh;
999     SMESH_ComputeErrorPtr      _error;
1000
1001     vector<                    _SolidData >  _sdVec;
1002     TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
1003     TopTools_MapOfShape        _shrinkedFaces;
1004
1005     int                        _tmpFaceID;
1006     PyDump*                    _pyDump;
1007   };
1008   //--------------------------------------------------------------------------------
1009   /*!
1010    * \brief Shrinker of nodes on the EDGE
1011    */
1012   class _Shrinker1D
1013   {
1014     TopoDS_Edge                   _geomEdge;
1015     vector<double>                _initU;
1016     vector<double>                _normPar;
1017     vector<const SMDS_MeshNode*>  _nodes;
1018     const _LayerEdge*             _edges[2];
1019     bool                          _done;
1020   public:
1021     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1022     void Compute(bool set3D, SMESH_MesherHelper& helper);
1023     void RestoreParams();
1024     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1025     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1026     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1027     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1028     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1029     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1030   };
1031   //--------------------------------------------------------------------------------
1032   /*!
1033    * \brief Smoother of _LayerEdge's on EDGE.
1034    */
1035   struct _Smoother1D
1036   {
1037     struct OffPnt // point of the offsetted EDGE
1038     {
1039       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1040       double      _len;    // length reached at previous inflation step
1041       double      _param;  // on EDGE
1042       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1043       gp_XYZ      _edgeDir;// EDGE tangent at _param
1044       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1045     };
1046     vector< OffPnt >   _offPoints;
1047     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1048     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1049     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1050     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1051     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1052     _EdgesOnShape&     _eos;
1053     double             _curveLen; // length of the EDGE
1054     std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1055
1056     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1057                                               _EdgesOnShape&      eos,
1058                                               SMESH_MesherHelper& helper);
1059
1060     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1061                  _EdgesOnShape&     eos )
1062       : _anaCurve( curveForSmooth ), _eos( eos )
1063     {
1064     }
1065     bool Perform(_SolidData&                    data,
1066                  Handle(ShapeAnalysis_Surface)& surface,
1067                  const TopoDS_Face&             F,
1068                  SMESH_MesherHelper&            helper );
1069
1070     void prepare(_SolidData& data );
1071
1072     void findEdgesToSmooth();
1073
1074     bool isToSmooth( int iE );
1075
1076     bool smoothAnalyticEdge( _SolidData&                    data,
1077                              Handle(ShapeAnalysis_Surface)& surface,
1078                              const TopoDS_Face&             F,
1079                              SMESH_MesherHelper&            helper);
1080     bool smoothComplexEdge( _SolidData&                    data,
1081                             Handle(ShapeAnalysis_Surface)& surface,
1082                             const TopoDS_Face&             F,
1083                             SMESH_MesherHelper&            helper);
1084     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1085                             const gp_XYZ&  edgeDir);
1086     _LayerEdge* getLEdgeOnV( bool is2nd )
1087     {
1088       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1089     }
1090     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1091
1092     void offPointsToPython() const; // debug
1093   };
1094   //--------------------------------------------------------------------------------
1095   /*!
1096    * \brief Class of temporary mesh face.
1097    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1098    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1099    */
1100   struct _TmpMeshFace : public SMDS_MeshElement
1101   {
1102     vector<const SMDS_MeshNode* > _nn;
1103     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1104                   int id, int faceID=-1, int idInFace=-1):
1105       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1106     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1107     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1108     virtual vtkIdType GetVtkType() const                      { return -1; }
1109     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1110     virtual SMDSAbs_GeometryType GetGeomType() const
1111     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1112     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1113     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1114   };
1115   //--------------------------------------------------------------------------------
1116   /*!
1117    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1118    */
1119   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1120   {
1121     _LayerEdge *_le1, *_le2;
1122     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1123       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1124     {
1125       _nn[0]=_le1->_nodes[0];
1126       _nn[1]=_le1->_nodes.back();
1127       _nn[2]=_le2->_nodes.back();
1128       _nn[3]=_le2->_nodes[0];
1129     }
1130     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1131     {
1132       SMESH_TNodeXYZ p0s( _nn[0] );
1133       SMESH_TNodeXYZ p0t( _nn[1] );
1134       SMESH_TNodeXYZ p1t( _nn[2] );
1135       SMESH_TNodeXYZ p1s( _nn[3] );
1136       gp_XYZ  v0 = p0t - p0s;
1137       gp_XYZ  v1 = p1t - p1s;
1138       gp_XYZ v01 = p1s - p0s;
1139       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1140       gp_XYZ   d = v01 ^ n;
1141       d.Normalize();
1142       return d;
1143     }
1144     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1145     {
1146       _nn[0]=le1->_nodes[0];
1147       _nn[1]=le1->_nodes.back();
1148       _nn[2]=le2->_nodes.back();
1149       _nn[3]=le2->_nodes[0];
1150       return GetDir();
1151     }
1152   };
1153   //--------------------------------------------------------------------------------
1154   /*!
1155    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1156    * \warning Location of a surface is ignored
1157    */
1158   struct _NodeCoordHelper
1159   {
1160     SMESH_MesherHelper&        _helper;
1161     const TopoDS_Face&         _face;
1162     Handle(Geom_Surface)       _surface;
1163     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1164
1165     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1166       : _helper( helper ), _face( F )
1167     {
1168       if ( is2D )
1169       {
1170         TopLoc_Location loc;
1171         _surface = BRep_Tool::Surface( _face, loc );
1172       }
1173       if ( _surface.IsNull() )
1174         _fun = & _NodeCoordHelper::direct;
1175       else
1176         _fun = & _NodeCoordHelper::byUV;
1177     }
1178     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1179
1180   private:
1181     gp_XYZ direct(const SMDS_MeshNode* n) const
1182     {
1183       return SMESH_TNodeXYZ( n );
1184     }
1185     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1186     {
1187       gp_XY uv = _helper.GetNodeUV( _face, n );
1188       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1189     }
1190   };
1191
1192   //================================================================================
1193   /*!
1194    * \brief Check angle between vectors 
1195    */
1196   //================================================================================
1197
1198   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1199   {
1200     double dot = v1 * v2; // cos * |v1| * |v2|
1201     double l1  = v1.SquareMagnitude();
1202     double l2  = v2.SquareMagnitude();
1203     return (( dot * cos >= 0 ) && 
1204             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1205   }
1206
1207 } // namespace VISCOUS_3D
1208
1209
1210
1211 //================================================================================
1212 // StdMeshers_ViscousLayers hypothesis
1213 //
1214 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1215   :SMESH_Hypothesis(hypId, studyId, gen),
1216    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1217    _method( SURF_OFFSET_SMOOTH )
1218 {
1219   _name = StdMeshers_ViscousLayers::GetHypType();
1220   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1221 } // --------------------------------------------------------------------------------
1222 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1223 {
1224   if ( faceIds != _shapeIds )
1225     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1226   if ( _isToIgnoreShapes != toIgnore )
1227     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1228 } // --------------------------------------------------------------------------------
1229 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1230 {
1231   if ( thickness != _thickness )
1232     _thickness = thickness, NotifySubMeshesHypothesisModification();
1233 } // --------------------------------------------------------------------------------
1234 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1235 {
1236   if ( _nbLayers != nb )
1237     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1238 } // --------------------------------------------------------------------------------
1239 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1240 {
1241   if ( _stretchFactor != factor )
1242     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1243 } // --------------------------------------------------------------------------------
1244 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1245 {
1246   if ( _method != method )
1247     _method = method, NotifySubMeshesHypothesisModification();
1248 } // --------------------------------------------------------------------------------
1249 SMESH_ProxyMesh::Ptr
1250 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1251                                   const TopoDS_Shape& theShape,
1252                                   const bool          toMakeN2NMap) const
1253 {
1254   using namespace VISCOUS_3D;
1255   _ViscousBuilder builder;
1256   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1257   if ( err && !err->IsOK() )
1258     return SMESH_ProxyMesh::Ptr();
1259
1260   vector<SMESH_ProxyMesh::Ptr> components;
1261   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1262   for ( ; exp.More(); exp.Next() )
1263   {
1264     if ( _MeshOfSolid* pm =
1265          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1266     {
1267       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1268         if ( !builder.MakeN2NMap( pm ))
1269           return SMESH_ProxyMesh::Ptr();
1270       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1271       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1272
1273       if ( pm->_warning && !pm->_warning->IsOK() )
1274       {
1275         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1276         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1277         if ( !smError || smError->IsOK() )
1278           smError = pm->_warning;
1279       }
1280     }
1281     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1282   }
1283   switch ( components.size() )
1284   {
1285   case 0: break;
1286
1287   case 1: return components[0];
1288
1289   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1290   }
1291   return SMESH_ProxyMesh::Ptr();
1292 } // --------------------------------------------------------------------------------
1293 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1294 {
1295   save << " " << _nbLayers
1296        << " " << _thickness
1297        << " " << _stretchFactor
1298        << " " << _shapeIds.size();
1299   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1300     save << " " << _shapeIds[i];
1301   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1302   save << " " << _method;
1303   return save;
1304 } // --------------------------------------------------------------------------------
1305 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1306 {
1307   int nbFaces, faceID, shapeToTreat, method;
1308   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1309   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1310     _shapeIds.push_back( faceID );
1311   if ( load >> shapeToTreat ) {
1312     _isToIgnoreShapes = !shapeToTreat;
1313     if ( load >> method )
1314       _method = (ExtrusionMethod) method;
1315   }
1316   else {
1317     _isToIgnoreShapes = true; // old behavior
1318   }
1319   return load;
1320 } // --------------------------------------------------------------------------------
1321 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1322                                                    const TopoDS_Shape& theShape)
1323 {
1324   // TODO
1325   return false;
1326 } // --------------------------------------------------------------------------------
1327 SMESH_ComputeErrorPtr
1328 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1329                                           const TopoDS_Shape&                  theShape,
1330                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1331 {
1332   VISCOUS_3D::_ViscousBuilder builder;
1333   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1334   if ( err && !err->IsOK() )
1335     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1336   else
1337     theStatus = SMESH_Hypothesis::HYP_OK;
1338
1339   return err;
1340 }
1341 // --------------------------------------------------------------------------------
1342 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1343 {
1344   bool isIn =
1345     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1346   return IsToIgnoreShapes() ? !isIn : isIn;
1347 }
1348 // END StdMeshers_ViscousLayers hypothesis
1349 //================================================================================
1350
1351 namespace VISCOUS_3D
1352 {
1353   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1354   {
1355     gp_Vec dir;
1356     double f,l;
1357     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1358     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1359     gp_Pnt p = BRep_Tool::Pnt( fromV );
1360     double distF = p.SquareDistance( c->Value( f ));
1361     double distL = p.SquareDistance( c->Value( l ));
1362     c->D1(( distF < distL ? f : l), p, dir );
1363     if ( distL < distF ) dir.Reverse();
1364     return dir.XYZ();
1365   }
1366   //--------------------------------------------------------------------------------
1367   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1368                      SMESH_MesherHelper& helper)
1369   {
1370     gp_Vec dir;
1371     double f,l; gp_Pnt p;
1372     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1373     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1374     double u = helper.GetNodeU( E, atNode );
1375     c->D1( u, p, dir );
1376     return dir.XYZ();
1377   }
1378   //--------------------------------------------------------------------------------
1379   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1380                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1381                      double* cosin=0);
1382   //--------------------------------------------------------------------------------
1383   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1384                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1385   {
1386     double f,l;
1387     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1388     if ( c.IsNull() )
1389     {
1390       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1391       return getFaceDir( F, v, node, helper, ok );
1392     }
1393     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1394     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1395     gp_Pnt p; gp_Vec du, dv, norm;
1396     surface->D1( uv.X(),uv.Y(), p, du,dv );
1397     norm = du ^ dv;
1398
1399     double u = helper.GetNodeU( fromE, node, 0, &ok );
1400     c->D1( u, p, du );
1401     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1402     if ( o == TopAbs_REVERSED )
1403       du.Reverse();
1404
1405     gp_Vec dir = norm ^ du;
1406
1407     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1408          helper.IsClosedEdge( fromE ))
1409     {
1410       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1411       else                        c->D1( f, p, dv );
1412       if ( o == TopAbs_REVERSED )
1413         dv.Reverse();
1414       gp_Vec dir2 = norm ^ dv;
1415       dir = dir.Normalized() + dir2.Normalized();
1416     }
1417     return dir.XYZ();
1418   }
1419   //--------------------------------------------------------------------------------
1420   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1421                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1422                      bool& ok, double* cosin)
1423   {
1424     TopoDS_Face faceFrw = F;
1425     faceFrw.Orientation( TopAbs_FORWARD );
1426     //double f,l; TopLoc_Location loc;
1427     TopoDS_Edge edges[2]; // sharing a vertex
1428     size_t nbEdges = 0;
1429     {
1430       TopoDS_Vertex VV[2];
1431       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1432       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1433       {
1434         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1435         if ( SMESH_Algo::isDegenerated( e )) continue;
1436         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1437         if ( VV[1].IsSame( fromV )) {
1438           nbEdges += edges[ 0 ].IsNull();
1439           edges[ 0 ] = e;
1440         }
1441         else if ( VV[0].IsSame( fromV )) {
1442           nbEdges += edges[ 1 ].IsNull();
1443           edges[ 1 ] = e;
1444         }
1445       }
1446     }
1447     gp_XYZ dir(0,0,0), edgeDir[2];
1448     if ( nbEdges == 2 )
1449     {
1450       // get dirs of edges going fromV
1451       ok = true;
1452       for ( size_t i = 0; i < nbEdges && ok; ++i )
1453       {
1454         edgeDir[i] = getEdgeDir( edges[i], fromV );
1455         double size2 = edgeDir[i].SquareModulus();
1456         if (( ok = size2 > numeric_limits<double>::min() ))
1457           edgeDir[i] /= sqrt( size2 );
1458       }
1459       if ( !ok ) return dir;
1460
1461       // get angle between the 2 edges
1462       gp_Vec faceNormal;
1463       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1464       if ( Abs( angle ) < 5 * M_PI/180 )
1465       {
1466         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1467       }
1468       else
1469       {
1470         dir = edgeDir[0] + edgeDir[1];
1471         if ( angle < 0 )
1472           dir.Reverse();
1473       }
1474       if ( cosin ) {
1475         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1476         *cosin = Cos( angle );
1477       }
1478     }
1479     else if ( nbEdges == 1 )
1480     {
1481       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1482       if ( cosin ) *cosin = 1.;
1483     }
1484     else
1485     {
1486       ok = false;
1487     }
1488
1489     return dir;
1490   }
1491
1492   //================================================================================
1493   /*!
1494    * \brief Finds concave VERTEXes of a FACE
1495    */
1496   //================================================================================
1497
1498   bool getConcaveVertices( const TopoDS_Face&  F,
1499                            SMESH_MesherHelper& helper,
1500                            set< TGeomID >*     vertices = 0)
1501   {
1502     // check angles at VERTEXes
1503     TError error;
1504     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1505     for ( size_t iW = 0; iW < wires.size(); ++iW )
1506     {
1507       const int nbEdges = wires[iW]->NbEdges();
1508       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1509         continue;
1510       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1511       {
1512         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1513         int iE2 = ( iE1 + 1 ) % nbEdges;
1514         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1515           iE2 = ( iE2 + 1 ) % nbEdges;
1516         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1517         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1518                                         wires[iW]->Edge( iE2 ), F, V );
1519         if ( angle < -5. * M_PI / 180. )
1520         {
1521           if ( !vertices )
1522             return true;
1523           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1524         }
1525       }
1526     }
1527     return vertices ? !vertices->empty() : false;
1528   }
1529
1530   //================================================================================
1531   /*!
1532    * \brief Returns true if a FACE is bound by a concave EDGE
1533    */
1534   //================================================================================
1535
1536   bool isConcave( const TopoDS_Face&  F,
1537                   SMESH_MesherHelper& helper,
1538                   set< TGeomID >*     vertices = 0 )
1539   {
1540     bool isConcv = false;
1541     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1542     //   return true;
1543     gp_Vec2d drv1, drv2;
1544     gp_Pnt2d p;
1545     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1546     for ( ; eExp.More(); eExp.Next() )
1547     {
1548       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1549       if ( SMESH_Algo::isDegenerated( E )) continue;
1550       // check if 2D curve is concave
1551       BRepAdaptor_Curve2d curve( E, F );
1552       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1553       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1554       curve.Intervals( intervals, GeomAbs_C2 );
1555       bool isConvex = true;
1556       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1557       {
1558         double u1 = intervals( i );
1559         double u2 = intervals( i+1 );
1560         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1561         double cross = drv1 ^ drv2;
1562         if ( E.Orientation() == TopAbs_REVERSED )
1563           cross = -cross;
1564         isConvex = ( cross > -1e-9 ); // 0.1 );
1565       }
1566       if ( !isConvex )
1567       {
1568         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1569         isConcv = true;
1570         if ( vertices )
1571           break;
1572         else
1573           return true;
1574       }
1575     }
1576
1577     // check angles at VERTEXes
1578     if ( getConcaveVertices( F, helper, vertices ))
1579       isConcv = true;
1580
1581     return isConcv;
1582   }
1583
1584   //================================================================================
1585   /*!
1586    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1587    *  \param [in] face - the mesh face to treat
1588    *  \param [in] nodeOnEdge - a node on the EDGE
1589    *  \param [out] faceSize - the computed distance
1590    *  \return bool - true if faceSize computed
1591    */
1592   //================================================================================
1593
1594   bool getDistFromEdge( const SMDS_MeshElement* face,
1595                         const SMDS_MeshNode*    nodeOnEdge,
1596                         double &                faceSize )
1597   {
1598     faceSize = Precision::Infinite();
1599     bool done = false;
1600
1601     int nbN  = face->NbCornerNodes();
1602     int iOnE = face->GetNodeIndex( nodeOnEdge );
1603     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1604                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1605     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1606                                       face->GetNode( iNext[1] ) };
1607     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1608     double segLen = -1.;
1609     // look for two neighbor not in-FACE nodes of face
1610     for ( int i = 0; i < 2; ++i )
1611     {
1612       if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1613           ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1614       {
1615         // look for an in-FACE node
1616         for ( int iN = 0; iN < nbN; ++iN )
1617         {
1618           if ( iN == iOnE || iN == iNext[i] )
1619             continue;
1620           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1621           gp_XYZ v = pInFace - segEnd;
1622           if ( segLen < 0 )
1623           {
1624             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1625             segLen = segVec.Modulus();
1626           }
1627           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1628           faceSize = Min( faceSize, distToSeg );
1629           done = true;
1630         }
1631         segLen = -1;
1632       }
1633     }
1634     return done;
1635   }
1636   //================================================================================
1637   /*!
1638    * \brief Return direction of axis or revolution of a surface
1639    */
1640   //================================================================================
1641
1642   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1643                           gp_Dir &                 axis )
1644   {
1645     switch ( surface.GetType() ) {
1646     case GeomAbs_Cone:
1647     {
1648       gp_Cone cone = surface.Cone();
1649       axis = cone.Axis().Direction();
1650       break;
1651     }
1652     case GeomAbs_Sphere:
1653     {
1654       gp_Sphere sphere = surface.Sphere();
1655       axis = sphere.Position().Direction();
1656       break;
1657     }
1658     case GeomAbs_SurfaceOfRevolution:
1659     {
1660       axis = surface.AxeOfRevolution().Direction();
1661       break;
1662     }
1663     //case GeomAbs_SurfaceOfExtrusion:
1664     case GeomAbs_OffsetSurface:
1665     {
1666       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1667       return getRovolutionAxis( base->Surface(), axis );
1668     }
1669     default: return false;
1670     }
1671     return true;
1672   }
1673
1674   //--------------------------------------------------------------------------------
1675   // DEBUG. Dump intermediate node positions into a python script
1676   // HOWTO use: run python commands written in a console to see
1677   //  construction steps of viscous layers
1678 #ifdef __myDEBUG
1679   ostream* py;
1680   int      theNbPyFunc;
1681   struct PyDump
1682   {
1683     PyDump(SMESH_Mesh& m) {
1684       int tag = 3 + m.GetId();
1685       const char* fname = "/tmp/viscous.py";
1686       cout << "execfile('"<<fname<<"')"<<endl;
1687       py = _pyStream = new ofstream(fname);
1688       *py << "import SMESH" << endl
1689           << "from salome.smesh import smeshBuilder" << endl
1690           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1691           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1692           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1693       theNbPyFunc = 0;
1694     }
1695     void Finish() {
1696       if (py) {
1697         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1698           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1699         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1700           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1701       }
1702       delete py; py=0;
1703     }
1704     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1705     struct MyStream : public ostream
1706     {
1707       template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1708     };
1709     void Pause() { py = &_mystream; }
1710     void Resume() { py = _pyStream; }
1711     MyStream _mystream;
1712     ostream* _pyStream;
1713   };
1714 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1715 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1716 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1717 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1718   void _dumpFunction(const string& fun, int ln)
1719   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1720   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1721   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1722                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1723   void _dumpCmd(const string& txt, int ln)
1724   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1725   void dumpFunctionEnd()
1726   { if (py) *py<< "  return"<< endl; }
1727   void dumpChangeNodes( const SMDS_MeshElement* f )
1728   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1729       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1730       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1731 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1732
1733 #else
1734
1735   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1736 #define dumpFunction(f) f
1737 #define dumpMove(n)
1738 #define dumpMoveComm(n,txt)
1739 #define dumpCmd(txt)
1740 #define dumpFunctionEnd()
1741 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1742 #define debugMsg( txt ) {}
1743
1744 #endif
1745 }
1746
1747 using namespace VISCOUS_3D;
1748
1749 //================================================================================
1750 /*!
1751  * \brief Constructor of _ViscousBuilder
1752  */
1753 //================================================================================
1754
1755 _ViscousBuilder::_ViscousBuilder()
1756 {
1757   _error = SMESH_ComputeError::New(COMPERR_OK);
1758   _tmpFaceID = 0;
1759 }
1760
1761 //================================================================================
1762 /*!
1763  * \brief Stores error description and returns false
1764  */
1765 //================================================================================
1766
1767 bool _ViscousBuilder::error(const string& text, int solidId )
1768 {
1769   const string prefix = string("Viscous layers builder: ");
1770   _error->myName    = COMPERR_ALGO_FAILED;
1771   _error->myComment = prefix + text;
1772   if ( _mesh )
1773   {
1774     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1775     if ( !sm && !_sdVec.empty() )
1776       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1777     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1778     {
1779       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1780       if ( smError && smError->myAlgo )
1781         _error->myAlgo = smError->myAlgo;
1782       smError = _error;
1783       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1784     }
1785     // set KO to all solids
1786     for ( size_t i = 0; i < _sdVec.size(); ++i )
1787     {
1788       if ( _sdVec[i]._index == solidId )
1789         continue;
1790       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1791       if ( !sm->IsEmpty() )
1792         continue;
1793       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1794       if ( !smError || smError->IsOK() )
1795       {
1796         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1797         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1798       }
1799     }
1800   }
1801   makeGroupOfLE(); // debug
1802
1803   return false;
1804 }
1805
1806 //================================================================================
1807 /*!
1808  * \brief At study restoration, restore event listeners used to clear an inferior
1809  *  dim sub-mesh modified by viscous layers
1810  */
1811 //================================================================================
1812
1813 void _ViscousBuilder::RestoreListeners()
1814 {
1815   // TODO
1816 }
1817
1818 //================================================================================
1819 /*!
1820  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1821  */
1822 //================================================================================
1823
1824 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1825 {
1826   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1827   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1828   for ( ; fExp.More(); fExp.Next() )
1829   {
1830     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1831     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1832
1833     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1834       continue;
1835     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1836       continue;
1837
1838     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1839       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1840
1841     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1842     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1843     while( prxIt->more() )
1844     {
1845       const SMDS_MeshElement* fSrc = srcIt->next();
1846       const SMDS_MeshElement* fPrx = prxIt->next();
1847       if ( fSrc->NbNodes() != fPrx->NbNodes())
1848         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1849       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1850         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1851     }
1852   }
1853   pm->_n2nMapComputed = true;
1854   return true;
1855 }
1856
1857 //================================================================================
1858 /*!
1859  * \brief Does its job
1860  */
1861 //================================================================================
1862
1863 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1864                                                const TopoDS_Shape& theShape)
1865 {
1866   _mesh = & theMesh;
1867
1868   // check if proxy mesh already computed
1869   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1870   if ( !exp.More() )
1871     return error("No SOLID's in theShape"), _error;
1872
1873   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1874     return SMESH_ComputeErrorPtr(); // everything already computed
1875
1876   PyDump debugDump( theMesh );
1877   _pyDump = &debugDump;
1878
1879   // TODO: ignore already computed SOLIDs 
1880   if ( !findSolidsWithLayers())
1881     return _error;
1882
1883   if ( !findFacesWithLayers() )
1884     return _error;
1885
1886   for ( size_t i = 0; i < _sdVec.size(); ++i )
1887   {
1888     size_t iSD = 0;
1889     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1890       if ( _sdVec[iSD]._before.IsEmpty() &&
1891            !_sdVec[iSD]._solid.IsNull() &&
1892            _sdVec[iSD]._n2eMap.empty() )
1893         break;
1894
1895     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1896       return _error;
1897
1898     if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1899     {
1900       _sdVec[iSD]._solid.Nullify();
1901       continue;
1902     }
1903
1904     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
1905       return _error;
1906
1907     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
1908       return _error;
1909
1910     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
1911       return _error;
1912
1913     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1914
1915     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1916     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1917       _sdVec[iSD]._before.Remove( solid );
1918   }
1919
1920   makeGroupOfLE(); // debug
1921   debugDump.Finish();
1922
1923   return _error;
1924 }
1925
1926 //================================================================================
1927 /*!
1928  * \brief Check validity of hypotheses
1929  */
1930 //================================================================================
1931
1932 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1933                                                         const TopoDS_Shape& shape )
1934 {
1935   _mesh = & mesh;
1936
1937   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1938     return SMESH_ComputeErrorPtr(); // everything already computed
1939
1940
1941   findSolidsWithLayers();
1942   bool ok = findFacesWithLayers( true );
1943
1944   // remove _MeshOfSolid's of _SolidData's
1945   for ( size_t i = 0; i < _sdVec.size(); ++i )
1946     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1947
1948   if ( !ok )
1949     return _error;
1950
1951   return SMESH_ComputeErrorPtr();
1952 }
1953
1954 //================================================================================
1955 /*!
1956  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1957  */
1958 //================================================================================
1959
1960 bool _ViscousBuilder::findSolidsWithLayers()
1961 {
1962   // get all solids
1963   TopTools_IndexedMapOfShape allSolids;
1964   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1965   _sdVec.reserve( allSolids.Extent());
1966
1967   SMESH_HypoFilter filter;
1968   for ( int i = 1; i <= allSolids.Extent(); ++i )
1969   {
1970     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1971     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1972     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1973       continue; // solid is already meshed
1974     SMESH_Algo* algo = sm->GetAlgo();
1975     if ( !algo ) continue;
1976     // TODO: check if algo is hidden
1977     const list <const SMESHDS_Hypothesis *> & allHyps =
1978       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1979     _SolidData* soData = 0;
1980     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1981     const StdMeshers_ViscousLayers* viscHyp = 0;
1982     for ( ; hyp != allHyps.end(); ++hyp )
1983       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1984       {
1985         TopoDS_Shape hypShape;
1986         filter.Init( filter.Is( viscHyp ));
1987         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1988
1989         if ( !soData )
1990         {
1991           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1992                                                                     allSolids(i),
1993                                                                     /*toCreate=*/true);
1994           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1995           soData = & _sdVec.back();
1996           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1997           soData->_helper = new SMESH_MesherHelper( *_mesh );
1998           soData->_helper->SetSubShape( allSolids(i) );
1999           _solids.Add( allSolids(i) );
2000         }
2001         soData->_hyps.push_back( viscHyp );
2002         soData->_hypShapes.push_back( hypShape );
2003       }
2004   }
2005   if ( _sdVec.empty() )
2006     return error
2007       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2008
2009   return true;
2010 }
2011
2012 //================================================================================
2013 /*!
2014  * \brief Set a _SolidData to be computed before another
2015  */
2016 //================================================================================
2017
2018 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2019 {
2020   // check possibility to set this order; get all solids before solidBefore
2021   TopTools_IndexedMapOfShape allSolidsBefore;
2022   allSolidsBefore.Add( solidBefore._solid );
2023   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2024   {
2025     int iSD = _solids.FindIndex( allSolidsBefore(i) );
2026     if ( iSD )
2027     {
2028       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2029       for ( ; soIt.More(); soIt.Next() )
2030         allSolidsBefore.Add( soIt.Value() );
2031     }
2032   }
2033   if ( allSolidsBefore.Contains( solidAfter._solid ))
2034     return false;
2035
2036   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2037     solidAfter._before.Add( allSolidsBefore(i) );
2038
2039   return true;
2040 }
2041
2042 //================================================================================
2043 /*!
2044  * \brief
2045  */
2046 //================================================================================
2047
2048 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2049 {
2050   SMESH_MesherHelper helper( *_mesh );
2051   TopExp_Explorer exp;
2052
2053   // collect all faces-to-ignore defined by hyp
2054   for ( size_t i = 0; i < _sdVec.size(); ++i )
2055   {
2056     // get faces-to-ignore defined by each hyp
2057     typedef const StdMeshers_ViscousLayers* THyp;
2058     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2059     list< TFacesOfHyp > ignoreFacesOfHyps;
2060     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2061     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2062     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2063     {
2064       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2065       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2066     }
2067
2068     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2069     const int nbHyps = _sdVec[i]._hyps.size();
2070     if ( nbHyps > 1 )
2071     {
2072       // check if two hypotheses define different parameters for the same FACE
2073       list< TFacesOfHyp >::iterator igFacesOfHyp;
2074       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2075       {
2076         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2077         THyp hyp = 0;
2078         igFacesOfHyp = ignoreFacesOfHyps.begin();
2079         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2080           if ( ! igFacesOfHyp->first.count( faceID ))
2081           {
2082             if ( hyp )
2083               return error(SMESH_Comment("Several hypotheses define "
2084                                          "Viscous Layers on the face #") << faceID );
2085             hyp = igFacesOfHyp->second;
2086           }
2087         if ( hyp )
2088           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2089         else
2090           _sdVec[i]._ignoreFaceIds.insert( faceID );
2091       }
2092
2093       // check if two hypotheses define different number of viscous layers for
2094       // adjacent faces of a solid
2095       set< int > nbLayersSet;
2096       igFacesOfHyp = ignoreFacesOfHyps.begin();
2097       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2098       {
2099         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2100       }
2101       if ( nbLayersSet.size() > 1 )
2102       {
2103         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2104         {
2105           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2106           THyp hyp1 = 0, hyp2 = 0;
2107           while( const TopoDS_Shape* face = fIt->next() )
2108           {
2109             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2110             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2111             if ( f2h != _sdVec[i]._face2hyp.end() )
2112             {
2113               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2114             }
2115           }
2116           if ( hyp1 && hyp2 &&
2117                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2118           {
2119             return error("Two hypotheses define different number of "
2120                          "viscous layers on adjacent faces");
2121           }
2122         }
2123       }
2124     } // if ( nbHyps > 1 )
2125     else
2126     {
2127       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2128     }
2129   } // loop on _sdVec
2130
2131   if ( onlyWith ) // is called to check hypotheses compatibility only
2132     return true;
2133
2134   // fill _SolidData::_reversedFaceIds
2135   for ( size_t i = 0; i < _sdVec.size(); ++i )
2136   {
2137     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2138     for ( ; exp.More(); exp.Next() )
2139     {
2140       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2141       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2142       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2143           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2144           helper.IsReversedSubMesh( face ))
2145       {
2146         _sdVec[i]._reversedFaceIds.insert( faceID );
2147       }
2148     }
2149   }
2150
2151   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2152   TopTools_IndexedMapOfShape shapes;
2153   std::string structAlgoName = "Hexa_3D";
2154   for ( size_t i = 0; i < _sdVec.size(); ++i )
2155   {
2156     shapes.Clear();
2157     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2158     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2159     {
2160       const TopoDS_Shape& edge = shapes(iE);
2161       // find 2 FACEs sharing an EDGE
2162       TopoDS_Shape FF[2];
2163       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2164       while ( fIt->more())
2165       {
2166         const TopoDS_Shape* f = fIt->next();
2167         FF[ int( !FF[0].IsNull()) ] = *f;
2168       }
2169       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2170
2171       // check presence of layers on them
2172       int ignore[2];
2173       for ( int j = 0; j < 2; ++j )
2174         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2175       if ( ignore[0] == ignore[1] )
2176         continue; // nothing interesting
2177       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2178
2179       // add EDGE to maps
2180       if ( !fWOL.IsNull())
2181       {
2182         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2183         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2184       }
2185     }
2186   }
2187
2188   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2189
2190   for ( size_t i = 0; i < _sdVec.size(); ++i )
2191   {
2192     shapes.Clear();
2193     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2194     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2195     {
2196       const TopoDS_Shape& vertex = shapes(iV);
2197       // find faces WOL sharing the vertex
2198       vector< TopoDS_Shape > facesWOL;
2199       size_t totalNbFaces = 0;
2200       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2201       while ( fIt->more())
2202       {
2203         const TopoDS_Shape* f = fIt->next();
2204         totalNbFaces++;
2205         const int fID = getMeshDS()->ShapeToIndex( *f );
2206         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2207           facesWOL.push_back( *f );
2208       }
2209       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2210         continue; // no layers at this vertex or no WOL
2211       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2212       switch ( facesWOL.size() )
2213       {
2214       case 1:
2215       {
2216         helper.SetSubShape( facesWOL[0] );
2217         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2218         {
2219           TopoDS_Shape seamEdge;
2220           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2221           while ( eIt->more() && seamEdge.IsNull() )
2222           {
2223             const TopoDS_Shape* e = eIt->next();
2224             if ( helper.IsRealSeam( *e ) )
2225               seamEdge = *e;
2226           }
2227           if ( !seamEdge.IsNull() )
2228           {
2229             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2230             break;
2231           }
2232         }
2233         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2234         break;
2235       }
2236       case 2:
2237       {
2238         // find an edge shared by 2 faces
2239         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2240         while ( eIt->more())
2241         {
2242           const TopoDS_Shape* e = eIt->next();
2243           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2244                helper.IsSubShape( *e, facesWOL[1]))
2245           {
2246             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2247           }
2248         }
2249         break;
2250       }
2251       default:
2252         return error("Not yet supported case", _sdVec[i]._index);
2253       }
2254     }
2255   }
2256
2257   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2258   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2259   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2260   for ( size_t i = 0; i < _sdVec.size(); ++i )
2261   {
2262     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2263     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2264     {
2265       const TopoDS_Shape& fWOL = e2f->second;
2266       const TGeomID     edgeID = e2f->first;
2267       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2268       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2269       if ( edge.ShapeType() != TopAbs_EDGE )
2270         continue; // shrink shape is VERTEX
2271
2272       TopoDS_Shape solid;
2273       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2274       while ( soIt->more() && solid.IsNull() )
2275       {
2276         const TopoDS_Shape* so = soIt->next();
2277         if ( !so->IsSame( _sdVec[i]._solid ))
2278           solid = *so;
2279       }
2280       if ( solid.IsNull() )
2281         continue;
2282
2283       bool noShrinkE = false;
2284       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2285       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2286       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2287       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2288       {
2289         // the adjacent SOLID has NO layers on fWOL;
2290         // shrink allowed if
2291         // - there are layers on the EDGE in the adjacent SOLID
2292         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2293         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2294         bool shrinkAllowed = (( hasWLAdj ) ||
2295                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2296         noShrinkE = !shrinkAllowed;
2297       }
2298       else if ( iSolid < _sdVec.size() )
2299       {
2300         // the adjacent SOLID has layers on fWOL;
2301         // check if SOLID's mesh is unstructured and then try to set it
2302         // to be computed after the i-th solid
2303         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2304           noShrinkE = true; // don't shrink fWOL
2305       }
2306       else
2307       {
2308         // the adjacent SOLID has NO layers at all
2309         noShrinkE = isStructured;
2310       }
2311
2312       if ( noShrinkE )
2313       {
2314         _sdVec[i]._noShrinkShapes.insert( edgeID );
2315
2316         // check if there is a collision with to-shrink-from EDGEs in iSolid
2317         // if ( iSolid < _sdVec.size() )
2318         // {
2319         //   shapes.Clear();
2320         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2321         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2322         //   {
2323         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2324         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2325         //     if ( eID == edgeID ||
2326         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2327         //          _sdVec[i]._noShrinkShapes.count( eID ))
2328         //       continue;
2329         //     for ( int is1st = 0; is1st < 2; ++is1st )
2330         //     {
2331         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2332         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2333         //       {
2334         //         return error("No way to make a conformal mesh with "
2335         //                      "the given set of faces with layers", _sdVec[i]._index);
2336         //       }
2337         //     }
2338         //   }
2339         // }
2340       }
2341
2342       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2343       // _shrinkShape2Shape is different in the adjacent SOLID
2344       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2345       {
2346         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2347         bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2348
2349         if ( iSolid < _sdVec.size() )
2350         {
2351           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2352           {
2353             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2354             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2355             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2356             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2357               noShrinkV = (( isStructured ) ||
2358                            ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2359             else
2360               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2361           }
2362           else
2363           {
2364             noShrinkV = noShrinkE;
2365           }
2366         }
2367         else
2368         {
2369           // the adjacent SOLID has NO layers at all
2370           if ( isStructured )
2371           {
2372             noShrinkV = true;
2373           }
2374           else
2375           {
2376             noShrinkV = noShrinkIfAdjMeshed =
2377               ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2378           }
2379         }
2380
2381         if ( noShrinkV && noShrinkIfAdjMeshed )
2382         {
2383           // noShrinkV if FACEs in the adjacent SOLID are meshed
2384           PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2385                                                        *_mesh, TopAbs_FACE, &solid );
2386           while ( fIt->more() )
2387           {
2388             const TopoDS_Shape* f = fIt->next();
2389             if ( !f->IsSame( fWOL ))
2390             {
2391               noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2392               break;
2393             }
2394           }
2395         }
2396         if ( noShrinkV )
2397           _sdVec[i]._noShrinkShapes.insert( vID );
2398       }
2399
2400     } // loop on _sdVec[i]._shrinkShape2Shape
2401   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2402
2403
2404     // add FACEs of other SOLIDs to _ignoreFaceIds
2405   for ( size_t i = 0; i < _sdVec.size(); ++i )
2406   {
2407     shapes.Clear();
2408     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2409
2410     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2411     {
2412       if ( !shapes.Contains( exp.Current() ))
2413         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2414     }
2415   }
2416
2417   return true;
2418 }
2419
2420 //================================================================================
2421 /*!
2422  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2423  */
2424 //================================================================================
2425
2426 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2427                                      const StdMeshers_ViscousLayers* hyp,
2428                                      const TopoDS_Shape&             hypShape,
2429                                      set<TGeomID>&                   ignoreFaceIds)
2430 {
2431   TopExp_Explorer exp;
2432
2433   vector<TGeomID> ids = hyp->GetBndShapes();
2434   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2435   {
2436     for ( size_t ii = 0; ii < ids.size(); ++ii )
2437     {
2438       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2439       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2440         ignoreFaceIds.insert( ids[ii] );
2441     }
2442   }
2443   else // FACEs with layers are given
2444   {
2445     exp.Init( solid, TopAbs_FACE );
2446     for ( ; exp.More(); exp.Next() )
2447     {
2448       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2449       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2450         ignoreFaceIds.insert( faceInd );
2451     }
2452   }
2453
2454   // ignore internal FACEs if inlets and outlets are specified
2455   if ( hyp->IsToIgnoreShapes() )
2456   {
2457     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2458     TopExp::MapShapesAndAncestors( hypShape,
2459                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2460
2461     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2462     {
2463       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2464       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2465         continue;
2466
2467       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2468       if ( nbSolids > 1 )
2469         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2470     }
2471   }
2472 }
2473
2474 //================================================================================
2475 /*!
2476  * \brief Create the inner surface of the viscous layer and prepare data for infation
2477  */
2478 //================================================================================
2479
2480 bool _ViscousBuilder::makeLayer(_SolidData& data)
2481 {
2482   // get all sub-shapes to make layers on
2483   set<TGeomID> subIds, faceIds;
2484   subIds = data._noShrinkShapes;
2485   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2486   for ( ; exp.More(); exp.Next() )
2487   {
2488     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2489     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2490       faceIds.insert( fSubM->GetId() );
2491   }
2492
2493   // make a map to find new nodes on sub-shapes shared with other SOLID
2494   map< TGeomID, TNode2Edge* >::iterator s2ne;
2495   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2496   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2497   {
2498     TGeomID shapeInd = s2s->first;
2499     for ( size_t i = 0; i < _sdVec.size(); ++i )
2500     {
2501       if ( _sdVec[i]._index == data._index ) continue;
2502       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2503       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2504            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2505       {
2506         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2507         break;
2508       }
2509     }
2510   }
2511
2512   // Create temporary faces and _LayerEdge's
2513
2514   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2515
2516   data._stepSize = Precision::Infinite();
2517   data._stepSizeNodes[0] = 0;
2518
2519   SMESH_MesherHelper helper( *_mesh );
2520   helper.SetSubShape( data._solid );
2521   helper.SetElementsOnShape( true );
2522
2523   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2524   TNode2Edge::iterator n2e2;
2525
2526   // collect _LayerEdge's of shapes they are based on
2527   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2528   const int nbShapes = getMeshDS()->MaxShapeIndex();
2529   edgesByGeom.resize( nbShapes+1 );
2530
2531   // set data of _EdgesOnShape's
2532   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2533   {
2534     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2535     while ( smIt->more() )
2536     {
2537       sm = smIt->next();
2538       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2539            !faceIds.count( sm->GetId() ))
2540         continue;
2541       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2542     }
2543   }
2544   // make _LayerEdge's
2545   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2546   {
2547     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2548     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2549     SMESH_ProxyMesh::SubMesh* proxySub =
2550       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2551
2552     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2553     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2554
2555     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2556     while ( eIt->more() )
2557     {
2558       const SMDS_MeshElement* face = eIt->next();
2559       double          faceMaxCosin = -1;
2560       _LayerEdge*     maxCosinEdge = 0;
2561       int             nbDegenNodes = 0;
2562
2563       newNodes.resize( face->NbCornerNodes() );
2564       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2565       {
2566         const SMDS_MeshNode* n = face->GetNode( i );
2567         const int      shapeID = n->getshapeId();
2568         const bool onDegenShap = helper.IsDegenShape( shapeID );
2569         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2570         if ( onDegenShap )
2571         {
2572           if ( onDegenEdge )
2573           {
2574             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2575             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2576             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2577             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2578               n = vN;
2579               nbDegenNodes++;
2580             }
2581           }
2582           else
2583           {
2584             nbDegenNodes++;
2585           }
2586         }
2587         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2588         if ( !(*n2e).second )
2589         {
2590           // add a _LayerEdge
2591           _LayerEdge* edge = new _LayerEdge();
2592           edge->_nodes.push_back( n );
2593           n2e->second = edge;
2594           edgesByGeom[ shapeID ]._edges.push_back( edge );
2595           const bool noShrink = data._noShrinkShapes.count( shapeID );
2596
2597           SMESH_TNodeXYZ xyz( n );
2598
2599           // set edge data or find already refined _LayerEdge and get data from it
2600           if (( !noShrink                                                     ) &&
2601               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2602               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2603               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2604           {
2605             _LayerEdge* foundEdge = (*n2e2).second;
2606             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2607             foundEdge->_pos.push_back( lastPos );
2608             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2609             const_cast< SMDS_MeshNode* >
2610               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2611           }
2612           else
2613           {
2614             if ( !noShrink )
2615             {
2616               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2617             }
2618             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2619               return false;
2620
2621             if ( edge->_nodes.size() < 2 )
2622               edge->Block( data );
2623               //data._noShrinkShapes.insert( shapeID );
2624           }
2625           dumpMove(edge->_nodes.back());
2626
2627           if ( edge->_cosin > faceMaxCosin )
2628           {
2629             faceMaxCosin = edge->_cosin;
2630             maxCosinEdge = edge;
2631           }
2632         }
2633         newNodes[ i ] = n2e->second->_nodes.back();
2634
2635         if ( onDegenEdge )
2636           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2637       }
2638       if ( newNodes.size() - nbDegenNodes < 2 )
2639         continue;
2640
2641       // create a temporary face
2642       const SMDS_MeshElement* newFace =
2643         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2644       proxySub->AddElement( newFace );
2645
2646       // compute inflation step size by min size of element on a convex surface
2647       if ( faceMaxCosin > theMinSmoothCosin )
2648         limitStepSize( data, face, maxCosinEdge );
2649
2650     } // loop on 2D elements on a FACE
2651   } // loop on FACEs of a SOLID to create _LayerEdge's
2652
2653
2654   // Set _LayerEdge::_neibors
2655   TNode2Edge::iterator n2e;
2656   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2657   {
2658     _EdgesOnShape& eos = data._edgesOnShape[iS];
2659     for ( size_t i = 0; i < eos._edges.size(); ++i )
2660     {
2661       _LayerEdge* edge = eos._edges[i];
2662       TIDSortedNodeSet nearNodes;
2663       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2664       while ( fIt->more() )
2665       {
2666         const SMDS_MeshElement* f = fIt->next();
2667         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2668           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2669       }
2670       nearNodes.erase( edge->_nodes[0] );
2671       edge->_neibors.reserve( nearNodes.size() );
2672       TIDSortedNodeSet::iterator node = nearNodes.begin();
2673       for ( ; node != nearNodes.end(); ++node )
2674         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2675           edge->_neibors.push_back( n2e->second );
2676     }
2677   }
2678
2679   data._epsilon = 1e-7;
2680   if ( data._stepSize < 1. )
2681     data._epsilon *= data._stepSize;
2682
2683   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2684     return false;
2685
2686   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2687   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2688
2689   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2690   const SMDS_MeshNode* nn[2];
2691   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2692   {
2693     _EdgesOnShape& eos = data._edgesOnShape[iS];
2694     for ( size_t i = 0; i < eos._edges.size(); ++i )
2695     {
2696       _LayerEdge* edge = eos._edges[i];
2697       if ( edge->IsOnEdge() )
2698       {
2699         // get neighbor nodes
2700         bool hasData = ( edge->_2neibors->_edges[0] );
2701         if ( hasData ) // _LayerEdge is a copy of another one
2702         {
2703           nn[0] = edge->_2neibors->srcNode(0);
2704           nn[1] = edge->_2neibors->srcNode(1);
2705         }
2706         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2707         {
2708           return false;
2709         }
2710         // set neighbor _LayerEdge's
2711         for ( int j = 0; j < 2; ++j )
2712         {
2713           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2714             return error("_LayerEdge not found by src node", data._index);
2715           edge->_2neibors->_edges[j] = n2e->second;
2716         }
2717         if ( !hasData )
2718           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2719       }
2720
2721       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2722       {
2723         _Simplex& s = edge->_simplices[j];
2724         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2725         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2726       }
2727
2728       // For an _LayerEdge on a degenerated EDGE, copy some data from
2729       // a corresponding _LayerEdge on a VERTEX
2730       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2731       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2732       {
2733         // Generally we should not get here
2734         if ( eos.ShapeType() != TopAbs_EDGE )
2735           continue;
2736         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2737         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2738         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2739           continue;
2740         const _LayerEdge* vEdge = n2e->second;
2741         edge->_normal    = vEdge->_normal;
2742         edge->_lenFactor = vEdge->_lenFactor;
2743         edge->_cosin     = vEdge->_cosin;
2744       }
2745
2746     } // loop on data._edgesOnShape._edges
2747   } // loop on data._edgesOnShape
2748
2749   // fix _LayerEdge::_2neibors on EDGEs to smooth
2750   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2751   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2752   //   if ( !e2c->second.IsNull() )
2753   //   {
2754   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2755   //       data.Sort2NeiborsOnEdge( eos->_edges );
2756   //   }
2757
2758   dumpFunctionEnd();
2759   return true;
2760 }
2761
2762 //================================================================================
2763 /*!
2764  * \brief Compute inflation step size by min size of element on a convex surface
2765  */
2766 //================================================================================
2767
2768 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2769                                      const SMDS_MeshElement* face,
2770                                      const _LayerEdge*       maxCosinEdge )
2771 {
2772   int iN = 0;
2773   double minSize = 10 * data._stepSize;
2774   const int nbNodes = face->NbCornerNodes();
2775   for ( int i = 0; i < nbNodes; ++i )
2776   {
2777     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2778     const SMDS_MeshNode*  curN = face->GetNode( i );
2779     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2780          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2781     {
2782       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2783       if ( dist < minSize )
2784         minSize = dist, iN = i;
2785     }
2786   }
2787   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2788   if ( newStep < data._stepSize )
2789   {
2790     data._stepSize = newStep;
2791     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2792     data._stepSizeNodes[0] = face->GetNode( iN );
2793     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2794   }
2795 }
2796
2797 //================================================================================
2798 /*!
2799  * \brief Compute inflation step size by min size of element on a convex surface
2800  */
2801 //================================================================================
2802
2803 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2804 {
2805   if ( minSize < data._stepSize )
2806   {
2807     data._stepSize = minSize;
2808     if ( data._stepSizeNodes[0] )
2809     {
2810       double dist =
2811         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2812       data._stepSizeCoeff = data._stepSize / dist;
2813     }
2814   }
2815 }
2816
2817 //================================================================================
2818 /*!
2819  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2820  */
2821 //================================================================================
2822
2823 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2824 {
2825   SMESH_MesherHelper helper( *_mesh );
2826
2827   BRepLProp_SLProps surfProp( 2, 1e-6 );
2828   data._convexFaces.clear();
2829
2830   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2831   {
2832     _EdgesOnShape& eof = data._edgesOnShape[iS];
2833     if ( eof.ShapeType() != TopAbs_FACE ||
2834          data._ignoreFaceIds.count( eof._shapeID ))
2835       continue;
2836
2837     TopoDS_Face        F = TopoDS::Face( eof._shape );
2838     const TGeomID faceID = eof._shapeID;
2839
2840     BRepAdaptor_Surface surface( F, false );
2841     surfProp.SetSurface( surface );
2842
2843     _ConvexFace cnvFace;
2844     cnvFace._face = F;
2845     cnvFace._normalsFixed = false;
2846     cnvFace._isTooCurved = false;
2847
2848     double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2849     if ( maxCurvature > 0 )
2850     {
2851       limitStepSize( data, 0.9 / maxCurvature );
2852       findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2853     }
2854     if ( !cnvFace._isTooCurved ) continue;
2855
2856     _ConvexFace & convFace =
2857       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2858
2859     // skip a closed surface (data._convexFaces is useful anyway)
2860     bool isClosedF = false;
2861     helper.SetSubShape( F );
2862     if ( helper.HasRealSeam() )
2863     {
2864       // in the closed surface there must be a closed EDGE
2865       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2866         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2867     }
2868     if ( isClosedF )
2869     {
2870       // limit _LayerEdge::_maxLen on the FACE
2871       const double oriFactor    = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2872       const double minCurvature =
2873         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2874       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2875       if ( id2eos != cnvFace._subIdToEOS.end() )
2876       {
2877         _EdgesOnShape& eos = * id2eos->second;
2878         for ( size_t i = 0; i < eos._edges.size(); ++i )
2879         {
2880           _LayerEdge* ledge = eos._edges[ i ];
2881           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2882           surfProp.SetParameters( uv.X(), uv.Y() );
2883           if ( surfProp.IsCurvatureDefined() )
2884           {
2885             double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2886                                     surfProp.MinCurvature() * oriFactor );
2887             if ( curvature > minCurvature )
2888               ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
2889           }
2890         }
2891       }
2892       continue;
2893     }
2894
2895     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2896     // prism distortion.
2897     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2898     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2899     {
2900       // there are _LayerEdge's on the FACE it-self;
2901       // select _LayerEdge's near EDGEs
2902       _EdgesOnShape& eos = * id2eos->second;
2903       for ( size_t i = 0; i < eos._edges.size(); ++i )
2904       {
2905         _LayerEdge* ledge = eos._edges[ i ];
2906         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2907           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2908           {
2909             // do not select _LayerEdge's neighboring sharp EDGEs
2910             bool sharpNbr = false;
2911             for ( size_t iN = 0; iN < ledge->_neibors.size()  && !sharpNbr; ++iN )
2912               sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
2913             if ( !sharpNbr )
2914               convFace._simplexTestEdges.push_back( ledge );
2915             break;
2916           }
2917       }
2918     }
2919     else
2920     {
2921       // where there are no _LayerEdge's on a _ConvexFace,
2922       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2923       // so that collision of viscous internal faces is not detected by check of
2924       // intersection of _LayerEdge's with the viscous internal faces.
2925
2926       set< const SMDS_MeshNode* > usedNodes;
2927
2928       // look for _LayerEdge's with null _sWOL
2929       id2eos = convFace._subIdToEOS.begin();
2930       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2931       {
2932         _EdgesOnShape& eos = * id2eos->second;
2933         if ( !eos._sWOL.IsNull() )
2934           continue;
2935         for ( size_t i = 0; i < eos._edges.size(); ++i )
2936         {
2937           _LayerEdge* ledge = eos._edges[ i ];
2938           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2939           if ( !usedNodes.insert( srcNode ).second ) continue;
2940
2941           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2942           {
2943             usedNodes.insert( ledge->_simplices[i]._nPrev );
2944             usedNodes.insert( ledge->_simplices[i]._nNext );
2945           }
2946           convFace._simplexTestEdges.push_back( ledge );
2947         }
2948       }
2949     }
2950   } // loop on FACEs of data._solid
2951 }
2952
2953 //================================================================================
2954 /*!
2955  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2956  */
2957 //================================================================================
2958
2959 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2960 {
2961   // define allowed thickness
2962   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2963
2964
2965   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2966   // boundary inclined to the shape at a sharp angle
2967
2968   TopTools_MapOfShape edgesOfSmooFaces;
2969   SMESH_MesherHelper helper( *_mesh );
2970   bool ok = true;
2971
2972   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2973   data._nbShapesToSmooth = 0;
2974
2975   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2976   {
2977     _EdgesOnShape& eos = edgesByGeom[iS];
2978     eos._toSmooth = false;
2979     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2980       continue;
2981
2982     double tgtThick = eos._hyp.GetTotalThickness();
2983     SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
2984     while ( subIt->more() && !eos._toSmooth )
2985     {
2986       TGeomID iSub = subIt->next()->GetId();
2987       const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
2988       if ( eSub.empty() ) continue;
2989
2990       double faceSize;
2991       for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
2992         if ( eSub[i]->_cosin > theMinSmoothCosin )
2993         {
2994           SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2995           while ( fIt->more() && !eos._toSmooth )
2996           {
2997             const SMDS_MeshElement* face = fIt->next();
2998             if ( face->getshapeId() == eos._shapeID &&
2999                  getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3000             {
3001               eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3002                                              tgtThick * eSub[i]->_lenFactor,
3003                                              faceSize);
3004             }
3005           }
3006         }
3007     }
3008     if ( eos._toSmooth )
3009     {
3010       for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3011         edgesOfSmooFaces.Add( eExp.Current() );
3012
3013       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3014     }
3015     data._nbShapesToSmooth += eos._toSmooth;
3016
3017   }  // check FACEs
3018
3019   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3020   {
3021     _EdgesOnShape& eos = edgesByGeom[iS];
3022     eos._edgeSmoother = NULL;
3023     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3024     if ( !eos._hyp.ToSmooth() ) continue;
3025
3026     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3027     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3028       continue;
3029
3030     double tgtThick = eos._hyp.GetTotalThickness();
3031     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3032     {
3033       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3034       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3035       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3036       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3037       double angle    = eDir.Angle( eV[0]->_normal );
3038       double cosin    = Cos( angle );
3039       double cosinAbs = Abs( cosin );
3040       if ( cosinAbs > theMinSmoothCosin )
3041       {
3042         // always smooth analytic EDGEs
3043         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3044         eos._toSmooth = ! curve.IsNull();
3045
3046         // compare tgtThick with the length of an end segment
3047         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3048         while ( eIt->more() && !eos._toSmooth )
3049         {
3050           const SMDS_MeshElement* endSeg = eIt->next();
3051           if ( endSeg->getshapeId() == (int) iS )
3052           {
3053             double segLen =
3054               SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3055             eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3056           }
3057         }
3058         if ( eos._toSmooth )
3059         {
3060           eos._edgeSmoother = new _Smoother1D( curve, eos );
3061
3062           // for ( size_t i = 0; i < eos._edges.size(); ++i )
3063           //   eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3064         }
3065       }
3066     }
3067     data._nbShapesToSmooth += eos._toSmooth;
3068
3069   } // check EDGEs
3070
3071   // Reset _cosin if no smooth is allowed by the user
3072   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3073   {
3074     _EdgesOnShape& eos = edgesByGeom[iS];
3075     if ( eos._edges.empty() ) continue;
3076
3077     if ( !eos._hyp.ToSmooth() )
3078       for ( size_t i = 0; i < eos._edges.size(); ++i )
3079         //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3080         eos._edges[i]->_lenFactor = 1;
3081   }
3082
3083
3084   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3085
3086   TopTools_MapOfShape c1VV;
3087
3088   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3089   {
3090     _EdgesOnShape& eos = edgesByGeom[iS];
3091     if ( eos._edges.empty() ||
3092          eos.ShapeType() != TopAbs_FACE ||
3093          !eos._toSmooth )
3094       continue;
3095
3096     // check EDGEs of a FACE
3097     TopTools_MapOfShape checkedEE, allVV;
3098     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3099     while ( !smQueue.empty() )
3100     {
3101       SMESH_subMesh* sm = smQueue.front();
3102       smQueue.pop_front();
3103       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3104       while ( smIt->more() )
3105       {
3106         sm = smIt->next();
3107         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3108           allVV.Add( sm->GetSubShape() );
3109         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3110              !checkedEE.Add( sm->GetSubShape() ))
3111           continue;
3112
3113         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3114         vector<_LayerEdge*>& eE = eoe->_edges;
3115         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3116           continue;
3117
3118         bool isC1 = true; // check continuity along an EDGE
3119         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3120           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3121         if ( !isC1 )
3122           continue;
3123
3124         // check that mesh faces are C1 as well
3125         {
3126           gp_XYZ norm1, norm2;
3127           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3128           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3129           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3130             continue;
3131           while ( fIt->more() && isC1 )
3132             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3133                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3134           if ( !isC1 )
3135             continue;
3136         }
3137
3138         // add the EDGE and an adjacent FACE to _eosC1
3139         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3140         while ( const TopoDS_Shape* face = fIt->next() )
3141         {
3142           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3143           if ( !eof ) continue; // other solid
3144           if ( eos._shapeID == eof->_shapeID ) continue;
3145           if ( !eos.HasC1( eof ))
3146           {
3147             // check the FACEs
3148             eos._eosC1.push_back( eof );
3149             eof->_toSmooth = false;
3150             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3151             smQueue.push_back( eof->_subMesh );
3152           }
3153           if ( !eos.HasC1( eoe ))
3154           {
3155             eos._eosC1.push_back( eoe );
3156             eoe->_toSmooth = false;
3157             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3158           }
3159         }
3160       }
3161     }
3162     if ( eos._eosC1.empty() )
3163       continue;
3164
3165     // check VERTEXes of C1 FACEs
3166     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3167     for ( ; vIt.More(); vIt.Next() )
3168     {
3169       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3170       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3171         continue;
3172
3173       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3174       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3175       while ( const TopoDS_Shape* face = fIt->next() )
3176       {
3177         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3178         if ( !eof ) continue; // other solid
3179         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3180         if ( !isC1 )
3181           break;
3182       }
3183       if ( isC1 )
3184       {
3185         eos._eosC1.push_back( eov );
3186         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3187         c1VV.Add( eov->_shape );
3188       }
3189     }
3190
3191   } // fill _eosC1 of FACEs
3192
3193
3194   // Find C1 EDGEs
3195
3196   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3197
3198   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3199   {
3200     _EdgesOnShape& eov = edgesByGeom[iS];
3201     if ( eov._edges.empty() ||
3202          eov.ShapeType() != TopAbs_VERTEX ||
3203          c1VV.Contains( eov._shape ))
3204       continue;
3205     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3206
3207     // get directions of surrounding EDGEs
3208     dirOfEdges.clear();
3209     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3210     while ( const TopoDS_Shape* e = fIt->next() )
3211     {
3212       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3213       if ( !eoe ) continue; // other solid
3214       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3215       if ( !Precision::IsInfinite( eDir.X() ))
3216         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3217     }
3218
3219     // find EDGEs with C1 directions
3220     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3221       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3222         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3223         {
3224           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3225           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3226           if ( isC1 )
3227           {
3228             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3229             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3230             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3231             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3232             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3233             dirOfEdges[i].first = 0;
3234             dirOfEdges[j].first = 0;
3235           }
3236         }
3237   } // fill _eosC1 of VERTEXes
3238
3239
3240
3241   return ok;
3242 }
3243
3244 //================================================================================
3245 /*!
3246  * \brief initialize data of _EdgesOnShape
3247  */
3248 //================================================================================
3249
3250 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3251                                     SMESH_subMesh* sm,
3252                                     _SolidData&    data )
3253 {
3254   if ( !eos._shape.IsNull() ||
3255        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3256     return;
3257
3258   SMESH_MesherHelper helper( *_mesh );
3259
3260   eos._subMesh = sm;
3261   eos._shapeID = sm->GetId();
3262   eos._shape   = sm->GetSubShape();
3263   if ( eos.ShapeType() == TopAbs_FACE )
3264     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3265   eos._toSmooth = false;
3266   eos._data = &data;
3267
3268   // set _SWOL
3269   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3270     data._shrinkShape2Shape.find( eos._shapeID );
3271   if ( s2s != data._shrinkShape2Shape.end() )
3272     eos._sWOL = s2s->second;
3273
3274   eos._isRegularSWOL = true;
3275   if ( eos.SWOLType() == TopAbs_FACE )
3276   {
3277     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3278     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3279     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3280   }
3281
3282   // set _hyp
3283   if ( data._hyps.size() == 1 )
3284   {
3285     eos._hyp = data._hyps.back();
3286   }
3287   else
3288   {
3289     // compute average StdMeshers_ViscousLayers parameters
3290     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3291     if ( eos.ShapeType() == TopAbs_FACE )
3292     {
3293       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3294         eos._hyp = f2hyp->second;
3295     }
3296     else
3297     {
3298       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3299       while ( const TopoDS_Shape* face = fIt->next() )
3300       {
3301         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3302         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3303           eos._hyp.Add( f2hyp->second );
3304       }
3305     }
3306   }
3307
3308   // set _faceNormals
3309   if ( ! eos._hyp.UseSurfaceNormal() )
3310   {
3311     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3312     {
3313       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3314       if ( !smDS ) return;
3315       eos._faceNormals.resize( smDS->NbElements() );
3316
3317       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3318       for ( int iF = 0; eIt->more(); ++iF )
3319       {
3320         const SMDS_MeshElement* face = eIt->next();
3321         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3322           eos._faceNormals[iF].SetCoord( 0,0,0 );
3323       }
3324
3325       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3326         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3327           eos._faceNormals[iF].Reverse();
3328     }
3329     else // find EOS of adjacent FACEs
3330     {
3331       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3332       while ( const TopoDS_Shape* face = fIt->next() )
3333       {
3334         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3335         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3336         if ( eos._faceEOS.back()->_shape.IsNull() )
3337           // avoid using uninitialised _shapeID in GetNormal()
3338           eos._faceEOS.back()->_shapeID = faceID;
3339       }
3340     }
3341   }
3342 }
3343
3344 //================================================================================
3345 /*!
3346  * \brief Returns normal of a face
3347  */
3348 //================================================================================
3349
3350 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3351 {
3352   bool ok = false;
3353   const _EdgesOnShape* eos = 0;
3354
3355   if ( face->getshapeId() == _shapeID )
3356   {
3357     eos = this;
3358   }
3359   else
3360   {
3361     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3362       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3363         eos = _faceEOS[ iF ];
3364   }
3365
3366   if (( eos ) &&
3367       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3368   {
3369     norm = eos->_faceNormals[ face->getIdInShape() ];
3370   }
3371   else if ( !eos )
3372   {
3373     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3374               << " on _shape #" << _shapeID );
3375   }
3376   return ok;
3377 }
3378
3379
3380 //================================================================================
3381 /*!
3382  * \brief Set data of _LayerEdge needed for smoothing
3383  */
3384 //================================================================================
3385
3386 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3387                                   _EdgesOnShape&      eos,
3388                                   SMESH_MesherHelper& helper,
3389                                   _SolidData&         data)
3390 {
3391   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3392
3393   edge._len       = 0;
3394   edge._maxLen    = Precision::Infinite();
3395   edge._minAngle  = 0;
3396   edge._2neibors  = 0;
3397   edge._curvature = 0;
3398   edge._flags     = 0;
3399
3400   // --------------------------
3401   // Compute _normal and _cosin
3402   // --------------------------
3403
3404   edge._cosin     = 0;
3405   edge._lenFactor = 1.;
3406   edge._normal.SetCoord(0,0,0);
3407   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3408
3409   int totalNbFaces = 0;
3410   TopoDS_Face F;
3411   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3412   gp_Vec geomNorm;
3413   bool normOK = true;
3414
3415   const bool onShrinkShape = !eos._sWOL.IsNull();
3416   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3417                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3418
3419   // get geom FACEs the node lies on
3420   //if ( useGeometry )
3421   {
3422     set<TGeomID> faceIds;
3423     if  ( eos.ShapeType() == TopAbs_FACE )
3424     {
3425       faceIds.insert( eos._shapeID );
3426     }
3427     else
3428     {
3429       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3430       while ( fIt->more() )
3431         faceIds.insert( fIt->next()->getshapeId() );
3432     }
3433     set<TGeomID>::iterator id = faceIds.begin();
3434     for ( ; id != faceIds.end(); ++id )
3435     {
3436       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3437       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3438         continue;
3439       F = TopoDS::Face( s );
3440       face2Norm[ totalNbFaces ].first = F;
3441       totalNbFaces++;
3442     }
3443   }
3444
3445   // find _normal
3446   bool fromVonF = false;
3447   if ( useGeometry )
3448   {
3449     fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3450                  eos.SWOLType()  == TopAbs_FACE  &&
3451                  totalNbFaces > 1 );
3452
3453     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3454     {
3455       if ( eos.SWOLType() == TopAbs_EDGE )
3456       {
3457         // inflate from VERTEX along EDGE
3458         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3459       }
3460       else if ( eos.ShapeType() == TopAbs_VERTEX )
3461       {
3462         // inflate from VERTEX along FACE
3463         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3464                                    node, helper, normOK, &edge._cosin);
3465       }
3466       else
3467       {
3468         // inflate from EDGE along FACE
3469         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3470                                    node, helper, normOK);
3471       }
3472     }
3473     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3474     {
3475       if ( fromVonF )
3476         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3477
3478       int nbOkNorms = 0;
3479       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3480       {
3481         F = face2Norm[ iF ].first;
3482         geomNorm = getFaceNormal( node, F, helper, normOK );
3483         if ( !normOK ) continue;
3484         nbOkNorms++;
3485
3486         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3487           geomNorm.Reverse();
3488         face2Norm[ iF ].second = geomNorm.XYZ();
3489         edge._normal += geomNorm.XYZ();
3490       }
3491       if ( nbOkNorms == 0 )
3492         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3493
3494       if ( totalNbFaces >= 3 )
3495       {
3496         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3497       }
3498
3499       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3500       {
3501         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3502         edge._normal.SetCoord( 0,0,0 );
3503         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3504         {
3505           const TopoDS_Face& F = face2Norm[iF].first;
3506           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3507           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3508             geomNorm.Reverse();
3509           if ( normOK )
3510             face2Norm[ iF ].second = geomNorm.XYZ();
3511           edge._normal += face2Norm[ iF ].second;
3512         }
3513       }
3514     }
3515   }
3516   else // !useGeometry - get _normal using surrounding mesh faces
3517   {
3518     edge._normal = getWeigthedNormal( &edge );
3519
3520     // set<TGeomID> faceIds;
3521     //
3522     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3523     // while ( fIt->more() )
3524     // {
3525     //   const SMDS_MeshElement* face = fIt->next();
3526     //   if ( eos.GetNormal( face, geomNorm ))
3527     //   {
3528     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3529     //       continue; // use only one mesh face on FACE
3530     //     edge._normal += geomNorm.XYZ();
3531     //     totalNbFaces++;
3532     //   }
3533     // }
3534   }
3535
3536   // compute _cosin
3537   //if ( eos._hyp.UseSurfaceNormal() )
3538   {
3539     switch ( eos.ShapeType() )
3540     {
3541     case TopAbs_FACE: {
3542       edge._cosin = 0;
3543       break;
3544     }
3545     case TopAbs_EDGE: {
3546       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3547       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3548       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3549       edge._cosin      = Cos( angle );
3550       break;
3551     }
3552     case TopAbs_VERTEX: {
3553       if ( fromVonF )
3554       {
3555         getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3556                     node, helper, normOK, &edge._cosin );
3557       }
3558       else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3559       {
3560         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3561         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3562         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3563         edge._cosin      = Cos( angle );
3564         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3565           for ( int iF = 1; iF < totalNbFaces; ++iF )
3566           {
3567             F = face2Norm[ iF ].first;
3568             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3569             if ( normOK ) {
3570               double angle = inFaceDir.Angle( edge._normal );
3571               double cosin = Cos( angle );
3572               if ( Abs( cosin ) > Abs( edge._cosin ))
3573                 edge._cosin = cosin;
3574             }
3575           }
3576       }
3577       break;
3578     }
3579     default:
3580       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3581     }
3582   }
3583
3584   double normSize = edge._normal.SquareModulus();
3585   if ( normSize < numeric_limits<double>::min() )
3586     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3587
3588   edge._normal /= sqrt( normSize );
3589
3590   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3591   {
3592     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3593     edge._nodes.resize( 1 );
3594     edge._normal.SetCoord( 0,0,0 );
3595     edge.SetMaxLen( 0 );
3596   }
3597
3598   // Set the rest data
3599   // --------------------
3600
3601   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3602
3603   if ( onShrinkShape )
3604   {
3605     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3606     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3607       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3608
3609     // set initial position which is parameters on _sWOL in this case
3610     if ( eos.SWOLType() == TopAbs_EDGE )
3611     {
3612       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3613       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3614       if ( edge._nodes.size() > 1 )
3615         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3616     }
3617     else // eos.SWOLType() == TopAbs_FACE
3618     {
3619       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3620       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3621       if ( edge._nodes.size() > 1 )
3622         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3623     }
3624
3625     if ( edge._nodes.size() > 1 )
3626     {
3627       // check if an angle between a FACE with layers and SWOL is sharp,
3628       // else the edge should not inflate
3629       F.Nullify();
3630       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3631         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3632           F = face2Norm[iF].first;
3633       if ( !F.IsNull())
3634       {
3635         geomNorm = getFaceNormal( node, F, helper, normOK );
3636         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3637           geomNorm.Reverse(); // inside the SOLID
3638         if ( geomNorm * edge._normal < -0.001 )
3639         {
3640           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3641           edge._nodes.resize( 1 );
3642         }
3643         else if ( edge._lenFactor > 3 )
3644         {
3645           edge._lenFactor = 2;
3646           edge.Set( _LayerEdge::RISKY_SWOL );
3647         }
3648       }
3649     }
3650   }
3651   else
3652   {
3653     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3654
3655     if ( eos.ShapeType() == TopAbs_FACE )
3656     {
3657       double angle;
3658       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3659       {
3660         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3661         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3662       }
3663     }
3664   }
3665
3666   // Set neighbor nodes for a _LayerEdge based on EDGE
3667
3668   if ( eos.ShapeType() == TopAbs_EDGE /*||
3669        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3670   {
3671     edge._2neibors = new _2NearEdges;
3672     // target nodes instead of source ones will be set later
3673   }
3674
3675   return true;
3676 }
3677
3678 //================================================================================
3679 /*!
3680  * \brief Return normal to a FACE at a node
3681  *  \param [in] n - node
3682  *  \param [in] face - FACE
3683  *  \param [in] helper - helper
3684  *  \param [out] isOK - true or false
3685  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3686  *  \return gp_XYZ - normal
3687  */
3688 //================================================================================
3689
3690 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3691                                       const TopoDS_Face&   face,
3692                                       SMESH_MesherHelper&  helper,
3693                                       bool&                isOK,
3694                                       bool                 shiftInside)
3695 {
3696   gp_XY uv;
3697   if ( shiftInside )
3698   {
3699     // get a shifted position
3700     gp_Pnt p = SMESH_TNodeXYZ( node );
3701     gp_XYZ shift( 0,0,0 );
3702     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3703     switch ( S.ShapeType() ) {
3704     case TopAbs_VERTEX:
3705     {
3706       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3707       break;
3708     }
3709     case TopAbs_EDGE:
3710     {
3711       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3712       break;
3713     }
3714     default:
3715       isOK = false;
3716     }
3717     if ( isOK )
3718       shift.Normalize();
3719     p.Translate( shift * 1e-5 );
3720
3721     TopLoc_Location loc;
3722     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3723
3724     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3725     
3726     projector.Perform( p );
3727     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3728     {
3729       isOK = false;
3730       return p.XYZ();
3731     }
3732     Standard_Real U,V;
3733     projector.LowerDistanceParameters(U,V);
3734     uv.SetCoord( U,V );
3735   }
3736   else
3737   {
3738     uv = helper.GetNodeUV( face, node, 0, &isOK );
3739   }
3740
3741   gp_Dir normal;
3742   isOK = false;
3743
3744   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3745
3746   if ( !shiftInside &&
3747        helper.IsDegenShape( node->getshapeId() ) &&
3748        getFaceNormalAtSingularity( uv, face, helper, normal ))
3749   {
3750     isOK = true;
3751     return normal.XYZ();
3752   }
3753
3754   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3755   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3756
3757   if ( pointKind == IMPOSSIBLE &&
3758        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3759   {
3760     // probably NormEstim() failed due to a too high tolerance
3761     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3762     isOK = ( pointKind < IMPOSSIBLE );
3763   }
3764   if ( pointKind < IMPOSSIBLE )
3765   {
3766     if ( pointKind != REGULAR &&
3767          !shiftInside &&
3768          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3769     {
3770       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3771       if ( normShift * normal.XYZ() < 0. )
3772         normal = normShift;
3773     }
3774     isOK = true;
3775   }
3776
3777   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3778   {
3779     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3780
3781     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3782     while ( fIt->more() )
3783     {
3784       const SMDS_MeshElement* f = fIt->next();
3785       if ( f->getshapeId() == faceID )
3786       {
3787         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3788         if ( isOK )
3789         {
3790           TopoDS_Face ff = face;
3791           ff.Orientation( TopAbs_FORWARD );
3792           if ( helper.IsReversedSubMesh( ff ))
3793             normal.Reverse();
3794           break;
3795         }
3796       }
3797     }
3798   }
3799   return normal.XYZ();
3800 }
3801
3802 //================================================================================
3803 /*!
3804  * \brief Try to get normal at a singularity of a surface basing on it's nature
3805  */
3806 //================================================================================
3807
3808 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3809                                                   const TopoDS_Face&  face,
3810                                                   SMESH_MesherHelper& helper,
3811                                                   gp_Dir&             normal )
3812 {
3813   BRepAdaptor_Surface surface( face );
3814   gp_Dir axis;
3815   if ( !getRovolutionAxis( surface, axis ))
3816     return false;
3817
3818   double f,l, d, du, dv;
3819   f = surface.FirstUParameter();
3820   l = surface.LastUParameter();
3821   d = ( uv.X() - f ) / ( l - f );
3822   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3823   f = surface.FirstVParameter();
3824   l = surface.LastVParameter();
3825   d = ( uv.Y() - f ) / ( l - f );
3826   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3827
3828   gp_Dir refDir;
3829   gp_Pnt2d testUV = uv;
3830   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3831   double tol = 1e-5;
3832   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3833   for ( int iLoop = 0; true ; ++iLoop )
3834   {
3835     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3836     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3837       break;
3838     if ( iLoop > 20 )
3839       return false;
3840     tol /= 10.;
3841   }
3842
3843   if ( axis * refDir < 0. )
3844     axis.Reverse();
3845
3846   normal = axis;
3847
3848   return true;
3849 }
3850
3851 //================================================================================
3852 /*!
3853  * \brief Return a normal at a node weighted with angles taken by faces
3854  */
3855 //================================================================================
3856
3857 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3858 {
3859   const SMDS_MeshNode* n = edge->_nodes[0];
3860
3861   gp_XYZ resNorm(0,0,0);
3862   SMESH_TNodeXYZ p0( n ), pP, pN;
3863   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3864   {
3865     pP.Set( edge->_simplices[i]._nPrev );
3866     pN.Set( edge->_simplices[i]._nNext );
3867     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3868     double l0P = v0P.SquareMagnitude();
3869     double l0N = v0N.SquareMagnitude();
3870     double lPN = vPN.SquareMagnitude();
3871     if ( l0P < std::numeric_limits<double>::min() ||
3872          l0N < std::numeric_limits<double>::min() ||
3873          lPN < std::numeric_limits<double>::min() )
3874       continue;
3875     double lNorm = norm.SquareMagnitude();
3876     double  sin2 = lNorm / l0P / l0N;
3877     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3878
3879     double weight = sin2 * angle / lPN;
3880     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3881   }
3882
3883   return resNorm;
3884 }
3885
3886 //================================================================================
3887 /*!
3888  * \brief Return a normal at a node by getting a common point of offset planes
3889  *        defined by the FACE normals
3890  */
3891 //================================================================================
3892
3893 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3894                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3895                                            int                              nbFaces,
3896                                            bool                             lastNoOffset)
3897 {
3898   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3899
3900   gp_XYZ resNorm(0,0,0);
3901   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3902   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3903   {
3904     for ( int i = 0; i < nbFaces; ++i )
3905       resNorm += f2Normal[i].second;
3906     return resNorm;
3907   }
3908
3909   // prepare _OffsetPlane's
3910   vector< _OffsetPlane > pln( nbFaces );
3911   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3912   {
3913     pln[i]._faceIndex = i;
3914     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3915   }
3916   if ( lastNoOffset )
3917   {
3918     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3919     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3920   }
3921
3922   // intersect neighboring OffsetPlane's
3923   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3924   while ( const TopoDS_Shape* edge = edgeIt->next() )
3925   {
3926     int f1 = -1, f2 = -1;
3927     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3928       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3929         (( f1 < 0 ) ? f1 : f2 ) = i;
3930
3931     if ( f2 >= 0 )
3932       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3933   }
3934
3935   // get a common point
3936   gp_XYZ commonPnt( 0, 0, 0 );
3937   int nbPoints = 0;
3938   bool isPointFound;
3939   for ( int i = 0; i < nbFaces; ++i )
3940   {
3941     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3942     nbPoints  += isPointFound;
3943   }
3944   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3945   if ( nbPoints == 0 )
3946     return wgtNorm;
3947
3948   commonPnt /= nbPoints;
3949   resNorm = commonPnt - p0;
3950   if ( lastNoOffset )
3951     return resNorm;
3952
3953   // choose the best among resNorm and wgtNorm
3954   resNorm.Normalize();
3955   wgtNorm.Normalize();
3956   double resMinDot = std::numeric_limits<double>::max();
3957   double wgtMinDot = std::numeric_limits<double>::max();
3958   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3959   {
3960     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3961     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3962   }
3963
3964   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3965   {
3966     edge->Set( _LayerEdge::MULTI_NORMAL );
3967   }
3968
3969   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3970 }
3971
3972 //================================================================================
3973 /*!
3974  * \brief Compute line of intersection of 2 planes
3975  */
3976 //================================================================================
3977
3978 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3979                                             const TopoDS_Edge&   E,
3980                                             const TopoDS_Vertex& V )
3981 {
3982   int iNext = bool( _faceIndexNext[0] >= 0 );
3983   _faceIndexNext[ iNext ] = pln._faceIndex;
3984
3985   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3986   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3987
3988   gp_XYZ lineDir = n1 ^ n2;
3989
3990   double x = Abs( lineDir.X() );
3991   double y = Abs( lineDir.Y() );
3992   double z = Abs( lineDir.Z() );
3993
3994   int cooMax; // max coordinate
3995   if (x > y) {
3996     if (x > z) cooMax = 1;
3997     else       cooMax = 3;
3998   }
3999   else {
4000     if (y > z) cooMax = 2;
4001     else       cooMax = 3;
4002   }
4003
4004   gp_Pnt linePos;
4005   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4006   {
4007     // parallel planes - intersection is an offset of the common EDGE
4008     gp_Pnt p = BRep_Tool::Pnt( V );
4009     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4010     lineDir  = getEdgeDir( E, V );
4011   }
4012   else
4013   {
4014     // the constants in the 2 plane equations
4015     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
4016     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4017
4018     switch ( cooMax ) {
4019     case 1:
4020       linePos.SetX(  0 );
4021       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4022       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4023       break;
4024     case 2:
4025       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4026       linePos.SetY(  0 );
4027       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4028       break;
4029     case 3:
4030       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4031       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4032       linePos.SetZ(  0 );
4033     }
4034   }
4035   gp_Lin& line = _lines[ iNext ];
4036   line.SetDirection( lineDir );
4037   line.SetLocation ( linePos );
4038
4039   _isLineOK[ iNext ] = true;
4040
4041
4042   iNext = bool( pln._faceIndexNext[0] >= 0 );
4043   pln._lines        [ iNext ] = line;
4044   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4045   pln._isLineOK     [ iNext ] = true;
4046 }
4047
4048 //================================================================================
4049 /*!
4050  * \brief Computes intersection point of two _lines
4051  */
4052 //================================================================================
4053
4054 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4055                                     const TopoDS_Vertex & V) const
4056 {
4057   gp_XYZ p( 0,0,0 );
4058   isFound = false;
4059
4060   if ( NbLines() == 2 )
4061   {
4062     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4063     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4064     if ( Abs( dot01 ) > 0.05 )
4065     {
4066       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4067       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4068       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4069       isFound = true;
4070     }
4071     else
4072     {
4073       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4074       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4075       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4076       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4077       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4078       isFound = true;
4079     }
4080   }
4081
4082   return p;
4083 }
4084
4085 //================================================================================
4086 /*!
4087  * \brief Find 2 neigbor nodes of a node on EDGE
4088  */
4089 //================================================================================
4090
4091 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4092                                         const SMDS_MeshNode*& n1,
4093                                         const SMDS_MeshNode*& n2,
4094                                         _EdgesOnShape&        eos,
4095                                         _SolidData&           data)
4096 {
4097   const SMDS_MeshNode* node = edge->_nodes[0];
4098   const int        shapeInd = eos._shapeID;
4099   SMESHDS_SubMesh*   edgeSM = 0;
4100   if ( eos.ShapeType() == TopAbs_EDGE )
4101   {
4102     edgeSM = eos._subMesh->GetSubMeshDS();
4103     if ( !edgeSM || edgeSM->NbElements() == 0 )
4104       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4105   }
4106   int iN = 0;
4107   n2 = 0;
4108   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4109   while ( eIt->more() && !n2 )
4110   {
4111     const SMDS_MeshElement* e = eIt->next();
4112     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4113     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4114     if ( edgeSM )
4115     {
4116       if (!edgeSM->Contains(e)) continue;
4117     }
4118     else
4119     {
4120       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4121       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4122     }
4123     ( iN++ ? n2 : n1 ) = nNeibor;
4124   }
4125   if ( !n2 )
4126     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4127   return true;
4128 }
4129
4130 //================================================================================
4131 /*!
4132  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4133  */
4134 //================================================================================
4135
4136 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4137                                      const SMDS_MeshNode* n2,
4138                                      const _EdgesOnShape& eos,
4139                                      SMESH_MesherHelper&  helper)
4140 {
4141   if ( eos.ShapeType() != TopAbs_EDGE )
4142     return;
4143   if ( _curvature && Is( SMOOTHED_C1 ))
4144     return;
4145
4146   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4147   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4148   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4149
4150   // Set _curvature
4151
4152   double      sumLen = vec1.Modulus() + vec2.Modulus();
4153   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4154   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4155   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4156   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4157   if ( _curvature ) delete _curvature;
4158   _curvature = _Curvature::New( avgNormProj, avgLen );
4159   // if ( _curvature )
4160   //   debugMsg( _nodes[0]->GetID()
4161   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4162   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4163   //             << _curvature->lenDelta(0) );
4164
4165   // Set _plnNorm
4166
4167   if ( eos._sWOL.IsNull() )
4168   {
4169     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4170     // if ( SMESH_Algo::isDegenerated( E ))
4171     //   return;
4172     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4173     gp_XYZ plnNorm = dirE ^ _normal;
4174     double proj0   = plnNorm * vec1;
4175     double proj1   = plnNorm * vec2;
4176     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4177     {
4178       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4179       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4180     }
4181   }
4182 }
4183
4184 //================================================================================
4185 /*!
4186  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4187  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4188  */
4189 //================================================================================
4190
4191 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4192                          _EdgesOnShape&      eos,
4193                          SMESH_MesherHelper& helper )
4194 {
4195   _nodes     = other._nodes;
4196   _normal    = other._normal;
4197   _len       = 0;
4198   _lenFactor = other._lenFactor;
4199   _cosin     = other._cosin;
4200   _2neibors  = other._2neibors;
4201   _curvature = 0; std::swap( _curvature, other._curvature );
4202   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4203
4204   gp_XYZ lastPos( 0,0,0 );
4205   if ( eos.SWOLType() == TopAbs_EDGE )
4206   {
4207     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4208     _pos.push_back( gp_XYZ( u, 0, 0));
4209
4210     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4211     lastPos.SetX( u );
4212   }
4213   else // TopAbs_FACE
4214   {
4215     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4216     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4217
4218     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4219     lastPos.SetX( uv.X() );
4220     lastPos.SetY( uv.Y() );
4221   }
4222   return lastPos;
4223 }
4224
4225 //================================================================================
4226 /*!
4227  * \brief Set _cosin and _lenFactor
4228  */
4229 //================================================================================
4230
4231 void _LayerEdge::SetCosin( double cosin )
4232 {
4233   _cosin = cosin;
4234   cosin = Abs( _cosin );
4235   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4236   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4237 }
4238
4239 //================================================================================
4240 /*!
4241  * \brief Check if another _LayerEdge is a neighbor on EDGE
4242  */
4243 //================================================================================
4244
4245 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4246 {
4247   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4248           ( edge->_2neibors && edge->_2neibors->include( this )));
4249 }
4250
4251 //================================================================================
4252 /*!
4253  * \brief Fills a vector<_Simplex > 
4254  */
4255 //================================================================================
4256
4257 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4258                              vector<_Simplex>&    simplices,
4259                              const set<TGeomID>&  ingnoreShapes,
4260                              const _SolidData*    dataToCheckOri,
4261                              const bool           toSort)
4262 {
4263   simplices.clear();
4264   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4265   while ( fIt->more() )
4266   {
4267     const SMDS_MeshElement* f = fIt->next();
4268     const TGeomID    shapeInd = f->getshapeId();
4269     if ( ingnoreShapes.count( shapeInd )) continue;
4270     const int nbNodes = f->NbCornerNodes();
4271     const int  srcInd = f->GetNodeIndex( node );
4272     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4273     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4274     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4275     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4276       std::swap( nPrev, nNext );
4277     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4278   }
4279
4280   if ( toSort )
4281     SortSimplices( simplices );
4282 }
4283
4284 //================================================================================
4285 /*!
4286  * \brief Set neighbor simplices side by side
4287  */
4288 //================================================================================
4289
4290 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4291 {
4292   vector<_Simplex> sortedSimplices( simplices.size() );
4293   sortedSimplices[0] = simplices[0];
4294   size_t nbFound = 0;
4295   for ( size_t i = 1; i < simplices.size(); ++i )
4296   {
4297     for ( size_t j = 1; j < simplices.size(); ++j )
4298       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4299       {
4300         sortedSimplices[i] = simplices[j];
4301         nbFound++;
4302         break;
4303       }
4304   }
4305   if ( nbFound == simplices.size() - 1 )
4306     simplices.swap( sortedSimplices );
4307 }
4308
4309 //================================================================================
4310 /*!
4311  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4312  */
4313 //================================================================================
4314
4315 void _ViscousBuilder::makeGroupOfLE()
4316 {
4317 #ifdef _DEBUG_
4318   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4319   {
4320     if ( _sdVec[i]._n2eMap.empty() ) continue;
4321
4322     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4323     TNode2Edge::iterator n2e;
4324     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4325     {
4326       _LayerEdge* le = n2e->second;
4327       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4328       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4329       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4330       if ( le ) {
4331         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4332                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4333       }
4334     }
4335     dumpFunctionEnd();
4336
4337     dumpFunction( SMESH_Comment("makeNormals") << i );
4338     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4339     {
4340       _LayerEdge* edge = n2e->second;
4341       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4342       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4343       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4344               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4345     }
4346     dumpFunctionEnd();
4347
4348     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4349     dumpCmd( "faceId1 = mesh.NbElements()" );
4350     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4351     for ( ; fExp.More(); fExp.Next() )
4352     {
4353       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4354       {
4355         if ( sm->NbElements() == 0 ) continue;
4356         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4357         while ( fIt->more())
4358         {
4359           const SMDS_MeshElement* e = fIt->next();
4360           SMESH_Comment cmd("mesh.AddFace([");
4361           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4362             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4363           dumpCmd( cmd );
4364         }
4365       }
4366     }
4367     dumpCmd( "faceId2 = mesh.NbElements()" );
4368     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4369              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4370              << "'%s-%s' % (faceId1+1, faceId2))");
4371     dumpFunctionEnd();
4372   }
4373 #endif
4374 }
4375
4376 //================================================================================
4377 /*!
4378  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4379  */
4380 //================================================================================
4381
4382 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4383 {
4384   data._geomSize = Precision::Infinite();
4385   double intersecDist;
4386   const SMDS_MeshElement* face;
4387   SMESH_MesherHelper helper( *_mesh );
4388
4389   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4390     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4391                                            data._proxyMesh->GetFaces( data._solid )));
4392
4393   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4394   {
4395     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4396     if ( eos._edges.empty() )
4397       continue;
4398     // get neighbor faces, intersection with which should not be considered since
4399     // collisions are avoided by means of smoothing
4400     set< TGeomID > neighborFaces;
4401     if ( eos._hyp.ToSmooth() )
4402     {
4403       SMESH_subMeshIteratorPtr subIt =
4404         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4405       while ( subIt->more() )
4406       {
4407         SMESH_subMesh* sm = subIt->next();
4408         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4409         while ( const TopoDS_Shape* face = fIt->next() )
4410           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4411       }
4412     }
4413     // find intersections
4414     double thinkness = eos._hyp.GetTotalThickness();
4415     for ( size_t i = 0; i < eos._edges.size(); ++i )
4416     {
4417       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4418       eos._edges[i]->SetMaxLen( thinkness );
4419       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4420       if ( intersecDist > 0 && face )
4421       {
4422         data._geomSize = Min( data._geomSize, intersecDist );
4423         if ( !neighborFaces.count( face->getshapeId() ))
4424           eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4425       }
4426     }
4427   }
4428
4429   data._maxThickness = 0;
4430   data._minThickness = 1e100;
4431   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4432   for ( ; hyp != data._hyps.end(); ++hyp )
4433   {
4434     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4435     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4436   }
4437
4438   // Limit inflation step size by geometry size found by intersecting
4439   // normals of _LayerEdge's with mesh faces
4440   if ( data._stepSize > 0.3 * data._geomSize )
4441     limitStepSize( data, 0.3 * data._geomSize );
4442
4443   if ( data._stepSize > data._minThickness )
4444     limitStepSize( data, data._minThickness );
4445
4446
4447   // -------------------------------------------------------------------------
4448   // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4449   // so no need in detecting intersection at each inflation step
4450   // -------------------------------------------------------------------------
4451
4452   int nbSteps = data._maxThickness / data._stepSize;
4453   if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4454     return;
4455
4456   vector< const SMDS_MeshElement* > closeFaces;
4457   int nbDetected = 0;
4458
4459   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4460   {
4461     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4462     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4463       continue;
4464
4465     for ( size_t i = 0; i < eos.size(); ++i )
4466     {
4467       SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4468       double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4469       closeFaces.clear();
4470       searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4471
4472       bool toIgnore = true;
4473       for ( size_t iF = 0; iF < closeFaces.size()  && toIgnore; ++iF )
4474         if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4475                              data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4476         {
4477           // check if a _LayerEdge will inflate in a direction opposite to a direction
4478           // toward a close face
4479           bool allBehind = true;
4480           for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes()  && allBehind; ++iN )
4481           {
4482             SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4483             allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4484           }
4485           toIgnore = allBehind;
4486         }
4487
4488
4489       if ( toIgnore ) // no need to detect intersection
4490       {
4491         eos[i]->Set( _LayerEdge::INTERSECTED );
4492         ++nbDetected;
4493       }
4494     }
4495   }
4496
4497   debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4498
4499   return;
4500 }
4501
4502 //================================================================================
4503 /*!
4504  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4505  */
4506 //================================================================================
4507
4508 bool _ViscousBuilder::inflate(_SolidData& data)
4509 {
4510   SMESH_MesherHelper helper( *_mesh );
4511
4512   const double tgtThick = data._maxThickness;
4513
4514   if ( data._stepSize < 1. )
4515     data._epsilon = data._stepSize * 1e-7;
4516
4517   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4518   _pyDump->Pause();
4519
4520   findCollisionEdges( data, helper );
4521
4522   limitMaxLenByCurvature( data, helper );
4523
4524   _pyDump->Resume();
4525
4526   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4527   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4528     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4529          data._edgesOnShape[i]._edges.size() > 0 &&
4530          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4531     {
4532       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4533       data._edgesOnShape[i]._edges[0]->Block( data );
4534     }
4535
4536   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4537
4538   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4539   int nbSteps = 0, nbRepeats = 0;
4540   while ( avgThick < 0.99 )
4541   {
4542     // new target length
4543     double prevThick = curThick;
4544     curThick += data._stepSize;
4545     if ( curThick > tgtThick )
4546     {
4547       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4548       nbRepeats++;
4549     }
4550
4551     double stepSize = curThick - prevThick;
4552     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4553
4554     // Elongate _LayerEdge's
4555     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4556     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4557     {
4558       _EdgesOnShape& eos = data._edgesOnShape[iS];
4559       if ( eos._edges.empty() ) continue;
4560
4561       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4562       for ( size_t i = 0; i < eos._edges.size(); ++i )
4563       {
4564         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4565       }
4566     }
4567     dumpFunctionEnd();
4568
4569     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4570       return false;
4571
4572     // Improve and check quality
4573     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4574     {
4575       if ( nbSteps > 0 )
4576       {
4577 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4578         debugMsg("NOT INVALIDATED STEP!");
4579         return error("Smoothing failed", data._index);
4580 #endif
4581         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4582         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4583         {
4584           _EdgesOnShape& eos = data._edgesOnShape[iS];
4585           for ( size_t i = 0; i < eos._edges.size(); ++i )
4586             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4587         }
4588         dumpFunctionEnd();
4589       }
4590       break; // no more inflating possible
4591     }
4592     nbSteps++;
4593
4594     // Evaluate achieved thickness
4595     avgThick = 0;
4596     int nbActiveEdges = 0;
4597     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4598     {
4599       _EdgesOnShape& eos = data._edgesOnShape[iS];
4600       if ( eos._edges.empty() ) continue;
4601
4602       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4603       for ( size_t i = 0; i < eos._edges.size(); ++i )
4604       {
4605         if ( eos._edges[i]->_nodes.size() > 1 )
4606           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4607         else
4608           avgThick    += shapeTgtThick;
4609         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4610       }
4611     }
4612     avgThick /= data._n2eMap.size();
4613     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4614
4615 #ifdef BLOCK_INFLATION
4616     if ( nbActiveEdges == 0 )
4617     {
4618       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4619       break;
4620     }
4621 #else
4622     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4623     {
4624       debugMsg( "-- Stop inflation since "
4625                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4626                 << tgtThick * avgThick << " ) * " << safeFactor );
4627       break;
4628     }
4629 #endif
4630
4631     // new step size
4632     limitStepSize( data, 0.25 * distToIntersection );
4633     if ( data._stepSizeNodes[0] )
4634       data._stepSize = data._stepSizeCoeff *
4635         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4636
4637   } // while ( avgThick < 0.99 )
4638
4639   if ( nbSteps == 0 )
4640     return error("failed at the very first inflation step", data._index);
4641
4642   if ( avgThick < 0.99 )
4643   {
4644     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4645     {
4646       data._proxyMesh->_warning.reset
4647         ( new SMESH_ComputeError (COMPERR_WARNING,
4648                                   SMESH_Comment("Thickness ") << tgtThick <<
4649                                   " of viscous layers not reached,"
4650                                   " average reached thickness is " << avgThick*tgtThick));
4651     }
4652   }
4653
4654   // Restore position of src nodes moved by inflation on _noShrinkShapes
4655   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4656   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4657   {
4658     _EdgesOnShape& eos = data._edgesOnShape[iS];
4659     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4660       for ( size_t i = 0; i < eos._edges.size(); ++i )
4661       {
4662         restoreNoShrink( *eos._edges[ i ] );
4663       }
4664   }
4665   dumpFunctionEnd();
4666
4667   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4668 }
4669
4670 //================================================================================
4671 /*!
4672  * \brief Improve quality of layer inner surface and check intersection
4673  */
4674 //================================================================================
4675
4676 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4677                                      const int   infStep,
4678                                      double &    distToIntersection)
4679 {
4680   if ( data._nbShapesToSmooth == 0 )
4681     return true; // no shapes needing smoothing
4682
4683   bool moved, improved;
4684   double vol;
4685   vector< _LayerEdge* >    movedEdges, badEdges;
4686   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4687   vector< bool >           isConcaveFace;
4688
4689   SMESH_MesherHelper helper(*_mesh);
4690   Handle(ShapeAnalysis_Surface) surface;
4691   TopoDS_Face F;
4692
4693   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4694   {
4695     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4696
4697     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4698     {
4699       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4700       if ( !eos._toSmooth ||
4701            eos.ShapeType() != shapeType ||
4702            eos._edges.empty() )
4703         continue;
4704
4705       // already smoothed?
4706       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4707       // if ( !toSmooth ) continue;
4708
4709       if ( !eos._hyp.ToSmooth() )
4710       {
4711         // smooth disabled by the user; check validy only
4712         if ( !isFace ) continue;
4713         badEdges.clear();
4714         for ( size_t i = 0; i < eos._edges.size(); ++i )
4715         {
4716           _LayerEdge* edge = eos._edges[i];
4717           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4718             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4719             {
4720               // debugMsg( "-- Stop inflation. Bad simplex ("
4721               //           << " "<< edge->_nodes[0]->GetID()
4722               //           << " "<< edge->_nodes.back()->GetID()
4723               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4724               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4725               // return false;
4726               badEdges.push_back( edge );
4727             }
4728         }
4729         if ( !badEdges.empty() )
4730         {
4731           eosC1.resize(1);
4732           eosC1[0] = &eos;
4733           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4734           if ( nbBad > 0 )
4735             return false;
4736         }
4737         continue; // goto the next EDGE or FACE
4738       }
4739
4740       // prepare data
4741       if ( eos.SWOLType() == TopAbs_FACE )
4742       {
4743         if ( !F.IsSame( eos._sWOL )) {
4744           F = TopoDS::Face( eos._sWOL );
4745           helper.SetSubShape( F );
4746           surface = helper.GetSurface( F );
4747         }
4748       }
4749       else
4750       {
4751         F.Nullify(); surface.Nullify();
4752       }
4753       const TGeomID sInd = eos._shapeID;
4754
4755       // perform smoothing
4756
4757       if ( eos.ShapeType() == TopAbs_EDGE )
4758       {
4759         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4760
4761         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4762         {
4763           // smooth on EDGE's (normally we should not get here)
4764           int step = 0;
4765           do {
4766             moved = false;
4767             for ( size_t i = 0; i < eos._edges.size(); ++i )
4768             {
4769               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4770             }
4771             dumpCmd( SMESH_Comment("# end step ")<<step);
4772           }
4773           while ( moved && step++ < 5 );
4774         }
4775         dumpFunctionEnd();
4776       }
4777
4778       else // smooth on FACE
4779       {
4780         eosC1.clear();
4781         eosC1.push_back( & eos );
4782         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4783
4784         movedEdges.clear();
4785         isConcaveFace.resize( eosC1.size() );
4786         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4787         {
4788           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4789           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4790           for ( size_t i = 0; i < edges.size(); ++i )
4791             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4792                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4793               movedEdges.push_back( edges[i] );
4794
4795           makeOffsetSurface( *eosC1[ iEOS ], helper );
4796         }
4797
4798         int step = 0, stepLimit = 5, nbBad = 0;
4799         while (( ++step <= stepLimit ) || improved )
4800         {
4801           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4802                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4803           int oldBadNb = nbBad;
4804           badEdges.clear();
4805
4806 #ifdef INCREMENTAL_SMOOTH
4807           bool findBest = false; // ( step == stepLimit );
4808           for ( size_t i = 0; i < movedEdges.size(); ++i )
4809           {
4810             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4811             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4812               badEdges.push_back( movedEdges[i] );
4813           }
4814 #else
4815           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4816           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4817           {
4818             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4819             for ( size_t i = 0; i < edges.size(); ++i )
4820             {
4821               edges[i]->Unset( _LayerEdge::SMOOTHED );
4822               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4823                 badEdges.push_back( eos._edges[i] );
4824             }
4825           }
4826 #endif
4827           nbBad = badEdges.size();
4828
4829           if ( nbBad > 0 )
4830             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4831
4832           if ( !badEdges.empty() && step >= stepLimit / 2 )
4833           {
4834             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4835               stepLimit = 9;
4836
4837             // resolve hard smoothing situation around concave VERTEXes
4838             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4839             {
4840               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4841               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4842                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4843                                                          step, badEdges );
4844             }
4845             // look for the best smooth of _LayerEdge's neighboring badEdges
4846             nbBad = 0;
4847             for ( size_t i = 0; i < badEdges.size(); ++i )
4848             {
4849               _LayerEdge* ledge = badEdges[i];
4850               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4851               {
4852                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4853                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4854               }
4855               ledge->Unset( _LayerEdge::SMOOTHED );
4856               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4857             }
4858             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4859           }
4860
4861           if ( nbBad == oldBadNb  &&
4862                nbBad > 0 &&
4863                step < stepLimit ) // smooth w/o chech of validity
4864           {
4865             dumpFunctionEnd();
4866             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4867                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4868             for ( size_t i = 0; i < movedEdges.size(); ++i )
4869             {
4870               movedEdges[i]->SmoothWoCheck();
4871             }
4872             if ( stepLimit < 9 )
4873               stepLimit++;
4874           }
4875
4876           improved = ( nbBad < oldBadNb );
4877
4878           dumpFunctionEnd();
4879
4880           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4881             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4882             {
4883               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4884             }
4885
4886         } // smoothing steps
4887
4888         // project -- to prevent intersections or fix bad simplices
4889         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4890         {
4891           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4892             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4893         }
4894
4895         //if ( !badEdges.empty() )
4896         {
4897           badEdges.clear();
4898           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4899           {
4900             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4901             {
4902               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4903
4904               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4905               edge->CheckNeiborsOnBoundary( & badEdges );
4906               if (( nbBad > 0 ) ||
4907                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4908               {
4909                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4910                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4911                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4912                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4913                   {
4914                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4915                              << " "<< tgtXYZ._node->GetID()
4916                              << " "<< edge->_simplices[j]._nPrev->GetID()
4917                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4918                     badEdges.push_back( edge );
4919                     break;
4920                   }
4921               }
4922             }
4923           }
4924
4925           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4926           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4927
4928           if ( nbBad > 0 )
4929             return false;
4930         }
4931
4932       } // // smooth on FACE's
4933     } // loop on shapes
4934   } // smooth on [ EDGEs, FACEs ]
4935
4936   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4937   eosC1.resize(1);
4938   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4939   {
4940     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4941     if ( eos.ShapeType() == TopAbs_FACE ||
4942          eos._edges.empty() ||
4943          !eos._sWOL.IsNull() )
4944       continue;
4945
4946     badEdges.clear();
4947     for ( size_t i = 0; i < eos._edges.size(); ++i )
4948     {
4949       _LayerEdge*      edge = eos._edges[i];
4950       if ( edge->_nodes.size() < 2 ) continue;
4951       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4952       //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
4953       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4954       //const gp_XYZ& prevXYZ = edge->PrevPos();
4955       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4956         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4957         {
4958           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4959                    << " "<< tgtXYZ._node->GetID()
4960                    << " "<< edge->_simplices[j]._nPrev->GetID()
4961                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4962           badEdges.push_back( edge );
4963           break;
4964         }
4965     }
4966
4967     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4968     eosC1[0] = &eos;
4969     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4970     if ( nbBad > 0 )
4971       return false;
4972   }
4973
4974
4975   // Check if the last segments of _LayerEdge intersects 2D elements;
4976   // checked elements are either temporary faces or faces on surfaces w/o the layers
4977
4978   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4979     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4980                                            data._proxyMesh->GetFaces( data._solid )) );
4981
4982 #ifdef BLOCK_INFLATION
4983   const bool toBlockInfaltion = true;
4984 #else
4985   const bool toBlockInfaltion = false;
4986 #endif
4987   distToIntersection = Precision::Infinite();
4988   double dist;
4989   const SMDS_MeshElement* intFace = 0;
4990   const SMDS_MeshElement* closestFace = 0;
4991   _LayerEdge* le = 0;
4992   bool is1stBlocked = true; // dbg
4993   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4994   {
4995     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4996     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4997       continue;
4998     for ( size_t i = 0; i < eos._edges.size(); ++i )
4999     {
5000       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5001            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5002         continue;
5003       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5004       {
5005         return false;
5006         // commented due to "Illegal hash-positionPosition" error in NETGEN
5007         // on Debian60 on viscous_layers_01/B2 case
5008         // Collision; try to deflate _LayerEdge's causing it
5009         // badEdges.clear();
5010         // badEdges.push_back( eos._edges[i] );
5011         // eosC1[0] = & eos;
5012         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5013         // if ( nbBad > 0 )
5014         //   return false;
5015
5016         // badEdges.clear();
5017         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5018         // {
5019         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5020         //   {
5021         //     const SMDS_MeshElement* srcFace =
5022         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5023         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5024         //     while ( nIt->more() )
5025         //     {
5026         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5027         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5028         //       if ( n2e != data._n2eMap.end() )
5029         //         badEdges.push_back( n2e->second );
5030         //     }
5031         //     eosC1[0] = eof;
5032         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5033         //     if ( nbBad > 0 )
5034         //       return false;
5035         //   }
5036         // }
5037         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5038         //   return false;
5039         // else
5040         //   continue;
5041       }
5042       if ( !intFace )
5043       {
5044         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5045         debugMsg( msg );
5046         continue;
5047       }
5048
5049       const bool isShorterDist = ( distToIntersection > dist );
5050       if ( toBlockInfaltion || isShorterDist )
5051       {
5052         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5053         // lying on this _ConvexFace
5054         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5055           if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5056             continue;
5057
5058         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5059         // ( avoid limiting the thickness on the case of issue 22576)
5060         if ( intFace->getshapeId() == eos._shapeID  )
5061           continue;
5062
5063         // ignore intersection with intFace of an adjacent FACE
5064         if ( dist > 0.1 * eos._edges[i]->_len )
5065         {
5066           bool toIgnore = false;
5067           if (  eos._toSmooth )
5068           {
5069             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5070             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5071             {
5072               TopExp_Explorer sub( eos._shape,
5073                                    eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5074               for ( ; !toIgnore && sub.More(); sub.Next() )
5075                 // is adjacent - has a common EDGE or VERTEX
5076                 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5077
5078               if ( toIgnore ) // check angle between normals
5079               {
5080                 gp_XYZ normal;
5081                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5082                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
5083               }
5084             }
5085           }
5086           if ( !toIgnore ) // check if the edge is a neighbor of intFace
5087           {
5088             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
5089             {
5090               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5091               toIgnore = ( nInd >= 0 );
5092             }
5093           }
5094           if ( toIgnore )
5095             continue;
5096         }
5097
5098         // intersection not ignored
5099
5100         if ( toBlockInfaltion &&
5101              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5102         {
5103           if ( is1stBlocked ) { is1stBlocked = false; // debug
5104             dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5105           }
5106           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5107           eos._edges[i]->Block( data );                  // not to inflate
5108
5109           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5110           {
5111             // block _LayerEdge's, on top of which intFace is
5112             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5113             {
5114               const SMDS_MeshElement* srcFace =
5115                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5116               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5117               while ( nIt->more() )
5118               {
5119                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5120                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5121                 if ( n2e != data._n2eMap.end() )
5122                   n2e->second->Block( data );
5123               }
5124             }
5125           }
5126         }
5127
5128         if ( isShorterDist )
5129         {
5130           distToIntersection = dist;
5131           le = eos._edges[i];
5132           closestFace = intFace;
5133         }
5134
5135       } // if ( toBlockInfaltion || isShorterDist )
5136     } // loop on eos._edges
5137   } // loop on data._edgesOnShape
5138
5139   if ( !is1stBlocked )
5140     dumpFunctionEnd();
5141
5142   if ( closestFace && le )
5143   {
5144 #ifdef __myDEBUG
5145     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5146     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5147          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5148          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5149          << ") distance = " << distToIntersection<< endl;
5150 #endif
5151   }
5152
5153   return true;
5154 }
5155
5156 //================================================================================
5157 /*!
5158  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5159  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5160  *  \return int - resulting nb of bad _LayerEdge's
5161  */
5162 //================================================================================
5163
5164 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5165                                           SMESH_MesherHelper&       helper,
5166                                           vector< _LayerEdge* >&    badSmooEdges,
5167                                           vector< _EdgesOnShape* >& eosC1,
5168                                           const int                 infStep )
5169 {
5170   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5171
5172   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5173
5174   enum {
5175     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5176     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5177     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5178   };
5179   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5180
5181   double vol;
5182   bool haveInvalidated = true;
5183   while ( haveInvalidated )
5184   {
5185     haveInvalidated = false;
5186     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5187     {
5188       _LayerEdge*   edge = badSmooEdges[i];
5189       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5190       edge->Set( ADDED );
5191       bool invalidated = false;
5192       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5193       {
5194         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5195         edge->Block( data );
5196         edge->Set( INVALIDATED );
5197         edge->Unset( TO_INVALIDATE );
5198         invalidated = true;
5199         haveInvalidated = true;
5200       }
5201
5202       // look for _LayerEdge's of bad _simplices
5203       int nbBad = 0;
5204       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5205       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5206       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5207       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5208       {
5209         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5210             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5211           continue;
5212
5213         bool isBad = true;
5214         _LayerEdge* ee[2] = { 0,0 };
5215         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5216           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5217             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5218
5219         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5220         while ( maxNbSteps > edge->NbSteps() && isBad )
5221         {
5222           --maxNbSteps;
5223           for ( int iE = 0; iE < 2; ++iE )
5224           {
5225             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5226                  ee[ iE ]->NbSteps() > 1 )
5227             {
5228               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5229               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5230               ee[ iE ]->Block( data );
5231               ee[ iE ]->Set( INVALIDATED );
5232               haveInvalidated = true;
5233             }
5234           }
5235           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5236               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5237             isBad = false;
5238         }
5239         nbBad += isBad;
5240         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5241         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5242         ee[0]->Set( ADDED );
5243         ee[1]->Set( ADDED );
5244         if ( isBad )
5245         {
5246           ee[0]->Set( TO_INVALIDATE );
5247           ee[1]->Set( TO_INVALIDATE );
5248         }
5249       }
5250
5251       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5252       {
5253         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5254         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5255         edge->Block( data );
5256         edge->Set( INVALIDATED );
5257         edge->Unset( TO_INVALIDATE );
5258         haveInvalidated = true;
5259       }
5260     } // loop on badSmooEdges
5261   } // while ( haveInvalidated )
5262
5263   // re-smooth on analytical EDGEs
5264   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5265   {
5266     _LayerEdge* edge = badSmooEdges[i];
5267     if ( !edge->Is( INVALIDATED )) continue;
5268
5269     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5270     if ( eos->ShapeType() == TopAbs_VERTEX )
5271     {
5272       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5273       while ( const TopoDS_Shape* e = eIt->next() )
5274         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5275           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5276           {
5277             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5278             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5279             //   F       = TopoDS::Face( eoe->_sWOL );
5280             //   surface = helper.GetSurface( F );
5281             // }
5282             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5283             eoe->_edgeSmoother->_anaCurve.Nullify();
5284           }
5285     }
5286   }
5287
5288
5289   // check result of invalidation
5290
5291   int nbBad = 0;
5292   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5293   {
5294     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5295     {
5296       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5297       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5298       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5299       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5300       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5301         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5302         {
5303           ++nbBad;
5304           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5305                    << " "<< tgtXYZ._node->GetID()
5306                    << " "<< edge->_simplices[j]._nPrev->GetID()
5307                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5308         }
5309     }
5310   }
5311   dumpFunctionEnd();
5312
5313   return nbBad;
5314 }
5315
5316 //================================================================================
5317 /*!
5318  * \brief Create an offset surface
5319  */
5320 //================================================================================
5321
5322 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5323 {
5324   if ( eos._offsetSurf.IsNull() ||
5325        eos._edgeForOffset == 0 ||
5326        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5327     return;
5328
5329   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5330
5331   // find offset
5332   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5333   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5334   double offset = baseSurface->Gap();
5335
5336   eos._offsetSurf.Nullify();
5337
5338   try
5339   {
5340     BRepOffsetAPI_MakeOffsetShape offsetMaker;
5341     offsetMaker.PerformByJoin( eos._shape, -offset, Precision::Confusion() );
5342     if ( !offsetMaker.IsDone() ) return;
5343
5344     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5345     if ( !fExp.More() ) return;
5346
5347     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5348     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5349     if ( surf.IsNull() ) return;
5350
5351     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5352   }
5353   catch ( Standard_Failure )
5354   {
5355   }
5356 }
5357
5358 //================================================================================
5359 /*!
5360  * \brief Put nodes of a curved FACE to its offset surface
5361  */
5362 //================================================================================
5363
5364 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5365                                           int                       infStep,
5366                                           vector< _EdgesOnShape* >& eosC1,
5367                                           int                       smooStep,
5368                                           int                       moveAll )
5369 {
5370   _EdgesOnShape * eof = & eos;
5371   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5372   {
5373     eof = 0;
5374     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5375     {
5376       if ( eosC1[i]->_offsetSurf.IsNull() ||
5377            eosC1[i]->ShapeType() != TopAbs_FACE ||
5378            eosC1[i]->_edgeForOffset == 0 ||
5379            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5380         continue;
5381       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5382         eof = eosC1[i];
5383     }
5384   }
5385   if ( !eof ||
5386        eof->_offsetSurf.IsNull() ||
5387        eof->ShapeType() != TopAbs_FACE ||
5388        eof->_edgeForOffset == 0 ||
5389        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5390     return;
5391
5392   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5393   for ( size_t i = 0; i < eos._edges.size(); ++i )
5394   {
5395     _LayerEdge* edge = eos._edges[i];
5396     edge->Unset( _LayerEdge::MARKED );
5397     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5398       continue;
5399     if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5400     {
5401       if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5402         continue;
5403     }
5404     else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5405       continue;
5406
5407     int nbBlockedAround = 0;
5408     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5409       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5410     if ( nbBlockedAround > 1 )
5411       continue;
5412
5413     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5414     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5415     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5416     edge->_curvature->_uv = uv;
5417     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5418
5419     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5420     gp_XYZ prevP = edge->PrevCheckPos();
5421     bool      ok = true;
5422     if ( !moveAll )
5423       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5424       {
5425         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5426       }
5427     if ( ok )
5428     {
5429       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5430       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5431       edge->_pos.back() = newP;
5432
5433       edge->Set( _LayerEdge::MARKED );
5434       if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5435       {
5436         edge->_normal = ( newP - prevP ).Normalized();
5437       }
5438     }
5439   }
5440
5441
5442
5443 #ifdef _DEBUG_
5444   // dumpMove() for debug
5445   size_t i = 0;
5446   for ( ; i < eos._edges.size(); ++i )
5447     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5448       break;
5449   if ( i < eos._edges.size() )
5450   {
5451     dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5452                  << "_InfStep" << infStep << "_" << smooStep );
5453     for ( ; i < eos._edges.size(); ++i )
5454     {
5455       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5456         dumpMove( eos._edges[i]->_nodes.back() );
5457     }
5458     dumpFunctionEnd();
5459   }
5460 #endif
5461
5462   _ConvexFace* cnvFace;
5463   if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5464        eos.ShapeType() == TopAbs_FACE &&
5465        (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5466        !cnvFace->_normalsFixedOnBorders )
5467   {
5468     // put on the surface nodes built on FACE boundaries
5469     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5470     while ( smIt->more() )
5471     {
5472       SMESH_subMesh* sm = smIt->next();
5473       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5474       if ( !subEOS->_sWOL.IsNull() ) continue;
5475       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5476
5477       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5478     }
5479     cnvFace->_normalsFixedOnBorders = true;
5480   }
5481 }
5482
5483 //================================================================================
5484 /*!
5485  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5486  *        _LayerEdge's to be in a consequent order
5487  */
5488 //================================================================================
5489
5490 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5491                                                 _EdgesOnShape&      eos,
5492                                                 SMESH_MesherHelper& helper)
5493 {
5494   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5495
5496   TopLoc_Location loc; double f,l;
5497
5498   Handle(Geom_Line)   line;
5499   Handle(Geom_Circle) circle;
5500   bool isLine, isCirc;
5501   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5502   {
5503     // check if the EDGE is a line
5504     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5505     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5506       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5507
5508     line   = Handle(Geom_Line)::DownCast( curve );
5509     circle = Handle(Geom_Circle)::DownCast( curve );
5510     isLine = (!line.IsNull());
5511     isCirc = (!circle.IsNull());
5512
5513     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5514     {
5515       isLine = SMESH_Algo::IsStraight( E );
5516
5517       if ( isLine )
5518         line = new Geom_Line( gp::OX() ); // only type does matter
5519     }
5520     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5521     {
5522       // TODO
5523     }
5524   }
5525   else //////////////////////////////////////////////////////////////////////// 2D case
5526   {
5527     if ( !eos._isRegularSWOL ) // 23190
5528       return NULL;
5529
5530     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5531
5532     // check if the EDGE is a line
5533     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5534     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5535       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5536
5537     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5538     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5539     isLine = (!line2d.IsNull());
5540     isCirc = (!circle2d.IsNull());
5541
5542     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5543     {
5544       Bnd_B2d bndBox;
5545       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5546       while ( nIt->more() )
5547         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5548       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5549
5550       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5551       for ( int i = 0; i < 2 && !isLine; ++i )
5552         isLine = ( size.Coord( i+1 ) <= lineTol );
5553     }
5554     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5555     {
5556       // TODO
5557     }
5558     if ( isLine )
5559     {
5560       line = new Geom_Line( gp::OX() ); // only type does matter
5561     }
5562     else if ( isCirc )
5563     {
5564       gp_Pnt2d p = circle2d->Location();
5565       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5566       circle = new Geom_Circle( ax, 1.); // only center position does matter
5567     }
5568   }
5569
5570   if ( isLine )
5571     return line;
5572   if ( isCirc )
5573     return circle;
5574
5575   return Handle(Geom_Curve)();
5576 }
5577
5578 //================================================================================
5579 /*!
5580  * \brief Smooth edges on EDGE
5581  */
5582 //================================================================================
5583
5584 bool _Smoother1D::Perform(_SolidData&                    data,
5585                           Handle(ShapeAnalysis_Surface)& surface,
5586                           const TopoDS_Face&             F,
5587                           SMESH_MesherHelper&            helper )
5588 {
5589   if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5590     prepare( data );
5591
5592   findEdgesToSmooth();
5593   if ( isAnalytic() )
5594     return smoothAnalyticEdge( data, surface, F, helper );
5595   else
5596     return smoothComplexEdge ( data, surface, F, helper );
5597 }
5598
5599 //================================================================================
5600 /*!
5601  * \brief Find edges to smooth
5602  */
5603 //================================================================================
5604
5605 void _Smoother1D::findEdgesToSmooth()
5606 {
5607   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5608   for ( int iEnd = 0; iEnd < 2; ++iEnd )
5609     if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5610       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5611
5612   _eToSmooth[0].first = _eToSmooth[0].second = 0;
5613
5614   for ( size_t i = 0; i < _eos.size(); ++i )
5615   {
5616     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5617     {
5618       if ( needSmoothing( _leOnV[0]._cosin,
5619                           _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
5620            isToSmooth( i )
5621            )
5622         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5623       else
5624         break;
5625     }
5626     _eToSmooth[0].second = i+1;
5627   }
5628
5629   _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5630
5631   for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5632   {
5633     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5634     {
5635       if ( needSmoothing( _leOnV[1]._cosin,
5636                           _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
5637            isToSmooth( i ))
5638         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5639       else
5640         break;
5641     }
5642     _eToSmooth[1].first = i;
5643   }
5644 }
5645
5646 //================================================================================
5647 /*!
5648  * \brief Check if iE-th _LayerEdge needs smoothing
5649  */
5650 //================================================================================
5651
5652 bool _Smoother1D::isToSmooth( int iE )
5653 {
5654   SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5655   SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5656   SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5657   gp_XYZ       seg0 = pi - p0;
5658   gp_XYZ       seg1 = p1 - pi;
5659   gp_XYZ    tangent =  seg0 + seg1;
5660   double tangentLen = tangent.Modulus();
5661   double  segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5662   if ( tangentLen < std::numeric_limits<double>::min() )
5663     return false;
5664   tangent /= tangentLen;
5665
5666   for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5667   {
5668     _LayerEdge* ne = _eos[iE]->_neibors[i];
5669     if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5670          ne->_nodes.size() < 2 ||
5671          ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5672       continue;
5673     gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5674     double    proj = edgeVec * tangent;
5675     if ( needSmoothing( 1., proj, segMinLen ))
5676       return true;
5677   }
5678   return false;
5679 }
5680
5681 //================================================================================
5682 /*!
5683  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5684  */
5685 //================================================================================
5686
5687 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5688                                       Handle(ShapeAnalysis_Surface)& surface,
5689                                       const TopoDS_Face&             F,
5690                                       SMESH_MesherHelper&            helper)
5691 {
5692   if ( !isAnalytic() ) return false;
5693
5694   size_t iFrom = 0, iTo = _eos._edges.size();
5695
5696   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5697   {
5698     if ( F.IsNull() ) // 3D
5699     {
5700       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5701       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5702       //const   gp_XYZ lineDir = pSrc1 - pSrc0;
5703       //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5704       //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5705       // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5706       //                    vLE0->Is( _LayerEdge::BLOCKED ) ||
5707       //                    vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5708       //                    vLE1->Is( _LayerEdge::BLOCKED ));
5709       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5710       {
5711         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5712         if ( iFrom >= iTo ) continue;
5713         SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5714         SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5715         double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5716         double param1 = _leParams[ iTo ];
5717         for ( size_t i = iFrom; i < iTo; ++i )
5718         {
5719           _LayerEdge*       edge = _eos[i];
5720           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5721           double           param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5722           gp_XYZ          newPos = p0 * ( 1. - param ) + p1 * param;
5723
5724           // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5725           // {
5726           //   gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5727           //   double  shift = ( lineDir * ( newPos - pSrc0 ) -
5728           //                     lineDir * ( curPos - pSrc0 ));
5729           //   newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5730           // }
5731           if ( edge->Is( _LayerEdge::BLOCKED ))
5732           {
5733             SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5734             double curThick = pSrc.SquareDistance( tgtNode );
5735             double newThink = ( pSrc - newPos ).SquareModulus();
5736             if ( newThink > curThick )
5737               continue;
5738           }
5739           edge->_pos.back() = newPos;
5740           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5741           dumpMove( tgtNode );
5742         }
5743       }
5744     }
5745     else // 2D
5746     {
5747       _LayerEdge* eV0 = getLEdgeOnV( 0 );
5748       _LayerEdge* eV1 = getLEdgeOnV( 1 );
5749       gp_XY      uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5750       gp_XY      uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5751       if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5752       {
5753         int iPeriodic = helper.GetPeriodicIndex();
5754         if ( iPeriodic == 1 || iPeriodic == 2 )
5755         {
5756           uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5757           if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5758             std::swap( uvV0, uvV1 );
5759         }
5760       }
5761       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5762       {
5763         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5764         if ( iFrom >= iTo ) continue;
5765         _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5766         _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5767         gp_XY      uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5768         gp_XY      uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5769         double  param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5770         double  param1 = _leParams[ iTo ];
5771         gp_XY  rangeUV = uv1 - uv0;
5772         for ( size_t i = iFrom; i < iTo; ++i )
5773         {
5774           if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5775           double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5776           gp_XY newUV = uv0 + param * rangeUV;
5777
5778           gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5779           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5780           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5781           dumpMove( tgtNode );
5782
5783           SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5784           pos->SetUParameter( newUV.X() );
5785           pos->SetVParameter( newUV.Y() );
5786
5787           gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5788
5789           if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5790           {
5791             _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5792             if ( _eos[i]->_pos.size() > 2 )
5793             {
5794               // modify previous positions to make _LayerEdge less sharply bent
5795               vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5796               const gp_XYZ  uvShift = newUV0 - uvVec.back();
5797               const double     len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5798               int iPrev = uvVec.size() - 2;
5799               while ( iPrev > 0 )
5800               {
5801                 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5802                 uvVec[ iPrev ] += uvShift * r;
5803                 --iPrev;
5804               }
5805             }
5806           }
5807           _eos[i]->_pos.back() = newUV0;
5808         }
5809       }
5810     }
5811     return true;
5812   }
5813
5814   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5815   {
5816     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5817     gp_Pnt center3D = circle->Location();
5818
5819     if ( F.IsNull() ) // 3D
5820     {
5821       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5822         return true; // closed EDGE - nothing to do
5823
5824       // circle is a real curve of EDGE
5825       gp_Circ circ = circle->Circ();
5826
5827       // new center is shifted along its axis
5828       const gp_Dir& axis = circ.Axis().Direction();
5829       _LayerEdge*     e0 = getLEdgeOnV(0);
5830       _LayerEdge*     e1 = getLEdgeOnV(1);
5831       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5832       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5833       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5834       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5835       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5836
5837       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5838
5839       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5840       gp_Circ newCirc( newAxis, newRadius );
5841       gp_Vec  vecC1  ( newCenter, p1 );
5842
5843       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5844       if ( uLast < 0 )
5845         uLast += 2 * M_PI;
5846       
5847       for ( size_t i = 0; i < _eos.size(); ++i )
5848       {
5849         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5850         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5851         double u = uLast * _leParams[i];
5852         gp_Pnt p = ElCLib::Value( u, newCirc );
5853         _eos._edges[i]->_pos.back() = p.XYZ();
5854
5855         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5856         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5857         dumpMove( tgtNode );
5858       }
5859       return true;
5860     }
5861     else // 2D
5862     {
5863       const gp_XY center( center3D.X(), center3D.Y() );
5864
5865       _LayerEdge* e0 = getLEdgeOnV(0);
5866       _LayerEdge* eM = _eos._edges[ 0 ];
5867       _LayerEdge* e1 = getLEdgeOnV(1);
5868       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5869       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5870       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5871       gp_Vec2d vec0( center, uv0 );
5872       gp_Vec2d vecM( center, uvM );
5873       gp_Vec2d vec1( center, uv1 );
5874       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5875       double uMidl = vec0.Angle( vecM );
5876       if ( uLast * uMidl <= 0. )
5877         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5878       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5879
5880       gp_Ax2d   axis( center, vec0 );
5881       gp_Circ2d circ( axis, radius );
5882       for ( size_t i = 0; i < _eos.size(); ++i )
5883       {
5884         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5885         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5886         double    newU = uLast * _leParams[i];
5887         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5888         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5889
5890         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5891         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5892         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5893         dumpMove( tgtNode );
5894
5895         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5896         pos->SetUParameter( newUV.X() );
5897         pos->SetVParameter( newUV.Y() );
5898
5899         _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5900       }
5901     }
5902     return true;
5903   }
5904
5905   return false;
5906 }
5907
5908 //================================================================================
5909 /*!
5910  * \brief smooth _LayerEdge's on a an EDGE
5911  */
5912 //================================================================================
5913
5914 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5915                                      Handle(ShapeAnalysis_Surface)& surface,
5916                                      const TopoDS_Face&             F,
5917                                      SMESH_MesherHelper&            helper)
5918 {
5919   if ( _offPoints.empty() )
5920     return false;
5921
5922   // ----------------------------------------------
5923   // move _offPoints along normals of _LayerEdge's
5924   // ----------------------------------------------
5925
5926   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5927   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5928     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5929   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5930     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5931   _leOnV[0]._len = e[0]->_len;
5932   _leOnV[1]._len = e[1]->_len;
5933   for ( size_t i = 0; i < _offPoints.size(); i++ )
5934   {
5935     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5936     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5937     const double w0 = _offPoints[i]._2edges._wgt[0];
5938     const double w1 = _offPoints[i]._2edges._wgt[1];
5939     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5940     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5941     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5942     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5943          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5944       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5945
5946     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5947     _offPoints[i]._len  = avgLen;
5948   }
5949
5950   double fTol = 0;
5951   if ( !surface.IsNull() ) // project _offPoints to the FACE
5952   {
5953     fTol = 100 * BRep_Tool::Tolerance( F );
5954     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5955
5956     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5957     //if ( surface->Gap() < 0.5 * segLen )
5958       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5959
5960     for ( size_t i = 1; i < _offPoints.size(); ++i )
5961     {
5962       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5963       //if ( surface->Gap() < 0.5 * segLen )
5964         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5965     }
5966   }
5967
5968   // -----------------------------------------------------------------
5969   // project tgt nodes of extreme _LayerEdge's to the offset segments
5970   // -----------------------------------------------------------------
5971
5972   const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
5973   if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
5974   if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
5975
5976   gp_Pnt pExtreme[2], pProj[2];
5977   bool isProjected[2];
5978   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5979   {
5980     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5981     int  i = _iSeg[ is2nd ];
5982     int di = is2nd ? -1 : +1;
5983     bool & projected = isProjected[ is2nd ];
5984     projected = false;
5985     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5986     int nbWorse = 0;
5987     do {
5988       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5989       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5990       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5991       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5992       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5993       if ( dist < distMin || projected )
5994       {
5995         _iSeg[ is2nd ] = i;
5996         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5997         distMin = dist;
5998       }
5999       else if ( dist > distPrev )
6000       {
6001         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6002           break;
6003       }
6004       distPrev = dist;
6005       i += di;
6006     }
6007     while ( !projected &&
6008             i >= 0 && i+1 < (int)_offPoints.size() );
6009
6010     if ( !projected )
6011     {
6012       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6013       {
6014         _iSeg[0] = 0;
6015         _iSeg[1] = _offPoints.size()-2;
6016         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6017         return false;
6018       }
6019     }
6020   }
6021   if ( _iSeg[0] > _iSeg[1] )
6022   {
6023     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6024     return false;
6025   }
6026
6027   // adjust length of extreme LE (test viscous_layers_01/B7)
6028   gp_Vec vDiv0( pExtreme[0], pProj[0] );
6029   gp_Vec vDiv1( pExtreme[1], pProj[1] );
6030   double d0 = vDiv0.Magnitude();
6031   double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6032   if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6033     if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6034     else                                   e[0]->_len -= d0;
6035   }
6036   if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6037     if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6038     else                                   e[1]->_len -= d1;
6039   }
6040
6041   // ---------------------------------------------------------------------------------
6042   // compute normalized length of the offset segments located between the projections
6043   // ---------------------------------------------------------------------------------
6044
6045   // temporary replace extreme _offPoints by pExtreme
6046   gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0]   ]._xyz,
6047                       _offPoints[ _iSeg[1]+1 ]._xyz };
6048   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
6049   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6050
6051   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6052   vector< double > len( nbSeg + 1 );
6053   len[ iSeg++ ] = 0;
6054   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6055   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6056   {
6057     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6058   }
6059   // if ( isProjected[ 1 ])
6060   //   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6061   // else
6062   //   len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6063
6064   double fullLen = len.back() - d0 - d1;
6065   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6066     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6067
6068   // -------------------------------------------------------------
6069   // distribute tgt nodes of _LayerEdge's between the projections
6070   // -------------------------------------------------------------
6071
6072   iSeg = 0;
6073   for ( size_t i = 0; i < _eos.size(); ++i )
6074   {
6075     if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6076     //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6077     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6078       iSeg++;
6079     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6080     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
6081                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6082
6083     if ( surface.IsNull() )
6084     {
6085       _eos[i]->_pos.back() = p;
6086     }
6087     else // project a new node position to a FACE
6088     {
6089       gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6090       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6091
6092       p = surface->Value( uv2 ).XYZ();
6093       _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6094     }
6095     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6096     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6097     dumpMove( tgtNode );
6098   }
6099
6100   _offPoints[ _iSeg[0]   ]._xyz = opXYZ[0];
6101   _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6102
6103   return true;
6104 }
6105
6106 //================================================================================
6107 /*!
6108  * \brief Prepare for smoothing
6109  */
6110 //================================================================================
6111
6112 void _Smoother1D::prepare(_SolidData& data)
6113 {
6114   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6115   _curveLen = SMESH_Algo::EdgeLength( E );
6116
6117   // sort _LayerEdge's by position on the EDGE
6118   data.SortOnEdge( E, _eos._edges );
6119
6120   // compute normalized param of _eos._edges on EDGE
6121   _leParams.resize( _eos._edges.size() + 1 );
6122   {
6123     double curLen;
6124     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6125     _leParams[0] = 0;
6126     for ( size_t i = 0; i < _eos._edges.size(); ++i )
6127     {
6128       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6129       curLen         = p.Distance( pPrev );
6130       _leParams[i+1] = _leParams[i] + curLen;
6131       pPrev          = p;
6132     }
6133     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6134     for ( size_t i = 0; i < _leParams.size()-1; ++i )
6135       _leParams[i] = _leParams[i+1] / fullLen;
6136     _leParams.back() = 1.;
6137   }
6138
6139   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6140
6141   // get cosin to use in findEdgesToSmooth()
6142   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6143   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6144   _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6145   _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6146   if ( _eos._sWOL.IsNull() ) // 3D
6147     for ( int iEnd = 0; iEnd < 2; ++iEnd )
6148       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6149
6150   if ( isAnalytic() )
6151     return;
6152
6153   // divide E to have offset segments with low deflection
6154   BRepAdaptor_Curve c3dAdaptor( E );
6155   const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6156   const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6157   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6158   if ( discret.NbPoints() <= 2 )
6159   {
6160     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6161     return;
6162   }
6163
6164   const double u0 = c3dAdaptor.FirstParameter();
6165   gp_Pnt p; gp_Vec tangent;
6166   if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6167   {
6168     _offPoints.resize( discret.NbPoints() );
6169     for ( size_t i = 0; i < _offPoints.size(); i++ )
6170     {
6171       double u = discret.Parameter( i+1 );
6172       c3dAdaptor.D1( u, p, tangent );
6173       _offPoints[i]._xyz     = p.XYZ();
6174       _offPoints[i]._edgeDir = tangent.XYZ();
6175       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6176     }
6177   }
6178   else
6179   {
6180     std::vector< double > params( _eos.size() + 2 );
6181
6182     params[0]     = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6183     params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6184     for ( size_t i = 0; i < _eos.size(); i++ )
6185       params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6186
6187     if ( params[1] > params[ _eos.size() ] )
6188       std::reverse( params.begin() + 1, params.end() - 1 );
6189
6190     _offPoints.resize( _eos.size() + 2 );
6191     for ( size_t i = 0; i < _offPoints.size(); i++ )
6192     {
6193       const double u = params[i];
6194       c3dAdaptor.D1( u, p, tangent );
6195       _offPoints[i]._xyz     = p.XYZ();
6196       _offPoints[i]._edgeDir = tangent.XYZ();
6197       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6198     }
6199   }
6200
6201   // set _2edges
6202   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6203   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6204   _2NearEdges tmp2edges;
6205   tmp2edges._edges[1] = _eos._edges[0];
6206   _leOnV[0]._2neibors = & tmp2edges;
6207   _leOnV[0]._nodes    = leOnV[0]->_nodes;
6208   _leOnV[1]._nodes    = leOnV[1]->_nodes;
6209   _LayerEdge* eNext, *ePrev = & _leOnV[0];
6210   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6211   {
6212     // find _LayerEdge's located before and after an offset point
6213     // (_eos._edges[ iLE ] is next after ePrev)
6214     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6215       ePrev = _eos._edges[ iLE++ ];
6216     eNext = ePrev->_2neibors->_edges[1];
6217
6218     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6219     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6220     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6221     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6222   }
6223
6224   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6225   for ( size_t i = 0; i < _offPoints.size(); i++ )
6226     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6227       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6228     else break;
6229   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6230     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6231       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6232     else break;
6233
6234   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6235
6236   int iLBO = _offPoints.size() - 2; // last but one
6237
6238   if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6239     _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6240   else
6241     _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal,       _edgeDir[0] );
6242   if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6243     _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6244   else
6245     _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal,           _edgeDir[1] );
6246   _leOnV[ 0 ]._len = 0;
6247   _leOnV[ 1 ]._len = 0;
6248   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
6249   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6250
6251   _iSeg[0] = 0;
6252   _iSeg[1] = _offPoints.size()-2;
6253
6254   // initialize OffPnt::_len
6255   for ( size_t i = 0; i < _offPoints.size(); ++i )
6256     _offPoints[i]._len = 0;
6257
6258   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6259   {
6260     _leOnV[0]._len = leOnV[0]->_len;
6261     _leOnV[1]._len = leOnV[1]->_len;
6262     for ( size_t i = 0; i < _offPoints.size(); i++ )
6263     {
6264       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6265       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6266       const double w0 = _offPoints[i]._2edges._wgt[0];
6267       const double w1 = _offPoints[i]._2edges._wgt[1];
6268       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
6269       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6270                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6271       _offPoints[i]._xyz = avgXYZ;
6272       _offPoints[i]._len = avgLen;
6273     }
6274   }
6275 }
6276
6277 //================================================================================
6278 /*!
6279  * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6280  */
6281 //================================================================================
6282
6283 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6284                                      const gp_XYZ&  edgeDir)
6285 {
6286   gp_XYZ cross = normal ^ edgeDir;
6287   gp_XYZ  norm = edgeDir ^ cross;
6288   double  size = norm.Modulus();
6289
6290   // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6291   //   return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6292
6293   return norm / size;
6294 }
6295
6296 //================================================================================
6297 /*!
6298  * \brief Writes a script creating a mesh composed of _offPoints
6299  */
6300 //================================================================================
6301
6302 void _Smoother1D::offPointsToPython() const
6303 {
6304   const char* fname = "/tmp/offPoints.py";
6305   cout << "execfile('"<<fname<<"')"<<endl;
6306   ofstream py(fname);
6307   py << "import SMESH" << endl
6308      << "from salome.smesh import smeshBuilder" << endl
6309      << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
6310      << "mesh   = smesh.Mesh( 'offPoints' )"<<endl;
6311   for ( size_t i = 0; i < _offPoints.size(); i++ )
6312   {
6313     py << "mesh.AddNode( "
6314        << _offPoints[i]._xyz.X() << ", "
6315        << _offPoints[i]._xyz.Y() << ", "
6316        << _offPoints[i]._xyz.Z() << " )" << endl;
6317   }
6318 }
6319
6320 //================================================================================
6321 /*!
6322  * \brief Sort _LayerEdge's by a parameter on a given EDGE
6323  */
6324 //================================================================================
6325
6326 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
6327                              vector< _LayerEdge* >& edges)
6328 {
6329   map< double, _LayerEdge* > u2edge;
6330   for ( size_t i = 0; i < edges.size(); ++i )
6331     u2edge.insert( u2edge.end(),
6332                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6333
6334   ASSERT( u2edge.size() == edges.size() );
6335   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6336   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6337     edges[i] = u2e->second;
6338
6339   Sort2NeiborsOnEdge( edges );
6340 }
6341
6342 //================================================================================
6343 /*!
6344  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6345  */
6346 //================================================================================
6347
6348 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6349 {
6350   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6351
6352   for ( size_t i = 0; i < edges.size()-1; ++i )
6353     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6354       edges[i]->_2neibors->reverse();
6355
6356   const size_t iLast = edges.size() - 1;
6357   if ( edges.size() > 1 &&
6358        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6359     edges[iLast]->_2neibors->reverse();
6360 }
6361
6362 //================================================================================
6363 /*!
6364  * \brief Return _EdgesOnShape* corresponding to the shape
6365  */
6366 //================================================================================
6367
6368 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6369 {
6370   if ( shapeID < (int)_edgesOnShape.size() &&
6371        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6372     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6373
6374   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6375     if ( _edgesOnShape[i]._shapeID == shapeID )
6376       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6377
6378   return 0;
6379 }
6380
6381 //================================================================================
6382 /*!
6383  * \brief Return _EdgesOnShape* corresponding to the shape
6384  */
6385 //================================================================================
6386
6387 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6388 {
6389   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6390   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6391 }
6392
6393 //================================================================================
6394 /*!
6395  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6396  */
6397 //================================================================================
6398
6399 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6400 {
6401   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6402
6403   set< TGeomID > vertices;
6404   TopoDS_Face F;
6405   if ( eos->ShapeType() == TopAbs_FACE )
6406   {
6407     // check FACE concavity and get concave VERTEXes
6408     F = TopoDS::Face( eos->_shape );
6409     if ( isConcave( F, helper, &vertices ))
6410       _concaveFaces.insert( eos->_shapeID );
6411
6412     // set eos._eosConcaVer
6413     eos->_eosConcaVer.clear();
6414     eos->_eosConcaVer.reserve( vertices.size() );
6415     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6416     {
6417       _EdgesOnShape* eov = GetShapeEdges( *v );
6418       if ( eov && eov->_edges.size() == 1 )
6419       {
6420         eos->_eosConcaVer.push_back( eov );
6421         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6422           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6423       }
6424     }
6425
6426     // SetSmooLen() to _LayerEdge's on FACE
6427     // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6428     // {
6429     //   eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6430     // }
6431     // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6432     // while ( smIt->more() ) // loop on sub-shapes of the FACE
6433     // {
6434     //   _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6435     //   if ( !eoe ) continue;
6436
6437     //   vector<_LayerEdge*>& eE = eoe->_edges;
6438     //   for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6439     //   {
6440     //     if ( eE[iE]->_cosin <= theMinSmoothCosin )
6441     //       continue;
6442
6443     //     SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6444     //     while ( segIt->more() )
6445     //     {
6446     //       const SMDS_MeshElement* seg = segIt->next();
6447     //       if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6448     //         continue;
6449     //       if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6450     //         continue; // not to check a seg twice
6451     //       for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6452     //       {
6453     //         _LayerEdge* eN = eE[iE]->_neibors[iN];
6454     //         if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6455     //           continue;
6456     //         double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6457     //         double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6458     //         eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6459     //         eN->Set( _LayerEdge::NEAR_BOUNDARY );
6460     //       }
6461     //     }
6462     //   }
6463     // }
6464   } // if ( eos->ShapeType() == TopAbs_FACE )
6465
6466   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6467   {
6468     eos->_edges[i]->_smooFunction = 0;
6469     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6470   }
6471   bool isCurved = false;
6472   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6473   {
6474     _LayerEdge* edge = eos->_edges[i];
6475
6476     // get simplices sorted
6477     _Simplex::SortSimplices( edge->_simplices );
6478
6479     // smoothing function
6480     edge->ChooseSmooFunction( vertices, _n2eMap );
6481
6482     // set _curvature
6483     double avgNormProj = 0, avgLen = 0;
6484     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6485     {
6486       _Simplex& s = edge->_simplices[iS];
6487
6488       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6489       avgNormProj += edge->_normal * vec;
6490       avgLen      += vec.Modulus();
6491       if ( substituteSrcNodes )
6492       {
6493         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6494         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6495       }
6496     }
6497     avgNormProj /= edge->_simplices.size();
6498     avgLen      /= edge->_simplices.size();
6499     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6500     {
6501       edge->Set( _LayerEdge::SMOOTHED_C1 );
6502       isCurved = true;
6503       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6504       if ( !fPos )
6505         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6506           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6507       if ( fPos )
6508         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6509     }
6510   }
6511
6512   // prepare for putOnOffsetSurface()
6513   if (( eos->ShapeType() == TopAbs_FACE ) &&
6514       ( isCurved || !eos->_eosConcaVer.empty() ))
6515   {
6516     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6517     eos->_edgeForOffset = 0;
6518
6519     double maxCosin = -1;
6520     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6521     {
6522       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6523       if ( !eoe || eoe->_edges.empty() ) continue;
6524
6525       vector<_LayerEdge*>& eE = eoe->_edges;
6526       _LayerEdge* e = eE[ eE.size() / 2 ];
6527       if ( e->_cosin > maxCosin )
6528       {
6529         eos->_edgeForOffset = e;
6530         maxCosin = e->_cosin;
6531       }
6532     }
6533   }
6534 }
6535
6536 //================================================================================
6537 /*!
6538  * \brief Add faces for smoothing
6539  */
6540 //================================================================================
6541
6542 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6543                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6544 {
6545   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6546   for ( ; eos != eosToSmooth.end(); ++eos )
6547   {
6548     if ( !*eos || (*eos)->_toSmooth ) continue;
6549
6550     (*eos)->_toSmooth = true;
6551
6552     if ( (*eos)->ShapeType() == TopAbs_FACE )
6553     {
6554       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6555       (*eos)->_toSmooth = true;
6556     }
6557   }
6558
6559   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6560   if ( edgesNoAnaSmooth )
6561     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6562     {
6563       if ( (*eos)->_edgeSmoother )
6564         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6565     }
6566 }
6567
6568 //================================================================================
6569 /*!
6570  * \brief Limit _LayerEdge::_maxLen according to local curvature
6571  */
6572 //================================================================================
6573
6574 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6575 {
6576   // find intersection of neighbor _LayerEdge's to limit _maxLen
6577   // according to local curvature (IPAL52648)
6578
6579   // This method must be called after findCollisionEdges() where _LayerEdge's
6580   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6581
6582   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6583   {
6584     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6585     if ( eosI._edges.empty() ) continue;
6586     if ( !eosI._hyp.ToSmooth() )
6587     {
6588       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6589       {
6590         _LayerEdge* eI = eosI._edges[i];
6591         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6592         {
6593           _LayerEdge* eN = eI->_neibors[iN];
6594           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6595           {
6596             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6597             limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
6598           }
6599         }
6600       }
6601     }
6602     else if ( eosI.ShapeType() == TopAbs_EDGE )
6603     {
6604       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6605       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6606
6607       _LayerEdge* e0 = eosI._edges[0];
6608       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6609       {
6610         _LayerEdge* eI = eosI._edges[i];
6611         limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
6612         e0 = eI;
6613       }
6614     }
6615   }
6616 }
6617
6618 //================================================================================
6619 /*!
6620  * \brief Limit _LayerEdge::_maxLen according to local curvature
6621  */
6622 //================================================================================
6623
6624 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*    e1,
6625                                               _LayerEdge*    e2,
6626                                               _EdgesOnShape& eos1,
6627                                               _EdgesOnShape& eos2,
6628                                               const bool     isSmoothable )
6629 {
6630   if (( e1->_nodes[0]->GetPosition()->GetDim() !=
6631         e2->_nodes[0]->GetPosition()->GetDim() ) &&
6632       ( e1->_cosin < 0.75 ))
6633     return; // angle > 90 deg at e1
6634
6635   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6636   double norSize = plnNorm.SquareModulus();
6637   if ( norSize < std::numeric_limits<double>::min() )
6638     return; // parallel normals
6639
6640   // find closest points of skew _LayerEdge's
6641   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6642   gp_XYZ dir12 = src2 - src1;
6643   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6644   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6645   double  dot1 = perp2 * e1->_normal;
6646   double  dot2 = perp1 * e2->_normal;
6647   double    u1 =   ( perp2 * dir12 ) / dot1;
6648   double    u2 = - ( perp1 * dir12 ) / dot2;
6649   if ( u1 > 0 && u2 > 0 )
6650   {
6651     double ovl = ( u1 * e1->_normal * dir12 -
6652                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6653     if ( ovl > theSmoothThickToElemSizeRatio )
6654     {
6655       const double coef = 0.75;
6656       e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
6657       e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
6658     }
6659   }
6660 }
6661
6662 //================================================================================
6663 /*!
6664  * \brief Fill data._collisionEdges
6665  */
6666 //================================================================================
6667
6668 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6669 {
6670   data._collisionEdges.clear();
6671
6672   // set the full thickness of the layers to LEs
6673   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6674   {
6675     _EdgesOnShape& eos = data._edgesOnShape[iS];
6676     if ( eos._edges.empty() ) continue;
6677     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6678
6679     for ( size_t i = 0; i < eos._edges.size(); ++i )
6680     {
6681       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6682       double maxLen = eos._edges[i]->_maxLen;
6683       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6684       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6685       eos._edges[i]->_maxLen = maxLen;
6686     }
6687   }
6688
6689   // make temporary quadrangles got by extrusion of
6690   // mesh edges along _LayerEdge._normal's
6691
6692   vector< const SMDS_MeshElement* > tmpFaces;
6693
6694   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6695   {
6696     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6697     if ( eos.ShapeType() != TopAbs_EDGE )
6698       continue;
6699     if ( eos._edges.empty() )
6700     {
6701       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6702       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6703       while ( smIt->more() )
6704         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6705           if ( eov->_edges.size() == 1 )
6706             edge[ bool( edge[0]) ] = eov->_edges[0];
6707
6708       if ( edge[1] )
6709       {
6710         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6711         tmpFaces.push_back( f );
6712       }
6713     }
6714     for ( size_t i = 0; i < eos._edges.size(); ++i )
6715     {
6716       _LayerEdge* edge = eos._edges[i];
6717       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6718       {
6719         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6720         if ( src2->GetPosition()->GetDim() > 0 &&
6721              src2->GetID() < edge->_nodes[0]->GetID() )
6722           continue; // avoid using same segment twice
6723
6724         // a _LayerEdge containg tgt2
6725         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6726
6727         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6728         tmpFaces.push_back( f );
6729       }
6730     }
6731   }
6732
6733   // Find _LayerEdge's intersecting tmpFaces.
6734
6735   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6736                                                             tmpFaces.end()));
6737   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6738     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6739
6740   double dist1, dist2, segLen, eps = 0.5;
6741   _CollisionEdges collEdges;
6742   vector< const SMDS_MeshElement* > suspectFaces;
6743   const double angle45 = Cos( 45. * M_PI / 180. );
6744
6745   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6746   {
6747     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6748     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6749       continue;
6750     // find sub-shapes whose VL can influence VL on eos
6751     set< TGeomID > neighborShapes;
6752     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6753     while ( const TopoDS_Shape* face = fIt->next() )
6754     {
6755       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6756       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6757       {
6758         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6759         while ( subIt->more() )
6760           neighborShapes.insert( subIt->next()->GetId() );
6761       }
6762     }
6763     if ( eos.ShapeType() == TopAbs_VERTEX )
6764     {
6765       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6766       while ( const TopoDS_Shape* edge = eIt->next() )
6767         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6768     }
6769     // find intersecting _LayerEdge's
6770     for ( size_t i = 0; i < eos._edges.size(); ++i )
6771     {
6772       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6773       _LayerEdge*   edge = eos._edges[i];
6774       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6775       segLen *= 1.2;
6776
6777       gp_Vec eSegDir0, eSegDir1;
6778       if ( edge->IsOnEdge() )
6779       {
6780         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6781         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6782         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6783       }
6784       suspectFaces.clear();
6785       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6786                                      SMDSAbs_Face, suspectFaces );
6787       collEdges._intEdges.clear();
6788       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6789       {
6790         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6791         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6792         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6793         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6794         if ( edge->IsOnEdge() ) {
6795           if ( edge->_2neibors->include( f->_le1 ) ||
6796                edge->_2neibors->include( f->_le2 )) continue;
6797         }
6798         else {
6799           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6800               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6801         }
6802         dist1 = dist2 = Precision::Infinite();
6803         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6804           dist1 = Precision::Infinite();
6805         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6806           dist2 = Precision::Infinite();
6807         if (( dist1 > segLen ) && ( dist2 > segLen ))
6808           continue;
6809
6810         if ( edge->IsOnEdge() )
6811         {
6812           // skip perpendicular EDGEs
6813           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6814           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6815                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6816                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6817                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6818           if ( !isParallel )
6819             continue;
6820         }
6821
6822         // either limit inflation of edges or remember them for updating _normal
6823         // double dot = edge->_normal * f->GetDir();
6824         // if ( dot > 0.1 )
6825         {
6826           collEdges._intEdges.push_back( f->_le1 );
6827           collEdges._intEdges.push_back( f->_le2 );
6828         }
6829         // else
6830         // {
6831         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6832         //   edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
6833         // }
6834       }
6835
6836       if ( !collEdges._intEdges.empty() )
6837       {
6838         collEdges._edge = edge;
6839         data._collisionEdges.push_back( collEdges );
6840       }
6841     }
6842   }
6843
6844   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6845     delete tmpFaces[i];
6846
6847   // restore the zero thickness
6848   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6849   {
6850     _EdgesOnShape& eos = data._edgesOnShape[iS];
6851     if ( eos._edges.empty() ) continue;
6852     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6853
6854     for ( size_t i = 0; i < eos._edges.size(); ++i )
6855     {
6856       eos._edges[i]->InvalidateStep( 1, eos );
6857       eos._edges[i]->_len = 0;
6858     }
6859   }
6860 }
6861
6862 //================================================================================
6863 /*!
6864  * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
6865  *        will be updated at each inflation step
6866  */
6867 //================================================================================
6868
6869 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
6870                                                              _SolidData&         data,
6871                                                              SMESH_MesherHelper& helper )
6872 {
6873   const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
6874   const double       preci = BRep_Tool::Tolerance( convFace._face );
6875   Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
6876
6877   bool edgesToUpdateFound = false;
6878
6879   map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6880   for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6881   {
6882     _EdgesOnShape& eos = * id2eos->second;
6883     if ( !eos._sWOL.IsNull() ) continue;
6884     if ( !eos._hyp.ToSmooth() ) continue;
6885     for ( size_t i = 0; i < eos._edges.size(); ++i )
6886     {
6887       _LayerEdge* ledge = eos._edges[ i ];
6888       if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
6889       if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
6890
6891       gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
6892                         ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
6893
6894       // the normal must be updated if distance from tgtPos to surface is less than
6895       // target thickness
6896
6897       // find an initial UV for search of a projection of tgtPos to surface
6898       const SMDS_MeshNode* nodeInFace = 0;
6899       SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6900       while ( fIt->more() && !nodeInFace )
6901       {
6902         const SMDS_MeshElement* f = fIt->next();
6903         if ( convFaceID != f->getshapeId() ) continue;
6904
6905         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
6906         while ( nIt->more() && !nodeInFace )
6907         {
6908           const SMDS_MeshElement* n = nIt->next();
6909           if ( n->getshapeId() == convFaceID )
6910             nodeInFace = static_cast< const SMDS_MeshNode* >( n );
6911         }
6912       }
6913       if ( !nodeInFace )
6914         continue;
6915       gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
6916
6917       // projection
6918       surface->NextValueOfUV( uv, tgtPos, preci );
6919       double  dist = surface->Gap();
6920       if ( dist < 0.95 * ledge->_maxLen )
6921       {
6922         ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
6923         if ( !ledge->_curvature ) ledge->_curvature = new _Curvature;
6924         ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
6925         edgesToUpdateFound = true;
6926       }
6927     }
6928   }
6929
6930   if ( !convFace._isTooCurved && edgesToUpdateFound )
6931   {
6932     data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
6933   }
6934 }
6935
6936 //================================================================================
6937 /*!
6938  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6939  * _LayerEdge's on neighbor EDGE's
6940  */
6941 //================================================================================
6942
6943 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6944                                      SMESH_MesherHelper& helper,
6945                                      int                 stepNb,
6946                                      double              stepSize)
6947 {
6948   updateNormalsOfC1Vertices( data );
6949
6950   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6951     return false;
6952
6953   // map to store new _normal and _cosin for each intersected edge
6954   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6955   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6956   _LayerEdge zeroEdge;
6957   zeroEdge._normal.SetCoord( 0,0,0 );
6958   zeroEdge._maxLen = Precision::Infinite();
6959   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6960
6961   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6962
6963   double segLen, dist1, dist2, dist;
6964   vector< pair< _LayerEdge*, double > > intEdgesDist;
6965   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6966
6967   for ( int iter = 0; iter < 5; ++iter )
6968   {
6969     edge2newEdge.clear();
6970
6971     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6972     {
6973       _CollisionEdges& ce = data._collisionEdges[iE];
6974       _LayerEdge*   edge1 = ce._edge;
6975       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6976       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6977       if ( !eos1 ) continue;
6978
6979       // detect intersections
6980       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6981       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6982       double     eps = 0.5;
6983       intEdgesDist.clear();
6984       double minIntDist = Precision::Infinite();
6985       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6986       {
6987         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6988              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6989              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6990           continue;
6991         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6992         double fact = ( 1.1 + dot * dot );
6993         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6994         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6995         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6996         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6997         dist1 = dist2 = Precision::Infinite();
6998         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
6999              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7000           continue;
7001         dist = dist1;
7002         if ( dist > testLen || dist <= 0 )
7003         {
7004           dist = dist2;
7005           if ( dist > testLen || dist <= 0 )
7006             continue;
7007         }
7008         // choose a closest edge
7009         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7010         double d1 = intP.SquareDistance( pSrc0 );
7011         double d2 = intP.SquareDistance( pSrc1 );
7012         int iClose = i + ( d2 < d1 );
7013         _LayerEdge* edge2 = ce._intEdges[iClose];
7014         edge2->Unset( _LayerEdge::MARKED );
7015
7016         // choose a closest edge among neighbors
7017         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7018         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7019         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7020         {
7021           _LayerEdge * edgeJ = intEdgesDist[j].first;
7022           if ( edge2->IsNeiborOnEdge( edgeJ ))
7023           {
7024             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7025             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7026           }
7027         }
7028         intEdgesDist.push_back( make_pair( edge2, dist ));
7029         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7030         // {
7031         //   iClose = i + !( d2 < d1 );
7032         //   intEdges.push_back( ce._intEdges[iClose] );
7033         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7034         // }
7035         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7036       }
7037
7038       //ce._edge = 0;
7039
7040       // compute new _normals
7041       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7042       {
7043         _LayerEdge* edge2   = intEdgesDist[i].first;
7044         double      distWgt = edge1->_len / intEdgesDist[i].second;
7045         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7046         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
7047         if ( edge2->Is( _LayerEdge::MARKED )) continue;
7048         edge2->Set( _LayerEdge::MARKED );
7049
7050         // get a new normal
7051         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7052
7053         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7054         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7055         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7056         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
7057         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7058         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7059         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7060         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7061         newNormal.Normalize();
7062
7063         // get new cosin
7064         double newCos;
7065         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7066         if ( cos1 < theMinSmoothCosin )
7067         {
7068           newCos = cos2 * sgn1;
7069         }
7070         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7071         {
7072           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7073         }
7074         else
7075         {
7076           newCos = edge1->_cosin;
7077         }
7078
7079         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7080         e2neIt->second._normal += distWgt * newNormal;
7081         e2neIt->second._cosin   = newCos;
7082         e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7083         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7084           e2neIt->second._normal += dir2;
7085
7086         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7087         e2neIt->second._normal += distWgt * newNormal;
7088         if ( Precision::IsInfinite( zeroEdge._maxLen ))
7089         {
7090           e2neIt->second._cosin  = edge2->_cosin;
7091           e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7092         }
7093         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7094           e2neIt->second._normal += dir1;
7095       }
7096     }
7097
7098     if ( edge2newEdge.empty() )
7099       break; //return true;
7100
7101     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7102
7103     // Update data of edges depending on a new _normal
7104
7105     data.UnmarkEdges();
7106     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7107     {
7108       _LayerEdge*    edge = e2neIt->first;
7109       _LayerEdge& newEdge = e2neIt->second;
7110       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
7111       if ( edge->Is( _LayerEdge::BLOCKED && newEdge._maxLen > edge->_len ))
7112         continue;
7113
7114       // Check if a new _normal is OK:
7115       newEdge._normal.Normalize();
7116       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7117       {
7118         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7119         {
7120           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7121           edge->SetMaxLen( newEdge._maxLen );
7122           edge->SetNewLength( newEdge._maxLen, *eos, helper );
7123         }
7124         continue; // the new _normal is bad
7125       }
7126       // the new _normal is OK
7127
7128       // find shapes that need smoothing due to change of _normal
7129       if ( edge->_cosin   < theMinSmoothCosin &&
7130            newEdge._cosin > theMinSmoothCosin )
7131       {
7132         if ( eos->_sWOL.IsNull() )
7133         {
7134           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7135           while ( fIt->more() )
7136             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7137         }
7138         else // edge inflates along a FACE
7139         {
7140           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7141           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7142           while ( const TopoDS_Shape* E = eIt->next() )
7143           {
7144             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7145             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7146             if ( angle < M_PI / 2 )
7147               shapesToSmooth.insert( data.GetShapeEdges( *E ));
7148           }
7149         }
7150       }
7151
7152       double len = edge->_len;
7153       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7154       edge->SetNormal( newEdge._normal );
7155       edge->SetCosin( newEdge._cosin );
7156       edge->SetNewLength( len, *eos, helper );
7157       edge->Set( _LayerEdge::MARKED );
7158       edge->Set( _LayerEdge::NORMAL_UPDATED );
7159       edgesNoAnaSmooth.insert( eos );
7160     }
7161
7162     // Update normals and other dependent data of not intersecting _LayerEdge's
7163     // neighboring the intersecting ones
7164
7165     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7166     {
7167       _LayerEdge*   edge1 = e2neIt->first;
7168       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7169       if ( !edge1->Is( _LayerEdge::MARKED ))
7170         continue;
7171
7172       if ( edge1->IsOnEdge() )
7173       {
7174         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7175         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7176         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7177       }
7178
7179       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7180         continue;
7181       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7182       {
7183         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7184         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7185           continue; // j-th neighbor is also intersected
7186         _LayerEdge* prevEdge = edge1;
7187         const int nbSteps = 10;
7188         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7189         {
7190           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7191                neighbor->Is( _LayerEdge::MARKED ))
7192             break;
7193           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7194           if ( !eos ) continue;
7195           _LayerEdge* nextEdge = neighbor;
7196           if ( neighbor->_2neibors )
7197           {
7198             int iNext = 0;
7199             nextEdge = neighbor->_2neibors->_edges[iNext];
7200             if ( nextEdge == prevEdge )
7201               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7202           }
7203           double r = double(step-1)/nbSteps/(iter+1);
7204           if ( !nextEdge->_2neibors )
7205             r = Min( r, 0.5 );
7206
7207           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7208           newNorm.Normalize();
7209           if ( !isNewNormalOk( data, *neighbor, newNorm ))
7210             break;
7211
7212           double len = neighbor->_len;
7213           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7214           neighbor->SetNormal( newNorm );
7215           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7216           if ( neighbor->_2neibors )
7217             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7218           neighbor->SetNewLength( len, *eos, helper );
7219           neighbor->Set( _LayerEdge::MARKED );
7220           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7221           edgesNoAnaSmooth.insert( eos );
7222
7223           if ( !neighbor->_2neibors )
7224             break; // neighbor is on VERTEX
7225
7226           // goto the next neighbor
7227           prevEdge = neighbor;
7228           neighbor = nextEdge;
7229         }
7230       }
7231     }
7232     dumpFunctionEnd();
7233   } // iterations
7234
7235   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7236
7237   return true;
7238 }
7239
7240 //================================================================================
7241 /*!
7242  * \brief Check if a new normal is OK
7243  */
7244 //================================================================================
7245
7246 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
7247                                      _LayerEdge&   edge,
7248                                      const gp_XYZ& newNormal)
7249 {
7250   // check a min angle between the newNormal and surrounding faces
7251   vector<_Simplex> simplices;
7252   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7253   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7254   double newMinDot = 1, curMinDot = 1;
7255   for ( size_t i = 0; i < simplices.size(); ++i )
7256   {
7257     n1.Set( simplices[i]._nPrev );
7258     n2.Set( simplices[i]._nNext );
7259     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7260     double normLen2 = normFace.SquareModulus();
7261     if ( normLen2 < std::numeric_limits<double>::min() )
7262       continue;
7263     normFace /= Sqrt( normLen2 );
7264     newMinDot = Min( newNormal    * normFace, newMinDot );
7265     curMinDot = Min( edge._normal * normFace, curMinDot );
7266   }
7267   bool ok = true;
7268   if ( newMinDot < 0.5 )
7269   {
7270     ok = ( newMinDot >= curMinDot * 0.9 );
7271     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7272     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7273     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7274   }
7275
7276   return ok;
7277 }
7278
7279 //================================================================================
7280 /*!
7281  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7282  */
7283 //================================================================================
7284
7285 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
7286                                                SMESH_MesherHelper& helper,
7287                                                const int           nbSteps,
7288                                                const double        stepSize )
7289 {
7290   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7291     return true; // no shapes needing smoothing
7292
7293   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7294   {
7295     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7296     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
7297          !eos._hyp.ToSmooth() ||
7298          eos.ShapeType() != TopAbs_FACE ||
7299          eos._edges.empty() )
7300       continue;
7301
7302     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7303     if ( !toSmooth ) continue;
7304
7305     for ( size_t i = 0; i < eos._edges.size(); ++i )
7306     {
7307       _LayerEdge* edge = eos._edges[i];
7308       if ( !edge->Is( _LayerEdge::SMOOTHED ))
7309         continue;
7310       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7311         continue;
7312
7313       const gp_XYZ& pPrev = edge->PrevPos();
7314       const gp_XYZ& pLast = edge->_pos.back();
7315       gp_XYZ      stepVec = pLast - pPrev;
7316       double realStepSize = stepVec.Modulus();
7317       if ( realStepSize < numeric_limits<double>::min() )
7318         continue;
7319
7320       edge->_lenFactor = realStepSize / stepSize;
7321       edge->_normal    = stepVec / realStepSize;
7322       edge->Set( _LayerEdge::NORMAL_UPDATED );
7323     }
7324   }
7325
7326   return true;
7327 }
7328
7329 //================================================================================
7330 /*!
7331  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7332  */
7333 //================================================================================
7334
7335 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7336 {
7337   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7338   {
7339     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7340     if ( eov._eosC1.empty() ||
7341          eov.ShapeType() != TopAbs_VERTEX ||
7342          eov._edges.empty() )
7343       continue;
7344
7345     gp_XYZ newNorm   = eov._edges[0]->_normal;
7346     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7347     bool normChanged = false;
7348
7349     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7350     {
7351       _EdgesOnShape*   eoe = eov._eosC1[i];
7352       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7353       const double    eLen = SMESH_Algo::EdgeLength( e );
7354       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
7355       if ( oppV.IsSame( eov._shape ))
7356         oppV = SMESH_MesherHelper::IthVertex( 1, e );
7357       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7358       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7359       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7360
7361       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7362       if ( curThickOpp + curThick < eLen )
7363         continue;
7364
7365       double wgt = 2. * curThick / eLen;
7366       newNorm += wgt * eovOpp->_edges[0]->_normal;
7367       normChanged = true;
7368     }
7369     if ( normChanged )
7370     {
7371       eov._edges[0]->SetNormal( newNorm.Normalized() );
7372       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7373     }
7374   }
7375 }
7376
7377 //================================================================================
7378 /*!
7379  * \brief Modify normals of _LayerEdge's on _ConvexFace's
7380  */
7381 //================================================================================
7382
7383 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
7384                                                   SMESH_MesherHelper& helper,
7385                                                   int                 stepNb )
7386 {
7387   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7388   bool isOK;
7389
7390   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7391   for ( ; id2face != data._convexFaces.end(); ++id2face )
7392   {
7393     _ConvexFace & convFace = (*id2face).second;
7394     convFace._normalsFixedOnBorders = false; // to update at each inflation step
7395
7396     if ( convFace._normalsFixed )
7397       continue; // already fixed
7398     if ( convFace.CheckPrisms() )
7399       continue; // nothing to fix
7400
7401     convFace._normalsFixed = true;
7402
7403     BRepAdaptor_Surface surface ( convFace._face, false );
7404     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
7405
7406     // check if the convex FACE is of spherical shape
7407
7408     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7409     Bnd_B3d nodesBox;
7410     gp_Pnt  center;
7411
7412     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7413     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7414     {
7415       _EdgesOnShape& eos = *(id2eos->second);
7416       if ( eos.ShapeType() == TopAbs_VERTEX )
7417       {
7418         _LayerEdge* ledge = eos._edges[ 0 ];
7419         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7420           centersBox.Add( center );
7421       }
7422       for ( size_t i = 0; i < eos._edges.size(); ++i )
7423         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7424     }
7425     if ( centersBox.IsVoid() )
7426     {
7427       debugMsg( "Error: centersBox.IsVoid()" );
7428       return false;
7429     }
7430     const bool isSpherical =
7431       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7432
7433     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7434     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7435
7436     if ( isSpherical )
7437     {
7438       // set _LayerEdge::_normal as average of all normals
7439
7440       // WARNING: different density of nodes on EDGEs is not taken into account that
7441       // can lead to an improper new normal
7442
7443       gp_XYZ avgNormal( 0,0,0 );
7444       nbEdges = 0;
7445       id2eos = convFace._subIdToEOS.begin();
7446       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7447       {
7448         _EdgesOnShape& eos = *(id2eos->second);
7449         // set data of _CentralCurveOnEdge
7450         if ( eos.ShapeType() == TopAbs_EDGE )
7451         {
7452           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7453           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7454           if ( !eos._sWOL.IsNull() )
7455             ceCurve._adjFace.Nullify();
7456           else
7457             ceCurve._ledges.insert( ceCurve._ledges.end(),
7458                                     eos._edges.begin(), eos._edges.end());
7459         }
7460         // summarize normals
7461         for ( size_t i = 0; i < eos._edges.size(); ++i )
7462           avgNormal += eos._edges[ i ]->_normal;
7463       }
7464       double normSize = avgNormal.SquareModulus();
7465       if ( normSize < 1e-200 )
7466       {
7467         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7468         return false;
7469       }
7470       avgNormal /= Sqrt( normSize );
7471
7472       // compute new _LayerEdge::_cosin on EDGEs
7473       double avgCosin = 0;
7474       int     nbCosin = 0;
7475       gp_Vec inFaceDir;
7476       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7477       {
7478         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7479         if ( ceCurve._adjFace.IsNull() )
7480           continue;
7481         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7482         {
7483           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7484           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7485           if ( isOK )
7486           {
7487             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7488             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7489             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7490             nbCosin++;
7491           }
7492         }
7493       }
7494       if ( nbCosin > 0 )
7495         avgCosin /= nbCosin;
7496
7497       // set _LayerEdge::_normal = avgNormal
7498       id2eos = convFace._subIdToEOS.begin();
7499       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7500       {
7501         _EdgesOnShape& eos = *(id2eos->second);
7502         if ( eos.ShapeType() != TopAbs_EDGE )
7503           for ( size_t i = 0; i < eos._edges.size(); ++i )
7504             eos._edges[ i ]->_cosin = avgCosin;
7505
7506         for ( size_t i = 0; i < eos._edges.size(); ++i )
7507         {
7508           eos._edges[ i ]->SetNormal( avgNormal );
7509           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7510         }
7511       }
7512     }
7513     else // if ( isSpherical )
7514     {
7515       // We suppose that centers of curvature at all points of the FACE
7516       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7517       // having a common center of curvature we define the same new normal
7518       // as a sum of normals of _LayerEdge's on EDGEs among them.
7519
7520       // get all centers of curvature for each EDGE
7521
7522       helper.SetSubShape( convFace._face );
7523       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7524
7525       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7526       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7527       {
7528         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7529
7530         // set adjacent FACE
7531         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7532
7533         // get _LayerEdge's of the EDGE
7534         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7535         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7536         if ( !eos || eos->_edges.empty() )
7537         {
7538           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7539           for ( int iV = 0; iV < 2; ++iV )
7540           {
7541             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7542             TGeomID     vID = meshDS->ShapeToIndex( v );
7543             eos = data.GetShapeEdges( vID );
7544             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7545           }
7546           edgeLEdge    = &vertexLEdges[0];
7547           edgeLEdgeEnd = edgeLEdge + 2;
7548
7549           centerCurves[ iE ]._adjFace.Nullify();
7550         }
7551         else
7552         {
7553           if ( ! eos->_toSmooth )
7554             data.SortOnEdge( edge, eos->_edges );
7555           edgeLEdge    = &eos->_edges[ 0 ];
7556           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7557           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7558           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7559
7560           if ( ! eos->_sWOL.IsNull() )
7561             centerCurves[ iE ]._adjFace.Nullify();
7562         }
7563
7564         // Get curvature centers
7565
7566         centersBox.Clear();
7567
7568         if ( edgeLEdge[0]->IsOnEdge() &&
7569              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7570         { // 1st VERTEX
7571           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7572           centersBox.Add( center );
7573         }
7574         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7575           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7576           { // EDGE or VERTEXes
7577             centerCurves[ iE ].Append( center, *edgeLEdge );
7578             centersBox.Add( center );
7579           }
7580         if ( edgeLEdge[-1]->IsOnEdge() &&
7581              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7582         { // 2nd VERTEX
7583           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7584           centersBox.Add( center );
7585         }
7586         centerCurves[ iE ]._isDegenerated =
7587           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7588
7589       } // loop on EDGES of convFace._face to set up data of centerCurves
7590
7591       // Compute new normals for _LayerEdge's on EDGEs
7592
7593       double avgCosin = 0;
7594       int     nbCosin = 0;
7595       gp_Vec inFaceDir;
7596       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7597       {
7598         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7599         if ( ceCurve._isDegenerated )
7600           continue;
7601         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7602         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7603         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7604         {
7605           isOK = false;
7606           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7607           {
7608             if ( iE1 != iE2 )
7609               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7610           }
7611           if ( isOK && !ceCurve._adjFace.IsNull() )
7612           {
7613             // compute new _LayerEdge::_cosin
7614             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7615             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7616             if ( isOK )
7617             {
7618               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7619               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7620               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7621               nbCosin++;
7622             }
7623           }
7624         }
7625       }
7626       // set new normals to _LayerEdge's of NOT degenerated central curves
7627       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7628       {
7629         if ( centerCurves[ iE ]._isDegenerated )
7630           continue;
7631         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7632         {
7633           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7634           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7635         }
7636       }
7637       // set new normals to _LayerEdge's of     degenerated central curves
7638       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7639       {
7640         if ( !centerCurves[ iE ]._isDegenerated ||
7641              centerCurves[ iE ]._ledges.size() < 3 )
7642           continue;
7643         // new normal is an average of new normals at VERTEXes that
7644         // was computed on non-degenerated _CentralCurveOnEdge's
7645         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7646                            centerCurves[ iE ]._ledges.back ()->_normal );
7647         double sz = newNorm.Modulus();
7648         if ( sz < 1e-200 )
7649           continue;
7650         newNorm /= sz;
7651         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7652                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7653         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7654         {
7655           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7656           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7657           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7658         }
7659       }
7660
7661       // Find new normals for _LayerEdge's based on FACE
7662
7663       if ( nbCosin > 0 )
7664         avgCosin /= nbCosin;
7665       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7666       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7667       if ( id2eos != convFace._subIdToEOS.end() )
7668       {
7669         int iE = 0;
7670         gp_XYZ newNorm;
7671         _EdgesOnShape& eos = * ( id2eos->second );
7672         for ( size_t i = 0; i < eos._edges.size(); ++i )
7673         {
7674           _LayerEdge* ledge = eos._edges[ i ];
7675           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7676             continue;
7677           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7678           {
7679             iE = iE % centerCurves.size();
7680             if ( centerCurves[ iE ]._isDegenerated )
7681               continue;
7682             newNorm.SetCoord( 0,0,0 );
7683             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7684             {
7685               ledge->SetNormal( newNorm );
7686               ledge->_cosin  = avgCosin;
7687               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7688               break;
7689             }
7690           }
7691         }
7692       }
7693
7694     } // not a quasi-spherical FACE
7695
7696     // Update _LayerEdge's data according to a new normal
7697
7698     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7699                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7700
7701     id2eos = convFace._subIdToEOS.begin();
7702     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7703     {
7704       _EdgesOnShape& eos = * ( id2eos->second );
7705       for ( size_t i = 0; i < eos._edges.size(); ++i )
7706       {
7707         _LayerEdge* & ledge = eos._edges[ i ];
7708         double len = ledge->_len;
7709         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7710         ledge->SetCosin( ledge->_cosin );
7711         ledge->SetNewLength( len, eos, helper );
7712       }
7713       if ( eos.ShapeType() != TopAbs_FACE )
7714         for ( size_t i = 0; i < eos._edges.size(); ++i )
7715         {
7716           _LayerEdge* ledge = eos._edges[ i ];
7717           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7718           {
7719             _LayerEdge* neibor = ledge->_neibors[iN];
7720             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7721             {
7722               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7723               neibor->Set( _LayerEdge::MOVED );
7724               neibor->SetSmooLen( neibor->_len );
7725             }
7726           }
7727         }
7728     } // loop on sub-shapes of convFace._face
7729
7730     // Find FACEs adjacent to convFace._face that got necessity to smooth
7731     // as a result of normals modification
7732
7733     set< _EdgesOnShape* > adjFacesToSmooth;
7734     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7735     {
7736       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7737            centerCurves[ iE ]._adjFaceToSmooth )
7738         continue;
7739       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7740       {
7741         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7742         {
7743           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7744           break;
7745         }
7746       }
7747     }
7748     data.AddShapesToSmooth( adjFacesToSmooth );
7749
7750     dumpFunctionEnd();
7751
7752
7753   } // loop on data._convexFaces
7754
7755   return true;
7756 }
7757
7758 //================================================================================
7759 /*!
7760  * \brief Return max curvature of a FACE
7761  */
7762 //================================================================================
7763
7764 double _ConvexFace::GetMaxCurvature( _SolidData&         data,
7765                                      _EdgesOnShape&      eof,
7766                                      BRepLProp_SLProps&  surfProp,
7767                                      SMESH_MesherHelper& helper)
7768 {
7769   double maxCurvature = 0;
7770
7771   TopoDS_Face F = TopoDS::Face( eof._shape );
7772
7773   const int           nbTestPnt = 5;
7774   const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7775   SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7776   while ( smIt->more() )
7777   {
7778     SMESH_subMesh* sm = smIt->next();
7779     const TGeomID subID = sm->GetId();
7780
7781     // find _LayerEdge's of a sub-shape
7782     _EdgesOnShape* eos;
7783     if (( eos = data.GetShapeEdges( subID )))
7784       this->_subIdToEOS.insert( make_pair( subID, eos ));
7785     else
7786       continue;
7787
7788     // check concavity and curvature and limit data._stepSize
7789     const double minCurvature =
7790       1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7791     size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7792     for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7793     {
7794       gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7795       surfProp.SetParameters( uv.X(), uv.Y() );
7796       if ( surfProp.IsCurvatureDefined() )
7797       {
7798         double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7799                                 surfProp.MinCurvature() * oriFactor );
7800         maxCurvature = Max( maxCurvature, curvature );
7801
7802         if ( curvature > minCurvature )
7803           this->_isTooCurved = true;
7804       }
7805     }
7806   } // loop on sub-shapes of the FACE
7807
7808   return maxCurvature;
7809 }
7810
7811 //================================================================================
7812 /*!
7813  * \brief Finds a center of curvature of a surface at a _LayerEdge
7814  */
7815 //================================================================================
7816
7817 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7818                                         BRepLProp_SLProps&  surfProp,
7819                                         SMESH_MesherHelper& helper,
7820                                         gp_Pnt &            center ) const
7821 {
7822   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7823   surfProp.SetParameters( uv.X(), uv.Y() );
7824   if ( !surfProp.IsCurvatureDefined() )
7825     return false;
7826
7827   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7828   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7829   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7830   if ( surfCurvatureMin > surfCurvatureMax )
7831     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7832   else
7833     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7834
7835   return true;
7836 }
7837
7838 //================================================================================
7839 /*!
7840  * \brief Check that prisms are not distorted
7841  */
7842 //================================================================================
7843
7844 bool _ConvexFace::CheckPrisms() const
7845 {
7846   double vol = 0;
7847   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7848   {
7849     const _LayerEdge* edge = _simplexTestEdges[i];
7850     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7851     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7852       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7853       {
7854         debugMsg( "Bad simplex of _simplexTestEdges ("
7855                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7856                   << " "<< edge->_simplices[j]._nPrev->GetID()
7857                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7858         return false;
7859       }
7860   }
7861   return true;
7862 }
7863
7864 //================================================================================
7865 /*!
7866  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7867  *        stored in this _CentralCurveOnEdge.
7868  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7869  *  \param [in,out] newNormal - current normal at this point, to be redefined
7870  *  \return bool - true if succeeded.
7871  */
7872 //================================================================================
7873
7874 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7875 {
7876   if ( this->_isDegenerated )
7877     return false;
7878
7879   // find two centers the given one lies between
7880
7881   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7882   {
7883     double sl2 = 1.001 * _segLength2[ i ];
7884
7885     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7886     if ( d1 > sl2 )
7887       continue;
7888     
7889     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7890     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7891       continue;
7892
7893     d1 = Sqrt( d1 );
7894     d2 = Sqrt( d2 );
7895     double r = d1 / ( d1 + d2 );
7896     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7897                    (      r ) * _ledges[ i+1 ]->_normal );
7898     norm.Normalize();
7899
7900     newNormal += norm;
7901     double sz = newNormal.Modulus();
7902     if ( sz < 1e-200 )
7903       break;
7904     newNormal /= sz;
7905     return true;
7906   }
7907   return false;
7908 }
7909
7910 //================================================================================
7911 /*!
7912  * \brief Set shape members
7913  */
7914 //================================================================================
7915
7916 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7917                                      const _ConvexFace&  convFace,
7918                                      _SolidData&         data,
7919                                      SMESH_MesherHelper& helper)
7920 {
7921   _edge = edge;
7922
7923   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7924   while ( const TopoDS_Shape* F = fIt->next())
7925     if ( !convFace._face.IsSame( *F ))
7926     {
7927       _adjFace = TopoDS::Face( *F );
7928       _adjFaceToSmooth = false;
7929       // _adjFace already in a smoothing queue ?
7930       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7931         _adjFaceToSmooth = eos->_toSmooth;
7932       break;
7933     }
7934 }
7935
7936 //================================================================================
7937 /*!
7938  * \brief Looks for intersection of it's last segment with faces
7939  *  \param distance - returns shortest distance from the last node to intersection
7940  */
7941 //================================================================================
7942
7943 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7944                                    double &                 distance,
7945                                    const double&            epsilon,
7946                                    _EdgesOnShape&           eos,
7947                                    const SMDS_MeshElement** intFace)
7948 {
7949   vector< const SMDS_MeshElement* > suspectFaces;
7950   double segLen;
7951   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7952   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7953
7954   bool segmentIntersected = false;
7955   distance = Precision::Infinite();
7956   int iFace = -1; // intersected face
7957   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7958   {
7959     const SMDS_MeshElement* face = suspectFaces[j];
7960     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7961          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7962       continue; // face sharing _LayerEdge node
7963     const int nbNodes = face->NbCornerNodes();
7964     bool intFound = false;
7965     double dist;
7966     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7967     if ( nbNodes == 3 )
7968     {
7969       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7970     }
7971     else
7972     {
7973       const SMDS_MeshNode* tria[3];
7974       tria[0] = *nIt++;
7975       tria[1] = *nIt++;
7976       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7977       {
7978         tria[2] = *nIt++;
7979         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7980         tria[1] = tria[2];
7981       }
7982     }
7983     if ( intFound )
7984     {
7985       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7986         segmentIntersected = true;
7987       if ( distance > dist )
7988         distance = dist, iFace = j;
7989     }
7990   }
7991   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7992
7993   distance -= segLen;
7994
7995   if ( segmentIntersected )
7996   {
7997 #ifdef __myDEBUG
7998     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7999     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8000     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8001          << ", intersection with face ("
8002          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8003          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8004          << ") distance = " << distance << endl;
8005 #endif
8006   }
8007
8008   return segmentIntersected;
8009 }
8010
8011 //================================================================================
8012 /*!
8013  * \brief Returns a point used to check orientation of _simplices
8014  */
8015 //================================================================================
8016
8017 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8018 {
8019   size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8020
8021   if ( !eos || eos->_sWOL.IsNull() )
8022     return _pos[ i ];
8023
8024   if ( eos->SWOLType() == TopAbs_EDGE )
8025   {
8026     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8027   }
8028   //else //  TopAbs_FACE
8029
8030   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8031 }
8032
8033 //================================================================================
8034 /*!
8035  * \brief Returns size and direction of the last segment
8036  */
8037 //================================================================================
8038
8039 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8040 {
8041   // find two non-coincident positions
8042   gp_XYZ orig = _pos.back();
8043   gp_XYZ vec;
8044   int iPrev = _pos.size() - 2;
8045   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8046   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8047   while ( iPrev >= 0 )
8048   {
8049     vec = orig - _pos[iPrev];
8050     if ( vec.SquareModulus() > tol*tol )
8051       break;
8052     else
8053       iPrev--;
8054   }
8055
8056   // make gp_Ax1
8057   gp_Ax1 segDir;
8058   if ( iPrev < 0 )
8059   {
8060     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8061     segDir.SetDirection( _normal );
8062     segLen = 0;
8063   }
8064   else
8065   {
8066     gp_Pnt pPrev = _pos[ iPrev ];
8067     if ( !eos._sWOL.IsNull() )
8068     {
8069       TopLoc_Location loc;
8070       if ( eos.SWOLType() == TopAbs_EDGE )
8071       {
8072         double f,l;
8073         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8074         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8075       }
8076       else
8077       {
8078         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8079         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8080       }
8081       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8082     }
8083     segDir.SetLocation( pPrev );
8084     segDir.SetDirection( vec );
8085     segLen = vec.Modulus();
8086   }
8087
8088   return segDir;
8089 }
8090
8091 //================================================================================
8092 /*!
8093  * \brief Return the last (or \a which) position of the target node on a FACE. 
8094  *  \param [in] F - the FACE this _LayerEdge is inflated along
8095  *  \param [in] which - index of position
8096  *  \return gp_XY - result UV
8097  */
8098 //================================================================================
8099
8100 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8101 {
8102   if ( F.IsSame( eos._sWOL )) // F is my FACE
8103     return gp_XY( _pos.back().X(), _pos.back().Y() );
8104
8105   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8106     return gp_XY( 1e100, 1e100 );
8107
8108   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8109   double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8110   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8111   if ( !C2d.IsNull() && f <= u && u <= l )
8112     return C2d->Value( u ).XY();
8113
8114   return gp_XY( 1e100, 1e100 );
8115 }
8116
8117 //================================================================================
8118 /*!
8119  * \brief Test intersection of the last segment with a given triangle
8120  *   using Moller-Trumbore algorithm
8121  * Intersection is detected if distance to intersection is less than _LayerEdge._len
8122  */
8123 //================================================================================
8124
8125 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8126                                const gp_XYZ& vert0,
8127                                const gp_XYZ& vert1,
8128                                const gp_XYZ& vert2,
8129                                double&       t,
8130                                const double& EPSILON) const
8131 {
8132   const gp_Pnt& orig = lastSegment.Location();
8133   const gp_Dir& dir  = lastSegment.Direction();
8134
8135   /* calculate distance from vert0 to ray origin */
8136   //gp_XYZ tvec = orig.XYZ() - vert0;
8137
8138   //if ( tvec * dir > EPSILON )
8139     // intersected face is at back side of the temporary face this _LayerEdge belongs to
8140     //return false;
8141
8142   gp_XYZ edge1 = vert1 - vert0;
8143   gp_XYZ edge2 = vert2 - vert0;
8144
8145   /* begin calculating determinant - also used to calculate U parameter */
8146   gp_XYZ pvec = dir.XYZ() ^ edge2;
8147
8148   /* if determinant is near zero, ray lies in plane of triangle */
8149   double det = edge1 * pvec;
8150
8151   const double ANGL_EPSILON = 1e-12;
8152   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8153     return false;
8154
8155   /* calculate distance from vert0 to ray origin */
8156   gp_XYZ tvec = orig.XYZ() - vert0;
8157
8158   /* calculate U parameter and test bounds */
8159   double u = ( tvec * pvec ) / det;
8160   //if (u < 0.0 || u > 1.0)
8161   if ( u < -EPSILON || u > 1.0 + EPSILON )
8162     return false;
8163
8164   /* prepare to test V parameter */
8165   gp_XYZ qvec = tvec ^ edge1;
8166
8167   /* calculate V parameter and test bounds */
8168   double v = (dir.XYZ() * qvec) / det;
8169   //if ( v < 0.0 || u + v > 1.0 )
8170   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8171     return false;
8172
8173   /* calculate t, ray intersects triangle */
8174   t = (edge2 * qvec) / det;
8175
8176   //return true;
8177   return t > 0.;
8178 }
8179
8180 //================================================================================
8181 /*!
8182  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8183  *        neighbor _LayerEdge's by it's own inflation vector.
8184  *  \param [in] eov - EOS of the VERTEX
8185  *  \param [in] eos - EOS of the FACE
8186  *  \param [in] step - inflation step
8187  *  \param [in,out] badSmooEdges - tangled _LayerEdge's
8188  */
8189 //================================================================================
8190
8191 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
8192                                    const _EdgesOnShape*    eos,
8193                                    const int               step,
8194                                    vector< _LayerEdge* > & badSmooEdges )
8195 {
8196   // check if any of _neibors is in badSmooEdges
8197   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8198                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8199     return;
8200
8201   // get all edges to move
8202
8203   set< _LayerEdge* > edges;
8204
8205   // find a distance between _LayerEdge on VERTEX and its neighbors
8206   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
8207   double dist2 = 0;
8208   for ( size_t i = 0; i < _neibors.size(); ++i )
8209   {
8210     _LayerEdge* nEdge = _neibors[i];
8211     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8212     {
8213       edges.insert( nEdge );
8214       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8215     }
8216   }
8217   // add _LayerEdge's close to curPosV
8218   size_t nbE;
8219   do {
8220     nbE = edges.size();
8221     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8222     {
8223       _LayerEdge* edgeF = *e;
8224       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8225       {
8226         _LayerEdge* nEdge = edgeF->_neibors[i];
8227         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8228              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8229           edges.insert( nEdge );
8230       }
8231     }
8232   }
8233   while ( nbE < edges.size() );
8234
8235   // move the target node of the got edges
8236
8237   gp_XYZ prevPosV = PrevPos();
8238   if ( eov->SWOLType() == TopAbs_EDGE )
8239   {
8240     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8241     prevPosV = curve.Value( prevPosV.X() ).XYZ();
8242   }
8243   else if ( eov->SWOLType() == TopAbs_FACE )
8244   {
8245     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8246     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8247   }
8248
8249   SMDS_FacePosition* fPos;
8250   //double r = 1. - Min( 0.9, step / 10. );
8251   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8252   {
8253     _LayerEdge*       edgeF = *e;
8254     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
8255     const gp_XYZ    newPosF = curPosV + prevVF;
8256     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8257     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8258     edgeF->_pos.back() = newPosF;
8259     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8260
8261     // set _curvature to make edgeF updated by putOnOffsetSurface()
8262     if ( !edgeF->_curvature )
8263       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
8264       {
8265         edgeF->_curvature = new _Curvature;
8266         edgeF->_curvature->_r = 0;
8267         edgeF->_curvature->_k = 0;
8268         edgeF->_curvature->_h2lenRatio = 0;
8269         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8270       }
8271   }
8272   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8273   //                      SMESH_TNodeXYZ( _nodes[0]    ));
8274   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8275   // {
8276   //   _LayerEdge*      edgeF = *e;
8277   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8278   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8279   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8280   //   edgeF->_pos.back() = newPosF;
8281   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8282   // }
8283
8284   // smooth _LayerEdge's around moved nodes
8285   //size_t nbBadBefore = badSmooEdges.size();
8286   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8287   {
8288     _LayerEdge* edgeF = *e;
8289     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8290       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8291         //&& !edges.count( edgeF->_neibors[j] ))
8292       {
8293         _LayerEdge* edgeFN = edgeF->_neibors[j];
8294         edgeFN->Unset( SMOOTHED );
8295         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8296         // if ( nbBad > 0 )
8297         // {
8298         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8299         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8300         //   int        nbBadAfter = edgeFN->_simplices.size();
8301         //   double vol;
8302         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8303         //   {
8304         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8305         //   }
8306         //   if ( nbBadAfter <= nbBad )
8307         //   {
8308         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8309         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8310         //     edgeF->_pos.back() = newPosF;
8311         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8312         //     nbBad = nbBadAfter;
8313         //   }
8314         // }
8315         if ( nbBad > 0 )
8316           badSmooEdges.push_back( edgeFN );
8317       }
8318   }
8319     // move a bit not smoothed around moved nodes
8320   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8321   //   {
8322   //   _LayerEdge*      edgeF = badSmooEdges[i];
8323   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8324   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8325   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8326   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8327   //   edgeF->_pos.back() = newPosF;
8328   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8329   // }
8330 }
8331
8332 //================================================================================
8333 /*!
8334  * \brief Perform smooth of _LayerEdge's based on EDGE's
8335  *  \retval bool - true if node has been moved
8336  */
8337 //================================================================================
8338
8339 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8340                               const TopoDS_Face&             F,
8341                               SMESH_MesherHelper&            helper)
8342 {
8343   ASSERT( IsOnEdge() );
8344
8345   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8346   SMESH_TNodeXYZ oldPos( tgtNode );
8347   double dist01, distNewOld;
8348   
8349   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8350   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8351   dist01 = p0.Distance( _2neibors->tgtNode(1) );
8352
8353   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8354   double lenDelta = 0;
8355   if ( _curvature )
8356   {
8357     //lenDelta = _curvature->lenDelta( _len );
8358     lenDelta = _curvature->lenDeltaByDist( dist01 );
8359     newPos.ChangeCoord() += _normal * lenDelta;
8360   }
8361
8362   distNewOld = newPos.Distance( oldPos );
8363
8364   if ( F.IsNull() )
8365   {
8366     if ( _2neibors->_plnNorm )
8367     {
8368       // put newPos on the plane defined by source node and _plnNorm
8369       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8370       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8371       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8372     }
8373     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8374     _pos.back() = newPos.XYZ();
8375   }
8376   else
8377   {
8378     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8379     gp_XY uv( Precision::Infinite(), 0 );
8380     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8381     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8382
8383     newPos = surface->Value( uv );
8384     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8385   }
8386
8387   // commented for IPAL0052478
8388   // if ( _curvature && lenDelta < 0 )
8389   // {
8390   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8391   //   _len -= prevPos.Distance( oldPos );
8392   //   _len += prevPos.Distance( newPos );
8393   // }
8394   bool moved = distNewOld > dist01/50;
8395   //if ( moved )
8396   dumpMove( tgtNode ); // debug
8397
8398   return moved;
8399 }
8400
8401 //================================================================================
8402 /*!
8403  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8404  */
8405 //================================================================================
8406
8407 void _LayerEdge::SmoothWoCheck()
8408 {
8409   if ( Is( DIFFICULT ))
8410     return;
8411
8412   bool moved = Is( SMOOTHED );
8413   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
8414     moved = _neibors[i]->Is( SMOOTHED );
8415   if ( !moved )
8416     return;
8417
8418   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8419
8420   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8421   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8422   _pos.back() = newPos;
8423
8424   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8425 }
8426
8427 //================================================================================
8428 /*!
8429  * \brief Checks validity of _neibors on EDGEs and VERTEXes
8430  */
8431 //================================================================================
8432
8433 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8434 {
8435   if ( ! Is( NEAR_BOUNDARY ))
8436     return 0;
8437
8438   int nbBad = 0;
8439   double vol;
8440   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8441   {
8442     _LayerEdge* eN = _neibors[iN];
8443     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8444       continue;
8445     if ( needSmooth )
8446       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8447                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8448                        eN->_pos.size() != _pos.size() );
8449
8450     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8451     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8452     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8453       if ( eN->_nodes.size() > 1 &&
8454            eN->_simplices[i].Includes( _nodes.back() ) &&
8455            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8456       {
8457         ++nbBad;
8458         if ( badNeibors )
8459         {
8460           badNeibors->push_back( eN );
8461           debugMsg("Bad boundary simplex ( "
8462                    << " "<< eN->_nodes[0]->GetID()
8463                    << " "<< eN->_nodes.back()->GetID()
8464                    << " "<< eN->_simplices[i]._nPrev->GetID()
8465                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8466         }
8467         else
8468         {
8469           break;
8470         }
8471       }
8472   }
8473   return nbBad;
8474 }
8475
8476 //================================================================================
8477 /*!
8478  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8479  *  \retval int - nb of bad simplices around this _LayerEdge
8480  */
8481 //================================================================================
8482
8483 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8484 {
8485   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8486     return 0; // shape of simplices not changed
8487   if ( _simplices.size() < 2 )
8488     return 0; // _LayerEdge inflated along EDGE or FACE
8489
8490   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8491     findBest = true;
8492
8493   const gp_XYZ& curPos  = _pos.back();
8494   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8495
8496   // quality metrics (orientation) of tetras around _tgtNode
8497   int nbOkBefore = 0;
8498   double vol, minVolBefore = 1e100;
8499   for ( size_t i = 0; i < _simplices.size(); ++i )
8500   {
8501     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8502     minVolBefore = Min( minVolBefore, vol );
8503   }
8504   int nbBad = _simplices.size() - nbOkBefore;
8505
8506   bool bndNeedSmooth = false;
8507   if ( nbBad == 0 )
8508     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8509   if ( nbBad > 0 )
8510     Set( DISTORTED );
8511
8512   // evaluate min angle
8513   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8514   {
8515     size_t nbGoodAngles = _simplices.size();
8516     double angle;
8517     for ( size_t i = 0; i < _simplices.size(); ++i )
8518     {
8519       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8520         --nbGoodAngles;
8521     }
8522     if ( nbGoodAngles == _simplices.size() )
8523     {
8524       Unset( MOVED );
8525       return 0;
8526     }
8527   }
8528   if ( Is( ON_CONCAVE_FACE ))
8529     findBest = true;
8530
8531   if ( step % 2 == 0 )
8532     findBest = false;
8533
8534   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8535   {
8536     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8537       _smooFunction = _funs[ FUN_CENTROIDAL ];
8538     else
8539       _smooFunction = _funs[ FUN_LAPLACIAN ];
8540   }
8541
8542   // compute new position for the last _pos using different _funs
8543   gp_XYZ newPos;
8544   bool moved = false;
8545   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8546   {
8547     if ( iFun < 0 )
8548       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8549     else if ( _funs[ iFun ] == _smooFunction )
8550       continue; // _smooFunction again
8551     else if ( step > 1 )
8552       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8553     else
8554       break; // let "easy" functions improve elements around distorted ones
8555
8556     if ( _curvature )
8557     {
8558       double delta  = _curvature->lenDelta( _len );
8559       if ( delta > 0 )
8560         newPos += _normal * delta;
8561       else
8562       {
8563         double segLen = _normal * ( newPos - prevPos );
8564         if ( segLen + delta > 0 )
8565           newPos += _normal * delta;
8566       }
8567       // double segLenChange = _normal * ( curPos - newPos );
8568       // newPos += 0.5 * _normal * segLenChange;
8569     }
8570
8571     int nbOkAfter = 0;
8572     double minVolAfter = 1e100;
8573     for ( size_t i = 0; i < _simplices.size(); ++i )
8574     {
8575       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8576       minVolAfter = Min( minVolAfter, vol );
8577     }
8578     // get worse?
8579     if ( nbOkAfter < nbOkBefore )
8580       continue;
8581
8582     if (( findBest ) &&
8583         ( nbOkAfter == nbOkBefore ) &&
8584         ( minVolAfter <= minVolBefore ))
8585       continue;
8586
8587     nbBad        = _simplices.size() - nbOkAfter;
8588     minVolBefore = minVolAfter;
8589     nbOkBefore   = nbOkAfter;
8590     moved        = true;
8591
8592     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8593     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8594     _pos.back() = newPos;
8595
8596     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8597                   << (nbBad ? " --BAD" : ""));
8598
8599     if ( iFun > -1 )
8600     {
8601       continue; // look for a better function
8602     }
8603
8604     if ( !findBest )
8605       break;
8606
8607   } // loop on smoothing functions
8608
8609   if ( moved ) // notify _neibors
8610   {
8611     Set( SMOOTHED );
8612     for ( size_t i = 0; i < _neibors.size(); ++i )
8613       if ( !_neibors[i]->Is( MOVED ))
8614       {
8615         _neibors[i]->Set( MOVED );
8616         toSmooth.push_back( _neibors[i] );
8617       }
8618   }
8619
8620   return nbBad;
8621 }
8622
8623 //================================================================================
8624 /*!
8625  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8626  *  \retval int - nb of bad simplices around this _LayerEdge
8627  */
8628 //================================================================================
8629
8630 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8631 {
8632   if ( !_smooFunction )
8633     return 0; // _LayerEdge inflated along EDGE or FACE
8634   if ( Is( BLOCKED ))
8635     return 0; // not inflated
8636
8637   const gp_XYZ& curPos  = _pos.back();
8638   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8639
8640   // quality metrics (orientation) of tetras around _tgtNode
8641   int nbOkBefore = 0;
8642   double vol, minVolBefore = 1e100;
8643   for ( size_t i = 0; i < _simplices.size(); ++i )
8644   {
8645     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8646     minVolBefore = Min( minVolBefore, vol );
8647   }
8648   int nbBad = _simplices.size() - nbOkBefore;
8649
8650   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8651   {
8652     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8653       _smooFunction = _funs[ FUN_LAPLACIAN ];
8654     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8655       _smooFunction = _funs[ FUN_CENTROIDAL ];
8656   }
8657
8658   // compute new position for the last _pos using different _funs
8659   gp_XYZ newPos;
8660   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8661   {
8662     if ( iFun < 0 )
8663       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8664     else if ( _funs[ iFun ] == _smooFunction )
8665       continue; // _smooFunction again
8666     else if ( step > 1 )
8667       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8668     else
8669       break; // let "easy" functions improve elements around distorted ones
8670
8671     if ( _curvature )
8672     {
8673       double delta  = _curvature->lenDelta( _len );
8674       if ( delta > 0 )
8675         newPos += _normal * delta;
8676       else
8677       {
8678         double segLen = _normal * ( newPos - prevPos );
8679         if ( segLen + delta > 0 )
8680           newPos += _normal * delta;
8681       }
8682       // double segLenChange = _normal * ( curPos - newPos );
8683       // newPos += 0.5 * _normal * segLenChange;
8684     }
8685
8686     int nbOkAfter = 0;
8687     double minVolAfter = 1e100;
8688     for ( size_t i = 0; i < _simplices.size(); ++i )
8689     {
8690       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8691       minVolAfter = Min( minVolAfter, vol );
8692     }
8693     // get worse?
8694     if ( nbOkAfter < nbOkBefore )
8695       continue;
8696     if (( isConcaveFace || findBest ) &&
8697         ( nbOkAfter == nbOkBefore ) &&
8698         ( minVolAfter <= minVolBefore )
8699         )
8700       continue;
8701
8702     nbBad        = _simplices.size() - nbOkAfter;
8703     minVolBefore = minVolAfter;
8704     nbOkBefore   = nbOkAfter;
8705
8706     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8707     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8708     _pos.back() = newPos;
8709
8710     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8711                   << ( nbBad ? "--BAD" : ""));
8712
8713     // commented for IPAL0052478
8714     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8715     // _len += prevPos.Distance(newPos);
8716
8717     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8718     {
8719       //_smooFunction = _funs[ iFun ];
8720       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8721       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8722       // << " minVol: " << minVolAfter
8723       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8724       // << endl;
8725       continue; // look for a better function
8726     }
8727
8728     if ( !findBest )
8729       break;
8730
8731   } // loop on smoothing functions
8732
8733   return nbBad;
8734 }
8735
8736 //================================================================================
8737 /*!
8738  * \brief Chooses a smoothing technic giving a position most close to an initial one.
8739  *        For a correct result, _simplices must contain nodes lying on geometry.
8740  */
8741 //================================================================================
8742
8743 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8744                                      const TNode2Edge&     n2eMap)
8745 {
8746   if ( _smooFunction ) return;
8747
8748   // use smoothNefPolygon() near concaveVertices
8749   if ( !concaveVertices.empty() )
8750   {
8751     _smooFunction = _funs[ FUN_CENTROIDAL ];
8752
8753     Set( ON_CONCAVE_FACE );
8754
8755     for ( size_t i = 0; i < _simplices.size(); ++i )
8756     {
8757       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8758       {
8759         _smooFunction = _funs[ FUN_NEFPOLY ];
8760
8761         // set FUN_CENTROIDAL to neighbor edges
8762         for ( i = 0; i < _neibors.size(); ++i )
8763         {
8764           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8765           {
8766             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8767           }
8768         }
8769         return;
8770       }
8771     }
8772
8773     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8774     // // where the nodes are smoothed too far along a sphere thus creating
8775     // // inverted _simplices
8776     // double dist[theNbSmooFuns];
8777     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8778     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8779
8780     // double minDist = Precision::Infinite();
8781     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8782     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8783     // {
8784     //   gp_Pnt newP = (this->*_funs[i])();
8785     //   dist[i] = p.SquareDistance( newP );
8786     //   if ( dist[i]*coef[i] < minDist )
8787     //   {
8788     //     _smooFunction = _funs[i];
8789     //     minDist = dist[i]*coef[i];
8790     //   }
8791     // }
8792   }
8793   else
8794   {
8795     _smooFunction = _funs[ FUN_LAPLACIAN ];
8796   }
8797   // int minDim = 3;
8798   // for ( size_t i = 0; i < _simplices.size(); ++i )
8799   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8800   // if ( minDim == 0 )
8801   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8802   // else if ( minDim == 1 )
8803   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8804
8805
8806   // int iMin;
8807   // for ( int i = 0; i < FUN_NB; ++i )
8808   // {
8809   //   //cout << dist[i] << " ";
8810   //   if ( _smooFunction == _funs[i] ) {
8811   //     iMin = i;
8812   //     //debugMsg( fNames[i] );
8813   //     break;
8814   //   }
8815   // }
8816   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8817 }
8818
8819 //================================================================================
8820 /*!
8821  * \brief Returns a name of _SmooFunction
8822  */
8823 //================================================================================
8824
8825 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8826 {
8827   if ( !fun )
8828     fun = _smooFunction;
8829   for ( int i = 0; i < theNbSmooFuns; ++i )
8830     if ( fun == _funs[i] )
8831       return i;
8832
8833   return theNbSmooFuns;
8834 }
8835
8836 //================================================================================
8837 /*!
8838  * \brief Computes a new node position using Laplacian smoothing
8839  */
8840 //================================================================================
8841
8842 gp_XYZ _LayerEdge::smoothLaplacian()
8843 {
8844   gp_XYZ newPos (0,0,0);
8845   for ( size_t i = 0; i < _simplices.size(); ++i )
8846     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8847   newPos /= _simplices.size();
8848
8849   return newPos;
8850 }
8851
8852 //================================================================================
8853 /*!
8854  * \brief Computes a new node position using angular-based smoothing
8855  */
8856 //================================================================================
8857
8858 gp_XYZ _LayerEdge::smoothAngular()
8859 {
8860   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8861   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8862   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8863
8864   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8865   gp_XYZ pN( 0,0,0 );
8866   for ( size_t i = 0; i < _simplices.size(); ++i )
8867   {
8868     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8869     edgeDir.push_back( p - pPrev );
8870     edgeSize.push_back( edgeDir.back().Magnitude() );
8871     if ( edgeSize.back() < numeric_limits<double>::min() )
8872     {
8873       edgeDir.pop_back();
8874       edgeSize.pop_back();
8875     }
8876     else
8877     {
8878       edgeDir.back() /= edgeSize.back();
8879       points.push_back( p );
8880       pN += p;
8881     }
8882     pPrev = p;
8883   }
8884   edgeDir.push_back ( edgeDir[0] );
8885   edgeSize.push_back( edgeSize[0] );
8886   pN /= points.size();
8887
8888   gp_XYZ newPos(0,0,0);
8889   double sumSize = 0;
8890   for ( size_t i = 0; i < points.size(); ++i )
8891   {
8892     gp_Vec toN    = pN - points[i];
8893     double toNLen = toN.Magnitude();
8894     if ( toNLen < numeric_limits<double>::min() )
8895     {
8896       newPos += pN;
8897       continue;
8898     }
8899     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8900     double bisecLen = bisec.SquareMagnitude();
8901     if ( bisecLen < numeric_limits<double>::min() )
8902     {
8903       gp_Vec norm = edgeDir[i] ^ toN;
8904       bisec = norm ^ edgeDir[i];
8905       bisecLen = bisec.SquareMagnitude();
8906     }
8907     bisecLen = Sqrt( bisecLen );
8908     bisec /= bisecLen;
8909
8910 #if 1
8911     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8912     sumSize += bisecLen;
8913 #else
8914     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8915     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8916 #endif
8917     newPos += pNew;
8918   }
8919   newPos /= sumSize;
8920
8921   // project newPos to an average plane
8922
8923   gp_XYZ norm(0,0,0); // plane normal
8924   points.push_back( points[0] );
8925   for ( size_t i = 1; i < points.size(); ++i )
8926   {
8927     gp_XYZ vec1 = points[ i-1 ] - pN;
8928     gp_XYZ vec2 = points[ i   ] - pN;
8929     gp_XYZ cross = vec1 ^ vec2;
8930     try {
8931       cross.Normalize();
8932       if ( cross * norm < numeric_limits<double>::min() )
8933         norm += cross.Reversed();
8934       else
8935         norm += cross;
8936     }
8937     catch (Standard_Failure) { // if |cross| == 0.
8938     }
8939   }
8940   gp_XYZ vec = newPos - pN;
8941   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8942   newPos     = newPos - r * norm;
8943
8944   return newPos;
8945 }
8946
8947 //================================================================================
8948 /*!
8949  * \brief Computes a new node position using weigthed node positions
8950  */
8951 //================================================================================
8952
8953 gp_XYZ _LayerEdge::smoothLengthWeighted()
8954 {
8955   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8956   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8957
8958   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8959   for ( size_t i = 0; i < _simplices.size(); ++i )
8960   {
8961     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8962     edgeSize.push_back( ( p - pPrev ).Modulus() );
8963     if ( edgeSize.back() < numeric_limits<double>::min() )
8964     {
8965       edgeSize.pop_back();
8966     }
8967     else
8968     {
8969       points.push_back( p );
8970     }
8971     pPrev = p;
8972   }
8973   edgeSize.push_back( edgeSize[0] );
8974
8975   gp_XYZ newPos(0,0,0);
8976   double sumSize = 0;
8977   for ( size_t i = 0; i < points.size(); ++i )
8978   {
8979     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8980     sumSize += edgeSize[i] + edgeSize[i+1];
8981   }
8982   newPos /= sumSize;
8983   return newPos;
8984 }
8985
8986 //================================================================================
8987 /*!
8988  * \brief Computes a new node position using angular-based smoothing
8989  */
8990 //================================================================================
8991
8992 gp_XYZ _LayerEdge::smoothCentroidal()
8993 {
8994   gp_XYZ newPos(0,0,0);
8995   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8996   double sumSize = 0;
8997   for ( size_t i = 0; i < _simplices.size(); ++i )
8998   {
8999     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9000     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9001     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9002     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9003
9004     sumSize += size;
9005     newPos += gc * size;
9006   }
9007   newPos /= sumSize;
9008
9009   return newPos;
9010 }
9011
9012 //================================================================================
9013 /*!
9014  * \brief Computes a new node position located inside a Nef polygon
9015  */
9016 //================================================================================
9017
9018 gp_XYZ _LayerEdge::smoothNefPolygon()
9019 #ifdef OLD_NEF_POLYGON
9020 {
9021   gp_XYZ newPos(0,0,0);
9022
9023   // get a plane to search a solution on
9024
9025   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9026   size_t i;
9027   const double tol = numeric_limits<double>::min();
9028   gp_XYZ center(0,0,0);
9029   for ( i = 0; i < _simplices.size(); ++i )
9030   {
9031     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9032                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9033     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9034   }
9035   vecs.back() = vecs[0];
9036   center /= _simplices.size();
9037
9038   gp_XYZ zAxis(0,0,0);
9039   for ( i = 0; i < _simplices.size(); ++i )
9040     zAxis += vecs[i] ^ vecs[i+1];
9041
9042   gp_XYZ yAxis;
9043   for ( i = 0; i < _simplices.size(); ++i )
9044   {
9045     yAxis = vecs[i];
9046     if ( yAxis.SquareModulus() > tol )
9047       break;
9048   }
9049   gp_XYZ xAxis = yAxis ^ zAxis;
9050   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9051   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9052   //                             p0.Distance( _simplices[2]._nPrev ));
9053   // gp_XYZ center = smoothLaplacian();
9054   // gp_XYZ xAxis, yAxis, zAxis;
9055   // for ( i = 0; i < _simplices.size(); ++i )
9056   // {
9057   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9058   //   if ( xAxis.SquareModulus() > tol*tol )
9059   //     break;
9060   // }
9061   // for ( i = 1; i < _simplices.size(); ++i )
9062   // {
9063   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9064   //   zAxis = xAxis ^ yAxis;
9065   //   if ( zAxis.SquareModulus() > tol*tol )
9066   //     break;
9067   // }
9068   // if ( i == _simplices.size() ) return newPos;
9069
9070   yAxis = zAxis ^ xAxis;
9071   xAxis /= xAxis.Modulus();
9072   yAxis /= yAxis.Modulus();
9073
9074   // get half-planes of _simplices
9075
9076   vector< _halfPlane > halfPlns( _simplices.size() );
9077   int nbHP = 0;
9078   for ( size_t i = 0; i < _simplices.size(); ++i )
9079   {
9080     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9081     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9082     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9083     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9084     gp_XY  vec12 = p2 - p1;
9085     double dist12 = vec12.Modulus();
9086     if ( dist12 < tol )
9087       continue;
9088     vec12 /= dist12;
9089     halfPlns[ nbHP ]._pos = p1;
9090     halfPlns[ nbHP ]._dir = vec12;
9091     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9092     ++nbHP;
9093   }
9094
9095   // intersect boundaries of half-planes, define state of intersection points
9096   // in relation to all half-planes and calculate internal point of a 2D polygon
9097
9098   double sumLen = 0;
9099   gp_XY newPos2D (0,0);
9100
9101   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9102   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9103   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9104
9105   vector< vector< TIntPntState > > allIntPnts( nbHP );
9106   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9107   {
9108     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9109     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9110
9111     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9112     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9113
9114     int nbNotOut = 0;
9115     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9116
9117     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9118     {
9119       if ( iHP1 == iHP2 ) continue;
9120
9121       TIntPntState & ips1 = intPnts1[ iHP2 ];
9122       if ( ips1.second == UNDEF )
9123       {
9124         // find an intersection point of boundaries of iHP1 and iHP2
9125
9126         if ( iHP2 == iPrev ) // intersection with neighbors is known
9127           ips1.first = halfPlns[ iHP1 ]._pos;
9128         else if ( iHP2 == iNext )
9129           ips1.first = halfPlns[ iHP2 ]._pos;
9130         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9131           ips1.second = NO_INT;
9132
9133         // classify the found intersection point
9134         if ( ips1.second != NO_INT )
9135         {
9136           ips1.second = NOT_OUT;
9137           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9138             if ( i != iHP1 && i != iHP2 &&
9139                  halfPlns[ i ].IsOut( ips1.first, tol ))
9140               ips1.second = IS_OUT;
9141         }
9142         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9143         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9144         TIntPntState & ips2 = intPnts2[ iHP1 ];
9145         ips2 = ips1;
9146       }
9147       if ( ips1.second == NOT_OUT )
9148       {
9149         ++nbNotOut;
9150         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9151       }
9152     }
9153
9154     // find a NOT_OUT segment of boundary which is located between
9155     // two NOT_OUT int points
9156
9157     if ( nbNotOut < 2 )
9158       continue; // no such a segment
9159
9160     if ( nbNotOut > 2 )
9161     {
9162       // sort points along the boundary
9163       map< double, TIntPntState* > ipsByParam;
9164       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9165       {
9166         TIntPntState & ips1 = intPnts1[ iHP2 ];
9167         if ( ips1.second != NO_INT )
9168         {
9169           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9170           double param = op * halfPlns[ iHP1 ]._dir;
9171           ipsByParam.insert( make_pair( param, & ips1 ));
9172         }
9173       }
9174       // look for two neighboring NOT_OUT points
9175       nbNotOut = 0;
9176       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9177       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9178       {
9179         TIntPntState & ips1 = *(u2ips->second);
9180         if ( ips1.second == NOT_OUT )
9181           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9182         else if ( nbNotOut >= 2 )
9183           break;
9184         else
9185           nbNotOut = 0;
9186       }
9187     }
9188
9189     if ( nbNotOut >= 2 )
9190     {
9191       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9192       sumLen += len;
9193
9194       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9195     }
9196   }
9197
9198   if ( sumLen > 0 )
9199   {
9200     newPos2D /= sumLen;
9201     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9202   }
9203   else
9204   {
9205     newPos = center;
9206   }
9207
9208   return newPos;
9209 }
9210 #else // OLD_NEF_POLYGON
9211 { ////////////////////////////////// NEW
9212   gp_XYZ newPos(0,0,0);
9213
9214   // get a plane to search a solution on
9215
9216   size_t i;
9217   gp_XYZ center(0,0,0);
9218   for ( i = 0; i < _simplices.size(); ++i )
9219     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9220   center /= _simplices.size();
9221
9222   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9223   for ( i = 0; i < _simplices.size(); ++i )
9224     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9225   vecs.back() = vecs[0];
9226
9227   const double tol = numeric_limits<double>::min();
9228   gp_XYZ zAxis(0,0,0);
9229   for ( i = 0; i < _simplices.size(); ++i )
9230   {
9231     gp_XYZ cross = vecs[i] ^ vecs[i+1];
9232     try {
9233       cross.Normalize();
9234       if ( cross * zAxis < tol )
9235         zAxis += cross.Reversed();
9236       else
9237         zAxis += cross;
9238     }
9239     catch (Standard_Failure) { // if |cross| == 0.
9240     }
9241   }
9242
9243   gp_XYZ yAxis;
9244   for ( i = 0; i < _simplices.size(); ++i )
9245   {
9246     yAxis = vecs[i];
9247     if ( yAxis.SquareModulus() > tol )
9248       break;
9249   }
9250   gp_XYZ xAxis = yAxis ^ zAxis;
9251   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9252   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9253   //                             p0.Distance( _simplices[2]._nPrev ));
9254   // gp_XYZ center = smoothLaplacian();
9255   // gp_XYZ xAxis, yAxis, zAxis;
9256   // for ( i = 0; i < _simplices.size(); ++i )
9257   // {
9258   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9259   //   if ( xAxis.SquareModulus() > tol*tol )
9260   //     break;
9261   // }
9262   // for ( i = 1; i < _simplices.size(); ++i )
9263   // {
9264   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9265   //   zAxis = xAxis ^ yAxis;
9266   //   if ( zAxis.SquareModulus() > tol*tol )
9267   //     break;
9268   // }
9269   // if ( i == _simplices.size() ) return newPos;
9270
9271   yAxis = zAxis ^ xAxis;
9272   xAxis /= xAxis.Modulus();
9273   yAxis /= yAxis.Modulus();
9274
9275   // get half-planes of _simplices
9276
9277   vector< _halfPlane > halfPlns( _simplices.size() );
9278   int nbHP = 0;
9279   for ( size_t i = 0; i < _simplices.size(); ++i )
9280   {
9281     const gp_XYZ& OP1 = vecs[ i   ];
9282     const gp_XYZ& OP2 = vecs[ i+1 ];
9283     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9284     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9285     gp_XY  vec12 = p2 - p1;
9286     double dist12 = vec12.Modulus();
9287     if ( dist12 < tol )
9288       continue;
9289     vec12 /= dist12;
9290     halfPlns[ nbHP ]._pos = p1;
9291     halfPlns[ nbHP ]._dir = vec12;
9292     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9293     ++nbHP;
9294   }
9295
9296   // intersect boundaries of half-planes, define state of intersection points
9297   // in relation to all half-planes and calculate internal point of a 2D polygon
9298
9299   double sumLen = 0;
9300   gp_XY newPos2D (0,0);
9301
9302   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9303   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9304   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9305
9306   vector< vector< TIntPntState > > allIntPnts( nbHP );
9307   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9308   {
9309     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9310     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9311
9312     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9313     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9314
9315     int nbNotOut = 0;
9316     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9317
9318     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9319     {
9320       if ( iHP1 == iHP2 ) continue;
9321
9322       TIntPntState & ips1 = intPnts1[ iHP2 ];
9323       if ( ips1.second == UNDEF )
9324       {
9325         // find an intersection point of boundaries of iHP1 and iHP2
9326
9327         if ( iHP2 == iPrev ) // intersection with neighbors is known
9328           ips1.first = halfPlns[ iHP1 ]._pos;
9329         else if ( iHP2 == iNext )
9330           ips1.first = halfPlns[ iHP2 ]._pos;
9331         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9332           ips1.second = NO_INT;
9333
9334         // classify the found intersection point
9335         if ( ips1.second != NO_INT )
9336         {
9337           ips1.second = NOT_OUT;
9338           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9339             if ( i != iHP1 && i != iHP2 &&
9340                  halfPlns[ i ].IsOut( ips1.first, tol ))
9341               ips1.second = IS_OUT;
9342         }
9343         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9344         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9345         TIntPntState & ips2 = intPnts2[ iHP1 ];
9346         ips2 = ips1;
9347       }
9348       if ( ips1.second == NOT_OUT )
9349       {
9350         ++nbNotOut;
9351         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9352       }
9353     }
9354
9355     // find a NOT_OUT segment of boundary which is located between
9356     // two NOT_OUT int points
9357
9358     if ( nbNotOut < 2 )
9359       continue; // no such a segment
9360
9361     if ( nbNotOut > 2 )
9362     {
9363       // sort points along the boundary
9364       map< double, TIntPntState* > ipsByParam;
9365       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9366       {
9367         TIntPntState & ips1 = intPnts1[ iHP2 ];
9368         if ( ips1.second != NO_INT )
9369         {
9370           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9371           double param = op * halfPlns[ iHP1 ]._dir;
9372           ipsByParam.insert( make_pair( param, & ips1 ));
9373         }
9374       }
9375       // look for two neighboring NOT_OUT points
9376       nbNotOut = 0;
9377       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9378       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9379       {
9380         TIntPntState & ips1 = *(u2ips->second);
9381         if ( ips1.second == NOT_OUT )
9382           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9383         else if ( nbNotOut >= 2 )
9384           break;
9385         else
9386           nbNotOut = 0;
9387       }
9388     }
9389
9390     if ( nbNotOut >= 2 )
9391     {
9392       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9393       sumLen += len;
9394
9395       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9396     }
9397   }
9398
9399   if ( sumLen > 0 )
9400   {
9401     newPos2D /= sumLen;
9402     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9403   }
9404   else
9405   {
9406     newPos = center;
9407   }
9408
9409   return newPos;
9410 }
9411 #endif // OLD_NEF_POLYGON
9412
9413 //================================================================================
9414 /*!
9415  * \brief Add a new segment to _LayerEdge during inflation
9416  */
9417 //================================================================================
9418
9419 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9420 {
9421   if ( Is( BLOCKED ))
9422     return;
9423
9424   if ( len > _maxLen )
9425   {
9426     len = _maxLen;
9427     Block( eos.GetData() );
9428   }
9429   const double lenDelta = len - _len;
9430   if ( lenDelta < len * 1e-3  )
9431   {
9432     Block( eos.GetData() );
9433     return;
9434   }
9435
9436   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9437   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9438   gp_XYZ newXYZ;
9439   if ( eos._hyp.IsOffsetMethod() )
9440   {
9441     newXYZ = oldXYZ;
9442     gp_Vec faceNorm;
9443     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9444     while ( faceIt->more() )
9445     {
9446       const SMDS_MeshElement* face = faceIt->next();
9447       if ( !eos.GetNormal( face, faceNorm ))
9448         continue;
9449
9450       // translate plane of a face
9451       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9452
9453       // find point of intersection of the face plane located at baryCenter
9454       // and _normal located at newXYZ
9455       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9456       double dot =  ( faceNorm.XYZ() * _normal );
9457       if ( dot < std::numeric_limits<double>::min() )
9458         dot = lenDelta * 1e-3;
9459       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9460       newXYZ += step * _normal;
9461     }
9462     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9463   }
9464   else
9465   {
9466     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9467   }
9468
9469   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9470   _pos.push_back( newXYZ );
9471
9472   if ( !eos._sWOL.IsNull() )
9473   {
9474     double distXYZ[4];
9475     bool uvOK = false;
9476     if ( eos.SWOLType() == TopAbs_EDGE )
9477     {
9478       double u = Precision::Infinite(); // to force projection w/o distance check
9479       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9480                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9481       _pos.back().SetCoord( u, 0, 0 );
9482       if ( _nodes.size() > 1 && uvOK )
9483       {
9484         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9485         pos->SetUParameter( u );
9486       }
9487     }
9488     else //  TopAbs_FACE
9489     {
9490       gp_XY uv( Precision::Infinite(), 0 );
9491       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9492                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9493       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9494       if ( _nodes.size() > 1 && uvOK )
9495       {
9496         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9497         pos->SetUParameter( uv.X() );
9498         pos->SetVParameter( uv.Y() );
9499       }
9500     }
9501     if ( uvOK )
9502     {
9503       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9504     }
9505     else
9506     {
9507       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9508       _pos.pop_back();
9509       Block( eos.GetData() );
9510       return;
9511     }
9512   }
9513
9514   _len = len;
9515
9516   // notify _neibors
9517   if ( eos.ShapeType() != TopAbs_FACE )
9518   {
9519     for ( size_t i = 0; i < _neibors.size(); ++i )
9520       //if (  _len > _neibors[i]->GetSmooLen() )
9521         _neibors[i]->Set( MOVED );
9522
9523     Set( MOVED );
9524   }
9525   dumpMove( n ); //debug
9526 }
9527
9528 //================================================================================
9529 /*!
9530  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9531  */
9532 //================================================================================
9533
9534 void _LayerEdge::Block( _SolidData& data )
9535 {
9536   //if ( Is( BLOCKED )) return;
9537   Set( BLOCKED );
9538
9539   SMESH_Comment msg( "#BLOCK shape=");
9540   msg << data.GetShapeEdges( this )->_shapeID
9541       << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9542   dumpCmd( msg + " -- BEGIN");
9543
9544   SetMaxLen( _len );
9545   std::queue<_LayerEdge*> queue;
9546   queue.push( this );
9547
9548   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9549   while ( !queue.empty() )
9550   {
9551     _LayerEdge* edge = queue.front(); queue.pop();
9552     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9553     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9554     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9555     {
9556       _LayerEdge* neibor = edge->_neibors[iN];
9557       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9558         continue;
9559       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9560       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9561       double minDist = pSrc.SquareDistance( pSrcN );
9562       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9563       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9564       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9565       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9566       //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9567       {
9568         //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9569         // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9570         //                   neibor->_lenFactor / edge->_lenFactor );
9571       }
9572       if ( neibor->_maxLen > newMaxLen )
9573       {
9574         neibor->SetMaxLen( newMaxLen );
9575         if ( neibor->_maxLen < neibor->_len )
9576         {
9577           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9578           int       lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
9579           while ( neibor->_len > neibor->_maxLen &&
9580                   neibor->NbSteps() > lastStep )
9581             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9582           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9583           //neibor->Block( data );
9584         }
9585         queue.push( neibor );
9586       }
9587     }
9588   }
9589   dumpCmd( msg + " -- END");
9590 }
9591
9592 //================================================================================
9593 /*!
9594  * \brief Remove last inflation step
9595  */
9596 //================================================================================
9597
9598 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9599 {
9600   if ( _pos.size() > curStep && _nodes.size() > 1 )
9601   {
9602     _pos.resize( curStep );
9603
9604     gp_Pnt      nXYZ = _pos.back();
9605     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9606     SMESH_TNodeXYZ curXYZ( n );
9607     if ( !eos._sWOL.IsNull() )
9608     {
9609       TopLoc_Location loc;
9610       if ( eos.SWOLType() == TopAbs_EDGE )
9611       {
9612         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9613         pos->SetUParameter( nXYZ.X() );
9614         double f,l;
9615         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9616         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9617       }
9618       else
9619       {
9620         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9621         pos->SetUParameter( nXYZ.X() );
9622         pos->SetVParameter( nXYZ.Y() );
9623         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9624         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9625       }
9626     }
9627     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9628     dumpMove( n );
9629
9630     if ( restoreLength )
9631     {
9632       if ( NbSteps() == 0 )
9633         _len = 0.;
9634       else if ( IsOnFace() && Is( MOVED ))
9635         _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
9636       else
9637         _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9638     }
9639   }
9640   return;
9641 }
9642
9643 //================================================================================
9644 /*!
9645  * \brief Return index of a _pos distant from _normal
9646  */
9647 //================================================================================
9648
9649 int _LayerEdge::GetSmoothedPos( const double tol )
9650 {
9651   int iSmoothed = 0;
9652   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9653   {
9654     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9655     if ( normDist > tol * tol )
9656       iSmoothed = i;
9657   }
9658   return iSmoothed;
9659 }
9660
9661 //================================================================================
9662 /*!
9663  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9664  */
9665 //================================================================================
9666
9667 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9668 {
9669   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9670     return;
9671
9672   // find the 1st smoothed _pos
9673   int iSmoothed = GetSmoothedPos( tol );
9674   if ( !iSmoothed ) return;
9675
9676   //if ( 1 || Is( DISTORTED ))
9677   {
9678     gp_XYZ normal = _normal;
9679     if ( Is( NORMAL_UPDATED ))
9680       for ( size_t i = 1; i < _pos.size(); ++i )
9681       {
9682         normal = _pos[i] - _pos[0];
9683         double size = normal.Modulus();
9684         if ( size > RealSmall() )
9685         {
9686           normal /= size;
9687           break;
9688         }
9689       }
9690     const double r = 0.2;
9691     for ( int iter = 0; iter < 50; ++iter )
9692     {
9693       double minDot = 1;
9694       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9695       {
9696         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9697         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9698         _pos[i] = newPos;
9699         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9700         double newLen = ( 1-r ) * midLen + r * segLen[i];
9701         const_cast< double& >( segLen[i] ) = newLen;
9702         // check angle between normal and (_pos[i+1], _pos[i] )
9703         gp_XYZ posDir = _pos[i+1] - _pos[i];
9704         double size   = posDir.SquareModulus();
9705         if ( size > RealSmall() )
9706           minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9707       }
9708       if ( minDot > 0.5 * 0.5 )
9709         break;
9710     }
9711   }
9712   // else
9713   // {
9714   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
9715   //   {
9716   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
9717   //       continue;
9718
9719   //     double     wgt = segLen[i] / segLen.back();
9720   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9721   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
9722   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
9723   //     _pos[i] = newPos;
9724   //   }
9725   // }
9726 }
9727
9728 //================================================================================
9729 /*!
9730  * \brief Print flags
9731  */
9732 //================================================================================
9733
9734 std::string _LayerEdge::DumpFlags() const
9735 {
9736   SMESH_Comment dump;
9737   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9738     if ( _flags & flag )
9739     {
9740       EFlags f = (EFlags) flag;
9741       switch ( f ) {
9742       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
9743       case MOVED:           dump << "MOVED";           break;
9744       case SMOOTHED:        dump << "SMOOTHED";        break;
9745       case DIFFICULT:       dump << "DIFFICULT";       break;
9746       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9747       case BLOCKED:         dump << "BLOCKED";         break;
9748       case INTERSECTED:     dump << "INTERSECTED";     break;
9749       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
9750       case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9751       case MARKED:          dump << "MARKED";          break;
9752       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
9753       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
9754       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
9755       case DISTORTED:       dump << "DISTORTED";       break;
9756       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
9757       case SHRUNK:          dump << "SHRUNK";          break;
9758       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
9759       }
9760       dump << " ";
9761     }
9762   cout << dump << endl;
9763   return dump;
9764 }
9765
9766
9767 //================================================================================
9768 /*!
9769  * \brief Create layers of prisms
9770  */
9771 //================================================================================
9772
9773 bool _ViscousBuilder::refine(_SolidData& data)
9774 {
9775   SMESH_MesherHelper& helper = data.GetHelper();
9776   helper.SetElementsOnShape(false);
9777
9778   Handle(Geom_Curve) curve;
9779   Handle(ShapeAnalysis_Surface) surface;
9780   TopoDS_Edge geomEdge;
9781   TopoDS_Face geomFace;
9782   TopLoc_Location loc;
9783   double f,l, u = 0;
9784   gp_XY uv;
9785   vector< gp_XYZ > pos3D;
9786   bool isOnEdge, isTooConvexFace = false;
9787   TGeomID prevBaseId = -1;
9788   TNode2Edge* n2eMap = 0;
9789   TNode2Edge::iterator n2e;
9790
9791   // Create intermediate nodes on each _LayerEdge
9792
9793   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9794   {
9795     _EdgesOnShape& eos = data._edgesOnShape[iS];
9796     if ( eos._edges.empty() ) continue;
9797
9798     if ( eos._edges[0]->_nodes.size() < 2 )
9799       continue; // on _noShrinkShapes
9800
9801     // get data of a shrink shape
9802     isOnEdge = false;
9803     geomEdge.Nullify(); geomFace.Nullify();
9804     curve.Nullify(); surface.Nullify();
9805     if ( !eos._sWOL.IsNull() )
9806     {
9807       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9808       if ( isOnEdge )
9809       {
9810         geomEdge = TopoDS::Edge( eos._sWOL );
9811         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9812       }
9813       else
9814       {
9815         geomFace = TopoDS::Face( eos._sWOL );
9816         surface  = helper.GetSurface( geomFace );
9817       }
9818     }
9819     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9820     {
9821       geomFace = TopoDS::Face( eos._shape );
9822       surface  = helper.GetSurface( geomFace );
9823       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9824       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9825         eos._eosC1[ i ]->_toSmooth = true;
9826
9827       isTooConvexFace = false;
9828       if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
9829         isTooConvexFace = cf->_isTooCurved;
9830     }
9831
9832     vector< double > segLen;
9833     for ( size_t i = 0; i < eos._edges.size(); ++i )
9834     {
9835       _LayerEdge& edge = *eos._edges[i];
9836       if ( edge._pos.size() < 2 )
9837         continue;
9838
9839       // get accumulated length of segments
9840       segLen.resize( edge._pos.size() );
9841       segLen[0] = 0.0;
9842       if ( eos._sWOL.IsNull() )
9843       {
9844         bool useNormal = true;
9845         bool    usePos = false;
9846         bool  smoothed = false;
9847         double   preci = 0.1 * edge._len;
9848         if ( eos._toSmooth && edge._pos.size() > 2 )
9849         {
9850           smoothed = edge.GetSmoothedPos( preci );
9851         }
9852         if ( smoothed )
9853         {
9854           if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
9855           {
9856             useNormal = usePos = false;
9857             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9858             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9859             {
9860               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9861               if ( surface->Gap() < 2. * edge._len )
9862                 segLen[j] = surface->Gap();
9863               else
9864                 useNormal = true;
9865             }
9866           }
9867         }
9868         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9869         {
9870 #ifndef __NODES_AT_POS
9871           useNormal = usePos = false;
9872           edge._pos[1] = edge._pos.back();
9873           edge._pos.resize( 2 );
9874           segLen.resize( 2 );
9875           segLen[ 1 ] = edge._len;
9876 #endif
9877         }
9878         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9879         {
9880           useNormal = usePos = false;
9881           _LayerEdge tmpEdge; // get original _normal
9882           tmpEdge._nodes.push_back( edge._nodes[0] );
9883           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9884             usePos = true;
9885           else
9886             for ( size_t j = 1; j < edge._pos.size(); ++j )
9887               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9888         }
9889         if ( useNormal )
9890         {
9891           for ( size_t j = 1; j < edge._pos.size(); ++j )
9892             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9893         }
9894         if ( usePos )
9895         {
9896           for ( size_t j = 1; j < edge._pos.size(); ++j )
9897             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9898         }
9899         else
9900         {
9901           bool swapped = ( edge._pos.size() > 2 );
9902           while ( swapped )
9903           {
9904             swapped = false;
9905             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9906               if ( segLen[j] > segLen.back() )
9907               {
9908                 segLen.erase( segLen.begin() + j );
9909                 edge._pos.erase( edge._pos.begin() + j );
9910                 --j;
9911               }
9912               else if ( segLen[j] < segLen[j-1] )
9913               {
9914                 std::swap( segLen[j], segLen[j-1] );
9915                 std::swap( edge._pos[j], edge._pos[j-1] );
9916                 swapped = true;
9917               }
9918           }
9919         }
9920         // smooth a path formed by edge._pos
9921 #ifndef __NODES_AT_POS
9922         if (( smoothed ) /*&&
9923             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9924           edge.SmoothPos( segLen, preci );
9925 #endif
9926       }
9927       else if ( eos._isRegularSWOL ) // usual SWOL
9928       {
9929         if ( edge.Is( _LayerEdge::SMOOTHED ))
9930         {
9931           SMESH_NodeXYZ p0( edge._nodes[0] );
9932           for ( size_t j = 1; j < edge._pos.size(); ++j )
9933           {
9934             gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9935             segLen[j] = ( pj - p0 ) * edge._normal;
9936           }
9937         }
9938         else
9939         {
9940           for ( size_t j = 1; j < edge._pos.size(); ++j )
9941             segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9942         }
9943       }
9944       else if ( !surface.IsNull() ) // SWOL surface with singularities
9945       {
9946         pos3D.resize( edge._pos.size() );
9947         for ( size_t j = 0; j < edge._pos.size(); ++j )
9948           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9949
9950         for ( size_t j = 1; j < edge._pos.size(); ++j )
9951           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9952       }
9953
9954       // allocate memory for new nodes if it is not yet refined
9955       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9956       if ( edge._nodes.size() == 2 )
9957       {
9958 #ifdef __NODES_AT_POS
9959         int nbNodes = edge._pos.size();
9960 #else
9961         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9962 #endif
9963         edge._nodes.resize( nbNodes, 0 );
9964         edge._nodes[1] = 0;
9965         edge._nodes.back() = tgtNode;
9966       }
9967       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9968       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9969       if ( baseShapeId != prevBaseId )
9970       {
9971         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9972         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9973         prevBaseId = baseShapeId;
9974       }
9975       _LayerEdge* edgeOnSameNode = 0;
9976       bool        useExistingPos = false;
9977       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9978       {
9979         edgeOnSameNode = n2e->second;
9980         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9981         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9982         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9983         if ( isOnEdge )
9984         {
9985           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9986           epos->SetUParameter( otherTgtPos.X() );
9987         }
9988         else
9989         {
9990           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9991           fpos->SetUParameter( otherTgtPos.X() );
9992           fpos->SetVParameter( otherTgtPos.Y() );
9993         }
9994       }
9995       // calculate height of the first layer
9996       double h0;
9997       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9998       const double f = eos._hyp.GetStretchFactor();
9999       const int    N = eos._hyp.GetNumberLayers();
10000       const double fPowN = pow( f, N );
10001       if ( fPowN - 1 <= numeric_limits<double>::min() )
10002         h0 = T / N;
10003       else
10004         h0 = T * ( f - 1 )/( fPowN - 1 );
10005
10006       const double zeroLen = std::numeric_limits<double>::min();
10007
10008       // create intermediate nodes
10009       double hSum = 0, hi = h0/f;
10010       size_t iSeg = 1;
10011       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10012       {
10013         // compute an intermediate position
10014         hi *= f;
10015         hSum += hi;
10016         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10017           ++iSeg;
10018         int iPrevSeg = iSeg-1;
10019         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10020           --iPrevSeg;
10021         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10022         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10023 #ifdef __NODES_AT_POS
10024         pos = edge._pos[ iStep ];
10025 #endif
10026         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10027         if ( !eos._sWOL.IsNull() )
10028         {
10029           // compute XYZ by parameters <pos>
10030           if ( isOnEdge )
10031           {
10032             u = pos.X();
10033             if ( !node )
10034               pos = curve->Value( u ).Transformed(loc);
10035           }
10036           else if ( eos._isRegularSWOL )
10037           {
10038             uv.SetCoord( pos.X(), pos.Y() );
10039             if ( !node )
10040               pos = surface->Value( pos.X(), pos.Y() );
10041           }
10042           else
10043           {
10044             uv.SetCoord( pos.X(), pos.Y() );
10045             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10046             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10047             if ( !node )
10048               pos = surface->Value( uv );
10049           }
10050         }
10051         // create or update the node
10052         if ( !node )
10053         {
10054           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10055           if ( !eos._sWOL.IsNull() )
10056           {
10057             if ( isOnEdge )
10058               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10059             else
10060               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10061           }
10062           else
10063           {
10064             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10065           }
10066         }
10067         else
10068         {
10069           if ( !eos._sWOL.IsNull() )
10070           {
10071             // make average pos from new and current parameters
10072             if ( isOnEdge )
10073             {
10074               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10075               if ( useExistingPos )
10076                 u = helper.GetNodeU( geomEdge, node );
10077               pos = curve->Value( u ).Transformed(loc);
10078
10079               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
10080               epos->SetUParameter( u );
10081             }
10082             else
10083             {
10084               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10085               if ( useExistingPos )
10086                 uv = helper.GetNodeUV( geomFace, node );
10087               pos = surface->Value( uv );
10088
10089               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
10090               fpos->SetUParameter( uv.X() );
10091               fpos->SetVParameter( uv.Y() );
10092             }
10093           }
10094           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10095         }
10096       } // loop on edge._nodes
10097
10098       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10099       {
10100         if ( isOnEdge )
10101           edge._pos.back().SetCoord( u, 0,0);
10102         else
10103           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10104
10105         if ( edgeOnSameNode )
10106           edgeOnSameNode->_pos.back() = edge._pos.back();
10107       }
10108
10109     } // loop on eos._edges to create nodes
10110
10111
10112     if ( !getMeshDS()->IsEmbeddedMode() )
10113       // Log node movement
10114       for ( size_t i = 0; i < eos._edges.size(); ++i )
10115       {
10116         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10117         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10118       }
10119   }
10120
10121
10122   // Create volumes
10123
10124   helper.SetElementsOnShape(true);
10125
10126   vector< vector<const SMDS_MeshNode*>* > nnVec;
10127   set< vector<const SMDS_MeshNode*>* >    nnSet;
10128   set< int >                       degenEdgeInd;
10129   vector<const SMDS_MeshElement*>     degenVols;
10130
10131   TopExp_Explorer exp( data._solid, TopAbs_FACE );
10132   for ( ; exp.More(); exp.Next() )
10133   {
10134     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10135     if ( data._ignoreFaceIds.count( faceID ))
10136       continue;
10137     const bool isReversedFace = data._reversedFaceIds.count( faceID );
10138     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
10139     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
10140     while ( fIt->more() )
10141     {
10142       const SMDS_MeshElement* face = fIt->next();
10143       const int            nbNodes = face->NbCornerNodes();
10144       nnVec.resize( nbNodes );
10145       nnSet.clear();
10146       degenEdgeInd.clear();
10147       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10148       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10149       for ( int iN = 0; iN < nbNodes; ++iN )
10150       {
10151         const SMDS_MeshNode* n = nIt->next();
10152         _LayerEdge*       edge = data._n2eMap[ n ];
10153         const int i = isReversedFace ? nbNodes-1-iN : iN;
10154         nnVec[ i ] = & edge->_nodes;
10155         maxZ = std::max( maxZ, nnVec[ i ]->size() );
10156         minZ = std::min( minZ, nnVec[ i ]->size() );
10157
10158         if ( helper.HasDegeneratedEdges() )
10159           nnSet.insert( nnVec[ i ]);
10160       }
10161
10162       if ( maxZ == 0 )
10163         continue;
10164       if ( 0 < nnSet.size() && nnSet.size() < 3 )
10165         continue;
10166
10167       switch ( nbNodes )
10168       {
10169       case 3: // TRIA
10170       {
10171         // PENTA
10172         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10173           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10174                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
10175
10176         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10177         {
10178           for ( int iN = 0; iN < nbNodes; ++iN )
10179             if ( nnVec[ iN ]->size() < iZ+1 )
10180               degenEdgeInd.insert( iN );
10181
10182           if ( degenEdgeInd.size() == 1 )  // PYRAM
10183           {
10184             int i2 = *degenEdgeInd.begin();
10185             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10186             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10187             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10188                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
10189           }
10190           else  // TETRA
10191           {
10192             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10193             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10194                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10195                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10196                               (*nnVec[ i3 ])[ iZ ]);
10197           }
10198         }
10199         break; // TRIA
10200       }
10201       case 4: // QUAD
10202       {
10203         // HEX
10204         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10205           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10206                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10207                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
10208                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
10209
10210         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10211         {
10212           for ( int iN = 0; iN < nbNodes; ++iN )
10213             if ( nnVec[ iN ]->size() < iZ+1 )
10214               degenEdgeInd.insert( iN );
10215
10216           switch ( degenEdgeInd.size() )
10217           {
10218           case 2: // PENTA
10219           {
10220             int i2 = *degenEdgeInd.begin();
10221             int i3 = *degenEdgeInd.rbegin();
10222             bool ok = ( i3 - i2 == 1 );
10223             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10224             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10225             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10226
10227             const SMDS_MeshElement* vol =
10228               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10229                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10230             if ( !ok && vol )
10231               degenVols.push_back( vol );
10232           }
10233           break;
10234
10235           default: // degen HEX
10236           {
10237             const SMDS_MeshElement* vol =
10238               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10239                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10240                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10241                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10242                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
10243                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
10244                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
10245                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
10246             degenVols.push_back( vol );
10247           }
10248           }
10249         }
10250         break; // HEX
10251       }
10252       default:
10253         return error("Not supported type of element", data._index);
10254
10255       } // switch ( nbNodes )
10256     } // while ( fIt->more() )
10257   } // loop on FACEs
10258
10259   if ( !degenVols.empty() )
10260   {
10261     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10262     if ( !err || err->IsOK() )
10263     {
10264       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
10265                                          "Bad quality volumes created" ));
10266       err->myBadElements.insert( err->myBadElements.end(),
10267                                  degenVols.begin(),degenVols.end() );
10268     }
10269   }
10270
10271   return true;
10272 }
10273
10274 //================================================================================
10275 /*!
10276  * \brief Shrink 2D mesh on faces to let space for inflated layers
10277  */
10278 //================================================================================
10279
10280 bool _ViscousBuilder::shrink(_SolidData& theData)
10281 {
10282   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10283   // _LayerEdge's inflated along FACE or EDGE)
10284   map< TGeomID, list< _SolidData* > > f2sdMap;
10285   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10286   {
10287     _SolidData& data = _sdVec[i];
10288     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10289     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10290       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
10291       {
10292         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10293
10294         // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
10295         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10296         // by StdMeshers_QuadToTriaAdaptor
10297         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10298         {
10299           SMESH_ProxyMesh::SubMesh* proxySub =
10300             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10301           if ( proxySub->NbElements() == 0 )
10302           {
10303             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10304             while ( fIt->more() )
10305             {
10306               const SMDS_MeshElement* f = fIt->next();
10307               // as a result 3D algo will use elements from proxySub and not from smDS
10308               proxySub->AddElement( f );
10309               f->setIsMarked( true );
10310
10311               // Mark nodes on the FACE to discriminate them from nodes
10312               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10313               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10314               {
10315                 const SMDS_MeshNode* n = f->GetNode( iN );
10316                 if ( n->GetPosition()->GetDim() == 2 )
10317                   n->setIsMarked( true );
10318               }
10319             }
10320           }
10321         }
10322       }
10323   }
10324
10325   SMESH_MesherHelper helper( *_mesh );
10326   helper.ToFixNodeParameters( true );
10327
10328   // EDGEs to shrink
10329   map< TGeomID, _Shrinker1D > e2shrMap;
10330   vector< _EdgesOnShape* > subEOS;
10331   vector< _LayerEdge* > lEdges;
10332
10333   // loop on FACEs to srink mesh on
10334   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10335   for ( ; f2sd != f2sdMap.end(); ++f2sd )
10336   {
10337     list< _SolidData* > & dataList = f2sd->second;
10338     if ( dataList.front()->_n2eMap.empty() ||
10339          dataList.back() ->_n2eMap.empty() )
10340       continue; // not yet computed
10341     if ( dataList.front() != &theData &&
10342          dataList.back()  != &theData )
10343       continue;
10344
10345     _SolidData&      data = *dataList.front();
10346     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
10347     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10348     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
10349     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10350
10351     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10352
10353     _shrinkedFaces.Add( F );
10354     helper.SetSubShape( F );
10355
10356     // ===========================
10357     // Prepare data for shrinking
10358     // ===========================
10359
10360     // Collect nodes to smooth (they are marked at the beginning of this method)
10361     vector < const SMDS_MeshNode* > smoothNodes;
10362     {
10363       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
10364       while ( nIt->more() )
10365       {
10366         const SMDS_MeshNode* n = nIt->next();
10367         if ( n->isMarked() )
10368           smoothNodes.push_back( n );
10369       }
10370     }
10371     // Find out face orientation
10372     double refSign = 1;
10373     const set<TGeomID> ignoreShapes;
10374     bool isOkUV;
10375     if ( !smoothNodes.empty() )
10376     {
10377       vector<_Simplex> simplices;
10378       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
10379       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
10380       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
10381       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
10382       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
10383         refSign = -1;
10384     }
10385
10386     // Find _LayerEdge's inflated along F
10387     subEOS.clear();
10388     lEdges.clear();
10389     {
10390       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
10391                                                                 /*complexFirst=*/true); //!!!
10392       while ( subIt->more() )
10393       {
10394         const TGeomID subID = subIt->next()->GetId();
10395         if ( data._noShrinkShapes.count( subID ))
10396           continue;
10397         _EdgesOnShape* eos = data.GetShapeEdges( subID );
10398         if ( !eos || eos->_sWOL.IsNull() )
10399           if ( data2 ) // check in adjacent SOLID
10400           {
10401             eos = data2->GetShapeEdges( subID );
10402             if ( !eos || eos->_sWOL.IsNull() )
10403               continue;
10404           }
10405         subEOS.push_back( eos );
10406
10407         for ( size_t i = 0; i < eos->_edges.size(); ++i )
10408         {
10409           lEdges.push_back( eos->_edges[ i ] );
10410           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
10411         }
10412       }
10413     }
10414
10415     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
10416     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10417     while ( fIt->more() )
10418       if ( const SMDS_MeshElement* f = fIt->next() )
10419         dumpChangeNodes( f );
10420     dumpFunctionEnd();
10421
10422     // Replace source nodes by target nodes in mesh faces to shrink
10423     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
10424     const SMDS_MeshNode* nodes[20];
10425     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10426     {
10427       _EdgesOnShape& eos = * subEOS[ iS ];
10428       for ( size_t i = 0; i < eos._edges.size(); ++i )
10429       {
10430         _LayerEdge& edge = *eos._edges[i];
10431         const SMDS_MeshNode* srcNode = edge._nodes[0];
10432         const SMDS_MeshNode* tgtNode = edge._nodes.back();
10433         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
10434         while ( fIt->more() )
10435         {
10436           const SMDS_MeshElement* f = fIt->next();
10437           if ( !smDS->Contains( f ) || !f->isMarked() )
10438             continue;
10439           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
10440           for ( int iN = 0; nIt->more(); ++iN )
10441           {
10442             const SMDS_MeshNode* n = nIt->next();
10443             nodes[iN] = ( n == srcNode ? tgtNode : n );
10444           }
10445           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
10446           dumpChangeNodes( f );
10447         }
10448       }
10449     }
10450     dumpFunctionEnd();
10451
10452     // find out if a FACE is concave
10453     const bool isConcaveFace = isConcave( F, helper );
10454
10455     // Create _SmoothNode's on face F
10456     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
10457     {
10458       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
10459       const bool sortSimplices = isConcaveFace;
10460       for ( size_t i = 0; i < smoothNodes.size(); ++i )
10461       {
10462         const SMDS_MeshNode* n = smoothNodes[i];
10463         nodesToSmooth[ i ]._node = n;
10464         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
10465         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
10466         // fix up incorrect uv of nodes on the FACE
10467         helper.GetNodeUV( F, n, 0, &isOkUV);
10468         dumpMove( n );
10469       }
10470       dumpFunctionEnd();
10471     }
10472     //if ( nodesToSmooth.empty() ) continue;
10473
10474     // Find EDGE's to shrink and set simpices to LayerEdge's
10475     set< _Shrinker1D* > eShri1D;
10476     {
10477       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10478       {
10479         _EdgesOnShape& eos = * subEOS[ iS ];
10480         if ( eos.SWOLType() == TopAbs_EDGE )
10481         {
10482           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
10483           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
10484           eShri1D.insert( & srinker );
10485           srinker.AddEdge( eos._edges[0], eos, helper );
10486           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
10487           // restore params of nodes on EGDE if the EDGE has been already
10488           // srinked while srinking other FACE
10489           srinker.RestoreParams();
10490         }
10491         for ( size_t i = 0; i < eos._edges.size(); ++i )
10492         {
10493           _LayerEdge& edge = * eos._edges[i];
10494           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
10495
10496           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
10497           // not-marked nodes are those added by refine()
10498           edge._nodes.back()->setIsMarked( true );
10499         }
10500       }
10501     }
10502
10503     bool toFixTria = false; // to improve quality of trias by diagonal swap
10504     if ( isConcaveFace )
10505     {
10506       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
10507       if ( hasTria != hasQuad ) {
10508         toFixTria = hasTria;
10509       }
10510       else {
10511         set<int> nbNodesSet;
10512         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10513         while ( fIt->more() && nbNodesSet.size() < 2 )
10514           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
10515         toFixTria = ( *nbNodesSet.begin() == 3 );
10516       }
10517     }
10518
10519     // ==================
10520     // Perform shrinking
10521     // ==================
10522
10523     bool shrinked = true;
10524     int nbBad, shriStep=0, smooStep=0;
10525     _SmoothNode::SmoothType smoothType
10526       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
10527     SMESH_Comment errMsg;
10528     while ( shrinked )
10529     {
10530       shriStep++;
10531       // Move boundary nodes (actually just set new UV)
10532       // -----------------------------------------------
10533       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
10534       shrinked = false;
10535       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10536       {
10537         _EdgesOnShape& eos = * subEOS[ iS ];
10538         for ( size_t i = 0; i < eos._edges.size(); ++i )
10539         {
10540           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10541         }
10542       }
10543       dumpFunctionEnd();
10544
10545       // Move nodes on EDGE's
10546       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10547       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10548       for ( ; shr != eShri1D.end(); ++shr )
10549         (*shr)->Compute( /*set3D=*/false, helper );
10550
10551       // Smoothing in 2D
10552       // -----------------
10553       int nbNoImpSteps = 0;
10554       bool       moved = true;
10555       nbBad = 1;
10556       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10557       {
10558         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10559
10560         int oldBadNb = nbBad;
10561         nbBad = 0;
10562         moved = false;
10563         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10564         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10565         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10566         {
10567           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10568                                             smooTy, /*set3D=*/isConcaveFace);
10569         }
10570         if ( nbBad < oldBadNb )
10571           nbNoImpSteps = 0;
10572         else
10573           nbNoImpSteps++;
10574
10575         dumpFunctionEnd();
10576       }
10577
10578       errMsg.clear();
10579       if ( nbBad > 0 )
10580         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10581       if ( shriStep > 200 )
10582         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10583       if ( !errMsg.empty() )
10584         break;
10585
10586       // Fix narrow triangles by swapping diagonals
10587       // ---------------------------------------
10588       if ( toFixTria )
10589       {
10590         set<const SMDS_MeshNode*> usedNodes;
10591         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10592
10593         // update working data
10594         set<const SMDS_MeshNode*>::iterator n;
10595         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10596         {
10597           n = usedNodes.find( nodesToSmooth[ i ]._node );
10598           if ( n != usedNodes.end())
10599           {
10600             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10601                                     nodesToSmooth[ i ]._simplices,
10602                                     ignoreShapes, NULL,
10603                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10604             usedNodes.erase( n );
10605           }
10606         }
10607         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10608         {
10609           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10610           if ( n != usedNodes.end())
10611           {
10612             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10613                                     lEdges[i]->_simplices,
10614                                     ignoreShapes );
10615             usedNodes.erase( n );
10616           }
10617         }
10618       }
10619       // TODO: check effect of this additional smooth
10620       // additional laplacian smooth to increase allowed shrink step
10621       // for ( int st = 1; st; --st )
10622       // {
10623       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10624       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10625       //   {
10626       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10627       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
10628       //   }
10629       // }
10630
10631     } // while ( shrinked )
10632
10633     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10634     {
10635       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10636
10637       // remove faces
10638       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10639       {
10640         vector< const SMDS_MeshElement* > facesToRm;
10641         if ( psm )
10642         {
10643           facesToRm.reserve( psm->NbElements() );
10644           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10645             facesToRm.push_back( ite->next() );
10646
10647           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10648             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10649               psm->Clear();
10650         }
10651         for ( size_t i = 0; i < facesToRm.size(); ++i )
10652           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10653       }
10654       // remove nodes
10655       {
10656         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10657         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10658           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10659             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10660                                 subEOS[iS]->_edges[i]->_nodes.end() );
10661         }
10662         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10663         while ( itn->more() ) {
10664           const SMDS_MeshNode* n = itn->next();
10665           if ( !nodesToKeep.count( n ))
10666             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10667         }
10668       }
10669       // restore position and UV of target nodes
10670       gp_Pnt p;
10671       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10672         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10673         {
10674           _LayerEdge*       edge = subEOS[iS]->_edges[i];
10675           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10676           if ( edge->_pos.empty() ||
10677                edge->Is( _LayerEdge::SHRUNK )) continue;
10678           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10679           {
10680             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10681             pos->SetUParameter( edge->_pos[0].X() );
10682             pos->SetVParameter( edge->_pos[0].Y() );
10683             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10684           }
10685           else
10686           {
10687             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10688             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10689             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10690           }
10691           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10692           dumpMove( tgtNode );
10693         }
10694       // shrink EDGE sub-meshes and set proxy sub-meshes
10695       UVPtStructVec uvPtVec;
10696       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10697       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10698       {
10699         _Shrinker1D* shr = (*shrIt);
10700         shr->Compute( /*set3D=*/true, helper );
10701
10702         // set proxy mesh of EDGEs w/o layers
10703         map< double, const SMDS_MeshNode* > nodes;
10704         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10705         // remove refinement nodes
10706         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10707         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10708         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10709         if ( u2n->second == sn0 || u2n->second == sn1 )
10710         {
10711           while ( u2n->second != tn0 && u2n->second != tn1 )
10712             ++u2n;
10713           nodes.erase( nodes.begin(), u2n );
10714         }
10715         u2n = --nodes.end();
10716         if ( u2n->second == sn0 || u2n->second == sn1 )
10717         {
10718           while ( u2n->second != tn0 && u2n->second != tn1 )
10719             --u2n;
10720           nodes.erase( ++u2n, nodes.end() );
10721         }
10722         // set proxy sub-mesh
10723         uvPtVec.resize( nodes.size() );
10724         u2n = nodes.begin();
10725         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10726         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10727         {
10728           uvPtVec[ i ].node = u2n->second;
10729           uvPtVec[ i ].param = u2n->first;
10730           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10731         }
10732         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10733         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10734       }
10735
10736       // set proxy mesh of EDGEs with layers
10737       vector< _LayerEdge* > edges;
10738       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10739       {
10740         _EdgesOnShape& eos = * subEOS[ iS ];
10741         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10742
10743         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10744         data.SortOnEdge( E, eos._edges );
10745
10746         edges.clear();
10747         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10748           if ( !eov->_edges.empty() )
10749             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10750
10751         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10752
10753         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10754           if ( !eov->_edges.empty() )
10755             edges.push_back( eov->_edges[0] ); // on last VERTEX
10756
10757         uvPtVec.resize( edges.size() );
10758         for ( size_t i = 0; i < edges.size(); ++i )
10759         {
10760           uvPtVec[ i ].node = edges[i]->_nodes.back();
10761           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10762           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10763         }
10764         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10765         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10766         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10767       }
10768       // temporary clear the FACE sub-mesh from faces made by refine()
10769       vector< const SMDS_MeshElement* > elems;
10770       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10771       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10772         elems.push_back( ite->next() );
10773       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10774         elems.push_back( ite->next() );
10775       smDS->Clear();
10776
10777       // compute the mesh on the FACE
10778       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10779       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10780
10781       // re-fill proxy sub-meshes of the FACE
10782       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10783         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10784           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10785             psm->AddElement( ite->next() );
10786
10787       // re-fill smDS
10788       for ( size_t i = 0; i < elems.size(); ++i )
10789         smDS->AddElement( elems[i] );
10790
10791       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10792         return error( errMsg );
10793
10794     } // end of re-meshing in case of failed smoothing
10795     else
10796     {
10797       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10798       bool isStructuredFixed = false;
10799       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10800         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10801       if ( !isStructuredFixed )
10802       {
10803         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10804           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10805
10806         for ( int st = 3; st; --st )
10807         {
10808           switch( st ) {
10809           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10810           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10811           case 3: smoothType = _SmoothNode::ANGULAR; break;
10812           }
10813           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10814           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10815           {
10816             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10817                                      smoothType,/*set3D=*/st==1 );
10818           }
10819           dumpFunctionEnd();
10820         }
10821       }
10822       if ( !getMeshDS()->IsEmbeddedMode() )
10823         // Log node movement
10824         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10825         {
10826           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10827           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10828         }
10829     }
10830
10831     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10832     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10833     if ( data2 )
10834       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
10835
10836   } // loop on FACES to srink mesh on
10837
10838
10839   // Replace source nodes by target nodes in shrinked mesh edges
10840
10841   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10842   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10843     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10844
10845   return true;
10846 }
10847
10848 //================================================================================
10849 /*!
10850  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10851  */
10852 //================================================================================
10853
10854 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10855                                            _EdgesOnShape&         eos,
10856                                            SMESH_MesherHelper&    helper,
10857                                            const SMESHDS_SubMesh* faceSubMesh)
10858 {
10859   const SMDS_MeshNode* srcNode = edge._nodes[0];
10860   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10861
10862   if ( eos.SWOLType() == TopAbs_FACE )
10863   {
10864     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10865     {
10866       edge._pos.clear();
10867       edge.Set( _LayerEdge::SHRUNK );
10868       return srcNode == tgtNode;
10869     }
10870     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10871     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10872     gp_Vec2d uvDir( srcUV, tgtUV );
10873     double uvLen = uvDir.Magnitude();
10874     uvDir /= uvLen;
10875     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10876     edge._len = uvLen;
10877
10878     //edge._pos.resize(1);
10879     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10880
10881     // set UV of source node to target node
10882     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10883     pos->SetUParameter( srcUV.X() );
10884     pos->SetVParameter( srcUV.Y() );
10885   }
10886   else // _sWOL is TopAbs_EDGE
10887   {
10888     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10889     {
10890       edge._pos.clear();
10891       edge.Set( _LayerEdge::SHRUNK );
10892       return srcNode == tgtNode;
10893     }
10894     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10895     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10896     if ( !edgeSM || edgeSM->NbElements() == 0 )
10897       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10898
10899     const SMDS_MeshNode* n2 = 0;
10900     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10901     while ( eIt->more() && !n2 )
10902     {
10903       const SMDS_MeshElement* e = eIt->next();
10904       if ( !edgeSM->Contains(e)) continue;
10905       n2 = e->GetNode( 0 );
10906       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10907     }
10908     if ( !n2 )
10909       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10910
10911     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10912     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10913     double u2   = helper.GetNodeU( E, n2,      srcNode );
10914
10915     //edge._pos.clear();
10916
10917     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10918     {
10919       // tgtNode is located so that it does not make faces with wrong orientation
10920       edge.Set( _LayerEdge::SHRUNK );
10921       return true;
10922     }
10923     //edge._pos.resize(1);
10924     edge._pos[0].SetCoord( U_TGT, uTgt );
10925     edge._pos[0].SetCoord( U_SRC, uSrc );
10926     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10927
10928     edge._simplices.resize( 1 );
10929     edge._simplices[0]._nPrev = n2;
10930
10931     // set U of source node to the target node
10932     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10933     pos->SetUParameter( uSrc );
10934   }
10935   return true;
10936 }
10937
10938 //================================================================================
10939 /*!
10940  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10941  */
10942 //================================================================================
10943
10944 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10945 {
10946   if ( edge._nodes.size() == 1 )
10947   {
10948     edge._pos.clear();
10949     edge._len = 0;
10950
10951     const SMDS_MeshNode* srcNode = edge._nodes[0];
10952     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10953     if ( S.IsNull() ) return;
10954
10955     gp_Pnt p;
10956
10957     switch ( S.ShapeType() )
10958     {
10959     case TopAbs_EDGE:
10960     {
10961       double f,l;
10962       TopLoc_Location loc;
10963       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10964       if ( curve.IsNull() ) return;
10965       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10966       p = curve->Value( ePos->GetUParameter() );
10967       break;
10968     }
10969     case TopAbs_VERTEX:
10970     {
10971       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10972       break;
10973     }
10974     default: return;
10975     }
10976     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10977     dumpMove( srcNode );
10978   }
10979 }
10980
10981 //================================================================================
10982 /*!
10983  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10984  */
10985 //================================================================================
10986
10987 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10988                                   SMESH_MesherHelper&         helper,
10989                                   const bool                  is2D,
10990                                   const int                   step,
10991                                   set<const SMDS_MeshNode*> * involvedNodes)
10992 {
10993   SMESH::Controls::AspectRatio qualifier;
10994   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10995   const double maxAspectRatio = is2D ? 4. : 2;
10996   _NodeCoordHelper xyz( F, helper, is2D );
10997
10998   // find bad triangles
10999
11000   vector< const SMDS_MeshElement* > badTrias;
11001   vector< double >                  badAspects;
11002   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
11003   SMDS_ElemIteratorPtr fIt = sm->GetElements();
11004   while ( fIt->more() )
11005   {
11006     const SMDS_MeshElement * f = fIt->next();
11007     if ( f->NbCornerNodes() != 3 ) continue;
11008     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
11009     double aspect = qualifier.GetValue( points );
11010     if ( aspect > maxAspectRatio )
11011     {
11012       badTrias.push_back( f );
11013       badAspects.push_back( aspect );
11014     }
11015   }
11016   if ( step == 1 )
11017   {
11018     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
11019     SMDS_ElemIteratorPtr fIt = sm->GetElements();
11020     while ( fIt->more() )
11021     {
11022       const SMDS_MeshElement * f = fIt->next();
11023       if ( f->NbCornerNodes() == 3 )
11024         dumpChangeNodes( f );
11025     }
11026     dumpFunctionEnd();
11027   }
11028   if ( badTrias.empty() )
11029     return;
11030
11031   // find couples of faces to swap diagonal
11032
11033   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
11034   vector< T2Trias > triaCouples; 
11035
11036   TIDSortedElemSet involvedFaces, emptySet;
11037   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
11038   {
11039     T2Trias trias    [3];
11040     double  aspRatio [3];
11041     int i1, i2, i3;
11042
11043     if ( !involvedFaces.insert( badTrias[iTia] ).second )
11044       continue;
11045     for ( int iP = 0; iP < 3; ++iP )
11046       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
11047
11048     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
11049     int bestCouple = -1;
11050     for ( int iSide = 0; iSide < 3; ++iSide )
11051     {
11052       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
11053       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
11054       trias [iSide].first  = badTrias[iTia];
11055       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
11056                                                              & i1, & i2 );
11057       if (( ! trias[iSide].second ) ||
11058           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
11059           ( ! sm->Contains( trias[iSide].second )))
11060         continue;
11061
11062       // aspect ratio of an adjacent tria
11063       for ( int iP = 0; iP < 3; ++iP )
11064         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
11065       double aspectInit = qualifier.GetValue( points2 );
11066
11067       // arrange nodes as after diag-swaping
11068       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
11069         i3 = helper.WrapIndex( i1-1, 3 );
11070       else
11071         i3 = helper.WrapIndex( i1+1, 3 );
11072       points1 = points;
11073       points1( 1+ iSide ) = points2( 1+ i3 );
11074       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
11075
11076       // aspect ratio after diag-swaping
11077       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
11078       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
11079         continue;
11080
11081       // prevent inversion of a triangle
11082       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
11083       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
11084       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
11085         continue;
11086
11087       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
11088         bestCouple = iSide;
11089     }
11090
11091     if ( bestCouple >= 0 )
11092     {
11093       triaCouples.push_back( trias[bestCouple] );
11094       involvedFaces.insert ( trias[bestCouple].second );
11095     }
11096     else
11097     {
11098       involvedFaces.erase( badTrias[iTia] );
11099     }
11100   }
11101   if ( triaCouples.empty() )
11102     return;
11103
11104   // swap diagonals
11105
11106   SMESH_MeshEditor editor( helper.GetMesh() );
11107   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11108   for ( size_t i = 0; i < triaCouples.size(); ++i )
11109   {
11110     dumpChangeNodes( triaCouples[i].first );
11111     dumpChangeNodes( triaCouples[i].second );
11112     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11113   }
11114
11115   if ( involvedNodes )
11116     for ( size_t i = 0; i < triaCouples.size(); ++i )
11117     {
11118       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11119                              triaCouples[i].first->end_nodes() );
11120       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11121                              triaCouples[i].second->end_nodes() );
11122     }
11123
11124   // just for debug dump resulting triangles
11125   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11126   for ( size_t i = 0; i < triaCouples.size(); ++i )
11127   {
11128     dumpChangeNodes( triaCouples[i].first );
11129     dumpChangeNodes( triaCouples[i].second );
11130   }
11131 }
11132
11133 //================================================================================
11134 /*!
11135  * \brief Move target node to it's final position on the FACE during shrinking
11136  */
11137 //================================================================================
11138
11139 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
11140                                  const TopoDS_Face&    F,
11141                                  _EdgesOnShape&        eos,
11142                                  SMESH_MesherHelper&   helper )
11143 {
11144   if ( Is( SHRUNK ))
11145     return false; // already at the target position
11146
11147   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11148
11149   if ( eos.SWOLType() == TopAbs_FACE )
11150   {
11151     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
11152     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11153     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11154     const double uvLen = tgtUV.Distance( curUV );
11155     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11156
11157     // Select shrinking step such that not to make faces with wrong orientation.
11158     double stepSize = 1e100;
11159     for ( size_t i = 0; i < _simplices.size(); ++i )
11160     {
11161       if ( !_simplices[i]._nPrev->isMarked() ||
11162            !_simplices[i]._nNext->isMarked() )
11163         continue; // simplex of quadrangle created by addBoundaryElements()
11164
11165       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11166       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11167       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11168       gp_XY dirN = uvN2 - uvN1;
11169       double det = uvDir.Crossed( dirN );
11170       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
11171       gp_XY dirN2Cur = curUV - uvN1;
11172       double step = dirN.Crossed( dirN2Cur ) / det;
11173       if ( step > 0 )
11174         stepSize = Min( step, stepSize );
11175     }
11176     gp_Pnt2d newUV;
11177     if ( uvLen <= stepSize )
11178     {
11179       newUV = tgtUV;
11180       Set( SHRUNK );
11181       //_pos.clear();
11182     }
11183     else if ( stepSize > 0 )
11184     {
11185       newUV = curUV + uvDir.XY() * stepSize * kSafe;
11186     }
11187     else
11188     {
11189       return true;
11190     }
11191     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
11192     pos->SetUParameter( newUV.X() );
11193     pos->SetVParameter( newUV.Y() );
11194
11195 #ifdef __myDEBUG
11196     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11197     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11198     dumpMove( tgtNode );
11199 #endif
11200   }
11201   else // _sWOL is TopAbs_EDGE
11202   {
11203     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
11204     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
11205     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
11206
11207     const double u2     = helper.GetNodeU( E, n2, tgtNode );
11208     const double uSrc   = _pos[0].Coord( U_SRC );
11209     const double lenTgt = _pos[0].Coord( LEN_TGT );
11210
11211     double newU = _pos[0].Coord( U_TGT );
11212     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11213     {
11214       Set( _LayerEdge::SHRUNK );
11215       //_pos.clear();
11216     }
11217     else
11218     {
11219       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11220     }
11221     tgtPos->SetUParameter( newU );
11222 #ifdef __myDEBUG
11223     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11224     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11225     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11226     dumpMove( tgtNode );
11227 #endif
11228   }
11229
11230   return true;
11231 }
11232
11233 //================================================================================
11234 /*!
11235  * \brief Perform smooth on the FACE
11236  *  \retval bool - true if the node has been moved
11237  */
11238 //================================================================================
11239
11240 bool _SmoothNode::Smooth(int&                  nbBad,
11241                          Handle(Geom_Surface)& surface,
11242                          SMESH_MesherHelper&   helper,
11243                          const double          refSign,
11244                          SmoothType            how,
11245                          bool                  set3D)
11246 {
11247   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11248
11249   // get uv of surrounding nodes
11250   vector<gp_XY> uv( _simplices.size() );
11251   for ( size_t i = 0; i < _simplices.size(); ++i )
11252     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11253
11254   // compute new UV for the node
11255   gp_XY newPos (0,0);
11256   if ( how == TFI && _simplices.size() == 4 )
11257   {
11258     gp_XY corners[4];
11259     for ( size_t i = 0; i < _simplices.size(); ++i )
11260       if ( _simplices[i]._nOpp )
11261         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11262       else
11263         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11264
11265     newPos = helper.calcTFI ( 0.5, 0.5,
11266                               corners[0], corners[1], corners[2], corners[3],
11267                               uv[1], uv[2], uv[3], uv[0] );
11268   }
11269   else if ( how == ANGULAR )
11270   {
11271     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11272   }
11273   else if ( how == CENTROIDAL && _simplices.size() > 3 )
11274   {
11275     // average centers of diagonals wieghted with their reciprocal lengths
11276     if ( _simplices.size() == 4 )
11277     {
11278       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11279       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11280       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11281     }
11282     else
11283     {
11284       double sumWeight = 0;
11285       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11286       for ( int i = 0; i < nb; ++i )
11287       {
11288         int iFrom = i + 2;
11289         int iTo   = i + _simplices.size() - 1;
11290         for ( int j = iFrom; j < iTo; ++j )
11291         {
11292           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11293           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11294           sumWeight += w;
11295           newPos += w * ( uv[i]+uv[i2] );
11296         }
11297       }
11298       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11299     }
11300   }
11301   else
11302   {
11303     // Laplacian smooth
11304     for ( size_t i = 0; i < _simplices.size(); ++i )
11305       newPos += uv[i];
11306     newPos /= _simplices.size();
11307   }
11308
11309   // count quality metrics (orientation) of triangles around the node
11310   int nbOkBefore = 0;
11311   gp_XY tgtUV = helper.GetNodeUV( face, _node );
11312   for ( size_t i = 0; i < _simplices.size(); ++i )
11313     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11314
11315   int nbOkAfter = 0;
11316   for ( size_t i = 0; i < _simplices.size(); ++i )
11317     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11318
11319   if ( nbOkAfter < nbOkBefore )
11320   {
11321     nbBad += _simplices.size() - nbOkBefore;
11322     return false;
11323   }
11324
11325   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
11326   pos->SetUParameter( newPos.X() );
11327   pos->SetVParameter( newPos.Y() );
11328
11329 #ifdef __myDEBUG
11330   set3D = true;
11331 #endif
11332   if ( set3D )
11333   {
11334     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
11335     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
11336     dumpMove( _node );
11337   }
11338
11339   nbBad += _simplices.size() - nbOkAfter;
11340   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
11341 }
11342
11343 //================================================================================
11344 /*!
11345  * \brief Computes new UV using angle based smoothing technic
11346  */
11347 //================================================================================
11348
11349 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
11350                                      const gp_XY&   uvToFix,
11351                                      const double   refSign)
11352 {
11353   uv.push_back( uv.front() );
11354
11355   vector< gp_XY >  edgeDir ( uv.size() );
11356   vector< double > edgeSize( uv.size() );
11357   for ( size_t i = 1; i < edgeDir.size(); ++i )
11358   {
11359     edgeDir [i-1] = uv[i] - uv[i-1];
11360     edgeSize[i-1] = edgeDir[i-1].Modulus();
11361     if ( edgeSize[i-1] < numeric_limits<double>::min() )
11362       edgeDir[i-1].SetX( 100 );
11363     else
11364       edgeDir[i-1] /= edgeSize[i-1] * refSign;
11365   }
11366   edgeDir.back()  = edgeDir.front();
11367   edgeSize.back() = edgeSize.front();
11368
11369   gp_XY  newPos(0,0);
11370   //int    nbEdges = 0;
11371   double sumSize = 0;
11372   for ( size_t i = 1; i < edgeDir.size(); ++i )
11373   {
11374     if ( edgeDir[i-1].X() > 1. ) continue;
11375     int i1 = i-1;
11376     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
11377     if ( i == edgeDir.size() ) break;
11378     gp_XY p = uv[i];
11379     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
11380     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
11381     gp_XY bisec = norm1 + norm2;
11382     double bisecSize = bisec.Modulus();
11383     if ( bisecSize < numeric_limits<double>::min() )
11384     {
11385       bisec = -edgeDir[i1] + edgeDir[i];
11386       bisecSize = bisec.Modulus();
11387     }
11388     bisec /= bisecSize;
11389
11390     gp_XY  dirToN  = uvToFix - p;
11391     double distToN = dirToN.Modulus();
11392     if ( bisec * dirToN < 0 )
11393       distToN = -distToN;
11394
11395     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
11396     //++nbEdges;
11397     sumSize += edgeSize[i1] + edgeSize[i];
11398   }
11399   newPos /= /*nbEdges * */sumSize;
11400   return newPos;
11401 }
11402
11403 //================================================================================
11404 /*!
11405  * \brief Delete _SolidData
11406  */
11407 //================================================================================
11408
11409 _SolidData::~_SolidData()
11410 {
11411   TNode2Edge::iterator n2e = _n2eMap.begin();
11412   for ( ; n2e != _n2eMap.end(); ++n2e )
11413   {
11414     _LayerEdge* & e = n2e->second;
11415     if ( e )
11416     {
11417       delete e->_curvature;
11418       if ( e->_2neibors )
11419         delete e->_2neibors->_plnNorm;
11420       delete e->_2neibors;
11421     }
11422     delete e;
11423     e = 0;
11424   }
11425   _n2eMap.clear();
11426
11427   delete _helper;
11428   _helper = 0;
11429 }
11430
11431 //================================================================================
11432 /*!
11433  * \brief Keep a _LayerEdge inflated along the EDGE
11434  */
11435 //================================================================================
11436
11437 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
11438                            _EdgesOnShape&      eos,
11439                            SMESH_MesherHelper& helper )
11440 {
11441   // init
11442   if ( _nodes.empty() )
11443   {
11444     _edges[0] = _edges[1] = 0;
11445     _done = false;
11446   }
11447   // check _LayerEdge
11448   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
11449     return;
11450   if ( eos.SWOLType() != TopAbs_EDGE )
11451     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11452   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
11453     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11454
11455   // store _LayerEdge
11456   _geomEdge = TopoDS::Edge( eos._sWOL );
11457   double f,l;
11458   BRep_Tool::Range( _geomEdge, f,l );
11459   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
11460   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
11461
11462   // Update _nodes
11463
11464   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
11465   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
11466
11467   if ( _nodes.empty() )
11468   {
11469     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
11470     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
11471       return;
11472     TopLoc_Location loc;
11473     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
11474     GeomAdaptor_Curve aCurve(C, f,l);
11475     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
11476
11477     int nbExpectNodes = eSubMesh->NbNodes();
11478     _initU  .reserve( nbExpectNodes );
11479     _normPar.reserve( nbExpectNodes );
11480     _nodes  .reserve( nbExpectNodes );
11481     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
11482     while ( nIt->more() )
11483     {
11484       const SMDS_MeshNode* node = nIt->next();
11485
11486       // skip refinement nodes
11487       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
11488            node == tgtNode0 || node == tgtNode1 )
11489         continue;
11490       bool hasMarkedFace = false;
11491       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
11492       while ( fIt->more() && !hasMarkedFace )
11493         hasMarkedFace = fIt->next()->isMarked();
11494       if ( !hasMarkedFace )
11495         continue;
11496
11497       _nodes.push_back( node );
11498       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
11499       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
11500       _normPar.push_back(  len / totLen );
11501     }
11502   }
11503   else
11504   {
11505     // remove target node of the _LayerEdge from _nodes
11506     size_t nbFound = 0;
11507     for ( size_t i = 0; i < _nodes.size(); ++i )
11508       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
11509         _nodes[i] = 0, nbFound++;
11510     if ( nbFound == _nodes.size() )
11511       _nodes.clear();
11512   }
11513 }
11514
11515 //================================================================================
11516 /*!
11517  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
11518  */
11519 //================================================================================
11520
11521 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
11522 {
11523   if ( _done || _nodes.empty())
11524     return;
11525   const _LayerEdge* e = _edges[0];
11526   if ( !e ) e = _edges[1];
11527   if ( !e ) return;
11528
11529   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
11530             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
11531
11532   double f,l;
11533   if ( set3D || _done )
11534   {
11535     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
11536     GeomAdaptor_Curve aCurve(C, f,l);
11537
11538     if ( _edges[0] )
11539       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11540     if ( _edges[1] )
11541       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11542     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
11543
11544     for ( size_t i = 0; i < _nodes.size(); ++i )
11545     {
11546       if ( !_nodes[i] ) continue;
11547       double len = totLen * _normPar[i];
11548       GCPnts_AbscissaPoint discret( aCurve, len, f );
11549       if ( !discret.IsDone() )
11550         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11551       double u = discret.Parameter();
11552       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11553       pos->SetUParameter( u );
11554       gp_Pnt p = C->Value( u );
11555       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11556     }
11557   }
11558   else
11559   {
11560     BRep_Tool::Range( _geomEdge, f,l );
11561     if ( _edges[0] )
11562       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11563     if ( _edges[1] )
11564       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11565     
11566     for ( size_t i = 0; i < _nodes.size(); ++i )
11567     {
11568       if ( !_nodes[i] ) continue;
11569       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11570       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11571       pos->SetUParameter( u );
11572     }
11573   }
11574 }
11575
11576 //================================================================================
11577 /*!
11578  * \brief Restore initial parameters of nodes on EDGE
11579  */
11580 //================================================================================
11581
11582 void _Shrinker1D::RestoreParams()
11583 {
11584   if ( _done )
11585     for ( size_t i = 0; i < _nodes.size(); ++i )
11586     {
11587       if ( !_nodes[i] ) continue;
11588       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11589       pos->SetUParameter( _initU[i] );
11590     }
11591   _done = false;
11592 }
11593
11594 //================================================================================
11595 /*!
11596  * \brief Replace source nodes by target nodes in shrinked mesh edges
11597  */
11598 //================================================================================
11599
11600 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11601 {
11602   const SMDS_MeshNode* nodes[3];
11603   for ( int i = 0; i < 2; ++i )
11604   {
11605     if ( !_edges[i] ) continue;
11606
11607     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11608     if ( !eSubMesh ) return;
11609     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11610     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11611     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11612     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11613     while ( eIt->more() )
11614     {
11615       const SMDS_MeshElement* e = eIt->next();
11616       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11617           continue;
11618       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11619       for ( int iN = 0; iN < e->NbNodes(); ++iN )
11620       {
11621         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11622         nodes[iN] = ( n == srcNode ? tgtNode : n );
11623       }
11624       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11625     }
11626   }
11627 }
11628
11629 //================================================================================
11630 /*!
11631  * \brief Creates 2D and 1D elements on boundaries of new prisms
11632  */
11633 //================================================================================
11634
11635 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11636 {
11637   SMESH_MesherHelper helper( *_mesh );
11638
11639   vector< const SMDS_MeshNode* > faceNodes;
11640
11641   //for ( size_t i = 0; i < _sdVec.size(); ++i )
11642   {
11643     //_SolidData& data = _sdVec[i];
11644     TopTools_IndexedMapOfShape geomEdges;
11645     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11646     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11647     {
11648       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11649       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
11650       if ( data._noShrinkShapes.count( edgeID ))
11651         continue;
11652
11653       // Get _LayerEdge's based on E
11654
11655       map< double, const SMDS_MeshNode* > u2nodes;
11656       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11657         continue;
11658
11659       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11660       TNode2Edge & n2eMap = data._n2eMap;
11661       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11662       {
11663         //check if 2D elements are needed on E
11664         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11665         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11666         ledges.push_back( n2e->second );
11667         u2n++;
11668         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11669           continue; // no layers on E
11670         ledges.push_back( n2eMap[ u2n->second ]);
11671
11672         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11673         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11674         int nbSharedPyram = 0;
11675         SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
11676         while ( vIt->more() )
11677         {
11678           const SMDS_MeshElement* v = vIt->next();
11679           nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
11680         }
11681         if ( nbSharedPyram > 1 )
11682           continue; // not free border of the pyramid
11683
11684         faceNodes.clear();
11685         faceNodes.push_back( ledges[0]->_nodes[0] );
11686         faceNodes.push_back( ledges[1]->_nodes[0] );
11687         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11688         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11689
11690         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11691           continue; // faces already created
11692       }
11693       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11694         ledges.push_back( n2eMap[ u2n->second ]);
11695
11696       // Find out orientation and type of face to create
11697
11698       bool reverse = false, isOnFace;
11699       TopoDS_Shape F;
11700
11701       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
11702       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11703       {
11704         F = e2f->second.Oriented( TopAbs_FORWARD );
11705         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11706         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11707           reverse = !reverse, F.Reverse();
11708         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11709           reverse = !reverse;
11710       }
11711       else if ( !data._ignoreFaceIds.count( e2f->first ))
11712       {
11713         // find FACE with layers sharing E
11714         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11715         if ( fIt->more() )
11716           F = *( fIt->next() );
11717       }
11718       // Find the sub-mesh to add new faces
11719       SMESHDS_SubMesh* sm = 0;
11720       if ( isOnFace )
11721         sm = getMeshDS()->MeshElements( F );
11722       else
11723         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11724       if ( !sm )
11725         return error("error in addBoundaryElements()", data._index);
11726
11727       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
11728       // faces for 3D meshing (PAL23414)
11729       SMESHDS_SubMesh* adjSM = 0;
11730       if ( isOnFace )
11731       {
11732         const TGeomID   faceID = sm->GetID();
11733         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
11734         while ( const TopoDS_Shape* solid = soIt->next() )
11735           if ( !solid->IsSame( data._solid ))
11736           {
11737             size_t iData = _solids.FindIndex( *solid ) - 1;
11738             if ( iData < _sdVec.size() &&
11739                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
11740                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
11741             {
11742               SMESH_ProxyMesh::SubMesh* proxySub =
11743                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
11744               if ( proxySub && proxySub->NbElements() > 0 )
11745                 adjSM = proxySub;
11746             }
11747           }
11748       }
11749
11750       // Make faces
11751       const int dj1 = reverse ? 0 : 1;
11752       const int dj2 = reverse ? 1 : 0;
11753       vector< const SMDS_MeshElement*> ff; // new faces row
11754       SMESHDS_Mesh* m = getMeshDS();
11755       for ( size_t j = 1; j < ledges.size(); ++j )
11756       {
11757         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11758         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11759         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
11760         if ( nn1.size() == nn2.size() )
11761         {
11762           if ( isOnFace )
11763             for ( size_t z = 1; z < nn1.size(); ++z )
11764               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11765           else
11766             for ( size_t z = 1; z < nn1.size(); ++z )
11767               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11768         }
11769         else if ( nn1.size() == 1 )
11770         {
11771           if ( isOnFace )
11772             for ( size_t z = 1; z < nn2.size(); ++z )
11773               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11774           else
11775             for ( size_t z = 1; z < nn2.size(); ++z )
11776               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11777         }
11778         else
11779         {
11780           if ( isOnFace )
11781             for ( size_t z = 1; z < nn1.size(); ++z )
11782               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11783           else
11784             for ( size_t z = 1; z < nn1.size(); ++z )
11785               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11786         }
11787
11788         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
11789         {
11790           for ( size_t z = 0; z < ff.size(); ++z )
11791             if ( ff[ z ])
11792               adjSM->AddElement( ff[ z ]);
11793           ff.clear();
11794         }
11795       }
11796
11797       // Make edges
11798       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11799       {
11800         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11801         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11802         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11803         {
11804           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11805           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
11806             continue;
11807           helper.SetSubShape( eos->_sWOL );
11808           helper.SetElementsOnShape( true );
11809           for ( size_t z = 1; z < nn.size(); ++z )
11810             helper.AddEdge( nn[z-1], nn[z] );
11811         }
11812       }
11813
11814     } // loop on EDGE's
11815   } // loop on _SolidData's
11816
11817   return true;
11818 }