Salome HOME
IPAL54633: Bad viscous layers
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2019  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "ObjectPool.hxx"
27 #include "SMDS_EdgePosition.hxx"
28 #include "SMDS_FaceOfNodes.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_MeshNode.hxx"
31 #include "SMDS_PolygonalFaceOfNodes.hxx"
32 #include "SMDS_SetIterator.hxx"
33 #include "SMESHDS_Group.hxx"
34 #include "SMESHDS_Hypothesis.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESH_Algo.hxx"
37 #include "SMESH_Block.hxx"
38 #include "SMESH_ComputeError.hxx"
39 #include "SMESH_ControlsDef.hxx"
40 #include "SMESH_Gen.hxx"
41 #include "SMESH_Group.hxx"
42 #include "SMESH_HypoFilter.hxx"
43 #include "SMESH_Mesh.hxx"
44 #include "SMESH_MeshAlgos.hxx"
45 #include "SMESH_MeshEditor.hxx"
46 #include "SMESH_MesherHelper.hxx"
47 #include "SMESH_ProxyMesh.hxx"
48 #include "SMESH_subMesh.hxx"
49 #include "SMESH_subMeshEventListener.hxx"
50 #include "StdMeshers_FaceSide.hxx"
51 #include "StdMeshers_ProjectionUtils.hxx"
52 #include "StdMeshers_ViscousLayers2D.hxx"
53
54 #include <Adaptor3d_HSurface.hxx>
55 #include <BRepAdaptor_Curve.hxx>
56 #include <BRepAdaptor_Curve2d.hxx>
57 #include <BRepAdaptor_Surface.hxx>
58 //#include <BRepLProp_CLProps.hxx>
59 #include <BRepLProp_SLProps.hxx>
60 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
61 #include <BRep_Tool.hxx>
62 #include <Bnd_B2d.hxx>
63 #include <Bnd_B3d.hxx>
64 #include <ElCLib.hxx>
65 #include <GCPnts_AbscissaPoint.hxx>
66 #include <GCPnts_TangentialDeflection.hxx>
67 #include <Geom2d_Circle.hxx>
68 #include <Geom2d_Line.hxx>
69 #include <Geom2d_TrimmedCurve.hxx>
70 #include <GeomAdaptor_Curve.hxx>
71 #include <GeomLib.hxx>
72 #include <Geom_Circle.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Line.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <Precision.hxx>
77 #include <Standard_ErrorHandler.hxx>
78 #include <Standard_Failure.hxx>
79 #include <TColStd_Array1OfReal.hxx>
80 #include <TopExp.hxx>
81 #include <TopExp_Explorer.hxx>
82 #include <TopTools_IndexedMapOfShape.hxx>
83 #include <TopTools_ListOfShape.hxx>
84 #include <TopTools_MapIteratorOfMapOfShape.hxx>
85 #include <TopTools_MapOfShape.hxx>
86 #include <TopoDS.hxx>
87 #include <TopoDS_Edge.hxx>
88 #include <TopoDS_Face.hxx>
89 #include <TopoDS_Vertex.hxx>
90 #include <gp_Ax1.hxx>
91 #include <gp_Cone.hxx>
92 #include <gp_Sphere.hxx>
93 #include <gp_Vec.hxx>
94 #include <gp_XY.hxx>
95
96 #include <cmath>
97 #include <limits>
98 #include <list>
99 #include <queue>
100 #include <string>
101 #include <unordered_map>
102
103 #ifdef _DEBUG_
104 //#define __myDEBUG
105 //#define __NOT_INVALIDATE_BAD_SMOOTH
106 //#define __NODES_AT_POS
107 #endif
108
109 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
110 #define BLOCK_INFLATION // of individual _LayerEdge's
111 #define OLD_NEF_POLYGON
112
113 using namespace std;
114
115 //================================================================================
116 namespace VISCOUS_3D
117 {
118   typedef int TGeomID;
119
120   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
121
122   const double theMinSmoothCosin = 0.1;
123   const double theSmoothThickToElemSizeRatio = 0.6;
124   const double theMinSmoothTriaAngle = 30;
125   const double theMinSmoothQuadAngle = 45;
126
127   // what part of thickness is allowed till intersection
128   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
129   const double theThickToIntersection = 1.5;
130
131   bool needSmoothing( double cosin, double tgtThick, double elemSize )
132   {
133     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
134   }
135   double getSmoothingThickness( double cosin, double elemSize )
136   {
137     return theSmoothThickToElemSizeRatio * elemSize / cosin;
138   }
139
140   /*!
141    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
142    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
143    */
144   struct _MeshOfSolid : public SMESH_ProxyMesh,
145                         public SMESH_subMeshEventListenerData
146   {
147     bool                  _n2nMapComputed;
148     SMESH_ComputeErrorPtr _warning;
149
150     _MeshOfSolid( SMESH_Mesh* mesh)
151       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
152     {
153       SMESH_ProxyMesh::setMesh( *mesh );
154     }
155
156     // returns submesh for a geom face
157     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
158     {
159       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
160       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
161     }
162     void setNode2Node(const SMDS_MeshNode*                 srcNode,
163                       const SMDS_MeshNode*                 proxyNode,
164                       const SMESH_ProxyMesh::SubMesh* subMesh)
165     {
166       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
167     }
168   };
169   //--------------------------------------------------------------------------------
170   /*!
171    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
172    * It is used to clear an inferior dim sub-meshes modified by viscous layers
173    */
174   class _ShrinkShapeListener : SMESH_subMeshEventListener
175   {
176     _ShrinkShapeListener()
177       : SMESH_subMeshEventListener(/*isDeletable=*/false,
178                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
179   public:
180     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
181     virtual void ProcessEvent(const int                       event,
182                               const int                       eventType,
183                               SMESH_subMesh*                  solidSM,
184                               SMESH_subMeshEventListenerData* data,
185                               const SMESH_Hypothesis*         hyp)
186     {
187       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
188       {
189         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
190       }
191     }
192   };
193   //--------------------------------------------------------------------------------
194   /*!
195    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
196    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
197    * delete the data as soon as it has been used
198    */
199   class _ViscousListener : SMESH_subMeshEventListener
200   {
201     _ViscousListener():
202       SMESH_subMeshEventListener(/*isDeletable=*/false,
203                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
204     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
205   public:
206     virtual void ProcessEvent(const int                       event,
207                               const int                       eventType,
208                               SMESH_subMesh*                  subMesh,
209                               SMESH_subMeshEventListenerData* data,
210                               const SMESH_Hypothesis*         hyp)
211     {
212       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
213           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
214             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
215       {
216         // delete SMESH_ProxyMesh containing temporary faces
217         subMesh->DeleteEventListener( this );
218       }
219     }
220     // Finds or creates proxy mesh of the solid
221     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
222                                       const TopoDS_Shape& solid,
223                                       bool                toCreate=false)
224     {
225       if ( !mesh ) return 0;
226       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
227       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
228       if ( !data && toCreate )
229       {
230         data = new _MeshOfSolid(mesh);
231         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
232         sm->SetEventListener( Get(), data, sm );
233       }
234       return data;
235     }
236     // Removes proxy mesh of the solid
237     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
238     {
239       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
240     }
241   };
242   
243   //================================================================================
244   /*!
245    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
246    * the main shape when sub-mesh of the main shape is cleared,
247    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
248    * is cleared
249    */
250   //================================================================================
251
252   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
253   {
254     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
255     SMESH_subMeshEventListenerData* data =
256       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
257     if ( data )
258     {
259       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
260            data->mySubMeshes.end())
261         data->mySubMeshes.push_back( sub );
262     }
263     else
264     {
265       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
266       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
267     }
268   }
269   struct _SolidData;
270   //--------------------------------------------------------------------------------
271   /*!
272    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
273    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
274    * The class is used to check validity of face or volumes around a smoothed node;
275    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
276    */
277   struct _Simplex
278   {
279     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
280     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
281     _Simplex(const SMDS_MeshNode* nPrev=0,
282              const SMDS_MeshNode* nNext=0,
283              const SMDS_MeshNode* nOpp=0)
284       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
285     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
286     {
287       const double M[3][3] =
288         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
289          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
290          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
291       vol = ( + M[0][0] * M[1][1] * M[2][2]
292               + M[0][1] * M[1][2] * M[2][0]
293               + M[0][2] * M[1][0] * M[2][1]
294               - M[0][0] * M[1][2] * M[2][1]
295               - M[0][1] * M[1][0] * M[2][2]
296               - M[0][2] * M[1][1] * M[2][0]);
297       return vol > 1e-100;
298     }
299     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
300     {
301       SMESH_TNodeXYZ pSrc( nSrc );
302       return IsForward( &pSrc, &pTgt, vol );
303     }
304     bool IsForward(const gp_XY&         tgtUV,
305                    const SMDS_MeshNode* smoothedNode,
306                    const TopoDS_Face&   face,
307                    SMESH_MesherHelper&  helper,
308                    const double         refSign) const
309     {
310       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
311       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
312       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
313       double d = v1 ^ v2;
314       return d*refSign > 1e-100;
315     }
316     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
317     {
318       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
319       if ( !_nOpp ) // triangle
320       {
321         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
322         double tp2 = tp.SquareMagnitude();
323         double pn2 = pn.SquareMagnitude();
324         double nt2 = nt.SquareMagnitude();
325
326         if ( tp2 < pn2 && tp2 < nt2 )
327           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
328         else if ( pn2 < nt2 )
329           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
330         else
331           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
332
333         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
334                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
335         return minAngle < theMaxCos2;
336       }
337       else // quadrangle
338       {
339         SMESH_TNodeXYZ pOpp( _nOpp );
340         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
341         double tp2 = tp.SquareMagnitude();
342         double po2 = po.SquareMagnitude();
343         double on2 = on.SquareMagnitude();
344         double nt2 = nt.SquareMagnitude();
345         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
346                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
347                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
348                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
349
350         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
351                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
352         return minAngle < theMaxCos2;
353       }
354     }
355     bool IsNeighbour(const _Simplex& other) const
356     {
357       return _nPrev == other._nNext || _nNext == other._nPrev;
358     }
359     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
360     static void GetSimplices( const SMDS_MeshNode* node,
361                               vector<_Simplex>&   simplices,
362                               const set<TGeomID>& ingnoreShapes,
363                               const _SolidData*   dataToCheckOri = 0,
364                               const bool          toSort = false);
365     static void SortSimplices(vector<_Simplex>& simplices);
366   };
367   //--------------------------------------------------------------------------------
368   /*!
369    * Structure used to take into account surface curvature while smoothing
370    */
371   struct _Curvature
372   {
373     double   _r; // radius
374     double   _k; // factor to correct node smoothed position
375     double   _h2lenRatio; // avgNormProj / (2*avgDist)
376     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
377   public:
378     static _Curvature* New( double avgNormProj, double avgDist );
379     double lenDelta(double len) const { return _k * ( _r + len ); }
380     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
381   };
382   //--------------------------------------------------------------------------------
383
384   struct _2NearEdges;
385   struct _LayerEdge;
386   struct _EdgesOnShape;
387   struct _Smoother1D;
388   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
389
390   //--------------------------------------------------------------------------------
391   /*!
392    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
393    * and a node of the most internal layer (_nodes.back())
394    */
395   struct _LayerEdge
396   {
397     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
398
399     vector< const SMDS_MeshNode*> _nodes;
400
401     gp_XYZ              _normal;    // to boundary of solid
402     vector<gp_XYZ>      _pos;       // points computed during inflation
403     double              _len;       // length achieved with the last inflation step
404     double              _maxLen;    // maximal possible length
405     double              _cosin;     // of angle (_normal ^ surface)
406     double              _minAngle;  // of _simplices
407     double              _lenFactor; // to compute _len taking _cosin into account
408     int                 _flags;
409
410     // simplices connected to the source node (_nodes[0]);
411     // used for smoothing and quality check of _LayerEdge's based on the FACE
412     vector<_Simplex>    _simplices;
413     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
414     PSmooFun            _smooFunction; // smoothing function
415     _Curvature*         _curvature;
416     // data for smoothing of _LayerEdge's based on the EDGE
417     _2NearEdges*        _2neibors;
418
419     enum EFlags { TO_SMOOTH       = 0x0000001,
420                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
421                   SMOOTHED        = 0x0000004, // set by _LayerEdge::Smooth()
422                   DIFFICULT       = 0x0000008, // near concave VERTEX
423                   ON_CONCAVE_FACE = 0x0000010,
424                   BLOCKED         = 0x0000020, // not to inflate any more
425                   INTERSECTED     = 0x0000040, // close intersection with a face found
426                   NORMAL_UPDATED  = 0x0000080,
427                   UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
428                   MARKED          = 0x0000200, // local usage
429                   MULTI_NORMAL    = 0x0000400, // a normal is invisible by some of surrounding faces
430                   NEAR_BOUNDARY   = 0x0000800, // is near FACE boundary forcing smooth
431                   SMOOTHED_C1     = 0x0001000, // is on _eosC1
432                   DISTORTED       = 0x0002000, // was bad before smoothing
433                   RISKY_SWOL      = 0x0004000, // SWOL is parallel to a source FACE
434                   SHRUNK          = 0x0008000, // target node reached a tgt position while shrink()
435                   UNUSED_FLAG     = 0x0100000  // to add user flags after
436     };
437     bool Is   ( int flag ) const { return _flags & flag; }
438     void Set  ( int flag ) { _flags |= flag; }
439     void Unset( int flag ) { _flags &= ~flag; }
440     std::string DumpFlags() const; // debug
441
442     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
443     bool SetNewLength2d( Handle(Geom_Surface)& surface,
444                          const TopoDS_Face&    F,
445                          _EdgesOnShape&        eos,
446                          SMESH_MesherHelper&   helper );
447     void SetDataByNeighbors( const SMDS_MeshNode* n1,
448                              const SMDS_MeshNode* n2,
449                              const _EdgesOnShape& eos,
450                              SMESH_MesherHelper&  helper);
451     void Block( _SolidData& data );
452     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
453     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
454                             const TNode2Edge&     n2eMap);
455     void SmoothPos( const vector< double >& segLen, const double tol );
456     int  GetSmoothedPos( const double tol );
457     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
458     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
459     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
460     void SmoothWoCheck();
461     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
462                       const TopoDS_Face&             F,
463                       SMESH_MesherHelper&            helper);
464     void MoveNearConcaVer( const _EdgesOnShape*    eov,
465                            const _EdgesOnShape*    eos,
466                            const int               step,
467                            vector< _LayerEdge* > & badSmooEdges);
468     bool FindIntersection( SMESH_ElementSearcher&   searcher,
469                            double &                 distance,
470                            const double&            epsilon,
471                            _EdgesOnShape&           eos,
472                            const SMDS_MeshElement** face = 0);
473     bool SegTriaInter( const gp_Ax1&        lastSegment,
474                        const gp_XYZ&        p0,
475                        const gp_XYZ&        p1,
476                        const gp_XYZ&        p2,
477                        double&              dist,
478                        const double&        epsilon) const;
479     bool SegTriaInter( const gp_Ax1&        lastSegment,
480                        const SMDS_MeshNode* n0,
481                        const SMDS_MeshNode* n1,
482                        const SMDS_MeshNode* n2,
483                        double&              dist,
484                        const double&        epsilon) const
485     { return SegTriaInter( lastSegment,
486                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
487                            dist, epsilon );
488     }
489     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
490     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
491     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
492     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
493     bool   IsOnEdge() const { return _2neibors; }
494     bool   IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
495     int    BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
496     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
497     void   SetCosin( double cosin );
498     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
499     void   SetMaxLen( double l ) { _maxLen = l; }
500     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
501     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
502     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
503       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
504     }
505     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
506
507     gp_XYZ smoothLaplacian();
508     gp_XYZ smoothAngular();
509     gp_XYZ smoothLengthWeighted();
510     gp_XYZ smoothCentroidal();
511     gp_XYZ smoothNefPolygon();
512
513     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
514     static const int theNbSmooFuns = FUN_NB;
515     static PSmooFun _funs[theNbSmooFuns];
516     static const char* _funNames[theNbSmooFuns+1];
517     int smooFunID( PSmooFun fun=0) const;
518   };
519   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
520                                                             &_LayerEdge::smoothLengthWeighted,
521                                                             &_LayerEdge::smoothCentroidal,
522                                                             &_LayerEdge::smoothNefPolygon,
523                                                             &_LayerEdge::smoothAngular };
524   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
525                                                          "LengthWeighted",
526                                                          "Centroidal",
527                                                          "NefPolygon",
528                                                          "Angular",
529                                                          "None"};
530   struct _LayerEdgeCmp
531   {
532     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
533     {
534       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
535       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
536     }
537   };
538   //--------------------------------------------------------------------------------
539   /*!
540    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
541    */
542   struct _halfPlane
543   {
544     gp_XY _pos, _dir, _inNorm;
545     bool IsOut( const gp_XY p, const double tol ) const
546     {
547       return _inNorm * ( p - _pos ) < -tol;
548     }
549     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
550     {
551       //const double eps = 1e-10;
552       double D = _dir.Crossed( hp._dir );
553       if ( fabs(D) < std::numeric_limits<double>::min())
554         return false;
555       gp_XY vec21 = _pos - hp._pos; 
556       double u = hp._dir.Crossed( vec21 ) / D; 
557       intPnt = _pos + _dir * u;
558       return true;
559     }
560   };
561   //--------------------------------------------------------------------------------
562   /*!
563    * Structure used to smooth a _LayerEdge based on an EDGE.
564    */
565   struct _2NearEdges
566   {
567     double               _wgt  [2]; // weights of _nodes
568     _LayerEdge*          _edges[2];
569
570      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
571     gp_XYZ*              _plnNorm;
572
573     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
574     ~_2NearEdges(){ delete _plnNorm; }
575     const SMDS_MeshNode* tgtNode(bool is2nd) {
576       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
577     }
578     const SMDS_MeshNode* srcNode(bool is2nd) {
579       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
580     }
581     void reverse() {
582       std::swap( _wgt  [0], _wgt  [1] );
583       std::swap( _edges[0], _edges[1] );
584     }
585     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
586       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
587     }
588     bool include( const _LayerEdge* e ) {
589       return ( _edges[0] == e || _edges[1] == e );
590     }
591   };
592
593
594   //--------------------------------------------------------------------------------
595   /*!
596    * \brief Layers parameters got by averaging several hypotheses
597    */
598   struct AverageHyp
599   {
600     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
601       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
602     {
603       Add( hyp );
604     }
605     void Add( const StdMeshers_ViscousLayers* hyp )
606     {
607       if ( hyp )
608       {
609         _nbHyps++;
610         _nbLayers       = hyp->GetNumberLayers();
611         //_thickness     += hyp->GetTotalThickness();
612         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
613         _stretchFactor += hyp->GetStretchFactor();
614         _method         = hyp->GetMethod();
615         if ( _groupName.empty() )
616           _groupName = hyp->GetGroupName();
617       }
618     }
619     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
620     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
621     int    GetNumberLayers()   const { return _nbLayers; }
622     int    GetMethod()         const { return _method; }
623     bool   ToCreateGroup()     const { return !_groupName.empty(); }
624     const std::string& GetGroupName() const { return _groupName; }
625
626     bool   UseSurfaceNormal()  const
627     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628     bool   ToSmooth()          const
629     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
630     bool   IsOffsetMethod()    const
631     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
632
633     bool operator==( const AverageHyp& other ) const
634     {
635       return ( _nbLayers == other._nbLayers &&
636                _method   == other._method   &&
637                Equals( GetTotalThickness(), other.GetTotalThickness() ) &&
638                Equals( GetStretchFactor(), other.GetStretchFactor() ));
639     }
640     static bool Equals( double v1, double v2 ) { return Abs( v1 - v2 ) < 0.01 * ( v1 + v2 ); }
641
642   private:
643     int         _nbLayers, _nbHyps, _method;
644     double      _thickness, _stretchFactor;
645     std::string _groupName;
646   };
647
648   //--------------------------------------------------------------------------------
649   /*!
650    * \brief _LayerEdge's on a shape and other shape data
651    */
652   struct _EdgesOnShape
653   {
654     vector< _LayerEdge* > _edges;
655
656     TopoDS_Shape          _shape;
657     TGeomID               _shapeID;
658     SMESH_subMesh *       _subMesh;
659     // face or edge w/o layer along or near which _edges are inflated
660     TopoDS_Shape          _sWOL;
661     bool                  _isRegularSWOL; // w/o singularities
662     // averaged StdMeshers_ViscousLayers parameters
663     AverageHyp            _hyp;
664     bool                  _toSmooth;
665     _Smoother1D*          _edgeSmoother;
666     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
667     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
668
669     typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
670     TFace2NormMap            _faceNormals; // if _shape is FACE
671     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
672
673     Handle(ShapeAnalysis_Surface) _offsetSurf;
674     _LayerEdge*                   _edgeForOffset;
675
676     _SolidData*            _data; // parent SOLID
677
678     _LayerEdge*      operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
679     size_t           size() const { return _edges.size(); }
680     TopAbs_ShapeEnum ShapeType() const
681     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
682     TopAbs_ShapeEnum SWOLType() const
683     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
684     bool             HasC1( const _EdgesOnShape* other ) const
685     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
686     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
687     _SolidData&      GetData() const { return *_data; }
688
689     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
690     ~_EdgesOnShape();
691   };
692
693   //--------------------------------------------------------------------------------
694   /*!
695    * \brief Convex FACE whose radius of curvature is less than the thickness of
696    *        layers. It is used to detect distortion of prisms based on a convex
697    *        FACE and to update normals to enable further increasing the thickness
698    */
699   struct _ConvexFace
700   {
701     TopoDS_Face                     _face;
702
703     // edges whose _simplices are used to detect prism distortion
704     vector< _LayerEdge* >           _simplexTestEdges;
705
706     // map a sub-shape to _SolidData::_edgesOnShape
707     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
708
709     bool                            _isTooCurved;
710     bool                            _normalsFixed;
711     bool                            _normalsFixedOnBorders; // used in putOnOffsetSurface()
712
713     double GetMaxCurvature( _SolidData&         data,
714                             _EdgesOnShape&      eof,
715                             BRepLProp_SLProps&  surfProp,
716                             SMESH_MesherHelper& helper);
717
718     bool GetCenterOfCurvature( _LayerEdge*         ledge,
719                                BRepLProp_SLProps&  surfProp,
720                                SMESH_MesherHelper& helper,
721                                gp_Pnt &            center ) const;
722     bool CheckPrisms() const;
723   };
724
725   //--------------------------------------------------------------------------------
726   /*!
727    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
728    *        at inflation up to the full thickness. A detected collision
729    *        is fixed in updateNormals()
730    */
731   struct _CollisionEdges
732   {
733     _LayerEdge*           _edge;
734     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
735     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
736     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
737   };
738
739   //--------------------------------------------------------------------------------
740   /*!
741    * \brief Data of a SOLID
742    */
743   struct _SolidData
744   {
745     typedef const StdMeshers_ViscousLayers* THyp;
746     TopoDS_Shape                    _solid;
747     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
748     TGeomID                         _index; // SOLID id
749     _MeshOfSolid*                   _proxyMesh;
750     bool                            _done;
751     list< THyp >                    _hyps;
752     list< TopoDS_Shape >            _hypShapes;
753     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
754     set< TGeomID >                  _reversedFaceIds;
755     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
756
757     double                          _stepSize, _stepSizeCoeff, _geomSize;
758     const SMDS_MeshNode*            _stepSizeNodes[2];
759
760     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
761
762     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
763     map< TGeomID, TNode2Edge* >     _s2neMap;
764     // _LayerEdge's with underlying shapes
765     vector< _EdgesOnShape >         _edgesOnShape;
766
767     // key:   an ID of shape (EDGE or VERTEX) shared by a FACE with
768     //        layers and a FACE w/o layers
769     // value: the shape (FACE or EDGE) to shrink mesh on.
770     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
771     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
772
773     // Convex FACEs whose radius of curvature is less than the thickness of layers
774     map< TGeomID, _ConvexFace >      _convexFaces;
775
776     // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
777     // the adjacent SOLID
778     set< TGeomID >                   _noShrinkShapes;
779
780     int                              _nbShapesToSmooth;
781
782     vector< _CollisionEdges >        _collisionEdges;
783     set< TGeomID >                   _concaveFaces;
784
785     double                           _maxThickness; // of all _hyps
786     double                           _minThickness; // of all _hyps
787
788     double                           _epsilon; // precision for SegTriaInter()
789
790     SMESH_MesherHelper*              _helper;
791
792     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
793                _MeshOfSolid*       m=0)
794       :_solid(s), _proxyMesh(m), _done(false),_helper(0) {}
795     ~_SolidData() { delete _helper; _helper = 0; }
796
797     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
798     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
799
800     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
801       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
802       return id2face == _convexFaces.end() ? 0 : & id2face->second;
803     }
804     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
805     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
806     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
807     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
808
809     SMESH_MesherHelper& GetHelper() const { return *_helper; }
810
811     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
812       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
813         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
814           _edgesOnShape[i]._edges[j]->Unset( flag );
815     }
816     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
817                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
818
819     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
820   };
821   //--------------------------------------------------------------------------------
822   /*!
823    * \brief Offset plane used in getNormalByOffset()
824    */
825   struct _OffsetPlane
826   {
827     gp_Pln _plane;
828     int    _faceIndex;
829     int    _faceIndexNext[2];
830     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
831     bool   _isLineOK[2];
832     _OffsetPlane() {
833       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
834     }
835     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
836                                     const TopoDS_Edge&   E,
837                                     const TopoDS_Vertex& V );
838     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
839     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
840   };
841   //--------------------------------------------------------------------------------
842   /*!
843    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
844    */
845   struct _CentralCurveOnEdge
846   {
847     bool                  _isDegenerated;
848     vector< gp_Pnt >      _curvaCenters;
849     vector< _LayerEdge* > _ledges;
850     vector< gp_XYZ >      _normals; // new normal for each of _ledges
851     vector< double >      _segLength2;
852
853     TopoDS_Edge           _edge;
854     TopoDS_Face           _adjFace;
855     bool                  _adjFaceToSmooth;
856
857     void Append( const gp_Pnt& center, _LayerEdge* ledge )
858     {
859       if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
860         return;
861       if ( _curvaCenters.size() > 0 )
862         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
863       _curvaCenters.push_back( center );
864       _ledges.push_back( ledge );
865       _normals.push_back( ledge->_normal );
866     }
867     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
868     void SetShapes( const TopoDS_Edge&  edge,
869                     const _ConvexFace&  convFace,
870                     _SolidData&         data,
871                     SMESH_MesherHelper& helper);
872   };
873   //--------------------------------------------------------------------------------
874   /*!
875    * \brief Data of node on a shrinked FACE
876    */
877   struct _SmoothNode
878   {
879     const SMDS_MeshNode*         _node;
880     vector<_Simplex>             _simplices; // for quality check
881
882     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
883
884     bool Smooth(int&                  badNb,
885                 Handle(Geom_Surface)& surface,
886                 SMESH_MesherHelper&   helper,
887                 const double          refSign,
888                 SmoothType            how,
889                 bool                  set3D);
890
891     gp_XY computeAngularPos(vector<gp_XY>& uv,
892                             const gp_XY&   uvToFix,
893                             const double   refSign );
894   };
895   struct PyDump;
896   struct Periodicity;
897   //--------------------------------------------------------------------------------
898   /*!
899    * \brief Builder of viscous layers
900    */
901   class _ViscousBuilder
902   {
903   public:
904     _ViscousBuilder();
905     // does it's job
906     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
907                                   const TopoDS_Shape& shape);
908     // check validity of hypotheses
909     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
910                                            const TopoDS_Shape& shape );
911
912     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
913     void RestoreListeners();
914
915     // computes SMESH_ProxyMesh::SubMesh::_n2n;
916     bool MakeN2NMap( _MeshOfSolid* pm );
917
918   private:
919
920     bool findSolidsWithLayers();
921     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
922     bool findFacesWithLayers(const bool onlyWith=false);
923     void findPeriodicFaces();
924     void getIgnoreFaces(const TopoDS_Shape&             solid,
925                         const StdMeshers_ViscousLayers* hyp,
926                         const TopoDS_Shape&             hypShape,
927                         set<TGeomID>&                   ignoreFaces);
928     void makeEdgesOnShape();
929     bool makeLayer(_SolidData& data);
930     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
931     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
932                       SMESH_MesherHelper& helper, _SolidData& data);
933     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
934                          const TopoDS_Face&   face,
935                          SMESH_MesherHelper&  helper,
936                          bool&                isOK,
937                          bool                 shiftInside=false);
938     bool getFaceNormalAtSingularity(const gp_XY&        uv,
939                                     const TopoDS_Face&  face,
940                                     SMESH_MesherHelper& helper,
941                                     gp_Dir&             normal );
942     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
943     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
944                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
945                               int                              nbFaces,
946                               bool                             lastNoOffset = false);
947     bool findNeiborsOnEdge(const _LayerEdge*     edge,
948                            const SMDS_MeshNode*& n1,
949                            const SMDS_MeshNode*& n2,
950                            _EdgesOnShape&        eos,
951                            _SolidData&           data);
952     void findSimplexTestEdges( _SolidData&                    data,
953                                vector< vector<_LayerEdge*> >& edgesByGeom);
954     void computeGeomSize( _SolidData& data );
955     bool findShapesToSmooth( _SolidData& data);
956     void limitStepSizeByCurvature( _SolidData&  data );
957     void limitStepSize( _SolidData&             data,
958                         const SMDS_MeshElement* face,
959                         const _LayerEdge*       maxCosinEdge );
960     void limitStepSize( _SolidData& data, const double minSize);
961     bool inflate(_SolidData& data);
962     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
963     int  invalidateBadSmooth( _SolidData&               data,
964                               SMESH_MesherHelper&       helper,
965                               vector< _LayerEdge* >&    badSmooEdges,
966                               vector< _EdgesOnShape* >& eosC1,
967                               const int                 infStep );
968     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
969     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
970                              vector< _EdgesOnShape* >& eosC1,
971                              int smooStep=0, int moveAll=false );
972     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
973     void findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
974                                                 _SolidData&         data,
975                                                 SMESH_MesherHelper& helper );
976     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
977     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
978                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
979                                  const bool isSmoothable );
980     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
981     bool updateNormalsOfConvexFaces( _SolidData&         data,
982                                      SMESH_MesherHelper& helper,
983                                      int                 stepNb );
984     void updateNormalsOfC1Vertices( _SolidData& data );
985     bool updateNormalsOfSmoothed( _SolidData&         data,
986                                   SMESH_MesherHelper& helper,
987                                   const int           nbSteps,
988                                   const double        stepSize );
989     bool isNewNormalOk( _SolidData&   data,
990                         _LayerEdge&   edge,
991                         const gp_XYZ& newNormal);
992     bool refine(_SolidData& data);
993     bool shrink(_SolidData& data);
994     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
995                               SMESH_MesherHelper& helper,
996                               const SMESHDS_SubMesh* faceSubMesh );
997     void restoreNoShrink( _LayerEdge& edge ) const;
998     void fixBadFaces(const TopoDS_Face&          F,
999                      SMESH_MesherHelper&         helper,
1000                      const bool                  is2D,
1001                      const int                   step,
1002                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
1003     bool addBoundaryElements(_SolidData& data);
1004
1005     bool error( const string& text, int solidID=-1 );
1006     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1007
1008     // debug
1009     void makeGroupOfLE();
1010
1011     SMESH_Mesh*                  _mesh;
1012     SMESH_ComputeErrorPtr        _error;
1013
1014     vector<                      _SolidData >  _sdVec;
1015     TopTools_IndexedMapOfShape   _solids; // to find _SolidData by a solid
1016     TopTools_MapOfShape          _shrunkFaces;
1017     std::unique_ptr<Periodicity> _periodicity;
1018
1019     int                          _tmpFaceID;
1020     PyDump*                      _pyDump;
1021   };
1022   //--------------------------------------------------------------------------------
1023   /*!
1024    * \brief Shrinker of nodes on the EDGE
1025    */
1026   class _Shrinker1D
1027   {
1028     TopoDS_Edge                   _geomEdge;
1029     vector<double>                _initU;
1030     vector<double>                _normPar;
1031     vector<const SMDS_MeshNode*>  _nodes;
1032     const _LayerEdge*             _edges[2];
1033     bool                          _done;
1034   public:
1035     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1036     void Compute(bool set3D, SMESH_MesherHelper& helper);
1037     void RestoreParams();
1038     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1039     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1040     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1041     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1042     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1043     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1044   };
1045   //--------------------------------------------------------------------------------
1046   /*!
1047    * \brief Smoother of _LayerEdge's on EDGE.
1048    */
1049   struct _Smoother1D
1050   {
1051     struct OffPnt // point of the offsetted EDGE
1052     {
1053       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1054       double      _len;    // length reached at previous inflation step
1055       double      _param;  // on EDGE
1056       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1057       gp_XYZ      _edgeDir;// EDGE tangent at _param
1058       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1059     };
1060     vector< OffPnt >   _offPoints;
1061     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1062     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1063     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1064     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1065     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1066     _EdgesOnShape&     _eos;
1067     double             _curveLen; // length of the EDGE
1068     std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1069
1070     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1071                                               _EdgesOnShape&      eos,
1072                                               SMESH_MesherHelper& helper);
1073
1074     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1075                  _EdgesOnShape&     eos )
1076       : _anaCurve( curveForSmooth ), _eos( eos )
1077     {
1078     }
1079     bool Perform(_SolidData&                    data,
1080                  Handle(ShapeAnalysis_Surface)& surface,
1081                  const TopoDS_Face&             F,
1082                  SMESH_MesherHelper&            helper );
1083
1084     void prepare(_SolidData& data );
1085
1086     void findEdgesToSmooth();
1087
1088     bool isToSmooth( int iE );
1089
1090     bool smoothAnalyticEdge( _SolidData&                    data,
1091                              Handle(ShapeAnalysis_Surface)& surface,
1092                              const TopoDS_Face&             F,
1093                              SMESH_MesherHelper&            helper);
1094     bool smoothComplexEdge( _SolidData&                    data,
1095                             Handle(ShapeAnalysis_Surface)& surface,
1096                             const TopoDS_Face&             F,
1097                             SMESH_MesherHelper&            helper);
1098     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1099                             const gp_XYZ&  edgeDir);
1100     _LayerEdge* getLEdgeOnV( bool is2nd )
1101     {
1102       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1103     }
1104     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1105
1106     void offPointsToPython() const; // debug
1107   };
1108   //--------------------------------------------------------------------------------
1109   /*!
1110    * \brief Class of temporary mesh face.
1111    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1112    * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1113    */
1114   struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1115   {
1116     const SMDS_MeshElement* _srcFace;
1117
1118     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1119                   int                                 ID,
1120                   int                                 faceID=-1,
1121                   const SMDS_MeshElement*             srcFace=0 ):
1122       SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1123     virtual SMDSAbs_EntityType  GetEntityType() const
1124     { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1125     virtual SMDSAbs_GeometryType GetGeomType()  const
1126     { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1127   };
1128   //--------------------------------------------------------------------------------
1129   /*!
1130    * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1131    */
1132   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1133   {
1134     _LayerEdge *_le1, *_le2;
1135     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1136       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1137     {
1138       myNodes[0]=_le1->_nodes[0];
1139       myNodes[1]=_le1->_nodes.back();
1140       myNodes[2]=_le2->_nodes.back();
1141       myNodes[3]=_le2->_nodes[0];
1142     }
1143     const SMDS_MeshNode* n( size_t i ) const
1144     {
1145       return myNodes[ i ];
1146     }
1147     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1148     {
1149       SMESH_TNodeXYZ p0s( myNodes[0] );
1150       SMESH_TNodeXYZ p0t( myNodes[1] );
1151       SMESH_TNodeXYZ p1t( myNodes[2] );
1152       SMESH_TNodeXYZ p1s( myNodes[3] );
1153       gp_XYZ  v0 = p0t - p0s;
1154       gp_XYZ  v1 = p1t - p1s;
1155       gp_XYZ v01 = p1s - p0s;
1156       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1157       gp_XYZ   d = v01 ^ n;
1158       d.Normalize();
1159       return d;
1160     }
1161     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1162     {
1163       myNodes[0]=le1->_nodes[0];
1164       myNodes[1]=le1->_nodes.back();
1165       myNodes[2]=le2->_nodes.back();
1166       myNodes[3]=le2->_nodes[0];
1167       return GetDir();
1168     }
1169   };
1170   //--------------------------------------------------------------------------------
1171   /*!
1172    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1173    * \warning Location of a surface is ignored
1174    */
1175   struct _NodeCoordHelper
1176   {
1177     SMESH_MesherHelper&        _helper;
1178     const TopoDS_Face&         _face;
1179     Handle(Geom_Surface)       _surface;
1180     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1181
1182     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1183       : _helper( helper ), _face( F )
1184     {
1185       if ( is2D )
1186       {
1187         TopLoc_Location loc;
1188         _surface = BRep_Tool::Surface( _face, loc );
1189       }
1190       if ( _surface.IsNull() )
1191         _fun = & _NodeCoordHelper::direct;
1192       else
1193         _fun = & _NodeCoordHelper::byUV;
1194     }
1195     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1196
1197   private:
1198     gp_XYZ direct(const SMDS_MeshNode* n) const
1199     {
1200       return SMESH_TNodeXYZ( n );
1201     }
1202     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1203     {
1204       gp_XY uv = _helper.GetNodeUV( _face, n );
1205       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1206     }
1207   };
1208
1209   //================================================================================
1210   /*!
1211    * \brief Check angle between vectors 
1212    */
1213   //================================================================================
1214
1215   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1216   {
1217     double dot = v1 * v2; // cos * |v1| * |v2|
1218     double l1  = v1.SquareMagnitude();
1219     double l2  = v2.SquareMagnitude();
1220     return (( dot * cos >= 0 ) && 
1221             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1222   }
1223
1224   class _Factory
1225   {
1226     ObjectPool< _LayerEdge >  _edgePool;
1227     ObjectPool< _Curvature >  _curvaturePool;
1228     ObjectPool< _2NearEdges > _nearEdgesPool;
1229
1230     static _Factory* & me()
1231     {
1232       static _Factory* theFactory = 0;
1233       return theFactory;
1234     }
1235   public:
1236
1237     _Factory()  { me() = this; }
1238     ~_Factory() { me() = 0; }
1239
1240     static _LayerEdge*  NewLayerEdge() { return me()->_edgePool.getNew(); }
1241     static _Curvature * NewCurvature() { return me()->_curvaturePool.getNew(); }
1242     static _2NearEdges* NewNearEdges() { return me()->_nearEdgesPool.getNew(); }
1243   };
1244
1245 } // namespace VISCOUS_3D
1246
1247
1248
1249 //================================================================================
1250 // StdMeshers_ViscousLayers hypothesis
1251 //
1252 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1253   :SMESH_Hypothesis(hypId, gen),
1254    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1255    _method( SURF_OFFSET_SMOOTH ),
1256    _groupName("")
1257 {
1258   _name = StdMeshers_ViscousLayers::GetHypType();
1259   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1260 } // --------------------------------------------------------------------------------
1261 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1262 {
1263   if ( faceIds != _shapeIds )
1264     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1265   if ( _isToIgnoreShapes != toIgnore )
1266     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1267 } // --------------------------------------------------------------------------------
1268 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1269 {
1270   if ( thickness != _thickness )
1271     _thickness = thickness, NotifySubMeshesHypothesisModification();
1272 } // --------------------------------------------------------------------------------
1273 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1274 {
1275   if ( _nbLayers != nb )
1276     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1277 } // --------------------------------------------------------------------------------
1278 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1279 {
1280   if ( _stretchFactor != factor )
1281     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1282 } // --------------------------------------------------------------------------------
1283 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1284 {
1285   if ( _method != method )
1286     _method = method, NotifySubMeshesHypothesisModification();
1287 } // --------------------------------------------------------------------------------
1288 void StdMeshers_ViscousLayers::SetGroupName(const std::string& name)
1289 {
1290   if ( _groupName != name )
1291   {
1292     _groupName = name;
1293     if ( !_groupName.empty() )
1294       NotifySubMeshesHypothesisModification();
1295   }
1296 } // --------------------------------------------------------------------------------
1297 SMESH_ProxyMesh::Ptr
1298 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1299                                   const TopoDS_Shape& theShape,
1300                                   const bool          toMakeN2NMap) const
1301 {
1302   using namespace VISCOUS_3D;
1303   _ViscousBuilder builder;
1304   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1305   if ( err && !err->IsOK() )
1306     return SMESH_ProxyMesh::Ptr();
1307
1308   vector<SMESH_ProxyMesh::Ptr> components;
1309   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1310   for ( ; exp.More(); exp.Next() )
1311   {
1312     if ( _MeshOfSolid* pm =
1313          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1314     {
1315       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1316         if ( !builder.MakeN2NMap( pm ))
1317           return SMESH_ProxyMesh::Ptr();
1318       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1319       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1320
1321       if ( pm->_warning && !pm->_warning->IsOK() )
1322       {
1323         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1324         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1325         if ( !smError || smError->IsOK() )
1326           smError = pm->_warning;
1327       }
1328     }
1329     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1330   }
1331   switch ( components.size() )
1332   {
1333   case 0: break;
1334
1335   case 1: return components[0];
1336
1337   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1338   }
1339   return SMESH_ProxyMesh::Ptr();
1340 } // --------------------------------------------------------------------------------
1341 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1342 {
1343   save << " " << _nbLayers
1344        << " " << _thickness
1345        << " " << _stretchFactor
1346        << " " << _shapeIds.size();
1347   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1348     save << " " << _shapeIds[i];
1349   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1350   save << " " << _method;
1351   save << " " << _groupName.size();
1352   if ( !_groupName.empty() )
1353     save << " " << _groupName;
1354   return save;
1355 } // --------------------------------------------------------------------------------
1356 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1357 {
1358   int nbFaces, faceID, shapeToTreat, method;
1359   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1360   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1361     _shapeIds.push_back( faceID );
1362   if ( load >> shapeToTreat ) {
1363     _isToIgnoreShapes = !shapeToTreat;
1364     if ( load >> method )
1365       _method = (ExtrusionMethod) method;
1366     int nameSize = 0;
1367     if ( load >> nameSize && nameSize > 0 )
1368     {
1369       _groupName.resize( nameSize );
1370       load.get( _groupName[0] ); // remove a white-space
1371       load.getline( &_groupName[0], nameSize + 1 );
1372     }
1373   }
1374   else {
1375     _isToIgnoreShapes = true; // old behavior
1376   }
1377   return load;
1378 } // --------------------------------------------------------------------------------
1379 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1380                                                    const TopoDS_Shape& theShape)
1381 {
1382   // TODO
1383   return false;
1384 } // --------------------------------------------------------------------------------
1385 SMESH_ComputeErrorPtr
1386 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1387                                           const TopoDS_Shape&                  theShape,
1388                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1389 {
1390   VISCOUS_3D::_ViscousBuilder builder;
1391   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1392   if ( err && !err->IsOK() )
1393     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1394   else
1395     theStatus = SMESH_Hypothesis::HYP_OK;
1396
1397   return err;
1398 }
1399 // --------------------------------------------------------------------------------
1400 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1401 {
1402   bool isIn =
1403     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1404   return IsToIgnoreShapes() ? !isIn : isIn;
1405 }
1406
1407 // --------------------------------------------------------------------------------
1408 SMDS_MeshGroup* StdMeshers_ViscousLayers::CreateGroup( const std::string&  theName,
1409                                                        SMESH_Mesh&         theMesh,
1410                                                        SMDSAbs_ElementType theType)
1411 {
1412   SMESH_Group*      group = 0;
1413   SMDS_MeshGroup* groupDS = 0;
1414
1415   if ( theName.empty() )
1416     return groupDS;
1417        
1418   if ( SMESH_Mesh::GroupIteratorPtr grIt = theMesh.GetGroups() )
1419     while( grIt->more() && !group )
1420     {
1421       group = grIt->next();
1422       if ( !group ||
1423            group->GetGroupDS()->GetType() != theType ||
1424            group->GetName()               != theName ||
1425            !dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() ))
1426         group = 0;
1427     }
1428   if ( !group )
1429     group = theMesh.AddGroup( theType, theName.c_str() );
1430
1431   groupDS = & dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
1432
1433   return groupDS;
1434 }
1435
1436 // END StdMeshers_ViscousLayers hypothesis
1437 //================================================================================
1438
1439 namespace VISCOUS_3D
1440 {
1441   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1442   {
1443     gp_Vec dir;
1444     double f,l;
1445     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1446     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1447     gp_Pnt p = BRep_Tool::Pnt( fromV );
1448     double distF = p.SquareDistance( c->Value( f ));
1449     double distL = p.SquareDistance( c->Value( l ));
1450     c->D1(( distF < distL ? f : l), p, dir );
1451     if ( distL < distF ) dir.Reverse();
1452     return dir.XYZ();
1453   }
1454   //--------------------------------------------------------------------------------
1455   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1456                      SMESH_MesherHelper& helper)
1457   {
1458     gp_Vec dir;
1459     double f,l; gp_Pnt p;
1460     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1461     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1462     double u = helper.GetNodeU( E, atNode );
1463     c->D1( u, p, dir );
1464     return dir.XYZ();
1465   }
1466   //--------------------------------------------------------------------------------
1467   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1468                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1469                      double* cosin=0);
1470   //--------------------------------------------------------------------------------
1471   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1472                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1473   {
1474     double f,l;
1475     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1476     if ( c.IsNull() )
1477     {
1478       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1479       return getFaceDir( F, v, node, helper, ok );
1480     }
1481     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1482     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1483     gp_Pnt p; gp_Vec du, dv, norm;
1484     surface->D1( uv.X(),uv.Y(), p, du,dv );
1485     norm = du ^ dv;
1486
1487     double u = helper.GetNodeU( fromE, node, 0, &ok );
1488     c->D1( u, p, du );
1489     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1490     if ( o == TopAbs_REVERSED )
1491       du.Reverse();
1492
1493     gp_Vec dir = norm ^ du;
1494
1495     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1496          helper.IsClosedEdge( fromE ))
1497     {
1498       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1499       else                        c->D1( f, p, dv );
1500       if ( o == TopAbs_REVERSED )
1501         dv.Reverse();
1502       gp_Vec dir2 = norm ^ dv;
1503       dir = dir.Normalized() + dir2.Normalized();
1504     }
1505     return dir.XYZ();
1506   }
1507   //--------------------------------------------------------------------------------
1508   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1509                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1510                      bool& ok, double* cosin)
1511   {
1512     TopoDS_Face faceFrw = F;
1513     faceFrw.Orientation( TopAbs_FORWARD );
1514     //double f,l; TopLoc_Location loc;
1515     TopoDS_Edge edges[2]; // sharing a vertex
1516     size_t nbEdges = 0;
1517     {
1518       TopoDS_Vertex VV[2];
1519       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1520       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1521       {
1522         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1523         if ( SMESH_Algo::isDegenerated( e )) continue;
1524         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1525         if ( VV[1].IsSame( fromV )) {
1526           nbEdges += edges[ 0 ].IsNull();
1527           edges[ 0 ] = e;
1528         }
1529         else if ( VV[0].IsSame( fromV )) {
1530           nbEdges += edges[ 1 ].IsNull();
1531           edges[ 1 ] = e;
1532         }
1533       }
1534     }
1535     gp_XYZ dir(0,0,0), edgeDir[2];
1536     if ( nbEdges == 2 )
1537     {
1538       // get dirs of edges going fromV
1539       ok = true;
1540       for ( size_t i = 0; i < nbEdges && ok; ++i )
1541       {
1542         edgeDir[i] = getEdgeDir( edges[i], fromV );
1543         double size2 = edgeDir[i].SquareModulus();
1544         if (( ok = size2 > numeric_limits<double>::min() ))
1545           edgeDir[i] /= sqrt( size2 );
1546       }
1547       if ( !ok ) return dir;
1548
1549       // get angle between the 2 edges
1550       gp_Vec faceNormal;
1551       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1552       if ( Abs( angle ) < 5 * M_PI/180 )
1553       {
1554         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1555       }
1556       else
1557       {
1558         dir = edgeDir[0] + edgeDir[1];
1559         if ( angle < 0 )
1560           dir.Reverse();
1561       }
1562       if ( cosin ) {
1563         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1564         *cosin = Cos( angle );
1565       }
1566     }
1567     else if ( nbEdges == 1 )
1568     {
1569       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1570       if ( cosin ) *cosin = 1.;
1571     }
1572     else
1573     {
1574       ok = false;
1575     }
1576
1577     return dir;
1578   }
1579
1580   //================================================================================
1581   /*!
1582    * \brief Finds concave VERTEXes of a FACE
1583    */
1584   //================================================================================
1585
1586   bool getConcaveVertices( const TopoDS_Face&  F,
1587                            SMESH_MesherHelper& helper,
1588                            set< TGeomID >*     vertices = 0)
1589   {
1590     // check angles at VERTEXes
1591     TError error;
1592     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1593     for ( size_t iW = 0; iW < wires.size(); ++iW )
1594     {
1595       const int nbEdges = wires[iW]->NbEdges();
1596       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1597         continue;
1598       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1599       {
1600         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1601         int iE2 = ( iE1 + 1 ) % nbEdges;
1602         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1603           iE2 = ( iE2 + 1 ) % nbEdges;
1604         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1605         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1606                                         wires[iW]->Edge( iE2 ), F, V );
1607         if ( angle < -5. * M_PI / 180. )
1608         {
1609           if ( !vertices )
1610             return true;
1611           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1612         }
1613       }
1614     }
1615     return vertices ? !vertices->empty() : false;
1616   }
1617
1618   //================================================================================
1619   /*!
1620    * \brief Returns true if a FACE is bound by a concave EDGE
1621    */
1622   //================================================================================
1623
1624   bool isConcave( const TopoDS_Face&  F,
1625                   SMESH_MesherHelper& helper,
1626                   set< TGeomID >*     vertices = 0 )
1627   {
1628     bool isConcv = false;
1629     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1630     //   return true;
1631     gp_Vec2d drv1, drv2;
1632     gp_Pnt2d p;
1633     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1634     for ( ; eExp.More(); eExp.Next() )
1635     {
1636       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1637       if ( SMESH_Algo::isDegenerated( E )) continue;
1638       // check if 2D curve is concave
1639       BRepAdaptor_Curve2d curve( E, F );
1640       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1641       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1642       curve.Intervals( intervals, GeomAbs_C2 );
1643       bool isConvex = true;
1644       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1645       {
1646         double u1 = intervals( i );
1647         double u2 = intervals( i+1 );
1648         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1649         double cross = drv1 ^ drv2;
1650         if ( E.Orientation() == TopAbs_REVERSED )
1651           cross = -cross;
1652         isConvex = ( cross > -1e-9 ); // 0.1 );
1653       }
1654       if ( !isConvex )
1655       {
1656         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1657         isConcv = true;
1658         if ( vertices )
1659           break;
1660         else
1661           return true;
1662       }
1663     }
1664
1665     // check angles at VERTEXes
1666     if ( getConcaveVertices( F, helper, vertices ))
1667       isConcv = true;
1668
1669     return isConcv;
1670   }
1671
1672   //================================================================================
1673   /*!
1674    * \brief Computes minimal distance of face in-FACE nodes from an EDGE
1675    *  \param [in] face - the mesh face to treat
1676    *  \param [in] nodeOnEdge - a node on the EDGE
1677    *  \param [out] faceSize - the computed distance
1678    *  \return bool - true if faceSize computed
1679    */
1680   //================================================================================
1681
1682   bool getDistFromEdge( const SMDS_MeshElement* face,
1683                         const SMDS_MeshNode*    nodeOnEdge,
1684                         double &                faceSize )
1685   {
1686     faceSize = Precision::Infinite();
1687     bool done = false;
1688
1689     int nbN  = face->NbCornerNodes();
1690     int iOnE = face->GetNodeIndex( nodeOnEdge );
1691     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1692                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1693     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1694                                       face->GetNode( iNext[1] ) };
1695     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1696     double segLen = -1.;
1697     // look for two neighbor not in-FACE nodes of face
1698     for ( int i = 0; i < 2; ++i )
1699     {
1700       if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1701           ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1702       {
1703         // look for an in-FACE node
1704         for ( int iN = 0; iN < nbN; ++iN )
1705         {
1706           if ( iN == iOnE || iN == iNext[i] )
1707             continue;
1708           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1709           gp_XYZ v = pInFace - segEnd;
1710           if ( segLen < 0 )
1711           {
1712             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1713             segLen = segVec.Modulus();
1714           }
1715           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1716           faceSize = Min( faceSize, distToSeg );
1717           done = true;
1718         }
1719         segLen = -1;
1720       }
1721     }
1722     return done;
1723   }
1724   //================================================================================
1725   /*!
1726    * \brief Return direction of axis or revolution of a surface
1727    */
1728   //================================================================================
1729
1730   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1731                           gp_Dir &                 axis )
1732   {
1733     switch ( surface.GetType() ) {
1734     case GeomAbs_Cone:
1735     {
1736       gp_Cone cone = surface.Cone();
1737       axis = cone.Axis().Direction();
1738       break;
1739     }
1740     case GeomAbs_Sphere:
1741     {
1742       gp_Sphere sphere = surface.Sphere();
1743       axis = sphere.Position().Direction();
1744       break;
1745     }
1746     case GeomAbs_SurfaceOfRevolution:
1747     {
1748       axis = surface.AxeOfRevolution().Direction();
1749       break;
1750     }
1751     //case GeomAbs_SurfaceOfExtrusion:
1752     case GeomAbs_OffsetSurface:
1753     {
1754       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1755       return getRovolutionAxis( base->Surface(), axis );
1756     }
1757     default: return false;
1758     }
1759     return true;
1760   }
1761
1762   //--------------------------------------------------------------------------------
1763   // DEBUG. Dump intermediate node positions into a python script
1764   // HOWTO use: run python commands written in a console to see
1765   //  construction steps of viscous layers
1766 #ifdef __myDEBUG
1767   ostream* py;
1768   int      theNbPyFunc;
1769   struct PyDump
1770   {
1771     PyDump(SMESH_Mesh& m) {
1772       int tag = 3 + m.GetId();
1773       const char* fname = "/tmp/viscous.py";
1774       cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
1775       py = _pyStream = new ofstream(fname);
1776       *py << "import SMESH" << endl
1777           << "from salome.smesh import smeshBuilder" << endl
1778           << "smesh  = smeshBuilder.New()" << endl
1779           << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1780           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1781       theNbPyFunc = 0;
1782     }
1783     void Finish() {
1784       if (py) {
1785         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1786           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1787         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1788           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1789       }
1790       delete py; py=0;
1791     }
1792     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1793     struct MyStream : public ostream
1794     {
1795       template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1796     };
1797     void Pause() { py = &_mystream; }
1798     void Resume() { py = _pyStream; }
1799     MyStream _mystream;
1800     ostream* _pyStream;
1801   };
1802 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1803 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1804 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1805 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1806   void _dumpFunction(const string& fun, int ln)
1807   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1808   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1809   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1810                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1811   void _dumpCmd(const string& txt, int ln)
1812   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1813   void dumpFunctionEnd()
1814   { if (py) *py<< "  return"<< endl; }
1815   void dumpChangeNodes( const SMDS_MeshElement* f )
1816   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1817       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1818       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1819 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1820
1821 #else
1822
1823   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1824 #define dumpFunction(f) f
1825 #define dumpMove(n)
1826 #define dumpMoveComm(n,txt)
1827 #define dumpCmd(txt)
1828 #define dumpFunctionEnd()
1829 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1830 #define debugMsg( txt ) {}
1831
1832 #endif
1833 }
1834
1835 using namespace VISCOUS_3D;
1836
1837 //================================================================================
1838 /*!
1839  * \brief Constructor of _ViscousBuilder
1840  */
1841 //================================================================================
1842
1843 _ViscousBuilder::_ViscousBuilder()
1844 {
1845   _error = SMESH_ComputeError::New(COMPERR_OK);
1846   _tmpFaceID = 0;
1847 }
1848
1849 //================================================================================
1850 /*!
1851  * \brief Stores error description and returns false
1852  */
1853 //================================================================================
1854
1855 bool _ViscousBuilder::error(const string& text, int solidId )
1856 {
1857   const string prefix = string("Viscous layers builder: ");
1858   _error->myName    = COMPERR_ALGO_FAILED;
1859   _error->myComment = prefix + text;
1860   if ( _mesh )
1861   {
1862     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1863     if ( !sm && !_sdVec.empty() )
1864       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1865     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1866     {
1867       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1868       if ( smError && smError->myAlgo )
1869         _error->myAlgo = smError->myAlgo;
1870       smError = _error;
1871       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1872     }
1873     // set KO to all solids
1874     for ( size_t i = 0; i < _sdVec.size(); ++i )
1875     {
1876       if ( _sdVec[i]._index == solidId )
1877         continue;
1878       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1879       if ( !sm->IsEmpty() )
1880         continue;
1881       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1882       if ( !smError || smError->IsOK() )
1883       {
1884         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1885         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1886       }
1887     }
1888   }
1889   makeGroupOfLE(); // debug
1890
1891   return false;
1892 }
1893
1894 //================================================================================
1895 /*!
1896  * \brief At study restoration, restore event listeners used to clear an inferior
1897  *  dim sub-mesh modified by viscous layers
1898  */
1899 //================================================================================
1900
1901 void _ViscousBuilder::RestoreListeners()
1902 {
1903   // TODO
1904 }
1905
1906 //================================================================================
1907 /*!
1908  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1909  */
1910 //================================================================================
1911
1912 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1913 {
1914   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1915   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1916   for ( ; fExp.More(); fExp.Next() )
1917   {
1918     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1919     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1920
1921     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1922       continue;
1923     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1924       continue;
1925
1926     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1927       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1928
1929     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1930     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1931     while( prxIt->more() )
1932     {
1933       const SMDS_MeshElement* fSrc = srcIt->next();
1934       const SMDS_MeshElement* fPrx = prxIt->next();
1935       if ( fSrc->NbNodes() != fPrx->NbNodes())
1936         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1937       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1938         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1939     }
1940   }
1941   pm->_n2nMapComputed = true;
1942   return true;
1943 }
1944
1945 //================================================================================
1946 /*!
1947  * \brief Does its job
1948  */
1949 //================================================================================
1950
1951 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1952                                                const TopoDS_Shape& theShape)
1953 {
1954   _mesh = & theMesh;
1955
1956   _Factory factory;
1957
1958   // check if proxy mesh already computed
1959   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1960   if ( !exp.More() )
1961     return error("No SOLID's in theShape"), _error;
1962
1963   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1964     return SMESH_ComputeErrorPtr(); // everything already computed
1965
1966   PyDump debugDump( theMesh );
1967   _pyDump = &debugDump;
1968
1969   // TODO: ignore already computed SOLIDs
1970   if ( !findSolidsWithLayers())
1971     return _error;
1972
1973   if ( !findFacesWithLayers() )
1974     return _error;
1975
1976   // for ( size_t i = 0; i < _sdVec.size(); ++i )
1977   // {
1978   //   if ( ! makeLayer( _sdVec[ i ]))   // create _LayerEdge's
1979   //     return _error;
1980   // }
1981
1982   makeEdgesOnShape();
1983
1984   findPeriodicFaces();
1985
1986   for ( size_t i = 0; i < _sdVec.size(); ++i )
1987   {
1988     size_t iSD = 0;
1989     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1990       if ( _sdVec[iSD]._before.IsEmpty() &&
1991            !_sdVec[iSD]._solid.IsNull() &&
1992            !_sdVec[iSD]._done )
1993         break;
1994
1995     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1996       return _error;
1997
1998     if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1999     {
2000       _sdVec[iSD]._solid.Nullify();
2001       continue;
2002     }
2003
2004     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
2005       return _error;
2006
2007     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
2008       return _error;
2009
2010     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
2011       return _error;
2012
2013     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
2014
2015     _sdVec[iSD]._done = true;
2016
2017     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
2018     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
2019       _sdVec[iSD]._before.Remove( solid );
2020   }
2021
2022   makeGroupOfLE(); // debug
2023   debugDump.Finish();
2024
2025   return _error;
2026 }
2027
2028 //================================================================================
2029 /*!
2030  * \brief Check validity of hypotheses
2031  */
2032 //================================================================================
2033
2034 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
2035                                                         const TopoDS_Shape& shape )
2036 {
2037   _mesh = & mesh;
2038
2039   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
2040     return SMESH_ComputeErrorPtr(); // everything already computed
2041
2042
2043   findSolidsWithLayers();
2044   bool ok = findFacesWithLayers( true );
2045
2046   // remove _MeshOfSolid's of _SolidData's
2047   for ( size_t i = 0; i < _sdVec.size(); ++i )
2048     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
2049
2050   if ( !ok )
2051     return _error;
2052
2053   return SMESH_ComputeErrorPtr();
2054 }
2055
2056 //================================================================================
2057 /*!
2058  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
2059  */
2060 //================================================================================
2061
2062 bool _ViscousBuilder::findSolidsWithLayers()
2063 {
2064   // get all solids
2065   TopTools_IndexedMapOfShape allSolids;
2066   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
2067   _sdVec.reserve( allSolids.Extent());
2068
2069   SMESH_HypoFilter filter;
2070   for ( int i = 1; i <= allSolids.Extent(); ++i )
2071   {
2072     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
2073     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
2074     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
2075       continue; // solid is already meshed
2076     SMESH_Algo* algo = sm->GetAlgo();
2077     if ( !algo ) continue;
2078     // TODO: check if algo is hidden
2079     const list <const SMESHDS_Hypothesis *> & allHyps =
2080       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
2081     _SolidData* soData = 0;
2082     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
2083     const StdMeshers_ViscousLayers* viscHyp = 0;
2084     for ( ; hyp != allHyps.end(); ++hyp )
2085       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
2086       {
2087         TopoDS_Shape hypShape;
2088         filter.Init( filter.Is( viscHyp ));
2089         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
2090
2091         if ( !soData )
2092         {
2093           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2094                                                                     allSolids(i),
2095                                                                     /*toCreate=*/true);
2096           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2097           soData = & _sdVec.back();
2098           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2099           soData->_helper = new SMESH_MesherHelper( *_mesh );
2100           soData->_helper->SetSubShape( allSolids(i) );
2101           _solids.Add( allSolids(i) );
2102         }
2103         soData->_hyps.push_back( viscHyp );
2104         soData->_hypShapes.push_back( hypShape );
2105       }
2106   }
2107   if ( _sdVec.empty() )
2108     return error
2109       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2110
2111   return true;
2112 }
2113
2114 //================================================================================
2115 /*!
2116  * \brief Set a _SolidData to be computed before another
2117  */
2118 //================================================================================
2119
2120 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2121 {
2122   // check possibility to set this order; get all solids before solidBefore
2123   TopTools_IndexedMapOfShape allSolidsBefore;
2124   allSolidsBefore.Add( solidBefore._solid );
2125   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2126   {
2127     int iSD = _solids.FindIndex( allSolidsBefore(i) );
2128     if ( iSD )
2129     {
2130       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2131       for ( ; soIt.More(); soIt.Next() )
2132         allSolidsBefore.Add( soIt.Value() );
2133     }
2134   }
2135   if ( allSolidsBefore.Contains( solidAfter._solid ))
2136     return false;
2137
2138   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2139     solidAfter._before.Add( allSolidsBefore(i) );
2140
2141   return true;
2142 }
2143
2144 //================================================================================
2145 /*!
2146  * \brief
2147  */
2148 //================================================================================
2149
2150 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2151 {
2152   SMESH_MesherHelper helper( *_mesh );
2153   TopExp_Explorer exp;
2154
2155   // collect all faces-to-ignore defined by hyp
2156   for ( size_t i = 0; i < _sdVec.size(); ++i )
2157   {
2158     // get faces-to-ignore defined by each hyp
2159     typedef const StdMeshers_ViscousLayers* THyp;
2160     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2161     list< TFacesOfHyp > ignoreFacesOfHyps;
2162     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2163     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2164     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2165     {
2166       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2167       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2168     }
2169
2170     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2171     const int nbHyps = _sdVec[i]._hyps.size();
2172     if ( nbHyps > 1 )
2173     {
2174       // check if two hypotheses define different parameters for the same FACE
2175       list< TFacesOfHyp >::iterator igFacesOfHyp;
2176       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2177       {
2178         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2179         THyp hyp = 0;
2180         igFacesOfHyp = ignoreFacesOfHyps.begin();
2181         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2182           if ( ! igFacesOfHyp->first.count( faceID ))
2183           {
2184             if ( hyp )
2185               return error(SMESH_Comment("Several hypotheses define "
2186                                          "Viscous Layers on the face #") << faceID );
2187             hyp = igFacesOfHyp->second;
2188           }
2189         if ( hyp )
2190           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2191         else
2192           _sdVec[i]._ignoreFaceIds.insert( faceID );
2193       }
2194
2195       // check if two hypotheses define different number of viscous layers for
2196       // adjacent faces of a solid
2197       set< int > nbLayersSet;
2198       igFacesOfHyp = ignoreFacesOfHyps.begin();
2199       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2200       {
2201         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2202       }
2203       if ( nbLayersSet.size() > 1 )
2204       {
2205         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2206         {
2207           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2208           THyp hyp1 = 0, hyp2 = 0;
2209           while( const TopoDS_Shape* face = fIt->next() )
2210           {
2211             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2212             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2213             if ( f2h != _sdVec[i]._face2hyp.end() )
2214             {
2215               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2216             }
2217           }
2218           if ( hyp1 && hyp2 &&
2219                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2220           {
2221             return error("Two hypotheses define different number of "
2222                          "viscous layers on adjacent faces");
2223           }
2224         }
2225       }
2226     } // if ( nbHyps > 1 )
2227     else
2228     {
2229       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2230     }
2231   } // loop on _sdVec
2232
2233   if ( onlyWith ) // is called to check hypotheses compatibility only
2234     return true;
2235
2236   // fill _SolidData::_reversedFaceIds
2237   for ( size_t i = 0; i < _sdVec.size(); ++i )
2238   {
2239     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2240     for ( ; exp.More(); exp.Next() )
2241     {
2242       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2243       const TGeomID    faceID = getMeshDS()->ShapeToIndex( face );
2244       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2245           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2246           helper.IsReversedSubMesh( face ))
2247       {
2248         _sdVec[i]._reversedFaceIds.insert( faceID );
2249       }
2250     }
2251   }
2252
2253   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2254   TopTools_IndexedMapOfShape shapes;
2255   std::string structAlgoName = "Hexa_3D";
2256   for ( size_t i = 0; i < _sdVec.size(); ++i )
2257   {
2258     shapes.Clear();
2259     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2260     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2261     {
2262       const TopoDS_Shape& edge = shapes(iE);
2263       // find 2 FACEs sharing an EDGE
2264       TopoDS_Shape FF[2];
2265       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2266       while ( fIt->more())
2267       {
2268         const TopoDS_Shape* f = fIt->next();
2269         FF[ int( !FF[0].IsNull()) ] = *f;
2270       }
2271       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2272
2273       // check presence of layers on them
2274       int ignore[2];
2275       for ( int j = 0; j < 2; ++j )
2276         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2277       if ( ignore[0] == ignore[1] )
2278         continue; // nothing interesting
2279       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ]; // FACE w/o layers
2280
2281       // add EDGE to maps
2282       if ( !fWOL.IsNull())
2283       {
2284         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2285         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2286       }
2287     }
2288   }
2289
2290   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2291
2292   for ( size_t i = 0; i < _sdVec.size(); ++i )
2293   {
2294     shapes.Clear();
2295     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2296     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2297     {
2298       const TopoDS_Shape& vertex = shapes(iV);
2299       // find faces WOL sharing the vertex
2300       vector< TopoDS_Shape > facesWOL;
2301       size_t totalNbFaces = 0;
2302       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2303       while ( fIt->more())
2304       {
2305         const TopoDS_Shape* f = fIt->next();
2306         totalNbFaces++;
2307         const int fID = getMeshDS()->ShapeToIndex( *f );
2308         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2309           facesWOL.push_back( *f );
2310       }
2311       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2312         continue; // no layers at this vertex or no WOL
2313       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2314       switch ( facesWOL.size() )
2315       {
2316       case 1:
2317       {
2318         helper.SetSubShape( facesWOL[0] );
2319         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2320         {
2321           TopoDS_Shape seamEdge;
2322           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2323           while ( eIt->more() && seamEdge.IsNull() )
2324           {
2325             const TopoDS_Shape* e = eIt->next();
2326             if ( helper.IsRealSeam( *e ) )
2327               seamEdge = *e;
2328           }
2329           if ( !seamEdge.IsNull() )
2330           {
2331             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2332             break;
2333           }
2334         }
2335         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2336         break;
2337       }
2338       case 2:
2339       {
2340         // find an edge shared by 2 faces
2341         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2342         while ( eIt->more())
2343         {
2344           const TopoDS_Shape* e = eIt->next();
2345           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2346                helper.IsSubShape( *e, facesWOL[1]))
2347           {
2348             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2349           }
2350         }
2351         break;
2352       }
2353       default:
2354         return error("Not yet supported case", _sdVec[i]._index);
2355       }
2356     }
2357   }
2358
2359   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrunk since
2360   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2361   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2362   for ( size_t i = 0; i < _sdVec.size(); ++i )
2363   {
2364     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2365     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2366     {
2367       const TopoDS_Shape& fWOL = e2f->second;
2368       const TGeomID     edgeID = e2f->first;
2369       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2370       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2371       if ( edge.ShapeType() != TopAbs_EDGE )
2372         continue; // shrink shape is VERTEX
2373
2374       TopoDS_Shape solid;
2375       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2376       while ( soIt->more() && solid.IsNull() )
2377       {
2378         const TopoDS_Shape* so = soIt->next();
2379         if ( !so->IsSame( _sdVec[i]._solid ))
2380           solid = *so;
2381       }
2382       if ( solid.IsNull() )
2383         continue;
2384
2385       bool noShrinkE = false;
2386       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2387       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2388       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2389       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2390       {
2391         // the adjacent SOLID has NO layers on fWOL;
2392         // shrink allowed if
2393         // - there are layers on the EDGE in the adjacent SOLID
2394         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2395         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2396         bool shrinkAllowed = (( hasWLAdj ) ||
2397                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2398         noShrinkE = !shrinkAllowed;
2399       }
2400       else if ( iSolid < _sdVec.size() )
2401       {
2402         // the adjacent SOLID has layers on fWOL;
2403         // check if SOLID's mesh is unstructured and then try to set it
2404         // to be computed after the i-th solid
2405         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2406           noShrinkE = true; // don't shrink fWOL
2407       }
2408       else
2409       {
2410         // the adjacent SOLID has NO layers at all
2411         noShrinkE = isStructured;
2412       }
2413
2414       if ( noShrinkE )
2415       {
2416         _sdVec[i]._noShrinkShapes.insert( edgeID );
2417
2418         // check if there is a collision with to-shrink-from EDGEs in iSolid
2419         // if ( iSolid < _sdVec.size() )
2420         // {
2421         //   shapes.Clear();
2422         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2423         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2424         //   {
2425         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2426         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2427         //     if ( eID == edgeID ||
2428         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2429         //          _sdVec[i]._noShrinkShapes.count( eID ))
2430         //       continue;
2431         //     for ( int is1st = 0; is1st < 2; ++is1st )
2432         //     {
2433         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2434         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2435         //       {
2436         //         return error("No way to make a conformal mesh with "
2437         //                      "the given set of faces with layers", _sdVec[i]._index);
2438         //       }
2439         //     }
2440         //   }
2441         // }
2442       }
2443
2444       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2445       // _shrinkShape2Shape is different in the adjacent SOLID
2446       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2447       {
2448         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2449         bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2450
2451         if ( iSolid < _sdVec.size() )
2452         {
2453           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2454           {
2455             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2456             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2457             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2458             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2459               noShrinkV = (( isStructured ) ||
2460                            ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2461             else
2462               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2463           }
2464           else
2465           {
2466             noShrinkV = noShrinkE;
2467           }
2468         }
2469         else
2470         {
2471           // the adjacent SOLID has NO layers at all
2472           if ( isStructured )
2473           {
2474             noShrinkV = true;
2475           }
2476           else
2477           {
2478             noShrinkV = noShrinkIfAdjMeshed =
2479               ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2480           }
2481         }
2482
2483         if ( noShrinkV && noShrinkIfAdjMeshed )
2484         {
2485           // noShrinkV if FACEs in the adjacent SOLID are meshed
2486           PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2487                                                        *_mesh, TopAbs_FACE, &solid );
2488           while ( fIt->more() )
2489           {
2490             const TopoDS_Shape* f = fIt->next();
2491             if ( !f->IsSame( fWOL ))
2492             {
2493               noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2494               break;
2495             }
2496           }
2497         }
2498         if ( noShrinkV )
2499           _sdVec[i]._noShrinkShapes.insert( vID );
2500       }
2501
2502     } // loop on _sdVec[i]._shrinkShape2Shape
2503   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2504
2505
2506     // add FACEs of other SOLIDs to _ignoreFaceIds
2507   for ( size_t i = 0; i < _sdVec.size(); ++i )
2508   {
2509     shapes.Clear();
2510     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2511
2512     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2513     {
2514       if ( !shapes.Contains( exp.Current() ))
2515         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2516     }
2517   }
2518
2519   return true;
2520 }
2521
2522 //================================================================================
2523 /*!
2524  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2525  */
2526 //================================================================================
2527
2528 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2529                                      const StdMeshers_ViscousLayers* hyp,
2530                                      const TopoDS_Shape&             hypShape,
2531                                      set<TGeomID>&                   ignoreFaceIds)
2532 {
2533   TopExp_Explorer exp;
2534
2535   vector<TGeomID> ids = hyp->GetBndShapes();
2536   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2537   {
2538     for ( size_t ii = 0; ii < ids.size(); ++ii )
2539     {
2540       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2541       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2542         ignoreFaceIds.insert( ids[ii] );
2543     }
2544   }
2545   else // FACEs with layers are given
2546   {
2547     exp.Init( solid, TopAbs_FACE );
2548     for ( ; exp.More(); exp.Next() )
2549     {
2550       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2551       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2552         ignoreFaceIds.insert( faceInd );
2553     }
2554   }
2555
2556   // ignore internal FACEs if inlets and outlets are specified
2557   if ( hyp->IsToIgnoreShapes() )
2558   {
2559     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2560     TopExp::MapShapesAndAncestors( hypShape,
2561                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2562
2563     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2564     {
2565       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2566       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2567         continue;
2568
2569       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2570       if ( nbSolids > 1 )
2571         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2572     }
2573   }
2574 }
2575
2576 //================================================================================
2577 /*!
2578  * \brief Create the inner surface of the viscous layer and prepare data for infation
2579  */
2580 //================================================================================
2581
2582 bool _ViscousBuilder::makeLayer(_SolidData& data)
2583 {
2584   // make a map to find new nodes on sub-shapes shared with other SOLID
2585   map< TGeomID, TNode2Edge* >::iterator s2ne;
2586   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2587   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2588   {
2589     TGeomID shapeInd = s2s->first;
2590     for ( size_t i = 0; i < _sdVec.size(); ++i )
2591     {
2592       if ( _sdVec[i]._index == data._index ) continue;
2593       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2594       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2595            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2596       {
2597         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2598         break;
2599       }
2600     }
2601   }
2602
2603   // Create temporary faces and _LayerEdge's
2604
2605   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2606
2607   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2608
2609   data._stepSize = Precision::Infinite();
2610   data._stepSizeNodes[0] = 0;
2611
2612   SMESH_MesherHelper helper( *_mesh );
2613   helper.SetSubShape( data._solid );
2614   helper.SetElementsOnShape( true );
2615
2616   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2617   TNode2Edge::iterator n2e2;
2618
2619   // make _LayerEdge's
2620   for ( TopExp_Explorer exp( data._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2621   {
2622     const TopoDS_Face& F = TopoDS::Face( exp.Current() );
2623     SMESH_subMesh*    sm = _mesh->GetSubMesh( F );
2624     const TGeomID     id = sm->GetId();
2625     if ( edgesByGeom[ id ]._shape.IsNull() )
2626       continue; // no layers
2627     SMESH_ProxyMesh::SubMesh* proxySub =
2628       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2629
2630     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2631     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << id, data._index );
2632
2633     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2634     while ( eIt->more() )
2635     {
2636       const SMDS_MeshElement* face = eIt->next();
2637       double          faceMaxCosin = -1;
2638       _LayerEdge*     maxCosinEdge = 0;
2639       int             nbDegenNodes = 0;
2640
2641       newNodes.resize( face->NbCornerNodes() );
2642       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2643       {
2644         const SMDS_MeshNode* n = face->GetNode( i );
2645         const int      shapeID = n->getshapeId();
2646         const bool onDegenShap = helper.IsDegenShape( shapeID );
2647         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2648         if ( onDegenShap )
2649         {
2650           if ( onDegenEdge )
2651           {
2652             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2653             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2654             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2655             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2656               n = vN;
2657               nbDegenNodes++;
2658             }
2659           }
2660           else
2661           {
2662             nbDegenNodes++;
2663           }
2664         }
2665         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2666         if ( !(*n2e).second )
2667         {
2668           // add a _LayerEdge
2669           _LayerEdge* edge = _Factory::NewLayerEdge();
2670           edge->_nodes.push_back( n );
2671           n2e->second = edge;
2672           edgesByGeom[ shapeID ]._edges.push_back( edge );
2673           const bool noShrink = data._noShrinkShapes.count( shapeID );
2674
2675           SMESH_TNodeXYZ xyz( n );
2676
2677           // set edge data or find already refined _LayerEdge and get data from it
2678           if (( !noShrink                                                     ) &&
2679               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2680               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2681               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2682           {
2683             _LayerEdge* foundEdge = (*n2e2).second;
2684             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2685             foundEdge->_pos.push_back( lastPos );
2686             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2687             const_cast< SMDS_MeshNode* >
2688               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2689           }
2690           else
2691           {
2692             if ( !noShrink )
2693             {
2694               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2695             }
2696             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2697               return false;
2698
2699             if ( edge->_nodes.size() < 2 )
2700               edge->Block( data );
2701               //data._noShrinkShapes.insert( shapeID );
2702           }
2703           dumpMove(edge->_nodes.back());
2704
2705           if ( edge->_cosin > faceMaxCosin )
2706           {
2707             faceMaxCosin = edge->_cosin;
2708             maxCosinEdge = edge;
2709           }
2710         }
2711         newNodes[ i ] = n2e->second->_nodes.back();
2712
2713         if ( onDegenEdge )
2714           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2715       }
2716       if ( newNodes.size() - nbDegenNodes < 2 )
2717         continue;
2718
2719       // create a temporary face
2720       const SMDS_MeshElement* newFace =
2721         new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2722       proxySub->AddElement( newFace );
2723
2724       // compute inflation step size by min size of element on a convex surface
2725       if ( faceMaxCosin > theMinSmoothCosin )
2726         limitStepSize( data, face, maxCosinEdge );
2727
2728     } // loop on 2D elements on a FACE
2729   } // loop on FACEs of a SOLID to create _LayerEdge's
2730
2731
2732   // Set _LayerEdge::_neibors
2733   TNode2Edge::iterator n2e;
2734   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2735   {
2736     _EdgesOnShape& eos = data._edgesOnShape[iS];
2737     for ( size_t i = 0; i < eos._edges.size(); ++i )
2738     {
2739       _LayerEdge* edge = eos._edges[i];
2740       TIDSortedNodeSet nearNodes;
2741       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2742       while ( fIt->more() )
2743       {
2744         const SMDS_MeshElement* f = fIt->next();
2745         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2746           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2747       }
2748       nearNodes.erase( edge->_nodes[0] );
2749       edge->_neibors.reserve( nearNodes.size() );
2750       TIDSortedNodeSet::iterator node = nearNodes.begin();
2751       for ( ; node != nearNodes.end(); ++node )
2752         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2753           edge->_neibors.push_back( n2e->second );
2754     }
2755   }
2756
2757   data._epsilon = 1e-7;
2758   if ( data._stepSize < 1. )
2759     data._epsilon *= data._stepSize;
2760
2761   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2762     return false;
2763
2764   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2765   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2766
2767   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2768   const SMDS_MeshNode* nn[2];
2769   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2770   {
2771     _EdgesOnShape& eos = data._edgesOnShape[iS];
2772     for ( size_t i = 0; i < eos._edges.size(); ++i )
2773     {
2774       _LayerEdge* edge = eos._edges[i];
2775       if ( edge->IsOnEdge() )
2776       {
2777         // get neighbor nodes
2778         bool hasData = ( edge->_2neibors->_edges[0] );
2779         if ( hasData ) // _LayerEdge is a copy of another one
2780         {
2781           nn[0] = edge->_2neibors->srcNode(0);
2782           nn[1] = edge->_2neibors->srcNode(1);
2783         }
2784         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2785         {
2786           return false;
2787         }
2788         // set neighbor _LayerEdge's
2789         for ( int j = 0; j < 2; ++j )
2790         {
2791           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2792             return error("_LayerEdge not found by src node", data._index);
2793           edge->_2neibors->_edges[j] = n2e->second;
2794         }
2795         if ( !hasData )
2796           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2797       }
2798
2799       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2800       {
2801         _Simplex& s = edge->_simplices[j];
2802         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2803         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2804       }
2805
2806       // For an _LayerEdge on a degenerated EDGE, copy some data from
2807       // a corresponding _LayerEdge on a VERTEX
2808       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2809       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2810       {
2811         // Generally we should not get here
2812         if ( eos.ShapeType() != TopAbs_EDGE )
2813           continue;
2814         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2815         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2816         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2817           continue;
2818         const _LayerEdge* vEdge = n2e->second;
2819         edge->_normal    = vEdge->_normal;
2820         edge->_lenFactor = vEdge->_lenFactor;
2821         edge->_cosin     = vEdge->_cosin;
2822       }
2823
2824     } // loop on data._edgesOnShape._edges
2825   } // loop on data._edgesOnShape
2826
2827   // fix _LayerEdge::_2neibors on EDGEs to smooth
2828   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2829   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2830   //   if ( !e2c->second.IsNull() )
2831   //   {
2832   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2833   //       data.Sort2NeiborsOnEdge( eos->_edges );
2834   //   }
2835
2836   dumpFunctionEnd();
2837   return true;
2838 }
2839
2840 //================================================================================
2841 /*!
2842  * \brief Compute inflation step size by min size of element on a convex surface
2843  */
2844 //================================================================================
2845
2846 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2847                                      const SMDS_MeshElement* face,
2848                                      const _LayerEdge*       maxCosinEdge )
2849 {
2850   int iN = 0;
2851   double minSize = 10 * data._stepSize;
2852   const int nbNodes = face->NbCornerNodes();
2853   for ( int i = 0; i < nbNodes; ++i )
2854   {
2855     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2856     const SMDS_MeshNode*  curN = face->GetNode( i );
2857     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2858          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2859     {
2860       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2861       if ( dist < minSize )
2862         minSize = dist, iN = i;
2863     }
2864   }
2865   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2866   if ( newStep < data._stepSize )
2867   {
2868     data._stepSize = newStep;
2869     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2870     data._stepSizeNodes[0] = face->GetNode( iN );
2871     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2872   }
2873 }
2874
2875 //================================================================================
2876 /*!
2877  * \brief Compute inflation step size by min size of element on a convex surface
2878  */
2879 //================================================================================
2880
2881 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2882 {
2883   if ( minSize < data._stepSize )
2884   {
2885     data._stepSize = minSize;
2886     if ( data._stepSizeNodes[0] )
2887     {
2888       double dist =
2889         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2890       data._stepSizeCoeff = data._stepSize / dist;
2891     }
2892   }
2893 }
2894
2895 //================================================================================
2896 /*!
2897  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2898  */
2899 //================================================================================
2900
2901 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2902 {
2903   SMESH_MesherHelper helper( *_mesh );
2904
2905   BRepLProp_SLProps surfProp( 2, 1e-6 );
2906   data._convexFaces.clear();
2907
2908   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2909   {
2910     _EdgesOnShape& eof = data._edgesOnShape[iS];
2911     if ( eof.ShapeType() != TopAbs_FACE ||
2912          data._ignoreFaceIds.count( eof._shapeID ))
2913       continue;
2914
2915     TopoDS_Face        F = TopoDS::Face( eof._shape );
2916     const TGeomID faceID = eof._shapeID;
2917
2918     BRepAdaptor_Surface surface( F, false );
2919     surfProp.SetSurface( surface );
2920
2921     _ConvexFace cnvFace;
2922     cnvFace._face = F;
2923     cnvFace._normalsFixed = false;
2924     cnvFace._isTooCurved = false;
2925
2926     double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2927     if ( maxCurvature > 0 )
2928     {
2929       limitStepSize( data, 0.9 / maxCurvature );
2930       findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2931     }
2932     if ( !cnvFace._isTooCurved ) continue;
2933
2934     _ConvexFace & convFace =
2935       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2936
2937     // skip a closed surface (data._convexFaces is useful anyway)
2938     bool isClosedF = false;
2939     helper.SetSubShape( F );
2940     if ( helper.HasRealSeam() )
2941     {
2942       // in the closed surface there must be a closed EDGE
2943       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2944         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2945     }
2946     if ( isClosedF )
2947     {
2948       // limit _LayerEdge::_maxLen on the FACE
2949       const double oriFactor    = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2950       const double minCurvature =
2951         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2952       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2953       if ( id2eos != cnvFace._subIdToEOS.end() )
2954       {
2955         _EdgesOnShape& eos = * id2eos->second;
2956         for ( size_t i = 0; i < eos._edges.size(); ++i )
2957         {
2958           _LayerEdge* ledge = eos._edges[ i ];
2959           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2960           surfProp.SetParameters( uv.X(), uv.Y() );
2961           if ( surfProp.IsCurvatureDefined() )
2962           {
2963             double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2964                                     surfProp.MinCurvature() * oriFactor );
2965             if ( curvature > minCurvature )
2966               ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
2967           }
2968         }
2969       }
2970       continue;
2971     }
2972
2973     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2974     // prism distortion.
2975     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2976     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2977     {
2978       // there are _LayerEdge's on the FACE it-self;
2979       // select _LayerEdge's near EDGEs
2980       _EdgesOnShape& eos = * id2eos->second;
2981       for ( size_t i = 0; i < eos._edges.size(); ++i )
2982       {
2983         _LayerEdge* ledge = eos._edges[ i ];
2984         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2985           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2986           {
2987             // do not select _LayerEdge's neighboring sharp EDGEs
2988             bool sharpNbr = false;
2989             for ( size_t iN = 0; iN < ledge->_neibors.size()  && !sharpNbr; ++iN )
2990               sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
2991             if ( !sharpNbr )
2992               convFace._simplexTestEdges.push_back( ledge );
2993             break;
2994           }
2995       }
2996     }
2997     else
2998     {
2999       // where there are no _LayerEdge's on a _ConvexFace,
3000       // as e.g. on a fillet surface with no internal nodes - issue 22580,
3001       // so that collision of viscous internal faces is not detected by check of
3002       // intersection of _LayerEdge's with the viscous internal faces.
3003
3004       set< const SMDS_MeshNode* > usedNodes;
3005
3006       // look for _LayerEdge's with null _sWOL
3007       id2eos = convFace._subIdToEOS.begin();
3008       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
3009       {
3010         _EdgesOnShape& eos = * id2eos->second;
3011         if ( !eos._sWOL.IsNull() )
3012           continue;
3013         for ( size_t i = 0; i < eos._edges.size(); ++i )
3014         {
3015           _LayerEdge* ledge = eos._edges[ i ];
3016           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
3017           if ( !usedNodes.insert( srcNode ).second ) continue;
3018
3019           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
3020           {
3021             usedNodes.insert( ledge->_simplices[i]._nPrev );
3022             usedNodes.insert( ledge->_simplices[i]._nNext );
3023           }
3024           convFace._simplexTestEdges.push_back( ledge );
3025         }
3026       }
3027     }
3028   } // loop on FACEs of data._solid
3029 }
3030
3031 //================================================================================
3032 /*!
3033  * \brief Detect shapes (and _LayerEdge's on them) to smooth
3034  */
3035 //================================================================================
3036
3037 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
3038 {
3039   // define allowed thickness
3040   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
3041
3042
3043   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
3044   // boundary inclined to the shape at a sharp angle
3045
3046   TopTools_MapOfShape edgesOfSmooFaces;
3047   SMESH_MesherHelper helper( *_mesh );
3048   bool ok = true;
3049
3050   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3051   data._nbShapesToSmooth = 0;
3052
3053   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3054   {
3055     _EdgesOnShape& eos = edgesByGeom[iS];
3056     eos._toSmooth = false;
3057     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
3058       continue;
3059
3060     double tgtThick = eos._hyp.GetTotalThickness();
3061     SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
3062     while ( subIt->more() && !eos._toSmooth )
3063     {
3064       TGeomID iSub = subIt->next()->GetId();
3065       const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
3066       if ( eSub.empty() ) continue;
3067
3068       double faceSize;
3069       for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3070         if ( eSub[i]->_cosin > theMinSmoothCosin )
3071         {
3072           SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3073           while ( fIt->more() && !eos._toSmooth )
3074           {
3075             const SMDS_MeshElement* face = fIt->next();
3076             if ( face->getshapeId() == eos._shapeID &&
3077                  getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3078             {
3079               eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3080                                              tgtThick * eSub[i]->_lenFactor,
3081                                              faceSize);
3082             }
3083           }
3084         }
3085     }
3086     if ( eos._toSmooth )
3087     {
3088       for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3089         edgesOfSmooFaces.Add( eExp.Current() );
3090
3091       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3092     }
3093     data._nbShapesToSmooth += eos._toSmooth;
3094
3095   }  // check FACEs
3096
3097   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3098   {
3099     _EdgesOnShape& eos = edgesByGeom[iS];
3100     eos._edgeSmoother = NULL;
3101     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3102     if ( !eos._hyp.ToSmooth() ) continue;
3103
3104     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3105     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3106       continue;
3107
3108     double tgtThick = eos._hyp.GetTotalThickness();
3109     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3110     {
3111       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3112       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3113       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3114       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3115       double angle    = eDir.Angle( eV[0]->_normal );
3116       double cosin    = Cos( angle );
3117       double cosinAbs = Abs( cosin );
3118       if ( cosinAbs > theMinSmoothCosin )
3119       {
3120         // always smooth analytic EDGEs
3121         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3122         eos._toSmooth = ! curve.IsNull();
3123
3124         // compare tgtThick with the length of an end segment
3125         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3126         while ( eIt->more() && !eos._toSmooth )
3127         {
3128           const SMDS_MeshElement* endSeg = eIt->next();
3129           if ( endSeg->getshapeId() == (int) iS )
3130           {
3131             double segLen =
3132               SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3133             eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3134           }
3135         }
3136         if ( eos._toSmooth )
3137         {
3138           eos._edgeSmoother = new _Smoother1D( curve, eos );
3139
3140           // for ( size_t i = 0; i < eos._edges.size(); ++i )
3141           //   eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3142         }
3143       }
3144     }
3145     data._nbShapesToSmooth += eos._toSmooth;
3146
3147   } // check EDGEs
3148
3149   // Reset _cosin if no smooth is allowed by the user
3150   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3151   {
3152     _EdgesOnShape& eos = edgesByGeom[iS];
3153     if ( eos._edges.empty() ) continue;
3154
3155     if ( !eos._hyp.ToSmooth() )
3156       for ( size_t i = 0; i < eos._edges.size(); ++i )
3157         //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3158         eos._edges[i]->_lenFactor = 1;
3159   }
3160
3161
3162   // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3163
3164   TopTools_MapOfShape c1VV;
3165
3166   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3167   {
3168     _EdgesOnShape& eos = edgesByGeom[iS];
3169     if ( eos._edges.empty() ||
3170          eos.ShapeType() != TopAbs_FACE ||
3171          !eos._toSmooth )
3172       continue;
3173
3174     // check EDGEs of a FACE
3175     TopTools_MapOfShape checkedEE, allVV;
3176     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3177     while ( !smQueue.empty() )
3178     {
3179       SMESH_subMesh* sm = smQueue.front();
3180       smQueue.pop_front();
3181       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3182       while ( smIt->more() )
3183       {
3184         sm = smIt->next();
3185         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3186           allVV.Add( sm->GetSubShape() );
3187         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3188              !checkedEE.Add( sm->GetSubShape() ))
3189           continue;
3190
3191         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3192         vector<_LayerEdge*>& eE = eoe->_edges;
3193         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3194           continue;
3195
3196         bool isC1 = true; // check continuity along an EDGE
3197         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3198           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3199         if ( !isC1 )
3200           continue;
3201
3202         // check that mesh faces are C1 as well
3203         {
3204           gp_XYZ norm1, norm2;
3205           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3206           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3207           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3208             continue;
3209           while ( fIt->more() && isC1 )
3210             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3211                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3212           if ( !isC1 )
3213             continue;
3214         }
3215
3216         // add the EDGE and an adjacent FACE to _eosC1
3217         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3218         while ( const TopoDS_Shape* face = fIt->next() )
3219         {
3220           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3221           if ( !eof ) continue; // other solid
3222           if ( eos._shapeID == eof->_shapeID ) continue;
3223           if ( !eos.HasC1( eof ))
3224           {
3225             // check the FACEs
3226             eos._eosC1.push_back( eof );
3227             eof->_toSmooth = false;
3228             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3229             smQueue.push_back( eof->_subMesh );
3230           }
3231           if ( !eos.HasC1( eoe ))
3232           {
3233             eos._eosC1.push_back( eoe );
3234             eoe->_toSmooth = false;
3235             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3236           }
3237         }
3238       }
3239     }
3240     if ( eos._eosC1.empty() )
3241       continue;
3242
3243     // check VERTEXes of C1 FACEs
3244     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3245     for ( ; vIt.More(); vIt.Next() )
3246     {
3247       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3248       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3249         continue;
3250
3251       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3252       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3253       while ( const TopoDS_Shape* face = fIt->next() )
3254       {
3255         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3256         if ( !eof ) continue; // other solid
3257         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3258         if ( !isC1 )
3259           break;
3260       }
3261       if ( isC1 )
3262       {
3263         eos._eosC1.push_back( eov );
3264         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3265         c1VV.Add( eov->_shape );
3266       }
3267     }
3268
3269   } // fill _eosC1 of FACEs
3270
3271
3272   // Find C1 EDGEs
3273
3274   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3275
3276   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3277   {
3278     _EdgesOnShape& eov = edgesByGeom[iS];
3279     if ( eov._edges.empty() ||
3280          eov.ShapeType() != TopAbs_VERTEX ||
3281          c1VV.Contains( eov._shape ))
3282       continue;
3283     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3284
3285     // get directions of surrounding EDGEs
3286     dirOfEdges.clear();
3287     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3288     while ( const TopoDS_Shape* e = fIt->next() )
3289     {
3290       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3291       if ( !eoe ) continue; // other solid
3292       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3293       if ( !Precision::IsInfinite( eDir.X() ))
3294         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3295     }
3296
3297     // find EDGEs with C1 directions
3298     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3299       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3300         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3301         {
3302           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3303           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3304           if ( isC1 )
3305           {
3306             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3307             for ( int isJ = 0; isJ < 2; ++isJ ) // loop on [i,j]
3308             {
3309               size_t k = isJ ? j : i;
3310               const TopoDS_Edge& e = TopoDS::Edge( dirOfEdges[k].first->_shape );
3311               double eLen = SMESH_Algo::EdgeLength( e );
3312               if ( eLen < maxEdgeLen )
3313               {
3314                 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
3315                 if ( oppV.IsSame( V ))
3316                   oppV = SMESH_MesherHelper::IthVertex( 1, e );
3317                 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
3318                 if ( dirOfEdges[k].second * eovOpp->_edges[0]->_normal < 0 )
3319                   eov._eosC1.push_back( dirOfEdges[k].first );
3320               }
3321               dirOfEdges[k].first = 0;
3322             }
3323           }
3324         }
3325   } // fill _eosC1 of VERTEXes
3326
3327
3328
3329   return ok;
3330 }
3331
3332 //================================================================================
3333 /*!
3334  * \brief Set up _SolidData::_edgesOnShape
3335  */
3336 //================================================================================
3337
3338 void _ViscousBuilder::makeEdgesOnShape()
3339 {
3340   const int nbShapes = getMeshDS()->MaxShapeIndex();
3341
3342   for ( size_t i = 0; i < _sdVec.size(); ++i )
3343   {
3344     _SolidData& data = _sdVec[ i ];
3345     vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3346     edgesByGeom.resize( nbShapes+1 );
3347
3348     // set data of _EdgesOnShape's
3349     if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
3350     {
3351       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3352       while ( smIt->more() )
3353       {
3354         sm = smIt->next();
3355         if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
3356              data._ignoreFaceIds.count( sm->GetId() ))
3357           continue;
3358
3359         setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
3360       }
3361     }
3362   }
3363 }
3364
3365 //================================================================================
3366 /*!
3367  * \brief initialize data of _EdgesOnShape
3368  */
3369 //================================================================================
3370
3371 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3372                                     SMESH_subMesh* sm,
3373                                     _SolidData&    data )
3374 {
3375   if ( !eos._shape.IsNull() ||
3376        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3377     return;
3378
3379   SMESH_MesherHelper helper( *_mesh );
3380
3381   eos._subMesh = sm;
3382   eos._shapeID = sm->GetId();
3383   eos._shape   = sm->GetSubShape();
3384   if ( eos.ShapeType() == TopAbs_FACE )
3385     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3386   eos._toSmooth = false;
3387   eos._data = &data;
3388
3389   // set _SWOL
3390   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3391     data._shrinkShape2Shape.find( eos._shapeID );
3392   if ( s2s != data._shrinkShape2Shape.end() )
3393     eos._sWOL = s2s->second;
3394
3395   eos._isRegularSWOL = true;
3396   if ( eos.SWOLType() == TopAbs_FACE )
3397   {
3398     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3399     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3400     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3401   }
3402
3403   // set _hyp
3404   if ( data._hyps.size() == 1 )
3405   {
3406     eos._hyp = data._hyps.back();
3407   }
3408   else
3409   {
3410     // compute average StdMeshers_ViscousLayers parameters
3411     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3412     if ( eos.ShapeType() == TopAbs_FACE )
3413     {
3414       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3415         eos._hyp = f2hyp->second;
3416     }
3417     else
3418     {
3419       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3420       while ( const TopoDS_Shape* face = fIt->next() )
3421       {
3422         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3423         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3424           eos._hyp.Add( f2hyp->second );
3425       }
3426     }
3427   }
3428
3429   // set _faceNormals
3430   if ( ! eos._hyp.UseSurfaceNormal() )
3431   {
3432     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3433     {
3434       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3435       if ( !smDS ) return;
3436       eos._faceNormals.reserve( smDS->NbElements() );
3437
3438       double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3439       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3440       for ( ; eIt->more(); )
3441       {
3442         const SMDS_MeshElement* face = eIt->next();
3443         gp_XYZ&                 norm = eos._faceNormals[face];
3444         if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3445           norm.SetCoord( 0,0,0 );
3446         norm *= oriFactor;
3447       }
3448     }
3449     else // find EOS of adjacent FACEs
3450     {
3451       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3452       while ( const TopoDS_Shape* face = fIt->next() )
3453       {
3454         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3455         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3456         if ( eos._faceEOS.back()->_shape.IsNull() )
3457           // avoid using uninitialised _shapeID in GetNormal()
3458           eos._faceEOS.back()->_shapeID = faceID;
3459       }
3460     }
3461   }
3462 }
3463
3464 //================================================================================
3465 /*!
3466  * \brief Returns normal of a face
3467  */
3468 //================================================================================
3469
3470 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3471 {
3472   bool ok = false;
3473   _EdgesOnShape* eos = 0;
3474
3475   if ( face->getshapeId() == _shapeID )
3476   {
3477     eos = this;
3478   }
3479   else
3480   {
3481     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3482       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3483         eos = _faceEOS[ iF ];
3484   }
3485
3486   if (( eos ) &&
3487       ( ok = ( eos->_faceNormals.count( face ) )))
3488   {
3489     norm = eos->_faceNormals[ face ];
3490   }
3491   else if ( !eos )
3492   {
3493     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3494               << " on _shape #" << _shapeID );
3495   }
3496   return ok;
3497 }
3498
3499 //================================================================================
3500 /*!
3501  * \brief EdgesOnShape destructor
3502  */
3503 //================================================================================
3504
3505 _EdgesOnShape::~_EdgesOnShape()
3506 {
3507   delete _edgeSmoother;
3508 }
3509
3510 //================================================================================
3511 /*!
3512  * \brief Set data of _LayerEdge needed for smoothing
3513  */
3514 //================================================================================
3515
3516 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3517                                   _EdgesOnShape&      eos,
3518                                   SMESH_MesherHelper& helper,
3519                                   _SolidData&         data)
3520 {
3521   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3522
3523   edge._len          = 0;
3524   edge._maxLen       = Precision::Infinite();
3525   edge._minAngle     = 0;
3526   edge._2neibors     = 0;
3527   edge._curvature    = 0;
3528   edge._flags        = 0;
3529   edge._smooFunction = 0;
3530
3531   // --------------------------
3532   // Compute _normal and _cosin
3533   // --------------------------
3534
3535   edge._cosin     = 0;
3536   edge._lenFactor = 1.;
3537   edge._normal.SetCoord(0,0,0);
3538   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3539
3540   int totalNbFaces = 0;
3541   TopoDS_Face F;
3542   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3543   gp_Vec geomNorm;
3544   bool normOK = true;
3545
3546   const bool onShrinkShape = !eos._sWOL.IsNull();
3547   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3548                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3549
3550   // get geom FACEs the node lies on
3551   //if ( useGeometry )
3552   {
3553     set<TGeomID> faceIds;
3554     if  ( eos.ShapeType() == TopAbs_FACE )
3555     {
3556       faceIds.insert( eos._shapeID );
3557     }
3558     else
3559     {
3560       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3561       while ( fIt->more() )
3562         faceIds.insert( fIt->next()->getshapeId() );
3563     }
3564     set<TGeomID>::iterator id = faceIds.begin();
3565     for ( ; id != faceIds.end(); ++id )
3566     {
3567       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3568       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3569         continue;
3570       F = TopoDS::Face( s );
3571       face2Norm[ totalNbFaces ].first = F;
3572       totalNbFaces++;
3573     }
3574   }
3575
3576   // find _normal
3577   bool fromVonF = false;
3578   if ( useGeometry )
3579   {
3580     fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3581                  eos.SWOLType()  == TopAbs_FACE  &&
3582                  totalNbFaces > 1 );
3583
3584     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3585     {
3586       if ( eos.SWOLType() == TopAbs_EDGE )
3587       {
3588         // inflate from VERTEX along EDGE
3589         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3590       }
3591       else if ( eos.ShapeType() == TopAbs_VERTEX )
3592       {
3593         // inflate from VERTEX along FACE
3594         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3595                                    node, helper, normOK, &edge._cosin);
3596       }
3597       else
3598       {
3599         // inflate from EDGE along FACE
3600         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3601                                    node, helper, normOK);
3602       }
3603     }
3604     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3605     {
3606       if ( fromVonF )
3607         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3608
3609       int nbOkNorms = 0;
3610       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3611       {
3612         F = face2Norm[ iF ].first;
3613         geomNorm = getFaceNormal( node, F, helper, normOK );
3614         if ( !normOK ) continue;
3615         nbOkNorms++;
3616
3617         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3618           geomNorm.Reverse();
3619         face2Norm[ iF ].second = geomNorm.XYZ();
3620         edge._normal += geomNorm.XYZ();
3621       }
3622       if ( nbOkNorms == 0 )
3623         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3624
3625       if ( totalNbFaces >= 3 )
3626       {
3627         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3628       }
3629
3630       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3631       {
3632         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3633         edge._normal.SetCoord( 0,0,0 );
3634         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3635         {
3636           const TopoDS_Face& F = face2Norm[iF].first;
3637           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3638           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3639             geomNorm.Reverse();
3640           if ( normOK )
3641             face2Norm[ iF ].second = geomNorm.XYZ();
3642           edge._normal += face2Norm[ iF ].second;
3643         }
3644       }
3645     }
3646   }
3647   else // !useGeometry - get _normal using surrounding mesh faces
3648   {
3649     edge._normal = getWeigthedNormal( &edge );
3650
3651     // set<TGeomID> faceIds;
3652     //
3653     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3654     // while ( fIt->more() )
3655     // {
3656     //   const SMDS_MeshElement* face = fIt->next();
3657     //   if ( eos.GetNormal( face, geomNorm ))
3658     //   {
3659     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3660     //       continue; // use only one mesh face on FACE
3661     //     edge._normal += geomNorm.XYZ();
3662     //     totalNbFaces++;
3663     //   }
3664     // }
3665   }
3666
3667   // compute _cosin
3668   //if ( eos._hyp.UseSurfaceNormal() )
3669   {
3670     switch ( eos.ShapeType() )
3671     {
3672     case TopAbs_FACE: {
3673       edge._cosin = 0;
3674       break;
3675     }
3676     case TopAbs_EDGE: {
3677       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3678       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3679       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3680       edge._cosin      = Cos( angle );
3681       break;
3682     }
3683     case TopAbs_VERTEX: {
3684       if ( fromVonF )
3685       {
3686         getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3687                     node, helper, normOK, &edge._cosin );
3688       }
3689       else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3690       {
3691         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3692         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3693         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3694         edge._cosin      = Cos( angle );
3695         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3696           for ( int iF = 1; iF < totalNbFaces; ++iF )
3697           {
3698             F = face2Norm[ iF ].first;
3699             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3700             if ( normOK ) {
3701               double angle = inFaceDir.Angle( edge._normal );
3702               double cosin = Cos( angle );
3703               if ( Abs( cosin ) > Abs( edge._cosin ))
3704                 edge._cosin = cosin;
3705             }
3706           }
3707       }
3708       break;
3709     }
3710     default:
3711       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3712     }
3713   }
3714
3715   double normSize = edge._normal.SquareModulus();
3716   if ( normSize < numeric_limits<double>::min() )
3717     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3718
3719   edge._normal /= sqrt( normSize );
3720
3721   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3722   {
3723     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3724     edge._nodes.resize( 1 );
3725     edge._normal.SetCoord( 0,0,0 );
3726     edge.SetMaxLen( 0 );
3727   }
3728
3729   // Set the rest data
3730   // --------------------
3731
3732   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3733
3734   if ( onShrinkShape )
3735   {
3736     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3737     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3738       sm->RemoveNode( tgtNode );
3739
3740     // set initial position which is parameters on _sWOL in this case
3741     if ( eos.SWOLType() == TopAbs_EDGE )
3742     {
3743       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3744       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3745       if ( edge._nodes.size() > 1 )
3746         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3747     }
3748     else // eos.SWOLType() == TopAbs_FACE
3749     {
3750       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3751       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3752       if ( edge._nodes.size() > 1 )
3753         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3754     }
3755
3756     if ( edge._nodes.size() > 1 )
3757     {
3758       // check if an angle between a FACE with layers and SWOL is sharp,
3759       // else the edge should not inflate
3760       F.Nullify();
3761       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3762         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3763           F = face2Norm[iF].first;
3764       if ( !F.IsNull())
3765       {
3766         geomNorm = getFaceNormal( node, F, helper, normOK );
3767         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3768           geomNorm.Reverse(); // inside the SOLID
3769         if ( geomNorm * edge._normal < -0.001 )
3770         {
3771           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3772           edge._nodes.resize( 1 );
3773         }
3774         else if ( edge._lenFactor > 3 )
3775         {
3776           edge._lenFactor = 2;
3777           edge.Set( _LayerEdge::RISKY_SWOL );
3778         }
3779       }
3780     }
3781   }
3782   else
3783   {
3784     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3785
3786     if ( eos.ShapeType() == TopAbs_FACE )
3787     {
3788       double angle;
3789       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3790       {
3791         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3792         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3793       }
3794     }
3795   }
3796
3797   // Set neighbor nodes for a _LayerEdge based on EDGE
3798
3799   if ( eos.ShapeType() == TopAbs_EDGE /*||
3800        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3801   {
3802     edge._2neibors = _Factory::NewNearEdges();
3803     // target nodes instead of source ones will be set later
3804   }
3805
3806   return true;
3807 }
3808
3809 //================================================================================
3810 /*!
3811  * \brief Return normal to a FACE at a node
3812  *  \param [in] n - node
3813  *  \param [in] face - FACE
3814  *  \param [in] helper - helper
3815  *  \param [out] isOK - true or false
3816  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3817  *  \return gp_XYZ - normal
3818  */
3819 //================================================================================
3820
3821 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3822                                       const TopoDS_Face&   face,
3823                                       SMESH_MesherHelper&  helper,
3824                                       bool&                isOK,
3825                                       bool                 shiftInside)
3826 {
3827   gp_XY uv;
3828   if ( shiftInside )
3829   {
3830     // get a shifted position
3831     gp_Pnt p = SMESH_TNodeXYZ( node );
3832     gp_XYZ shift( 0,0,0 );
3833     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3834     switch ( S.ShapeType() ) {
3835     case TopAbs_VERTEX:
3836     {
3837       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3838       break;
3839     }
3840     case TopAbs_EDGE:
3841     {
3842       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3843       break;
3844     }
3845     default:
3846       isOK = false;
3847     }
3848     if ( isOK )
3849       shift.Normalize();
3850     p.Translate( shift * 1e-5 );
3851
3852     TopLoc_Location loc;
3853     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3854
3855     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3856     
3857     projector.Perform( p );
3858     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3859     {
3860       isOK = false;
3861       return p.XYZ();
3862     }
3863     Standard_Real U,V;
3864     projector.LowerDistanceParameters(U,V);
3865     uv.SetCoord( U,V );
3866   }
3867   else
3868   {
3869     uv = helper.GetNodeUV( face, node, 0, &isOK );
3870   }
3871
3872   gp_Dir normal;
3873   isOK = false;
3874
3875   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3876
3877   if ( !shiftInside &&
3878        helper.IsDegenShape( node->getshapeId() ) &&
3879        getFaceNormalAtSingularity( uv, face, helper, normal ))
3880   {
3881     isOK = true;
3882     return normal.XYZ();
3883   }
3884
3885   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3886   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3887
3888   if ( pointKind == IMPOSSIBLE &&
3889        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3890   {
3891     // probably NormEstim() failed due to a too high tolerance
3892     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3893     isOK = ( pointKind < IMPOSSIBLE );
3894   }
3895   if ( pointKind < IMPOSSIBLE )
3896   {
3897     if ( pointKind != REGULAR &&
3898          !shiftInside &&
3899          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3900     {
3901       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3902       if ( normShift * normal.XYZ() < 0. )
3903         normal = normShift;
3904     }
3905     isOK = true;
3906   }
3907
3908   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3909   {
3910     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3911
3912     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3913     while ( fIt->more() )
3914     {
3915       const SMDS_MeshElement* f = fIt->next();
3916       if ( f->getshapeId() == faceID )
3917       {
3918         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3919         if ( isOK )
3920         {
3921           TopoDS_Face ff = face;
3922           ff.Orientation( TopAbs_FORWARD );
3923           if ( helper.IsReversedSubMesh( ff ))
3924             normal.Reverse();
3925           break;
3926         }
3927       }
3928     }
3929   }
3930   return normal.XYZ();
3931 }
3932
3933 //================================================================================
3934 /*!
3935  * \brief Try to get normal at a singularity of a surface basing on it's nature
3936  */
3937 //================================================================================
3938
3939 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3940                                                   const TopoDS_Face&  face,
3941                                                   SMESH_MesherHelper& helper,
3942                                                   gp_Dir&             normal )
3943 {
3944   BRepAdaptor_Surface surface( face );
3945   gp_Dir axis;
3946   if ( !getRovolutionAxis( surface, axis ))
3947     return false;
3948
3949   double f,l, d, du, dv;
3950   f = surface.FirstUParameter();
3951   l = surface.LastUParameter();
3952   d = ( uv.X() - f ) / ( l - f );
3953   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3954   f = surface.FirstVParameter();
3955   l = surface.LastVParameter();
3956   d = ( uv.Y() - f ) / ( l - f );
3957   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3958
3959   gp_Dir refDir;
3960   gp_Pnt2d testUV = uv;
3961   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3962   double tol = 1e-5;
3963   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3964   for ( int iLoop = 0; true ; ++iLoop )
3965   {
3966     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3967     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3968       break;
3969     if ( iLoop > 20 )
3970       return false;
3971     tol /= 10.;
3972   }
3973
3974   if ( axis * refDir < 0. )
3975     axis.Reverse();
3976
3977   normal = axis;
3978
3979   return true;
3980 }
3981
3982 //================================================================================
3983 /*!
3984  * \brief Return a normal at a node weighted with angles taken by faces
3985  */
3986 //================================================================================
3987
3988 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3989 {
3990   const SMDS_MeshNode* n = edge->_nodes[0];
3991
3992   gp_XYZ resNorm(0,0,0);
3993   SMESH_TNodeXYZ p0( n ), pP, pN;
3994   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3995   {
3996     pP.Set( edge->_simplices[i]._nPrev );
3997     pN.Set( edge->_simplices[i]._nNext );
3998     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3999     double l0P = v0P.SquareMagnitude();
4000     double l0N = v0N.SquareMagnitude();
4001     double lPN = vPN.SquareMagnitude();
4002     if ( l0P < std::numeric_limits<double>::min() ||
4003          l0N < std::numeric_limits<double>::min() ||
4004          lPN < std::numeric_limits<double>::min() )
4005       continue;
4006     double lNorm = norm.SquareMagnitude();
4007     double  sin2 = lNorm / l0P / l0N;
4008     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
4009
4010     double weight = sin2 * angle / lPN;
4011     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
4012   }
4013
4014   return resNorm;
4015 }
4016
4017 //================================================================================
4018 /*!
4019  * \brief Return a normal at a node by getting a common point of offset planes
4020  *        defined by the FACE normals
4021  */
4022 //================================================================================
4023
4024 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
4025                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
4026                                            int                              nbFaces,
4027                                            bool                             lastNoOffset)
4028 {
4029   SMESH_TNodeXYZ p0 = edge->_nodes[0];
4030
4031   gp_XYZ resNorm(0,0,0);
4032   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
4033   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
4034   {
4035     for ( int i = 0; i < nbFaces; ++i )
4036       resNorm += f2Normal[i].second;
4037     return resNorm;
4038   }
4039
4040   // prepare _OffsetPlane's
4041   vector< _OffsetPlane > pln( nbFaces );
4042   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4043   {
4044     pln[i]._faceIndex = i;
4045     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
4046   }
4047   if ( lastNoOffset )
4048   {
4049     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
4050     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
4051   }
4052
4053   // intersect neighboring OffsetPlane's
4054   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
4055   while ( const TopoDS_Shape* edge = edgeIt->next() )
4056   {
4057     int f1 = -1, f2 = -1;
4058     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
4059       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
4060         (( f1 < 0 ) ? f1 : f2 ) = i;
4061
4062     if ( f2 >= 0 )
4063       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
4064   }
4065
4066   // get a common point
4067   gp_XYZ commonPnt( 0, 0, 0 );
4068   int nbPoints = 0;
4069   bool isPointFound;
4070   for ( int i = 0; i < nbFaces; ++i )
4071   {
4072     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
4073     nbPoints  += isPointFound;
4074   }
4075   gp_XYZ wgtNorm = getWeigthedNormal( edge );
4076   if ( nbPoints == 0 )
4077     return wgtNorm;
4078
4079   commonPnt /= nbPoints;
4080   resNorm = commonPnt - p0;
4081   if ( lastNoOffset )
4082     return resNorm;
4083
4084   // choose the best among resNorm and wgtNorm
4085   resNorm.Normalize();
4086   wgtNorm.Normalize();
4087   double resMinDot = std::numeric_limits<double>::max();
4088   double wgtMinDot = std::numeric_limits<double>::max();
4089   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4090   {
4091     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
4092     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
4093   }
4094
4095   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
4096   {
4097     edge->Set( _LayerEdge::MULTI_NORMAL );
4098   }
4099
4100   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
4101 }
4102
4103 //================================================================================
4104 /*!
4105  * \brief Compute line of intersection of 2 planes
4106  */
4107 //================================================================================
4108
4109 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
4110                                             const TopoDS_Edge&   E,
4111                                             const TopoDS_Vertex& V )
4112 {
4113   int iNext = bool( _faceIndexNext[0] >= 0 );
4114   _faceIndexNext[ iNext ] = pln._faceIndex;
4115
4116   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
4117   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
4118
4119   gp_XYZ lineDir = n1 ^ n2;
4120
4121   double x = Abs( lineDir.X() );
4122   double y = Abs( lineDir.Y() );
4123   double z = Abs( lineDir.Z() );
4124
4125   int cooMax; // max coordinate
4126   if (x > y) {
4127     if (x > z) cooMax = 1;
4128     else       cooMax = 3;
4129   }
4130   else {
4131     if (y > z) cooMax = 2;
4132     else       cooMax = 3;
4133   }
4134
4135   gp_Pnt linePos;
4136   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4137   {
4138     // parallel planes - intersection is an offset of the common EDGE
4139     gp_Pnt p = BRep_Tool::Pnt( V );
4140     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4141     lineDir  = getEdgeDir( E, V );
4142   }
4143   else
4144   {
4145     // the constants in the 2 plane equations
4146     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
4147     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4148
4149     switch ( cooMax ) {
4150     case 1:
4151       linePos.SetX(  0 );
4152       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4153       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4154       break;
4155     case 2:
4156       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4157       linePos.SetY(  0 );
4158       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4159       break;
4160     case 3:
4161       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4162       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4163       linePos.SetZ(  0 );
4164     }
4165   }
4166   gp_Lin& line = _lines[ iNext ];
4167   line.SetDirection( lineDir );
4168   line.SetLocation ( linePos );
4169
4170   _isLineOK[ iNext ] = true;
4171
4172
4173   iNext = bool( pln._faceIndexNext[0] >= 0 );
4174   pln._lines        [ iNext ] = line;
4175   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4176   pln._isLineOK     [ iNext ] = true;
4177 }
4178
4179 //================================================================================
4180 /*!
4181  * \brief Computes intersection point of two _lines
4182  */
4183 //================================================================================
4184
4185 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4186                                     const TopoDS_Vertex & V) const
4187 {
4188   gp_XYZ p( 0,0,0 );
4189   isFound = false;
4190
4191   if ( NbLines() == 2 )
4192   {
4193     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4194     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4195     if ( Abs( dot01 ) > 0.05 )
4196     {
4197       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4198       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4199       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4200       isFound = true;
4201     }
4202     else
4203     {
4204       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4205       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4206       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4207       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4208       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4209       isFound = true;
4210     }
4211   }
4212
4213   return p;
4214 }
4215
4216 //================================================================================
4217 /*!
4218  * \brief Find 2 neighbor nodes of a node on EDGE
4219  */
4220 //================================================================================
4221
4222 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4223                                         const SMDS_MeshNode*& n1,
4224                                         const SMDS_MeshNode*& n2,
4225                                         _EdgesOnShape&        eos,
4226                                         _SolidData&           data)
4227 {
4228   const SMDS_MeshNode* node = edge->_nodes[0];
4229   const int        shapeInd = eos._shapeID;
4230   SMESHDS_SubMesh*   edgeSM = 0;
4231   if ( eos.ShapeType() == TopAbs_EDGE )
4232   {
4233     edgeSM = eos._subMesh->GetSubMeshDS();
4234     if ( !edgeSM || edgeSM->NbElements() == 0 )
4235       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4236   }
4237   int iN = 0;
4238   n2 = 0;
4239   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4240   while ( eIt->more() && !n2 )
4241   {
4242     const SMDS_MeshElement* e = eIt->next();
4243     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4244     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4245     if ( edgeSM )
4246     {
4247       if (!edgeSM->Contains(e)) continue;
4248     }
4249     else
4250     {
4251       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4252       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4253     }
4254     ( iN++ ? n2 : n1 ) = nNeibor;
4255   }
4256   if ( !n2 )
4257     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4258   return true;
4259 }
4260
4261 //================================================================================
4262 /*!
4263  * \brief Create _Curvature
4264  */
4265 //================================================================================
4266
4267 _Curvature* _Curvature::New( double avgNormProj, double avgDist )
4268 {
4269   // double   _r; // radius
4270   // double   _k; // factor to correct node smoothed position
4271   // double   _h2lenRatio; // avgNormProj / (2*avgDist)
4272   // gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
4273
4274   _Curvature* c = 0;
4275   if ( fabs( avgNormProj / avgDist ) > 1./200 )
4276   {
4277     c = _Factory::NewCurvature();
4278     c->_r = avgDist * avgDist / avgNormProj;
4279     c->_k = avgDist * avgDist / c->_r / c->_r;
4280     //c->_k = avgNormProj / c->_r;
4281     c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
4282     c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
4283
4284     c->_uv.SetCoord( 0., 0. );
4285   }
4286   return c;
4287 }
4288
4289 //================================================================================
4290 /*!
4291  * \brief Set _curvature and _2neibors->_plnNorm by 2 neighbor nodes residing the same EDGE
4292  */
4293 //================================================================================
4294
4295 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4296                                      const SMDS_MeshNode* n2,
4297                                      const _EdgesOnShape& eos,
4298                                      SMESH_MesherHelper&  helper)
4299 {
4300   if ( eos.ShapeType() != TopAbs_EDGE )
4301     return;
4302   if ( _curvature && Is( SMOOTHED_C1 ))
4303     return;
4304
4305   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4306   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4307   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4308
4309   // Set _curvature
4310
4311   double      sumLen = vec1.Modulus() + vec2.Modulus();
4312   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4313   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4314   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4315   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4316   _curvature = _Curvature::New( avgNormProj, avgLen );
4317   // if ( _curvature )
4318   //   debugMsg( _nodes[0]->GetID()
4319   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4320   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4321   //             << _curvature->lenDelta(0) );
4322
4323   // Set _plnNorm
4324
4325   if ( eos._sWOL.IsNull() )
4326   {
4327     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4328     // if ( SMESH_Algo::isDegenerated( E ))
4329     //   return;
4330     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4331     gp_XYZ plnNorm = dirE ^ _normal;
4332     double proj0   = plnNorm * vec1;
4333     double proj1   = plnNorm * vec2;
4334     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4335     {
4336       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4337       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4338     }
4339   }
4340 }
4341
4342 //================================================================================
4343 /*!
4344  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4345  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4346  */
4347 //================================================================================
4348
4349 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4350                          _EdgesOnShape&      eos,
4351                          SMESH_MesherHelper& helper )
4352 {
4353   _nodes     = other._nodes;
4354   _normal    = other._normal;
4355   _len       = 0;
4356   _lenFactor = other._lenFactor;
4357   _cosin     = other._cosin;
4358   _2neibors  = other._2neibors;
4359   _curvature = other._curvature;
4360   _2neibors  = other._2neibors;
4361   _maxLen    = Precision::Infinite();//other._maxLen;
4362   _flags     = 0;
4363   _smooFunction = 0;
4364
4365   gp_XYZ lastPos( 0,0,0 );
4366   if ( eos.SWOLType() == TopAbs_EDGE )
4367   {
4368     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4369     _pos.push_back( gp_XYZ( u, 0, 0));
4370
4371     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4372     lastPos.SetX( u );
4373   }
4374   else // TopAbs_FACE
4375   {
4376     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4377     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4378
4379     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4380     lastPos.SetX( uv.X() );
4381     lastPos.SetY( uv.Y() );
4382   }
4383   return lastPos;
4384 }
4385
4386 //================================================================================
4387 /*!
4388  * \brief Set _cosin and _lenFactor
4389  */
4390 //================================================================================
4391
4392 void _LayerEdge::SetCosin( double cosin )
4393 {
4394   _cosin = cosin;
4395   cosin = Abs( _cosin );
4396   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4397   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4398 }
4399
4400 //================================================================================
4401 /*!
4402  * \brief Check if another _LayerEdge is a neighbor on EDGE
4403  */
4404 //================================================================================
4405
4406 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4407 {
4408   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4409           ( edge->_2neibors && edge->_2neibors->include( this )));
4410 }
4411
4412 //================================================================================
4413 /*!
4414  * \brief Fills a vector<_Simplex > 
4415  */
4416 //================================================================================
4417
4418 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4419                              vector<_Simplex>&    simplices,
4420                              const set<TGeomID>&  ingnoreShapes,
4421                              const _SolidData*    dataToCheckOri,
4422                              const bool           toSort)
4423 {
4424   simplices.clear();
4425   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4426   while ( fIt->more() )
4427   {
4428     const SMDS_MeshElement* f = fIt->next();
4429     const TGeomID    shapeInd = f->getshapeId();
4430     if ( ingnoreShapes.count( shapeInd )) continue;
4431     const int nbNodes = f->NbCornerNodes();
4432     const int  srcInd = f->GetNodeIndex( node );
4433     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4434     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4435     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4436     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4437       std::swap( nPrev, nNext );
4438     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4439   }
4440
4441   if ( toSort )
4442     SortSimplices( simplices );
4443 }
4444
4445 //================================================================================
4446 /*!
4447  * \brief Set neighbor simplices side by side
4448  */
4449 //================================================================================
4450
4451 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4452 {
4453   vector<_Simplex> sortedSimplices( simplices.size() );
4454   sortedSimplices[0] = simplices[0];
4455   size_t nbFound = 0;
4456   for ( size_t i = 1; i < simplices.size(); ++i )
4457   {
4458     for ( size_t j = 1; j < simplices.size(); ++j )
4459       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4460       {
4461         sortedSimplices[i] = simplices[j];
4462         nbFound++;
4463         break;
4464       }
4465   }
4466   if ( nbFound == simplices.size() - 1 )
4467     simplices.swap( sortedSimplices );
4468 }
4469
4470 //================================================================================
4471 /*!
4472  * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4473  */
4474 //================================================================================
4475
4476 void _ViscousBuilder::makeGroupOfLE()
4477 {
4478 #ifdef _DEBUG_
4479   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4480   {
4481     if ( _sdVec[i]._n2eMap.empty() ) continue;
4482
4483     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4484     TNode2Edge::iterator n2e;
4485     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4486     {
4487       _LayerEdge* le = n2e->second;
4488       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4489       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4490       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4491       if ( le ) {
4492         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4493                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4494       }
4495     }
4496     dumpFunctionEnd();
4497
4498     dumpFunction( SMESH_Comment("makeNormals") << i );
4499     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4500     {
4501       _LayerEdge* edge = n2e->second;
4502       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4503       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4504       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4505               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4506     }
4507     dumpFunctionEnd();
4508
4509     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4510     dumpCmd( "faceId1 = mesh.NbElements()" );
4511     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4512     for ( ; fExp.More(); fExp.Next() )
4513     {
4514       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4515       {
4516         if ( sm->NbElements() == 0 ) continue;
4517         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4518         while ( fIt->more())
4519         {
4520           const SMDS_MeshElement* e = fIt->next();
4521           SMESH_Comment cmd("mesh.AddFace([");
4522           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4523             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4524           dumpCmd( cmd );
4525         }
4526       }
4527     }
4528     dumpCmd( "faceId2 = mesh.NbElements()" );
4529     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4530              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4531              << "'%s-%s' % (faceId1+1, faceId2))");
4532     dumpFunctionEnd();
4533   }
4534 #endif
4535 }
4536
4537 //================================================================================
4538 /*!
4539  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4540  */
4541 //================================================================================
4542
4543 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4544 {
4545   data._geomSize = Precision::Infinite();
4546   double intersecDist;
4547   const SMDS_MeshElement* face;
4548   SMESH_MesherHelper helper( *_mesh );
4549
4550   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4551     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4552                                            data._proxyMesh->GetFaces( data._solid )));
4553
4554   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4555   {
4556     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4557     if ( eos._edges.empty() )
4558       continue;
4559     // get neighbor faces, intersection with which should not be considered since
4560     // collisions are avoided by means of smoothing
4561     set< TGeomID > neighborFaces;
4562     if ( eos._hyp.ToSmooth() )
4563     {
4564       SMESH_subMeshIteratorPtr subIt =
4565         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4566       while ( subIt->more() )
4567       {
4568         SMESH_subMesh* sm = subIt->next();
4569         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4570         while ( const TopoDS_Shape* face = fIt->next() )
4571           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4572       }
4573     }
4574     // find intersections
4575     double thinkness = eos._hyp.GetTotalThickness();
4576     for ( size_t i = 0; i < eos._edges.size(); ++i )
4577     {
4578       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4579       eos._edges[i]->SetMaxLen( thinkness );
4580       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4581       if ( intersecDist > 0 && face )
4582       {
4583         data._geomSize = Min( data._geomSize, intersecDist );
4584         if ( !neighborFaces.count( face->getshapeId() ))
4585           eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4586       }
4587     }
4588   }
4589
4590   data._maxThickness = 0;
4591   data._minThickness = 1e100;
4592   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4593   for ( ; hyp != data._hyps.end(); ++hyp )
4594   {
4595     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4596     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4597   }
4598
4599   // Limit inflation step size by geometry size found by intersecting
4600   // normals of _LayerEdge's with mesh faces
4601   if ( data._stepSize > 0.3 * data._geomSize )
4602     limitStepSize( data, 0.3 * data._geomSize );
4603
4604   if ( data._stepSize > data._minThickness )
4605     limitStepSize( data, data._minThickness );
4606
4607
4608   // -------------------------------------------------------------------------
4609   // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4610   // so no need in detecting intersection at each inflation step
4611   // -------------------------------------------------------------------------
4612
4613   int nbSteps = data._maxThickness / data._stepSize;
4614   if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4615     return;
4616
4617   vector< const SMDS_MeshElement* > closeFaces;
4618   int nbDetected = 0;
4619
4620   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4621   {
4622     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4623     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4624       continue;
4625
4626     for ( size_t i = 0; i < eos.size(); ++i )
4627     {
4628       SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4629       double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4630       closeFaces.clear();
4631       searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4632
4633       bool toIgnore = true;
4634       for ( size_t iF = 0; iF < closeFaces.size()  && toIgnore; ++iF )
4635         if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4636                              data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4637         {
4638           // check if a _LayerEdge will inflate in a direction opposite to a direction
4639           // toward a close face
4640           bool allBehind = true;
4641           for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes()  && allBehind; ++iN )
4642           {
4643             SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4644             allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4645           }
4646           toIgnore = allBehind;
4647         }
4648
4649
4650       if ( toIgnore ) // no need to detect intersection
4651       {
4652         eos[i]->Set( _LayerEdge::INTERSECTED );
4653         ++nbDetected;
4654       }
4655     }
4656   }
4657
4658   debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4659
4660   return;
4661 }
4662
4663 //================================================================================
4664 /*!
4665  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4666  */
4667 //================================================================================
4668
4669 bool _ViscousBuilder::inflate(_SolidData& data)
4670 {
4671   SMESH_MesherHelper helper( *_mesh );
4672
4673   const double tgtThick = data._maxThickness;
4674
4675   if ( data._stepSize < 1. )
4676     data._epsilon = data._stepSize * 1e-7;
4677
4678   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4679   _pyDump->Pause();
4680
4681   findCollisionEdges( data, helper );
4682
4683   limitMaxLenByCurvature( data, helper );
4684
4685   _pyDump->Resume();
4686
4687   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4688   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4689     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4690          data._edgesOnShape[i]._edges.size() > 0 &&
4691          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4692     {
4693       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4694       data._edgesOnShape[i]._edges[0]->Block( data );
4695     }
4696
4697   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4698
4699   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4700   int nbSteps = 0, nbRepeats = 0;
4701   while ( avgThick < 0.99 )
4702   {
4703     // new target length
4704     double prevThick = curThick;
4705     curThick += data._stepSize;
4706     if ( curThick > tgtThick )
4707     {
4708       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4709       nbRepeats++;
4710     }
4711
4712     double stepSize = curThick - prevThick;
4713     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4714
4715     // Elongate _LayerEdge's
4716     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4717     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4718     {
4719       _EdgesOnShape& eos = data._edgesOnShape[iS];
4720       if ( eos._edges.empty() ) continue;
4721
4722       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4723       for ( size_t i = 0; i < eos._edges.size(); ++i )
4724       {
4725         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4726       }
4727     }
4728     dumpFunctionEnd();
4729
4730     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4731       return false;
4732
4733     // Improve and check quality
4734     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4735     {
4736       if ( nbSteps > 0 )
4737       {
4738 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4739         debugMsg("NOT INVALIDATED STEP!");
4740         return error("Smoothing failed", data._index);
4741 #endif
4742         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4743         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4744         {
4745           _EdgesOnShape& eos = data._edgesOnShape[iS];
4746           for ( size_t i = 0; i < eos._edges.size(); ++i )
4747             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4748         }
4749         dumpFunctionEnd();
4750       }
4751       break; // no more inflating possible
4752     }
4753     nbSteps++;
4754
4755     // Evaluate achieved thickness
4756     avgThick = 0;
4757     int nbActiveEdges = 0;
4758     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4759     {
4760       _EdgesOnShape& eos = data._edgesOnShape[iS];
4761       if ( eos._edges.empty() ) continue;
4762
4763       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4764       for ( size_t i = 0; i < eos._edges.size(); ++i )
4765       {
4766         if ( eos._edges[i]->_nodes.size() > 1 )
4767           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4768         else
4769           avgThick    += shapeTgtThick;
4770         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4771       }
4772     }
4773     avgThick /= data._n2eMap.size();
4774     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4775
4776 #ifdef BLOCK_INFLATION
4777     if ( nbActiveEdges == 0 )
4778     {
4779       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4780       break;
4781     }
4782 #else
4783     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4784     {
4785       debugMsg( "-- Stop inflation since "
4786                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4787                 << tgtThick * avgThick << " ) * " << safeFactor );
4788       break;
4789     }
4790 #endif
4791
4792     // new step size
4793     limitStepSize( data, 0.25 * distToIntersection );
4794     if ( data._stepSizeNodes[0] )
4795       data._stepSize = data._stepSizeCoeff *
4796         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4797
4798   } // while ( avgThick < 0.99 )
4799
4800   if ( nbSteps == 0 )
4801     return error("failed at the very first inflation step", data._index);
4802
4803   if ( avgThick < 0.99 )
4804   {
4805     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4806     {
4807       data._proxyMesh->_warning.reset
4808         ( new SMESH_ComputeError (COMPERR_WARNING,
4809                                   SMESH_Comment("Thickness ") << tgtThick <<
4810                                   " of viscous layers not reached,"
4811                                   " average reached thickness is " << avgThick*tgtThick));
4812     }
4813   }
4814
4815   // Restore position of src nodes moved by inflation on _noShrinkShapes
4816   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4817   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4818   {
4819     _EdgesOnShape& eos = data._edgesOnShape[iS];
4820     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4821       for ( size_t i = 0; i < eos._edges.size(); ++i )
4822       {
4823         restoreNoShrink( *eos._edges[ i ] );
4824       }
4825   }
4826   dumpFunctionEnd();
4827
4828   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4829 }
4830
4831 //================================================================================
4832 /*!
4833  * \brief Improve quality of layer inner surface and check intersection
4834  */
4835 //================================================================================
4836
4837 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4838                                      const int   infStep,
4839                                      double &    distToIntersection)
4840 {
4841   if ( data._nbShapesToSmooth == 0 )
4842     return true; // no shapes needing smoothing
4843
4844   bool moved, improved;
4845   double vol;
4846   vector< _LayerEdge* >    movedEdges, badEdges;
4847   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4848   vector< bool >           isConcaveFace;
4849
4850   SMESH_MesherHelper helper(*_mesh);
4851   Handle(ShapeAnalysis_Surface) surface;
4852   TopoDS_Face F;
4853
4854   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4855   {
4856     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4857
4858     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4859     {
4860       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4861       if ( !eos._toSmooth ||
4862            eos.ShapeType() != shapeType ||
4863            eos._edges.empty() )
4864         continue;
4865
4866       // already smoothed?
4867       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4868       // if ( !toSmooth ) continue;
4869
4870       if ( !eos._hyp.ToSmooth() )
4871       {
4872         // smooth disabled by the user; check validy only
4873         if ( !isFace ) continue;
4874         badEdges.clear();
4875         for ( size_t i = 0; i < eos._edges.size(); ++i )
4876         {
4877           _LayerEdge* edge = eos._edges[i];
4878           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4879             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4880             {
4881               // debugMsg( "-- Stop inflation. Bad simplex ("
4882               //           << " "<< edge->_nodes[0]->GetID()
4883               //           << " "<< edge->_nodes.back()->GetID()
4884               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4885               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4886               // return false;
4887               badEdges.push_back( edge );
4888             }
4889         }
4890         if ( !badEdges.empty() )
4891         {
4892           eosC1.resize(1);
4893           eosC1[0] = &eos;
4894           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4895           if ( nbBad > 0 )
4896             return false;
4897         }
4898         continue; // goto the next EDGE or FACE
4899       }
4900
4901       // prepare data
4902       if ( eos.SWOLType() == TopAbs_FACE )
4903       {
4904         if ( !F.IsSame( eos._sWOL )) {
4905           F = TopoDS::Face( eos._sWOL );
4906           helper.SetSubShape( F );
4907           surface = helper.GetSurface( F );
4908         }
4909       }
4910       else
4911       {
4912         F.Nullify(); surface.Nullify();
4913       }
4914       const TGeomID sInd = eos._shapeID;
4915
4916       // perform smoothing
4917
4918       if ( eos.ShapeType() == TopAbs_EDGE )
4919       {
4920         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4921
4922         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4923         {
4924           // smooth on EDGE's (normally we should not get here)
4925           int step = 0;
4926           do {
4927             moved = false;
4928             for ( size_t i = 0; i < eos._edges.size(); ++i )
4929             {
4930               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4931             }
4932             dumpCmd( SMESH_Comment("# end step ")<<step);
4933           }
4934           while ( moved && step++ < 5 );
4935         }
4936         dumpFunctionEnd();
4937       }
4938
4939       else // smooth on FACE
4940       {
4941         eosC1.clear();
4942         eosC1.push_back( & eos );
4943         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4944
4945         movedEdges.clear();
4946         isConcaveFace.resize( eosC1.size() );
4947         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4948         {
4949           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4950           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4951           for ( size_t i = 0; i < edges.size(); ++i )
4952             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4953                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4954               movedEdges.push_back( edges[i] );
4955
4956           makeOffsetSurface( *eosC1[ iEOS ], helper );
4957         }
4958
4959         int step = 0, stepLimit = 5, nbBad = 0;
4960         while (( ++step <= stepLimit ) || improved )
4961         {
4962           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4963                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4964           int oldBadNb = nbBad;
4965           badEdges.clear();
4966
4967 #ifdef INCREMENTAL_SMOOTH
4968           bool findBest = false; // ( step == stepLimit );
4969           for ( size_t i = 0; i < movedEdges.size(); ++i )
4970           {
4971             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4972             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4973               badEdges.push_back( movedEdges[i] );
4974           }
4975 #else
4976           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4977           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4978           {
4979             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4980             for ( size_t i = 0; i < edges.size(); ++i )
4981             {
4982               edges[i]->Unset( _LayerEdge::SMOOTHED );
4983               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4984                 badEdges.push_back( eos._edges[i] );
4985             }
4986           }
4987 #endif
4988           nbBad = badEdges.size();
4989
4990           if ( nbBad > 0 )
4991             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4992
4993           if ( !badEdges.empty() && step >= stepLimit / 2 )
4994           {
4995             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4996               stepLimit = 9;
4997
4998             // resolve hard smoothing situation around concave VERTEXes
4999             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5000             {
5001               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
5002               for ( size_t i = 0; i < eosCoVe.size(); ++i )
5003                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
5004                                                          step, badEdges );
5005             }
5006             // look for the best smooth of _LayerEdge's neighboring badEdges
5007             nbBad = 0;
5008             for ( size_t i = 0; i < badEdges.size(); ++i )
5009             {
5010               _LayerEdge* ledge = badEdges[i];
5011               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
5012               {
5013                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
5014                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
5015               }
5016               ledge->Unset( _LayerEdge::SMOOTHED );
5017               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
5018             }
5019             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5020           }
5021
5022           if ( nbBad == oldBadNb  &&
5023                nbBad > 0 &&
5024                step < stepLimit ) // smooth w/o check of validity
5025           {
5026             dumpFunctionEnd();
5027             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
5028                          <<"_InfStep"<<infStep<<"_"<<step); // debug
5029             for ( size_t i = 0; i < movedEdges.size(); ++i )
5030             {
5031               movedEdges[i]->SmoothWoCheck();
5032             }
5033             if ( stepLimit < 9 )
5034               stepLimit++;
5035           }
5036
5037           improved = ( nbBad < oldBadNb );
5038
5039           dumpFunctionEnd();
5040
5041           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
5042             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5043             {
5044               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
5045             }
5046
5047         } // smoothing steps
5048
5049         // project -- to prevent intersections or fix bad simplices
5050         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5051         {
5052           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
5053             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
5054         }
5055
5056         //if ( !badEdges.empty() )
5057         {
5058           badEdges.clear();
5059           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5060           {
5061             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5062             {
5063               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5064
5065               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5066               edge->CheckNeiborsOnBoundary( & badEdges );
5067               if (( nbBad > 0 ) ||
5068                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
5069               {
5070                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5071                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
5072                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5073                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5074                   {
5075                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
5076                              << " "<< tgtXYZ._node->GetID()
5077                              << " "<< edge->_simplices[j]._nPrev->GetID()
5078                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5079                     badEdges.push_back( edge );
5080                     break;
5081                   }
5082               }
5083             }
5084           }
5085
5086           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5087           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5088
5089           if ( nbBad > 0 )
5090             return false;
5091         }
5092
5093       } // // smooth on FACE's
5094     } // loop on shapes
5095   } // smooth on [ EDGEs, FACEs ]
5096
5097   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
5098   eosC1.resize(1);
5099   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5100   {
5101     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5102     if ( eos.ShapeType() == TopAbs_FACE ||
5103          eos._edges.empty() ||
5104          !eos._sWOL.IsNull() )
5105       continue;
5106
5107     badEdges.clear();
5108     for ( size_t i = 0; i < eos._edges.size(); ++i )
5109     {
5110       _LayerEdge*      edge = eos._edges[i];
5111       if ( edge->_nodes.size() < 2 ) continue;
5112       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5113       //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
5114       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
5115       //const gp_XYZ& prevXYZ = edge->PrevPos();
5116       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5117         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5118         {
5119           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
5120                    << " "<< tgtXYZ._node->GetID()
5121                    << " "<< edge->_simplices[j]._nPrev->GetID()
5122                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5123           badEdges.push_back( edge );
5124           break;
5125         }
5126     }
5127
5128     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5129     eosC1[0] = &eos;
5130     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5131     if ( nbBad > 0 )
5132       return false;
5133   }
5134
5135
5136   // Check if the last segments of _LayerEdge intersects 2D elements;
5137   // checked elements are either temporary faces or faces on surfaces w/o the layers
5138
5139   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5140     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
5141                                            data._proxyMesh->GetFaces( data._solid )) );
5142
5143 #ifdef BLOCK_INFLATION
5144   const bool toBlockInfaltion = true;
5145 #else
5146   const bool toBlockInfaltion = false;
5147 #endif
5148   distToIntersection = Precision::Infinite();
5149   double dist;
5150   const SMDS_MeshElement* intFace = 0;
5151   const SMDS_MeshElement* closestFace = 0;
5152   _LayerEdge* le = 0;
5153   bool is1stBlocked = true; // dbg
5154   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5155   {
5156     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5157     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5158       continue;
5159     for ( size_t i = 0; i < eos._edges.size(); ++i )
5160     {
5161       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5162            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5163         continue;
5164       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5165       {
5166         return false;
5167         // commented due to "Illegal hash-positionPosition" error in NETGEN
5168         // on Debian60 on viscous_layers_01/B2 case
5169         // Collision; try to deflate _LayerEdge's causing it
5170         // badEdges.clear();
5171         // badEdges.push_back( eos._edges[i] );
5172         // eosC1[0] = & eos;
5173         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5174         // if ( nbBad > 0 )
5175         //   return false;
5176
5177         // badEdges.clear();
5178         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5179         // {
5180         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5181         //   {
5182         //     const SMDS_MeshElement* srcFace =
5183         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5184         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5185         //     while ( nIt->more() )
5186         //     {
5187         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5188         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5189         //       if ( n2e != data._n2eMap.end() )
5190         //         badEdges.push_back( n2e->second );
5191         //     }
5192         //     eosC1[0] = eof;
5193         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5194         //     if ( nbBad > 0 )
5195         //       return false;
5196         //   }
5197         // }
5198         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5199         //   return false;
5200         // else
5201         //   continue;
5202       }
5203       if ( !intFace )
5204       {
5205         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5206         debugMsg( msg );
5207         continue;
5208       }
5209
5210       const bool isShorterDist = ( distToIntersection > dist );
5211       if ( toBlockInfaltion || isShorterDist )
5212       {
5213         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5214         // lying on this _ConvexFace
5215         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5216           if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5217             continue;
5218
5219         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5220         // ( avoid limiting the thickness on the case of issue 22576)
5221         if ( intFace->getshapeId() == eos._shapeID  )
5222           continue;
5223
5224         // ignore intersection with intFace of an adjacent FACE
5225         if ( dist > 0.1 * eos._edges[i]->_len )
5226         {
5227           bool toIgnore = false;
5228           if (  eos._toSmooth )
5229           {
5230             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5231             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5232             {
5233               TopExp_Explorer sub( eos._shape,
5234                                    eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5235               for ( ; !toIgnore && sub.More(); sub.Next() )
5236                 // is adjacent - has a common EDGE or VERTEX
5237                 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5238
5239               if ( toIgnore ) // check angle between normals
5240               {
5241                 gp_XYZ normal;
5242                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5243                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
5244               }
5245             }
5246           }
5247           if ( !toIgnore ) // check if the edge is a neighbor of intFace
5248           {
5249             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
5250             {
5251               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5252               toIgnore = ( nInd >= 0 );
5253             }
5254           }
5255           if ( toIgnore )
5256             continue;
5257         }
5258
5259         // intersection not ignored
5260
5261         if ( toBlockInfaltion &&
5262              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5263         {
5264           if ( is1stBlocked ) { is1stBlocked = false; // debug
5265             dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5266           }
5267           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5268           eos._edges[i]->Block( data );                  // not to inflate
5269
5270           //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5271           {
5272             // block _LayerEdge's, on top of which intFace is
5273             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5274             {
5275               const SMDS_MeshElement* srcFace = f->_srcFace;
5276               SMDS_ElemIteratorPtr        nIt = srcFace->nodesIterator();
5277               while ( nIt->more() )
5278               {
5279                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5280                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5281                 if ( n2e != data._n2eMap.end() )
5282                   n2e->second->Block( data );
5283               }
5284             }
5285           }
5286         }
5287
5288         if ( isShorterDist )
5289         {
5290           distToIntersection = dist;
5291           le = eos._edges[i];
5292           closestFace = intFace;
5293         }
5294
5295       } // if ( toBlockInfaltion || isShorterDist )
5296     } // loop on eos._edges
5297   } // loop on data._edgesOnShape
5298
5299   if ( !is1stBlocked )
5300     dumpFunctionEnd();
5301
5302   if ( closestFace && le )
5303   {
5304 #ifdef __myDEBUG
5305     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5306     cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5307          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5308          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5309          << ") distance = " << distToIntersection<< endl;
5310 #endif
5311   }
5312
5313   return true;
5314 }
5315
5316 //================================================================================
5317 /*!
5318  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5319  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5320  *  \return int - resulting nb of bad _LayerEdge's
5321  */
5322 //================================================================================
5323
5324 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5325                                           SMESH_MesherHelper&       helper,
5326                                           vector< _LayerEdge* >&    badSmooEdges,
5327                                           vector< _EdgesOnShape* >& eosC1,
5328                                           const int                 infStep )
5329 {
5330   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5331
5332   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5333
5334   enum {
5335     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5336     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5337     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5338   };
5339   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5340
5341   double vol;
5342   bool haveInvalidated = true;
5343   while ( haveInvalidated )
5344   {
5345     haveInvalidated = false;
5346     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5347     {
5348       _LayerEdge*   edge = badSmooEdges[i];
5349       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5350       edge->Set( ADDED );
5351       bool invalidated = false;
5352       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5353       {
5354         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5355         edge->Block( data );
5356         edge->Set( INVALIDATED );
5357         edge->Unset( TO_INVALIDATE );
5358         invalidated = true;
5359         haveInvalidated = true;
5360       }
5361
5362       // look for _LayerEdge's of bad _simplices
5363       int nbBad = 0;
5364       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5365       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5366       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5367       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5368       {
5369         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5370             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5371           continue;
5372
5373         bool isBad = true;
5374         _LayerEdge* ee[2] = { 0,0 };
5375         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5376           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5377             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5378
5379         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5380         while ( maxNbSteps > edge->NbSteps() && isBad )
5381         {
5382           --maxNbSteps;
5383           for ( int iE = 0; iE < 2; ++iE )
5384           {
5385             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5386                  ee[ iE ]->NbSteps() > 1 )
5387             {
5388               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5389               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5390               ee[ iE ]->Block( data );
5391               ee[ iE ]->Set( INVALIDATED );
5392               haveInvalidated = true;
5393             }
5394           }
5395           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5396               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5397             isBad = false;
5398         }
5399         nbBad += isBad;
5400         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5401         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5402         ee[0]->Set( ADDED );
5403         ee[1]->Set( ADDED );
5404         if ( isBad )
5405         {
5406           ee[0]->Set( TO_INVALIDATE );
5407           ee[1]->Set( TO_INVALIDATE );
5408         }
5409       }
5410
5411       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5412       {
5413         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5414         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5415         edge->Block( data );
5416         edge->Set( INVALIDATED );
5417         edge->Unset( TO_INVALIDATE );
5418         haveInvalidated = true;
5419       }
5420     } // loop on badSmooEdges
5421   } // while ( haveInvalidated )
5422
5423   // re-smooth on analytical EDGEs
5424   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5425   {
5426     _LayerEdge* edge = badSmooEdges[i];
5427     if ( !edge->Is( INVALIDATED )) continue;
5428
5429     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5430     if ( eos->ShapeType() == TopAbs_VERTEX )
5431     {
5432       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5433       while ( const TopoDS_Shape* e = eIt->next() )
5434         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5435           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5436           {
5437             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5438             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5439             //   F       = TopoDS::Face( eoe->_sWOL );
5440             //   surface = helper.GetSurface( F );
5441             // }
5442             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5443             eoe->_edgeSmoother->_anaCurve.Nullify();
5444           }
5445     }
5446   }
5447
5448
5449   // check result of invalidation
5450
5451   int nbBad = 0;
5452   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5453   {
5454     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5455     {
5456       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5457       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5458       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5459       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5460       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5461         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5462         {
5463           ++nbBad;
5464           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5465                    << " "<< tgtXYZ._node->GetID()
5466                    << " "<< edge->_simplices[j]._nPrev->GetID()
5467                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5468         }
5469     }
5470   }
5471   dumpFunctionEnd();
5472
5473   return nbBad;
5474 }
5475
5476 //================================================================================
5477 /*!
5478  * \brief Create an offset surface
5479  */
5480 //================================================================================
5481
5482 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5483 {
5484   if ( eos._offsetSurf.IsNull() ||
5485        eos._edgeForOffset == 0 ||
5486        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5487     return;
5488
5489   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5490
5491   // find offset
5492   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5493   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5494   double offset = baseSurface->Gap();
5495
5496   eos._offsetSurf.Nullify();
5497
5498   try
5499   {
5500     BRepOffsetAPI_MakeOffsetShape offsetMaker;
5501     offsetMaker.PerformByJoin( eos._shape, -offset, Precision::Confusion() );
5502     if ( !offsetMaker.IsDone() ) return;
5503
5504     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5505     if ( !fExp.More() ) return;
5506
5507     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5508     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5509     if ( surf.IsNull() ) return;
5510
5511     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5512   }
5513   catch ( Standard_Failure )
5514   {
5515   }
5516 }
5517
5518 //================================================================================
5519 /*!
5520  * \brief Put nodes of a curved FACE to its offset surface
5521  */
5522 //================================================================================
5523
5524 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5525                                           int                       infStep,
5526                                           vector< _EdgesOnShape* >& eosC1,
5527                                           int                       smooStep,
5528                                           int                       moveAll )
5529 {
5530   _EdgesOnShape * eof = & eos;
5531   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5532   {
5533     eof = 0;
5534     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5535     {
5536       if ( eosC1[i]->_offsetSurf.IsNull() ||
5537            eosC1[i]->ShapeType() != TopAbs_FACE ||
5538            eosC1[i]->_edgeForOffset == 0 ||
5539            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5540         continue;
5541       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5542         eof = eosC1[i];
5543     }
5544   }
5545   if ( !eof ||
5546        eof->_offsetSurf.IsNull() ||
5547        eof->ShapeType() != TopAbs_FACE ||
5548        eof->_edgeForOffset == 0 ||
5549        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5550     return;
5551
5552   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5553   for ( size_t i = 0; i < eos._edges.size(); ++i )
5554   {
5555     _LayerEdge* edge = eos._edges[i];
5556     edge->Unset( _LayerEdge::MARKED );
5557     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5558       continue;
5559     if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5560     {
5561       if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5562         continue;
5563     }
5564     else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5565       continue;
5566
5567     int nbBlockedAround = 0;
5568     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5569       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5570     if ( nbBlockedAround > 1 )
5571       continue;
5572
5573     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5574     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5575     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5576     edge->_curvature->_uv = uv;
5577     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5578
5579     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5580     gp_XYZ prevP = edge->PrevCheckPos();
5581     bool      ok = true;
5582     if ( !moveAll )
5583       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5584       {
5585         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5586       }
5587     if ( ok )
5588     {
5589       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5590       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5591       edge->_pos.back() = newP;
5592
5593       edge->Set( _LayerEdge::MARKED );
5594       if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5595       {
5596         edge->_normal = ( newP - prevP ).Normalized();
5597       }
5598     }
5599   }
5600
5601
5602
5603 #ifdef _DEBUG_
5604   // dumpMove() for debug
5605   size_t i = 0;
5606   for ( ; i < eos._edges.size(); ++i )
5607     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5608       break;
5609   if ( i < eos._edges.size() )
5610   {
5611     dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5612                  << "_InfStep" << infStep << "_" << smooStep );
5613     for ( ; i < eos._edges.size(); ++i )
5614     {
5615       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5616         dumpMove( eos._edges[i]->_nodes.back() );
5617     }
5618     dumpFunctionEnd();
5619   }
5620 #endif
5621
5622   _ConvexFace* cnvFace;
5623   if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5624        eos.ShapeType() == TopAbs_FACE &&
5625        (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5626        !cnvFace->_normalsFixedOnBorders )
5627   {
5628     // put on the surface nodes built on FACE boundaries
5629     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5630     while ( smIt->more() )
5631     {
5632       SMESH_subMesh* sm = smIt->next();
5633       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5634       if ( !subEOS->_sWOL.IsNull() ) continue;
5635       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5636
5637       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5638     }
5639     cnvFace->_normalsFixedOnBorders = true;
5640   }
5641 }
5642
5643 //================================================================================
5644 /*!
5645  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5646  *        _LayerEdge's to be in a consequent order
5647  */
5648 //================================================================================
5649
5650 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5651                                                 _EdgesOnShape&      eos,
5652                                                 SMESH_MesherHelper& helper)
5653 {
5654   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5655
5656   TopLoc_Location loc; double f,l;
5657
5658   Handle(Geom_Line)   line;
5659   Handle(Geom_Circle) circle;
5660   bool isLine, isCirc;
5661   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5662   {
5663     // check if the EDGE is a line
5664     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5665     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5666       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5667
5668     line   = Handle(Geom_Line)::DownCast( curve );
5669     circle = Handle(Geom_Circle)::DownCast( curve );
5670     isLine = (!line.IsNull());
5671     isCirc = (!circle.IsNull());
5672
5673     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5674     {
5675       isLine = SMESH_Algo::IsStraight( E );
5676
5677       if ( isLine )
5678         line = new Geom_Line( gp::OX() ); // only type does matter
5679     }
5680     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5681     {
5682       // TODO
5683     }
5684   }
5685   else //////////////////////////////////////////////////////////////////////// 2D case
5686   {
5687     if ( !eos._isRegularSWOL ) // 23190
5688       return NULL;
5689
5690     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5691
5692     // check if the EDGE is a line
5693     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5694     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5695       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5696
5697     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5698     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5699     isLine = (!line2d.IsNull());
5700     isCirc = (!circle2d.IsNull());
5701
5702     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5703     {
5704       Bnd_B2d bndBox;
5705       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5706       while ( nIt->more() )
5707         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5708       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5709
5710       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5711       for ( int i = 0; i < 2 && !isLine; ++i )
5712         isLine = ( size.Coord( i+1 ) <= lineTol );
5713     }
5714     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5715     {
5716       // TODO
5717     }
5718     if ( isLine )
5719     {
5720       line = new Geom_Line( gp::OX() ); // only type does matter
5721     }
5722     else if ( isCirc )
5723     {
5724       gp_Pnt2d p = circle2d->Location();
5725       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5726       circle = new Geom_Circle( ax, 1.); // only center position does matter
5727     }
5728   }
5729
5730   if ( isLine )
5731     return line;
5732   if ( isCirc )
5733     return circle;
5734
5735   return Handle(Geom_Curve)();
5736 }
5737
5738 //================================================================================
5739 /*!
5740  * \brief Smooth edges on EDGE
5741  */
5742 //================================================================================
5743
5744 bool _Smoother1D::Perform(_SolidData&                    data,
5745                           Handle(ShapeAnalysis_Surface)& surface,
5746                           const TopoDS_Face&             F,
5747                           SMESH_MesherHelper&            helper )
5748 {
5749   if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5750     prepare( data );
5751
5752   findEdgesToSmooth();
5753   if ( isAnalytic() )
5754     return smoothAnalyticEdge( data, surface, F, helper );
5755   else
5756     return smoothComplexEdge ( data, surface, F, helper );
5757 }
5758
5759 //================================================================================
5760 /*!
5761  * \brief Find edges to smooth
5762  */
5763 //================================================================================
5764
5765 void _Smoother1D::findEdgesToSmooth()
5766 {
5767   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5768   for ( int iEnd = 0; iEnd < 2; ++iEnd )
5769     if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5770       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5771
5772   _eToSmooth[0].first = _eToSmooth[0].second = 0;
5773
5774   for ( size_t i = 0; i < _eos.size(); ++i )
5775   {
5776     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5777     {
5778       if ( needSmoothing( _leOnV[0]._cosin,
5779                           _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
5780            isToSmooth( i )
5781            )
5782         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5783       else
5784         break;
5785     }
5786     _eToSmooth[0].second = i+1;
5787   }
5788
5789   _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5790
5791   for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5792   {
5793     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5794     {
5795       if ( needSmoothing( _leOnV[1]._cosin,
5796                           _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
5797            isToSmooth( i ))
5798         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5799       else
5800         break;
5801     }
5802     _eToSmooth[1].first = i;
5803   }
5804 }
5805
5806 //================================================================================
5807 /*!
5808  * \brief Check if iE-th _LayerEdge needs smoothing
5809  */
5810 //================================================================================
5811
5812 bool _Smoother1D::isToSmooth( int iE )
5813 {
5814   SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5815   SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5816   SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5817   gp_XYZ       seg0 = pi - p0;
5818   gp_XYZ       seg1 = p1 - pi;
5819   gp_XYZ    tangent =  seg0 + seg1;
5820   double tangentLen = tangent.Modulus();
5821   double  segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5822   if ( tangentLen < std::numeric_limits<double>::min() )
5823     return false;
5824   tangent /= tangentLen;
5825
5826   for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5827   {
5828     _LayerEdge* ne = _eos[iE]->_neibors[i];
5829     if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5830          ne->_nodes.size() < 2 ||
5831          ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5832       continue;
5833     gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5834     double    proj = edgeVec * tangent;
5835     if ( needSmoothing( 1., proj, segMinLen ))
5836       return true;
5837   }
5838   return false;
5839 }
5840
5841 //================================================================================
5842 /*!
5843  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5844  */
5845 //================================================================================
5846
5847 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5848                                       Handle(ShapeAnalysis_Surface)& surface,
5849                                       const TopoDS_Face&             F,
5850                                       SMESH_MesherHelper&            helper)
5851 {
5852   if ( !isAnalytic() ) return false;
5853
5854   size_t iFrom = 0, iTo = _eos._edges.size();
5855
5856   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5857   {
5858     if ( F.IsNull() ) // 3D
5859     {
5860       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5861       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5862       //const   gp_XYZ lineDir = pSrc1 - pSrc0;
5863       //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5864       //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5865       // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5866       //                    vLE0->Is( _LayerEdge::BLOCKED ) ||
5867       //                    vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5868       //                    vLE1->Is( _LayerEdge::BLOCKED ));
5869       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5870       {
5871         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5872         if ( iFrom >= iTo ) continue;
5873         SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5874         SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5875         double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5876         double param1 = _leParams[ iTo ];
5877         for ( size_t i = iFrom; i < iTo; ++i )
5878         {
5879           _LayerEdge*       edge = _eos[i];
5880           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5881           double           param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5882           gp_XYZ          newPos = p0 * ( 1. - param ) + p1 * param;
5883
5884           // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5885           // {
5886           //   gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5887           //   double  shift = ( lineDir * ( newPos - pSrc0 ) -
5888           //                     lineDir * ( curPos - pSrc0 ));
5889           //   newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5890           // }
5891           if ( edge->Is( _LayerEdge::BLOCKED ))
5892           {
5893             SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5894             double curThick = pSrc.SquareDistance( tgtNode );
5895             double newThink = ( pSrc - newPos ).SquareModulus();
5896             if ( newThink > curThick )
5897               continue;
5898           }
5899           edge->_pos.back() = newPos;
5900           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5901           dumpMove( tgtNode );
5902         }
5903       }
5904     }
5905     else // 2D
5906     {
5907       _LayerEdge* eV0 = getLEdgeOnV( 0 );
5908       _LayerEdge* eV1 = getLEdgeOnV( 1 );
5909       gp_XY      uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5910       gp_XY      uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5911       if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5912       {
5913         int iPeriodic = helper.GetPeriodicIndex();
5914         if ( iPeriodic == 1 || iPeriodic == 2 )
5915         {
5916           uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5917           if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5918             std::swap( uvV0, uvV1 );
5919         }
5920       }
5921       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5922       {
5923         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5924         if ( iFrom >= iTo ) continue;
5925         _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5926         _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5927         gp_XY      uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5928         gp_XY      uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5929         double  param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5930         double  param1 = _leParams[ iTo ];
5931         gp_XY  rangeUV = uv1 - uv0;
5932         for ( size_t i = iFrom; i < iTo; ++i )
5933         {
5934           if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5935           double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5936           gp_XY newUV = uv0 + param * rangeUV;
5937
5938           gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5939           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5940           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5941           dumpMove( tgtNode );
5942
5943           SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5944           pos->SetUParameter( newUV.X() );
5945           pos->SetVParameter( newUV.Y() );
5946
5947           gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5948
5949           if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5950           {
5951             _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5952             if ( _eos[i]->_pos.size() > 2 )
5953             {
5954               // modify previous positions to make _LayerEdge less sharply bent
5955               vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5956               const gp_XYZ  uvShift = newUV0 - uvVec.back();
5957               const double     len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5958               int iPrev = uvVec.size() - 2;
5959               while ( iPrev > 0 )
5960               {
5961                 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5962                 uvVec[ iPrev ] += uvShift * r;
5963                 --iPrev;
5964               }
5965             }
5966           }
5967           _eos[i]->_pos.back() = newUV0;
5968         }
5969       }
5970     }
5971     return true;
5972   }
5973
5974   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5975   {
5976     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5977     gp_Pnt center3D = circle->Location();
5978
5979     if ( F.IsNull() ) // 3D
5980     {
5981       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5982         return true; // closed EDGE - nothing to do
5983
5984       // circle is a real curve of EDGE
5985       gp_Circ circ = circle->Circ();
5986
5987       // new center is shifted along its axis
5988       const gp_Dir& axis = circ.Axis().Direction();
5989       _LayerEdge*     e0 = getLEdgeOnV(0);
5990       _LayerEdge*     e1 = getLEdgeOnV(1);
5991       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5992       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5993       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5994       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5995       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5996
5997       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5998
5999       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
6000       gp_Circ newCirc( newAxis, newRadius );
6001       gp_Vec  vecC1  ( newCenter, p1 );
6002
6003       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
6004       if ( uLast < 0 )
6005         uLast += 2 * M_PI;
6006       
6007       for ( size_t i = 0; i < _eos.size(); ++i )
6008       {
6009         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6010         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6011         double u = uLast * _leParams[i];
6012         gp_Pnt p = ElCLib::Value( u, newCirc );
6013         _eos._edges[i]->_pos.back() = p.XYZ();
6014
6015         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6016         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6017         dumpMove( tgtNode );
6018       }
6019       return true;
6020     }
6021     else // 2D
6022     {
6023       const gp_XY center( center3D.X(), center3D.Y() );
6024
6025       _LayerEdge* e0 = getLEdgeOnV(0);
6026       _LayerEdge* eM = _eos._edges[ 0 ];
6027       _LayerEdge* e1 = getLEdgeOnV(1);
6028       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
6029       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
6030       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
6031       gp_Vec2d vec0( center, uv0 );
6032       gp_Vec2d vecM( center, uvM );
6033       gp_Vec2d vec1( center, uv1 );
6034       double uLast = vec0.Angle( vec1 ); // -PI - +PI
6035       double uMidl = vec0.Angle( vecM );
6036       if ( uLast * uMidl <= 0. )
6037         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
6038       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
6039
6040       gp_Ax2d   axis( center, vec0 );
6041       gp_Circ2d circ( axis, radius );
6042       for ( size_t i = 0; i < _eos.size(); ++i )
6043       {
6044         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6045         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6046         double    newU = uLast * _leParams[i];
6047         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
6048         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
6049
6050         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6051         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6052         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6053         dumpMove( tgtNode );
6054
6055         SMDS_FacePositionPtr pos = tgtNode->GetPosition();
6056         pos->SetUParameter( newUV.X() );
6057         pos->SetVParameter( newUV.Y() );
6058
6059         _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6060       }
6061     }
6062     return true;
6063   }
6064
6065   return false;
6066 }
6067
6068 //================================================================================
6069 /*!
6070  * \brief smooth _LayerEdge's on a an EDGE
6071  */
6072 //================================================================================
6073
6074 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
6075                                      Handle(ShapeAnalysis_Surface)& surface,
6076                                      const TopoDS_Face&             F,
6077                                      SMESH_MesherHelper&            helper)
6078 {
6079   if ( _offPoints.empty() )
6080     return false;
6081
6082   // ----------------------------------------------
6083   // move _offPoints along normals of _LayerEdge's
6084   // ----------------------------------------------
6085
6086   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6087   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
6088     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
6089   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
6090     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
6091   _leOnV[0]._len = e[0]->_len;
6092   _leOnV[1]._len = e[1]->_len;
6093   for ( size_t i = 0; i < _offPoints.size(); i++ )
6094   {
6095     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6096     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6097     const double w0 = _offPoints[i]._2edges._wgt[0];
6098     const double w1 = _offPoints[i]._2edges._wgt[1];
6099     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
6100     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
6101     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
6102     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6103          e1->Is( _LayerEdge::NORMAL_UPDATED ))
6104       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
6105
6106     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
6107     _offPoints[i]._len  = avgLen;
6108   }
6109
6110   double fTol = 0;
6111   if ( !surface.IsNull() ) // project _offPoints to the FACE
6112   {
6113     fTol = 100 * BRep_Tool::Tolerance( F );
6114     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
6115
6116     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
6117     //if ( surface->Gap() < 0.5 * segLen )
6118       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
6119
6120     for ( size_t i = 1; i < _offPoints.size(); ++i )
6121     {
6122       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
6123       //if ( surface->Gap() < 0.5 * segLen )
6124         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
6125     }
6126   }
6127
6128   // -----------------------------------------------------------------
6129   // project tgt nodes of extreme _LayerEdge's to the offset segments
6130   // -----------------------------------------------------------------
6131
6132   const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
6133   if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
6134   if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
6135
6136   gp_Pnt pExtreme[2], pProj[2];
6137   bool isProjected[2];
6138   for ( int is2nd = 0; is2nd < 2; ++is2nd )
6139   {
6140     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
6141     int  i = _iSeg[ is2nd ];
6142     int di = is2nd ? -1 : +1;
6143     bool & projected = isProjected[ is2nd ];
6144     projected = false;
6145     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
6146     int nbWorse = 0;
6147     do {
6148       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
6149       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
6150       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
6151       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
6152       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
6153       if ( dist < distMin || projected )
6154       {
6155         _iSeg[ is2nd ] = i;
6156         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6157         distMin = dist;
6158       }
6159       else if ( dist > distPrev )
6160       {
6161         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6162           break;
6163       }
6164       distPrev = dist;
6165       i += di;
6166     }
6167     while ( !projected &&
6168             i >= 0 && i+1 < (int)_offPoints.size() );
6169
6170     if ( !projected )
6171     {
6172       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6173       {
6174         _iSeg[0] = 0;
6175         _iSeg[1] = _offPoints.size()-2;
6176         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6177         return false;
6178       }
6179     }
6180   }
6181   if ( _iSeg[0] > _iSeg[1] )
6182   {
6183     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6184     return false;
6185   }
6186
6187   // adjust length of extreme LE (test viscous_layers_01/B7)
6188   gp_Vec vDiv0( pExtreme[0], pProj[0] );
6189   gp_Vec vDiv1( pExtreme[1], pProj[1] );
6190   double d0 = vDiv0.Magnitude();
6191   double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6192   if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6193     if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6194     else                                   e[0]->_len -= d0;
6195   }
6196   if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6197     if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6198     else                                   e[1]->_len -= d1;
6199   }
6200
6201   // ---------------------------------------------------------------------------------
6202   // compute normalized length of the offset segments located between the projections
6203   // ---------------------------------------------------------------------------------
6204
6205   // temporary replace extreme _offPoints by pExtreme
6206   gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0]   ]._xyz,
6207                       _offPoints[ _iSeg[1]+1 ]._xyz };
6208   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
6209   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6210
6211   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6212   vector< double > len( nbSeg + 1 );
6213   len[ iSeg++ ] = 0;
6214   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6215   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6216   {
6217     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6218   }
6219   // if ( isProjected[ 1 ])
6220   //   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6221   // else
6222   //   len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6223
6224   double fullLen = len.back() - d0 - d1;
6225   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6226     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6227
6228   // -------------------------------------------------------------
6229   // distribute tgt nodes of _LayerEdge's between the projections
6230   // -------------------------------------------------------------
6231
6232   iSeg = 0;
6233   for ( size_t i = 0; i < _eos.size(); ++i )
6234   {
6235     if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6236     //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6237     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6238       iSeg++;
6239     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6240     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
6241                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6242
6243     if ( surface.IsNull() )
6244     {
6245       _eos[i]->_pos.back() = p;
6246     }
6247     else // project a new node position to a FACE
6248     {
6249       gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6250       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6251
6252       p = surface->Value( uv2 ).XYZ();
6253       _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6254     }
6255     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6256     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6257     dumpMove( tgtNode );
6258   }
6259
6260   _offPoints[ _iSeg[0]   ]._xyz = opXYZ[0];
6261   _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6262
6263   return true;
6264 }
6265
6266 //================================================================================
6267 /*!
6268  * \brief Prepare for smoothing
6269  */
6270 //================================================================================
6271
6272 void _Smoother1D::prepare(_SolidData& data)
6273 {
6274   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6275   _curveLen = SMESH_Algo::EdgeLength( E );
6276
6277   // sort _LayerEdge's by position on the EDGE
6278   data.SortOnEdge( E, _eos._edges );
6279
6280   // compute normalized param of _eos._edges on EDGE
6281   _leParams.resize( _eos._edges.size() + 1 );
6282   {
6283     double curLen;
6284     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6285     _leParams[0] = 0;
6286     for ( size_t i = 0; i < _eos._edges.size(); ++i )
6287     {
6288       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6289       curLen         = p.Distance( pPrev );
6290       _leParams[i+1] = _leParams[i] + curLen;
6291       pPrev          = p;
6292     }
6293     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6294     for ( size_t i = 0; i < _leParams.size()-1; ++i )
6295       _leParams[i] = _leParams[i+1] / fullLen;
6296     _leParams.back() = 1.;
6297   }
6298
6299   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6300
6301   // get cosin to use in findEdgesToSmooth()
6302   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6303   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6304   _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6305   _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6306   if ( _eos._sWOL.IsNull() ) // 3D
6307     for ( int iEnd = 0; iEnd < 2; ++iEnd )
6308       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6309
6310   if ( isAnalytic() )
6311     return;
6312
6313   // divide E to have offset segments with low deflection
6314   BRepAdaptor_Curve c3dAdaptor( E );
6315   const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6316   const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6317   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6318   if ( discret.NbPoints() <= 2 )
6319   {
6320     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6321     return;
6322   }
6323
6324   const double u0 = c3dAdaptor.FirstParameter();
6325   gp_Pnt p; gp_Vec tangent;
6326   if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6327   {
6328     _offPoints.resize( discret.NbPoints() );
6329     for ( size_t i = 0; i < _offPoints.size(); i++ )
6330     {
6331       double u = discret.Parameter( i+1 );
6332       c3dAdaptor.D1( u, p, tangent );
6333       _offPoints[i]._xyz     = p.XYZ();
6334       _offPoints[i]._edgeDir = tangent.XYZ();
6335       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6336     }
6337   }
6338   else
6339   {
6340     std::vector< double > params( _eos.size() + 2 );
6341
6342     params[0]     = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6343     params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6344     for ( size_t i = 0; i < _eos.size(); i++ )
6345       params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6346
6347     if ( params[1] > params[ _eos.size() ] )
6348       std::reverse( params.begin() + 1, params.end() - 1 );
6349
6350     _offPoints.resize( _eos.size() + 2 );
6351     for ( size_t i = 0; i < _offPoints.size(); i++ )
6352     {
6353       const double u = params[i];
6354       c3dAdaptor.D1( u, p, tangent );
6355       _offPoints[i]._xyz     = p.XYZ();
6356       _offPoints[i]._edgeDir = tangent.XYZ();
6357       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6358     }
6359   }
6360
6361   // set _2edges
6362   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6363   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6364   _2NearEdges tmp2edges;
6365   tmp2edges._edges[1] = _eos._edges[0];
6366   _leOnV[0]._2neibors = & tmp2edges;
6367   _leOnV[0]._nodes    = leOnV[0]->_nodes;
6368   _leOnV[1]._nodes    = leOnV[1]->_nodes;
6369   _LayerEdge* eNext, *ePrev = & _leOnV[0];
6370   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6371   {
6372     // find _LayerEdge's located before and after an offset point
6373     // (_eos._edges[ iLE ] is next after ePrev)
6374     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6375       ePrev = _eos._edges[ iLE++ ];
6376     eNext = ePrev->_2neibors->_edges[1];
6377
6378     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6379     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6380     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6381     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6382   }
6383
6384   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6385   for ( size_t i = 0; i < _offPoints.size(); i++ )
6386     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6387       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6388     else break;
6389   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6390     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6391       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6392     else break;
6393
6394   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6395
6396   int iLBO = _offPoints.size() - 2; // last but one
6397
6398   if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6399     _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6400   else
6401     _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal,       _edgeDir[0] );
6402   if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6403     _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6404   else
6405     _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal,           _edgeDir[1] );
6406   _leOnV[ 0 ]._len = 0;
6407   _leOnV[ 1 ]._len = 0;
6408   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
6409   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6410
6411   _iSeg[0] = 0;
6412   _iSeg[1] = _offPoints.size()-2;
6413
6414   // initialize OffPnt::_len
6415   for ( size_t i = 0; i < _offPoints.size(); ++i )
6416     _offPoints[i]._len = 0;
6417
6418   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6419   {
6420     _leOnV[0]._len = leOnV[0]->_len;
6421     _leOnV[1]._len = leOnV[1]->_len;
6422     for ( size_t i = 0; i < _offPoints.size(); i++ )
6423     {
6424       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6425       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6426       const double w0 = _offPoints[i]._2edges._wgt[0];
6427       const double w1 = _offPoints[i]._2edges._wgt[1];
6428       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
6429       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6430                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6431       _offPoints[i]._xyz = avgXYZ;
6432       _offPoints[i]._len = avgLen;
6433     }
6434   }
6435 }
6436
6437 //================================================================================
6438 /*!
6439  * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6440  */
6441 //================================================================================
6442
6443 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6444                                      const gp_XYZ&  edgeDir)
6445 {
6446   gp_XYZ cross = normal ^ edgeDir;
6447   gp_XYZ  norm = edgeDir ^ cross;
6448   double  size = norm.Modulus();
6449
6450   // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6451   //   return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6452
6453   return norm / size;
6454 }
6455
6456 //================================================================================
6457 /*!
6458  * \brief Writes a script creating a mesh composed of _offPoints
6459  */
6460 //================================================================================
6461
6462 void _Smoother1D::offPointsToPython() const
6463 {
6464   const char* fname = "/tmp/offPoints.py";
6465   cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
6466   ofstream py(fname);
6467   py << "import SMESH" << endl
6468      << "from salome.smesh import smeshBuilder" << endl
6469      << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
6470      << "mesh   = smesh.Mesh( 'offPoints' )"<<endl;
6471   for ( size_t i = 0; i < _offPoints.size(); i++ )
6472   {
6473     py << "mesh.AddNode( "
6474        << _offPoints[i]._xyz.X() << ", "
6475        << _offPoints[i]._xyz.Y() << ", "
6476        << _offPoints[i]._xyz.Z() << " )" << endl;
6477   }
6478 }
6479
6480 //================================================================================
6481 /*!
6482  * \brief Sort _LayerEdge's by a parameter on a given EDGE
6483  */
6484 //================================================================================
6485
6486 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
6487                              vector< _LayerEdge* >& edges)
6488 {
6489   map< double, _LayerEdge* > u2edge;
6490   for ( size_t i = 0; i < edges.size(); ++i )
6491     u2edge.insert( u2edge.end(),
6492                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6493
6494   ASSERT( u2edge.size() == edges.size() );
6495   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6496   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6497     edges[i] = u2e->second;
6498
6499   Sort2NeiborsOnEdge( edges );
6500 }
6501
6502 //================================================================================
6503 /*!
6504  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6505  */
6506 //================================================================================
6507
6508 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6509 {
6510   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6511
6512   for ( size_t i = 0; i < edges.size()-1; ++i )
6513     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6514       edges[i]->_2neibors->reverse();
6515
6516   const size_t iLast = edges.size() - 1;
6517   if ( edges.size() > 1 &&
6518        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6519     edges[iLast]->_2neibors->reverse();
6520 }
6521
6522 //================================================================================
6523 /*!
6524  * \brief Return _EdgesOnShape* corresponding to the shape
6525  */
6526 //================================================================================
6527
6528 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6529 {
6530   if ( shapeID < (int)_edgesOnShape.size() &&
6531        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6532     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6533
6534   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6535     if ( _edgesOnShape[i]._shapeID == shapeID )
6536       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6537
6538   return 0;
6539 }
6540
6541 //================================================================================
6542 /*!
6543  * \brief Return _EdgesOnShape* corresponding to the shape
6544  */
6545 //================================================================================
6546
6547 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6548 {
6549   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6550   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6551 }
6552
6553 //================================================================================
6554 /*!
6555  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6556  */
6557 //================================================================================
6558
6559 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6560 {
6561   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6562
6563   set< TGeomID > vertices;
6564   TopoDS_Face F;
6565   if ( eos->ShapeType() == TopAbs_FACE )
6566   {
6567     // check FACE concavity and get concave VERTEXes
6568     F = TopoDS::Face( eos->_shape );
6569     if ( isConcave( F, helper, &vertices ))
6570       _concaveFaces.insert( eos->_shapeID );
6571
6572     // set eos._eosConcaVer
6573     eos->_eosConcaVer.clear();
6574     eos->_eosConcaVer.reserve( vertices.size() );
6575     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6576     {
6577       _EdgesOnShape* eov = GetShapeEdges( *v );
6578       if ( eov && eov->_edges.size() == 1 )
6579       {
6580         eos->_eosConcaVer.push_back( eov );
6581         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6582           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6583       }
6584     }
6585
6586     // SetSmooLen() to _LayerEdge's on FACE
6587     // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6588     // {
6589     //   eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6590     // }
6591     // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6592     // while ( smIt->more() ) // loop on sub-shapes of the FACE
6593     // {
6594     //   _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6595     //   if ( !eoe ) continue;
6596
6597     //   vector<_LayerEdge*>& eE = eoe->_edges;
6598     //   for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6599     //   {
6600     //     if ( eE[iE]->_cosin <= theMinSmoothCosin )
6601     //       continue;
6602
6603     //     SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6604     //     while ( segIt->more() )
6605     //     {
6606     //       const SMDS_MeshElement* seg = segIt->next();
6607     //       if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6608     //         continue;
6609     //       if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6610     //         continue; // not to check a seg twice
6611     //       for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6612     //       {
6613     //         _LayerEdge* eN = eE[iE]->_neibors[iN];
6614     //         if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6615     //           continue;
6616     //         double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6617     //         double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6618     //         eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6619     //         eN->Set( _LayerEdge::NEAR_BOUNDARY );
6620     //       }
6621     //     }
6622     //   }
6623     // }
6624   } // if ( eos->ShapeType() == TopAbs_FACE )
6625
6626   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6627   {
6628     eos->_edges[i]->_smooFunction = 0;
6629     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6630   }
6631   bool isCurved = false;
6632   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6633   {
6634     _LayerEdge* edge = eos->_edges[i];
6635
6636     // get simplices sorted
6637     _Simplex::SortSimplices( edge->_simplices );
6638
6639     // smoothing function
6640     edge->ChooseSmooFunction( vertices, _n2eMap );
6641
6642     // set _curvature
6643     double avgNormProj = 0, avgLen = 0;
6644     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6645     {
6646       _Simplex& s = edge->_simplices[iS];
6647
6648       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6649       avgNormProj += edge->_normal * vec;
6650       avgLen      += vec.Modulus();
6651       if ( substituteSrcNodes )
6652       {
6653         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6654         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6655       }
6656     }
6657     avgNormProj /= edge->_simplices.size();
6658     avgLen      /= edge->_simplices.size();
6659     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6660     {
6661       edge->Set( _LayerEdge::SMOOTHED_C1 );
6662       isCurved = true;
6663       SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6664       if ( !fPos )
6665         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6666           fPos = edge->_simplices[iS]._nPrev->GetPosition();
6667       if ( fPos )
6668         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6669     }
6670   }
6671
6672   // prepare for putOnOffsetSurface()
6673   if (( eos->ShapeType() == TopAbs_FACE ) &&
6674       ( isCurved || !eos->_eosConcaVer.empty() ))
6675   {
6676     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6677     eos->_edgeForOffset = 0;
6678
6679     double maxCosin = -1;
6680     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6681     {
6682       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6683       if ( !eoe || eoe->_edges.empty() ) continue;
6684
6685       vector<_LayerEdge*>& eE = eoe->_edges;
6686       _LayerEdge* e = eE[ eE.size() / 2 ];
6687       if ( e->_cosin > maxCosin )
6688       {
6689         eos->_edgeForOffset = e;
6690         maxCosin = e->_cosin;
6691       }
6692     }
6693   }
6694 }
6695
6696 //================================================================================
6697 /*!
6698  * \brief Add faces for smoothing
6699  */
6700 //================================================================================
6701
6702 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6703                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6704 {
6705   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6706   for ( ; eos != eosToSmooth.end(); ++eos )
6707   {
6708     if ( !*eos || (*eos)->_toSmooth ) continue;
6709
6710     (*eos)->_toSmooth = true;
6711
6712     if ( (*eos)->ShapeType() == TopAbs_FACE )
6713     {
6714       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6715       (*eos)->_toSmooth = true;
6716     }
6717   }
6718
6719   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6720   if ( edgesNoAnaSmooth )
6721     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6722     {
6723       if ( (*eos)->_edgeSmoother )
6724         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6725     }
6726 }
6727
6728 //================================================================================
6729 /*!
6730  * \brief Limit _LayerEdge::_maxLen according to local curvature
6731  */
6732 //================================================================================
6733
6734 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6735 {
6736   // find intersection of neighbor _LayerEdge's to limit _maxLen
6737   // according to local curvature (IPAL52648)
6738
6739   // This method must be called after findCollisionEdges() where _LayerEdge's
6740   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6741
6742   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6743   {
6744     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6745     if ( eosI._edges.empty() ) continue;
6746     if ( !eosI._hyp.ToSmooth() )
6747     {
6748       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6749       {
6750         _LayerEdge* eI = eosI._edges[i];
6751         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6752         {
6753           _LayerEdge* eN = eI->_neibors[iN];
6754           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6755           {
6756             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6757             limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
6758           }
6759         }
6760       }
6761     }
6762     else if ( eosI.ShapeType() == TopAbs_EDGE )
6763     {
6764       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6765       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6766
6767       _LayerEdge* e0 = eosI._edges[0];
6768       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6769       {
6770         _LayerEdge* eI = eosI._edges[i];
6771         limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
6772         e0 = eI;
6773       }
6774     }
6775   }
6776 }
6777
6778 //================================================================================
6779 /*!
6780  * \brief Limit _LayerEdge::_maxLen according to local curvature
6781  */
6782 //================================================================================
6783
6784 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*    e1,
6785                                               _LayerEdge*    e2,
6786                                               _EdgesOnShape& eos1,
6787                                               _EdgesOnShape& eos2,
6788                                               const bool     isSmoothable )
6789 {
6790   if (( e1->_nodes[0]->GetPosition()->GetDim() !=
6791         e2->_nodes[0]->GetPosition()->GetDim() ) &&
6792       ( e1->_cosin < 0.75 ))
6793     return; // angle > 90 deg at e1
6794
6795   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6796   double norSize = plnNorm.SquareModulus();
6797   if ( norSize < std::numeric_limits<double>::min() )
6798     return; // parallel normals
6799
6800   // find closest points of skew _LayerEdge's
6801   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6802   gp_XYZ dir12 = src2 - src1;
6803   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6804   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6805   double  dot1 = perp2 * e1->_normal;
6806   double  dot2 = perp1 * e2->_normal;
6807   double    u1 =   ( perp2 * dir12 ) / dot1;
6808   double    u2 = - ( perp1 * dir12 ) / dot2;
6809   if ( u1 > 0 && u2 > 0 )
6810   {
6811     double ovl = ( u1 * e1->_normal * dir12 -
6812                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6813     if ( ovl > theSmoothThickToElemSizeRatio )
6814     {
6815       const double coef = 0.75;
6816       e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
6817       e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
6818     }
6819   }
6820 }
6821
6822 //================================================================================
6823 /*!
6824  * \brief Fill data._collisionEdges
6825  */
6826 //================================================================================
6827
6828 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6829 {
6830   data._collisionEdges.clear();
6831
6832   // set the full thickness of the layers to LEs
6833   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6834   {
6835     _EdgesOnShape& eos = data._edgesOnShape[iS];
6836     if ( eos._edges.empty() ) continue;
6837     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6838     if ( !eos._sWOL.IsNull() ) continue; // PAL23566
6839
6840     for ( size_t i = 0; i < eos._edges.size(); ++i )
6841     {
6842       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6843       double maxLen = eos._edges[i]->_maxLen;
6844       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6845       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6846       eos._edges[i]->_maxLen = maxLen;
6847     }
6848   }
6849
6850   // make temporary quadrangles got by extrusion of
6851   // mesh edges along _LayerEdge._normal's
6852
6853   vector< const SMDS_MeshElement* > tmpFaces;
6854
6855   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6856   {
6857     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6858     if ( eos.ShapeType() != TopAbs_EDGE )
6859       continue;
6860     if ( eos._edges.empty() )
6861     {
6862       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6863       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6864       while ( smIt->more() )
6865         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6866           if ( eov->_edges.size() == 1 )
6867             edge[ bool( edge[0]) ] = eov->_edges[0];
6868
6869       if ( edge[1] )
6870       {
6871         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6872         tmpFaces.push_back( f );
6873       }
6874     }
6875     for ( size_t i = 0; i < eos._edges.size(); ++i )
6876     {
6877       _LayerEdge* edge = eos._edges[i];
6878       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6879       {
6880         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6881         if ( src2->GetPosition()->GetDim() > 0 &&
6882              src2->GetID() < edge->_nodes[0]->GetID() )
6883           continue; // avoid using same segment twice
6884
6885         // a _LayerEdge containing tgt2
6886         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6887
6888         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6889         tmpFaces.push_back( f );
6890       }
6891     }
6892   }
6893
6894   // Find _LayerEdge's intersecting tmpFaces.
6895
6896   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6897                                                             tmpFaces.end()));
6898   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6899     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6900
6901   double dist1, dist2, segLen, eps = 0.5;
6902   _CollisionEdges collEdges;
6903   vector< const SMDS_MeshElement* > suspectFaces;
6904   const double angle45 = Cos( 45. * M_PI / 180. );
6905
6906   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6907   {
6908     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6909     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6910       continue;
6911     // find sub-shapes whose VL can influence VL on eos
6912     set< TGeomID > neighborShapes;
6913     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6914     while ( const TopoDS_Shape* face = fIt->next() )
6915     {
6916       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6917       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6918       {
6919         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6920         while ( subIt->more() )
6921           neighborShapes.insert( subIt->next()->GetId() );
6922       }
6923     }
6924     if ( eos.ShapeType() == TopAbs_VERTEX )
6925     {
6926       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6927       while ( const TopoDS_Shape* edge = eIt->next() )
6928         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6929     }
6930     // find intersecting _LayerEdge's
6931     for ( size_t i = 0; i < eos._edges.size(); ++i )
6932     {
6933       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6934       _LayerEdge*   edge = eos._edges[i];
6935       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6936       segLen *= 1.2;
6937
6938       gp_Vec eSegDir0, eSegDir1;
6939       if ( edge->IsOnEdge() )
6940       {
6941         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6942         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6943         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6944       }
6945       suspectFaces.clear();
6946       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6947                                      SMDSAbs_Face, suspectFaces );
6948       collEdges._intEdges.clear();
6949       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6950       {
6951         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6952         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6953         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6954         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6955         if ( edge->IsOnEdge() ) {
6956           if ( edge->_2neibors->include( f->_le1 ) ||
6957                edge->_2neibors->include( f->_le2 )) continue;
6958         }
6959         else {
6960           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6961               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6962         }
6963         dist1 = dist2 = Precision::Infinite();
6964         if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
6965           dist1 = Precision::Infinite();
6966         if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
6967           dist2 = Precision::Infinite();
6968         if (( dist1 > segLen ) && ( dist2 > segLen ))
6969           continue;
6970
6971         if ( edge->IsOnEdge() )
6972         {
6973           // skip perpendicular EDGEs
6974           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
6975           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6976                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6977                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6978                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6979           if ( !isParallel )
6980             continue;
6981         }
6982
6983         // either limit inflation of edges or remember them for updating _normal
6984         // double dot = edge->_normal * f->GetDir();
6985         // if ( dot > 0.1 )
6986         {
6987           collEdges._intEdges.push_back( f->_le1 );
6988           collEdges._intEdges.push_back( f->_le2 );
6989         }
6990         // else
6991         // {
6992         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6993         //   edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
6994         // }
6995       }
6996
6997       if ( !collEdges._intEdges.empty() )
6998       {
6999         collEdges._edge = edge;
7000         data._collisionEdges.push_back( collEdges );
7001       }
7002     }
7003   }
7004
7005   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
7006     delete tmpFaces[i];
7007
7008   // restore the zero thickness
7009   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7010   {
7011     _EdgesOnShape& eos = data._edgesOnShape[iS];
7012     if ( eos._edges.empty() ) continue;
7013     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7014
7015     for ( size_t i = 0; i < eos._edges.size(); ++i )
7016     {
7017       eos._edges[i]->InvalidateStep( 1, eos );
7018       eos._edges[i]->_len = 0;
7019     }
7020   }
7021 }
7022
7023 //================================================================================
7024 /*!
7025  * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
7026  *        will be updated at each inflation step
7027  */
7028 //================================================================================
7029
7030 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
7031                                                              _SolidData&         data,
7032                                                              SMESH_MesherHelper& helper )
7033 {
7034   const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
7035   const double       preci = BRep_Tool::Tolerance( convFace._face );
7036   Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
7037
7038   bool edgesToUpdateFound = false;
7039
7040   map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7041   for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7042   {
7043     _EdgesOnShape& eos = * id2eos->second;
7044     if ( !eos._sWOL.IsNull() ) continue;
7045     if ( !eos._hyp.ToSmooth() ) continue;
7046     for ( size_t i = 0; i < eos._edges.size(); ++i )
7047     {
7048       _LayerEdge* ledge = eos._edges[ i ];
7049       if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
7050       if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
7051
7052       gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
7053                         ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
7054
7055       // the normal must be updated if distance from tgtPos to surface is less than
7056       // target thickness
7057
7058       // find an initial UV for search of a projection of tgtPos to surface
7059       const SMDS_MeshNode* nodeInFace = 0;
7060       SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7061       while ( fIt->more() && !nodeInFace )
7062       {
7063         const SMDS_MeshElement* f = fIt->next();
7064         if ( convFaceID != f->getshapeId() ) continue;
7065
7066         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7067         while ( nIt->more() && !nodeInFace )
7068         {
7069           const SMDS_MeshElement* n = nIt->next();
7070           if ( n->getshapeId() == convFaceID )
7071             nodeInFace = static_cast< const SMDS_MeshNode* >( n );
7072         }
7073       }
7074       if ( !nodeInFace )
7075         continue;
7076       gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
7077
7078       // projection
7079       surface->NextValueOfUV( uv, tgtPos, preci );
7080       double  dist = surface->Gap();
7081       if ( dist < 0.95 * ledge->_maxLen )
7082       {
7083         ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
7084         if ( !ledge->_curvature ) ledge->_curvature = _Factory::NewCurvature();
7085         ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
7086         edgesToUpdateFound = true;
7087       }
7088     }
7089   }
7090
7091   if ( !convFace._isTooCurved && edgesToUpdateFound )
7092   {
7093     data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
7094   }
7095 }
7096
7097 //================================================================================
7098 /*!
7099  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
7100  * _LayerEdge's on neighbor EDGE's
7101  */
7102 //================================================================================
7103
7104 bool _ViscousBuilder::updateNormals( _SolidData&         data,
7105                                      SMESH_MesherHelper& helper,
7106                                      int                 stepNb,
7107                                      double              stepSize)
7108 {
7109   updateNormalsOfC1Vertices( data );
7110
7111   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
7112     return false;
7113
7114   // map to store new _normal and _cosin for each intersected edge
7115   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
7116   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
7117   _LayerEdge zeroEdge;
7118   zeroEdge._normal.SetCoord( 0,0,0 );
7119   zeroEdge._maxLen = Precision::Infinite();
7120   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
7121
7122   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
7123
7124   double segLen, dist1, dist2, dist;
7125   vector< pair< _LayerEdge*, double > > intEdgesDist;
7126   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
7127
7128   for ( int iter = 0; iter < 5; ++iter )
7129   {
7130     edge2newEdge.clear();
7131
7132     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
7133     {
7134       _CollisionEdges& ce = data._collisionEdges[iE];
7135       _LayerEdge*   edge1 = ce._edge;
7136       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
7137       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7138       if ( !eos1 ) continue;
7139
7140       // detect intersections
7141       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
7142       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
7143       double     eps = 0.5;
7144       intEdgesDist.clear();
7145       double minIntDist = Precision::Infinite();
7146       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
7147       {
7148         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7149              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
7150              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
7151           continue;
7152         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
7153         double fact = ( 1.1 + dot * dot );
7154         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7155         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7156         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7157         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7158         dist1 = dist2 = Precision::Infinite();
7159         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
7160              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7161           continue;
7162         dist = dist1;
7163         if ( dist > testLen || dist <= 0 )
7164         {
7165           dist = dist2;
7166           if ( dist > testLen || dist <= 0 )
7167             continue;
7168         }
7169         // choose a closest edge
7170         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7171         double d1 = intP.SquareDistance( pSrc0 );
7172         double d2 = intP.SquareDistance( pSrc1 );
7173         int iClose = i + ( d2 < d1 );
7174         _LayerEdge* edge2 = ce._intEdges[iClose];
7175         edge2->Unset( _LayerEdge::MARKED );
7176
7177         // choose a closest edge among neighbors
7178         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7179         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7180         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7181         {
7182           _LayerEdge * edgeJ = intEdgesDist[j].first;
7183           if ( edge2->IsNeiborOnEdge( edgeJ ))
7184           {
7185             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7186             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7187           }
7188         }
7189         intEdgesDist.push_back( make_pair( edge2, dist ));
7190         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7191         // {
7192         //   iClose = i + !( d2 < d1 );
7193         //   intEdges.push_back( ce._intEdges[iClose] );
7194         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7195         // }
7196         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7197       }
7198
7199       //ce._edge = 0;
7200
7201       // compute new _normals
7202       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7203       {
7204         _LayerEdge* edge2   = intEdgesDist[i].first;
7205         double      distWgt = edge1->_len / intEdgesDist[i].second;
7206         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7207         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
7208         if ( edge2->Is( _LayerEdge::MARKED )) continue;
7209         edge2->Set( _LayerEdge::MARKED );
7210
7211         // get a new normal
7212         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7213
7214         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7215         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7216         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7217         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
7218         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7219         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7220         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7221         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7222         newNormal.Normalize();
7223
7224         // get new cosin
7225         double newCos;
7226         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7227         if ( cos1 < theMinSmoothCosin )
7228         {
7229           newCos = cos2 * sgn1;
7230         }
7231         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7232         {
7233           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7234         }
7235         else
7236         {
7237           newCos = edge1->_cosin;
7238         }
7239
7240         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7241         e2neIt->second._normal += distWgt * newNormal;
7242         e2neIt->second._cosin   = newCos;
7243         e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7244         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7245           e2neIt->second._normal += dir2;
7246
7247         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7248         e2neIt->second._normal += distWgt * newNormal;
7249         if ( Precision::IsInfinite( zeroEdge._maxLen ))
7250         {
7251           e2neIt->second._cosin  = edge2->_cosin;
7252           e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7253         }
7254         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7255           e2neIt->second._normal += dir1;
7256       }
7257     }
7258
7259     if ( edge2newEdge.empty() )
7260       break; //return true;
7261
7262     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7263
7264     // Update data of edges depending on a new _normal
7265
7266     data.UnmarkEdges();
7267     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7268     {
7269       _LayerEdge*    edge = e2neIt->first;
7270       _LayerEdge& newEdge = e2neIt->second;
7271       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
7272       if ( edge->Is( _LayerEdge::BLOCKED && newEdge._maxLen > edge->_len ))
7273         continue;
7274
7275       // Check if a new _normal is OK:
7276       newEdge._normal.Normalize();
7277       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7278       {
7279         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7280         {
7281           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7282           edge->SetMaxLen( newEdge._maxLen );
7283           edge->SetNewLength( newEdge._maxLen, *eos, helper );
7284         }
7285         continue; // the new _normal is bad
7286       }
7287       // the new _normal is OK
7288
7289       // find shapes that need smoothing due to change of _normal
7290       if ( edge->_cosin   < theMinSmoothCosin &&
7291            newEdge._cosin > theMinSmoothCosin )
7292       {
7293         if ( eos->_sWOL.IsNull() )
7294         {
7295           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7296           while ( fIt->more() )
7297             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7298         }
7299         else // edge inflates along a FACE
7300         {
7301           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7302           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7303           while ( const TopoDS_Shape* E = eIt->next() )
7304           {
7305             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7306             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7307             if ( angle < M_PI / 2 )
7308               shapesToSmooth.insert( data.GetShapeEdges( *E ));
7309           }
7310         }
7311       }
7312
7313       double len = edge->_len;
7314       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7315       edge->SetNormal( newEdge._normal );
7316       edge->SetCosin( newEdge._cosin );
7317       edge->SetNewLength( len, *eos, helper );
7318       edge->Set( _LayerEdge::MARKED );
7319       edge->Set( _LayerEdge::NORMAL_UPDATED );
7320       edgesNoAnaSmooth.insert( eos );
7321     }
7322
7323     // Update normals and other dependent data of not intersecting _LayerEdge's
7324     // neighboring the intersecting ones
7325
7326     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7327     {
7328       _LayerEdge*   edge1 = e2neIt->first;
7329       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7330       if ( !edge1->Is( _LayerEdge::MARKED ))
7331         continue;
7332
7333       if ( edge1->IsOnEdge() )
7334       {
7335         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7336         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7337         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7338       }
7339
7340       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7341         continue;
7342       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7343       {
7344         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7345         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7346           continue; // j-th neighbor is also intersected
7347         _LayerEdge* prevEdge = edge1;
7348         const int nbSteps = 10;
7349         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7350         {
7351           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7352                neighbor->Is( _LayerEdge::MARKED ))
7353             break;
7354           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7355           if ( !eos ) continue;
7356           _LayerEdge* nextEdge = neighbor;
7357           if ( neighbor->_2neibors )
7358           {
7359             int iNext = 0;
7360             nextEdge = neighbor->_2neibors->_edges[iNext];
7361             if ( nextEdge == prevEdge )
7362               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7363           }
7364           double r = double(step-1)/nbSteps/(iter+1);
7365           if ( !nextEdge->_2neibors )
7366             r = Min( r, 0.5 );
7367
7368           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7369           newNorm.Normalize();
7370           if ( !isNewNormalOk( data, *neighbor, newNorm ))
7371             break;
7372
7373           double len = neighbor->_len;
7374           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7375           neighbor->SetNormal( newNorm );
7376           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7377           if ( neighbor->_2neibors )
7378             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7379           neighbor->SetNewLength( len, *eos, helper );
7380           neighbor->Set( _LayerEdge::MARKED );
7381           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7382           edgesNoAnaSmooth.insert( eos );
7383
7384           if ( !neighbor->_2neibors )
7385             break; // neighbor is on VERTEX
7386
7387           // goto the next neighbor
7388           prevEdge = neighbor;
7389           neighbor = nextEdge;
7390         }
7391       }
7392     }
7393     dumpFunctionEnd();
7394   } // iterations
7395
7396   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7397
7398   return true;
7399 }
7400
7401 //================================================================================
7402 /*!
7403  * \brief Check if a new normal is OK
7404  */
7405 //================================================================================
7406
7407 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
7408                                      _LayerEdge&   edge,
7409                                      const gp_XYZ& newNormal)
7410 {
7411   // check a min angle between the newNormal and surrounding faces
7412   vector<_Simplex> simplices;
7413   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7414   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7415   double newMinDot = 1, curMinDot = 1;
7416   for ( size_t i = 0; i < simplices.size(); ++i )
7417   {
7418     n1.Set( simplices[i]._nPrev );
7419     n2.Set( simplices[i]._nNext );
7420     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7421     double normLen2 = normFace.SquareModulus();
7422     if ( normLen2 < std::numeric_limits<double>::min() )
7423       continue;
7424     normFace /= Sqrt( normLen2 );
7425     newMinDot = Min( newNormal    * normFace, newMinDot );
7426     curMinDot = Min( edge._normal * normFace, curMinDot );
7427   }
7428   bool ok = true;
7429   if ( newMinDot < 0.5 )
7430   {
7431     ok = ( newMinDot >= curMinDot * 0.9 );
7432     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7433     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7434     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7435   }
7436
7437   return ok;
7438 }
7439
7440 //================================================================================
7441 /*!
7442  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7443  */
7444 //================================================================================
7445
7446 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
7447                                                SMESH_MesherHelper& helper,
7448                                                const int           nbSteps,
7449                                                const double        stepSize )
7450 {
7451   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7452     return true; // no shapes needing smoothing
7453
7454   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7455   {
7456     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7457     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
7458          !eos._hyp.ToSmooth() ||
7459          eos.ShapeType() != TopAbs_FACE ||
7460          eos._edges.empty() )
7461       continue;
7462
7463     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7464     if ( !toSmooth ) continue;
7465
7466     for ( size_t i = 0; i < eos._edges.size(); ++i )
7467     {
7468       _LayerEdge* edge = eos._edges[i];
7469       if ( !edge->Is( _LayerEdge::SMOOTHED ))
7470         continue;
7471       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7472         continue;
7473
7474       const gp_XYZ& pPrev = edge->PrevPos();
7475       const gp_XYZ& pLast = edge->_pos.back();
7476       gp_XYZ      stepVec = pLast - pPrev;
7477       double realStepSize = stepVec.Modulus();
7478       if ( realStepSize < numeric_limits<double>::min() )
7479         continue;
7480
7481       edge->_lenFactor = realStepSize / stepSize;
7482       edge->_normal    = stepVec / realStepSize;
7483       edge->Set( _LayerEdge::NORMAL_UPDATED );
7484     }
7485   }
7486
7487   return true;
7488 }
7489
7490 //================================================================================
7491 /*!
7492  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7493  */
7494 //================================================================================
7495
7496 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7497 {
7498   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7499   {
7500     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7501     if ( eov._eosC1.empty() ||
7502          eov.ShapeType() != TopAbs_VERTEX ||
7503          eov._edges.empty() )
7504       continue;
7505
7506     gp_XYZ newNorm   = eov._edges[0]->_normal;
7507     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7508     bool normChanged = false;
7509
7510     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7511     {
7512       _EdgesOnShape*   eoe = eov._eosC1[i];
7513       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7514       const double    eLen = SMESH_Algo::EdgeLength( e );
7515       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
7516       if ( oppV.IsSame( eov._shape ))
7517         oppV = SMESH_MesherHelper::IthVertex( 1, e );
7518       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7519       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7520       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7521
7522       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7523       if ( curThickOpp + curThick < eLen )
7524         continue;
7525
7526       double wgt = 2. * curThick / eLen;
7527       newNorm += wgt * eovOpp->_edges[0]->_normal;
7528       normChanged = true;
7529     }
7530     if ( normChanged )
7531     {
7532       eov._edges[0]->SetNormal( newNorm.Normalized() );
7533       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7534     }
7535   }
7536 }
7537
7538 //================================================================================
7539 /*!
7540  * \brief Modify normals of _LayerEdge's on _ConvexFace's
7541  */
7542 //================================================================================
7543
7544 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
7545                                                   SMESH_MesherHelper& helper,
7546                                                   int                 stepNb )
7547 {
7548   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7549   bool isOK;
7550
7551   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7552   for ( ; id2face != data._convexFaces.end(); ++id2face )
7553   {
7554     _ConvexFace & convFace = (*id2face).second;
7555     convFace._normalsFixedOnBorders = false; // to update at each inflation step
7556
7557     if ( convFace._normalsFixed )
7558       continue; // already fixed
7559     if ( convFace.CheckPrisms() )
7560       continue; // nothing to fix
7561
7562     convFace._normalsFixed = true;
7563
7564     BRepAdaptor_Surface surface ( convFace._face, false );
7565     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
7566
7567     // check if the convex FACE is of spherical shape
7568
7569     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7570     Bnd_B3d nodesBox;
7571     gp_Pnt  center;
7572
7573     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7574     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7575     {
7576       _EdgesOnShape& eos = *(id2eos->second);
7577       if ( eos.ShapeType() == TopAbs_VERTEX )
7578       {
7579         _LayerEdge* ledge = eos._edges[ 0 ];
7580         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7581           centersBox.Add( center );
7582       }
7583       for ( size_t i = 0; i < eos._edges.size(); ++i )
7584         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7585     }
7586     if ( centersBox.IsVoid() )
7587     {
7588       debugMsg( "Error: centersBox.IsVoid()" );
7589       return false;
7590     }
7591     const bool isSpherical =
7592       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7593
7594     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7595     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7596
7597     if ( isSpherical )
7598     {
7599       // set _LayerEdge::_normal as average of all normals
7600
7601       // WARNING: different density of nodes on EDGEs is not taken into account that
7602       // can lead to an improper new normal
7603
7604       gp_XYZ avgNormal( 0,0,0 );
7605       nbEdges = 0;
7606       id2eos = convFace._subIdToEOS.begin();
7607       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7608       {
7609         _EdgesOnShape& eos = *(id2eos->second);
7610         // set data of _CentralCurveOnEdge
7611         if ( eos.ShapeType() == TopAbs_EDGE )
7612         {
7613           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7614           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7615           if ( !eos._sWOL.IsNull() )
7616             ceCurve._adjFace.Nullify();
7617           else
7618             ceCurve._ledges.insert( ceCurve._ledges.end(),
7619                                     eos._edges.begin(), eos._edges.end());
7620         }
7621         // summarize normals
7622         for ( size_t i = 0; i < eos._edges.size(); ++i )
7623           avgNormal += eos._edges[ i ]->_normal;
7624       }
7625       double normSize = avgNormal.SquareModulus();
7626       if ( normSize < 1e-200 )
7627       {
7628         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7629         return false;
7630       }
7631       avgNormal /= Sqrt( normSize );
7632
7633       // compute new _LayerEdge::_cosin on EDGEs
7634       double avgCosin = 0;
7635       int     nbCosin = 0;
7636       gp_Vec inFaceDir;
7637       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7638       {
7639         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7640         if ( ceCurve._adjFace.IsNull() )
7641           continue;
7642         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7643         {
7644           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7645           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7646           if ( isOK )
7647           {
7648             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7649             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7650             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7651             nbCosin++;
7652           }
7653         }
7654       }
7655       if ( nbCosin > 0 )
7656         avgCosin /= nbCosin;
7657
7658       // set _LayerEdge::_normal = avgNormal
7659       id2eos = convFace._subIdToEOS.begin();
7660       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7661       {
7662         _EdgesOnShape& eos = *(id2eos->second);
7663         if ( eos.ShapeType() != TopAbs_EDGE )
7664           for ( size_t i = 0; i < eos._edges.size(); ++i )
7665             eos._edges[ i ]->_cosin = avgCosin;
7666
7667         for ( size_t i = 0; i < eos._edges.size(); ++i )
7668         {
7669           eos._edges[ i ]->SetNormal( avgNormal );
7670           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7671         }
7672       }
7673     }
7674     else // if ( isSpherical )
7675     {
7676       // We suppose that centers of curvature at all points of the FACE
7677       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7678       // having a common center of curvature we define the same new normal
7679       // as a sum of normals of _LayerEdge's on EDGEs among them.
7680
7681       // get all centers of curvature for each EDGE
7682
7683       helper.SetSubShape( convFace._face );
7684       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7685
7686       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7687       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7688       {
7689         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7690
7691         // set adjacent FACE
7692         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7693
7694         // get _LayerEdge's of the EDGE
7695         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7696         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7697         if ( !eos || eos->_edges.empty() )
7698         {
7699           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7700           for ( int iV = 0; iV < 2; ++iV )
7701           {
7702             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7703             TGeomID     vID = meshDS->ShapeToIndex( v );
7704             eos = data.GetShapeEdges( vID );
7705             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7706           }
7707           edgeLEdge    = &vertexLEdges[0];
7708           edgeLEdgeEnd = edgeLEdge + 2;
7709
7710           centerCurves[ iE ]._adjFace.Nullify();
7711         }
7712         else
7713         {
7714           if ( ! eos->_toSmooth )
7715             data.SortOnEdge( edge, eos->_edges );
7716           edgeLEdge    = &eos->_edges[ 0 ];
7717           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7718           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7719           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7720
7721           if ( ! eos->_sWOL.IsNull() )
7722             centerCurves[ iE ]._adjFace.Nullify();
7723         }
7724
7725         // Get curvature centers
7726
7727         centersBox.Clear();
7728
7729         if ( edgeLEdge[0]->IsOnEdge() &&
7730              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7731         { // 1st VERTEX
7732           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7733           centersBox.Add( center );
7734         }
7735         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7736           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7737           { // EDGE or VERTEXes
7738             centerCurves[ iE ].Append( center, *edgeLEdge );
7739             centersBox.Add( center );
7740           }
7741         if ( edgeLEdge[-1]->IsOnEdge() &&
7742              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7743         { // 2nd VERTEX
7744           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7745           centersBox.Add( center );
7746         }
7747         centerCurves[ iE ]._isDegenerated =
7748           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7749
7750       } // loop on EDGES of convFace._face to set up data of centerCurves
7751
7752       // Compute new normals for _LayerEdge's on EDGEs
7753
7754       double avgCosin = 0;
7755       int     nbCosin = 0;
7756       gp_Vec inFaceDir;
7757       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7758       {
7759         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7760         if ( ceCurve._isDegenerated )
7761           continue;
7762         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7763         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7764         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7765         {
7766           isOK = false;
7767           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7768           {
7769             if ( iE1 != iE2 )
7770               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7771           }
7772           if ( isOK && !ceCurve._adjFace.IsNull() )
7773           {
7774             // compute new _LayerEdge::_cosin
7775             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7776             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7777             if ( isOK )
7778             {
7779               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7780               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7781               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7782               nbCosin++;
7783             }
7784           }
7785         }
7786       }
7787       // set new normals to _LayerEdge's of NOT degenerated central curves
7788       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7789       {
7790         if ( centerCurves[ iE ]._isDegenerated )
7791           continue;
7792         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7793         {
7794           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7795           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7796         }
7797       }
7798       // set new normals to _LayerEdge's of     degenerated central curves
7799       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7800       {
7801         if ( !centerCurves[ iE ]._isDegenerated ||
7802              centerCurves[ iE ]._ledges.size() < 3 )
7803           continue;
7804         // new normal is an average of new normals at VERTEXes that
7805         // was computed on non-degenerated _CentralCurveOnEdge's
7806         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7807                            centerCurves[ iE ]._ledges.back ()->_normal );
7808         double sz = newNorm.Modulus();
7809         if ( sz < 1e-200 )
7810           continue;
7811         newNorm /= sz;
7812         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7813                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7814         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7815         {
7816           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7817           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7818           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7819         }
7820       }
7821
7822       // Find new normals for _LayerEdge's based on FACE
7823
7824       if ( nbCosin > 0 )
7825         avgCosin /= nbCosin;
7826       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7827       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7828       if ( id2eos != convFace._subIdToEOS.end() )
7829       {
7830         int iE = 0;
7831         gp_XYZ newNorm;
7832         _EdgesOnShape& eos = * ( id2eos->second );
7833         for ( size_t i = 0; i < eos._edges.size(); ++i )
7834         {
7835           _LayerEdge* ledge = eos._edges[ i ];
7836           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7837             continue;
7838           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7839           {
7840             iE = iE % centerCurves.size();
7841             if ( centerCurves[ iE ]._isDegenerated )
7842               continue;
7843             newNorm.SetCoord( 0,0,0 );
7844             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7845             {
7846               ledge->SetNormal( newNorm );
7847               ledge->_cosin  = avgCosin;
7848               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7849               break;
7850             }
7851           }
7852         }
7853       }
7854
7855     } // not a quasi-spherical FACE
7856
7857     // Update _LayerEdge's data according to a new normal
7858
7859     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7860                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7861
7862     id2eos = convFace._subIdToEOS.begin();
7863     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7864     {
7865       _EdgesOnShape& eos = * ( id2eos->second );
7866       for ( size_t i = 0; i < eos._edges.size(); ++i )
7867       {
7868         _LayerEdge* & ledge = eos._edges[ i ];
7869         double len = ledge->_len;
7870         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7871         ledge->SetCosin( ledge->_cosin );
7872         ledge->SetNewLength( len, eos, helper );
7873       }
7874       if ( eos.ShapeType() != TopAbs_FACE )
7875         for ( size_t i = 0; i < eos._edges.size(); ++i )
7876         {
7877           _LayerEdge* ledge = eos._edges[ i ];
7878           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7879           {
7880             _LayerEdge* neibor = ledge->_neibors[iN];
7881             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7882             {
7883               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7884               neibor->Set( _LayerEdge::MOVED );
7885               neibor->SetSmooLen( neibor->_len );
7886             }
7887           }
7888         }
7889     } // loop on sub-shapes of convFace._face
7890
7891     // Find FACEs adjacent to convFace._face that got necessity to smooth
7892     // as a result of normals modification
7893
7894     set< _EdgesOnShape* > adjFacesToSmooth;
7895     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7896     {
7897       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7898            centerCurves[ iE ]._adjFaceToSmooth )
7899         continue;
7900       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7901       {
7902         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7903         {
7904           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7905           break;
7906         }
7907       }
7908     }
7909     data.AddShapesToSmooth( adjFacesToSmooth );
7910
7911     dumpFunctionEnd();
7912
7913
7914   } // loop on data._convexFaces
7915
7916   return true;
7917 }
7918
7919 //================================================================================
7920 /*!
7921  * \brief Return max curvature of a FACE
7922  */
7923 //================================================================================
7924
7925 double _ConvexFace::GetMaxCurvature( _SolidData&         data,
7926                                      _EdgesOnShape&      eof,
7927                                      BRepLProp_SLProps&  surfProp,
7928                                      SMESH_MesherHelper& helper)
7929 {
7930   double maxCurvature = 0;
7931
7932   TopoDS_Face F = TopoDS::Face( eof._shape );
7933
7934   const int           nbTestPnt = 5;
7935   const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7936   SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7937   while ( smIt->more() )
7938   {
7939     SMESH_subMesh* sm = smIt->next();
7940     const TGeomID subID = sm->GetId();
7941
7942     // find _LayerEdge's of a sub-shape
7943     _EdgesOnShape* eos;
7944     if (( eos = data.GetShapeEdges( subID )))
7945       this->_subIdToEOS.insert( make_pair( subID, eos ));
7946     else
7947       continue;
7948
7949     // check concavity and curvature and limit data._stepSize
7950     const double minCurvature =
7951       1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7952     size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7953     for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7954     {
7955       gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7956       surfProp.SetParameters( uv.X(), uv.Y() );
7957       if ( surfProp.IsCurvatureDefined() )
7958       {
7959         double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7960                                 surfProp.MinCurvature() * oriFactor );
7961         maxCurvature = Max( maxCurvature, curvature );
7962
7963         if ( curvature > minCurvature )
7964           this->_isTooCurved = true;
7965       }
7966     }
7967   } // loop on sub-shapes of the FACE
7968
7969   return maxCurvature;
7970 }
7971
7972 //================================================================================
7973 /*!
7974  * \brief Finds a center of curvature of a surface at a _LayerEdge
7975  */
7976 //================================================================================
7977
7978 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7979                                         BRepLProp_SLProps&  surfProp,
7980                                         SMESH_MesherHelper& helper,
7981                                         gp_Pnt &            center ) const
7982 {
7983   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7984   surfProp.SetParameters( uv.X(), uv.Y() );
7985   if ( !surfProp.IsCurvatureDefined() )
7986     return false;
7987
7988   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7989   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7990   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7991   if ( surfCurvatureMin > surfCurvatureMax )
7992     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7993   else
7994     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7995
7996   return true;
7997 }
7998
7999 //================================================================================
8000 /*!
8001  * \brief Check that prisms are not distorted
8002  */
8003 //================================================================================
8004
8005 bool _ConvexFace::CheckPrisms() const
8006 {
8007   double vol = 0;
8008   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
8009   {
8010     const _LayerEdge* edge = _simplexTestEdges[i];
8011     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
8012     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
8013       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
8014       {
8015         debugMsg( "Bad simplex of _simplexTestEdges ("
8016                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
8017                   << " "<< edge->_simplices[j]._nPrev->GetID()
8018                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
8019         return false;
8020       }
8021   }
8022   return true;
8023 }
8024
8025 //================================================================================
8026 /*!
8027  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
8028  *        stored in this _CentralCurveOnEdge.
8029  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
8030  *  \param [in,out] newNormal - current normal at this point, to be redefined
8031  *  \return bool - true if succeeded.
8032  */
8033 //================================================================================
8034
8035 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
8036 {
8037   if ( this->_isDegenerated )
8038     return false;
8039
8040   // find two centers the given one lies between
8041
8042   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
8043   {
8044     double sl2 = 1.001 * _segLength2[ i ];
8045
8046     double d1 = center.SquareDistance( _curvaCenters[ i ]);
8047     if ( d1 > sl2 )
8048       continue;
8049     
8050     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
8051     if ( d2 > sl2 || d2 + d1 < 1e-100 )
8052       continue;
8053
8054     d1 = Sqrt( d1 );
8055     d2 = Sqrt( d2 );
8056     double r = d1 / ( d1 + d2 );
8057     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
8058                    (      r ) * _ledges[ i+1 ]->_normal );
8059     norm.Normalize();
8060
8061     newNormal += norm;
8062     double sz = newNormal.Modulus();
8063     if ( sz < 1e-200 )
8064       break;
8065     newNormal /= sz;
8066     return true;
8067   }
8068   return false;
8069 }
8070
8071 //================================================================================
8072 /*!
8073  * \brief Set shape members
8074  */
8075 //================================================================================
8076
8077 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
8078                                      const _ConvexFace&  convFace,
8079                                      _SolidData&         data,
8080                                      SMESH_MesherHelper& helper)
8081 {
8082   _edge = edge;
8083
8084   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
8085   while ( const TopoDS_Shape* F = fIt->next())
8086     if ( !convFace._face.IsSame( *F ))
8087     {
8088       _adjFace = TopoDS::Face( *F );
8089       _adjFaceToSmooth = false;
8090       // _adjFace already in a smoothing queue ?
8091       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
8092         _adjFaceToSmooth = eos->_toSmooth;
8093       break;
8094     }
8095 }
8096
8097 //================================================================================
8098 /*!
8099  * \brief Looks for intersection of it's last segment with faces
8100  *  \param distance - returns shortest distance from the last node to intersection
8101  */
8102 //================================================================================
8103
8104 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
8105                                    double &                 distance,
8106                                    const double&            epsilon,
8107                                    _EdgesOnShape&           eos,
8108                                    const SMDS_MeshElement** intFace)
8109 {
8110   vector< const SMDS_MeshElement* > suspectFaces;
8111   double segLen;
8112   gp_Ax1 lastSegment = LastSegment( segLen, eos );
8113   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
8114
8115   bool segmentIntersected = false;
8116   distance = Precision::Infinite();
8117   int iFace = -1; // intersected face
8118   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
8119   {
8120     const SMDS_MeshElement* face = suspectFaces[j];
8121     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
8122          face->GetNodeIndex( _nodes[0]     ) >= 0 )
8123       continue; // face sharing _LayerEdge node
8124     const int nbNodes = face->NbCornerNodes();
8125     bool intFound = false;
8126     double dist;
8127     SMDS_MeshElement::iterator nIt = face->begin_nodes();
8128     if ( nbNodes == 3 )
8129     {
8130       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
8131     }
8132     else
8133     {
8134       const SMDS_MeshNode* tria[3];
8135       tria[0] = *nIt++;
8136       tria[1] = *nIt++;
8137       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
8138       {
8139         tria[2] = *nIt++;
8140         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
8141         tria[1] = tria[2];
8142       }
8143     }
8144     if ( intFound )
8145     {
8146       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
8147         segmentIntersected = true;
8148       if ( distance > dist )
8149         distance = dist, iFace = j;
8150     }
8151   }
8152   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8153
8154   distance -= segLen;
8155
8156   if ( segmentIntersected )
8157   {
8158 #ifdef __myDEBUG
8159     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8160     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8161     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8162          << ", intersection with face ("
8163          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8164          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8165          << ") distance = " << distance << endl;
8166 #endif
8167   }
8168
8169   return segmentIntersected;
8170 }
8171
8172 //================================================================================
8173 /*!
8174  * \brief Returns a point used to check orientation of _simplices
8175  */
8176 //================================================================================
8177
8178 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8179 {
8180   size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8181
8182   if ( !eos || eos->_sWOL.IsNull() )
8183     return _pos[ i ];
8184
8185   if ( eos->SWOLType() == TopAbs_EDGE )
8186   {
8187     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8188   }
8189   //else //  TopAbs_FACE
8190
8191   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8192 }
8193
8194 //================================================================================
8195 /*!
8196  * \brief Returns size and direction of the last segment
8197  */
8198 //================================================================================
8199
8200 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8201 {
8202   // find two non-coincident positions
8203   gp_XYZ orig = _pos.back();
8204   gp_XYZ vec;
8205   int iPrev = _pos.size() - 2;
8206   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8207   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8208   while ( iPrev >= 0 )
8209   {
8210     vec = orig - _pos[iPrev];
8211     if ( vec.SquareModulus() > tol*tol )
8212       break;
8213     else
8214       iPrev--;
8215   }
8216
8217   // make gp_Ax1
8218   gp_Ax1 segDir;
8219   if ( iPrev < 0 )
8220   {
8221     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8222     segDir.SetDirection( _normal );
8223     segLen = 0;
8224   }
8225   else
8226   {
8227     gp_Pnt pPrev = _pos[ iPrev ];
8228     if ( !eos._sWOL.IsNull() )
8229     {
8230       TopLoc_Location loc;
8231       if ( eos.SWOLType() == TopAbs_EDGE )
8232       {
8233         double f,l;
8234         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8235         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8236       }
8237       else
8238       {
8239         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8240         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8241       }
8242       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8243     }
8244     segDir.SetLocation( pPrev );
8245     segDir.SetDirection( vec );
8246     segLen = vec.Modulus();
8247   }
8248
8249   return segDir;
8250 }
8251
8252 //================================================================================
8253 /*!
8254  * \brief Return the last (or \a which) position of the target node on a FACE. 
8255  *  \param [in] F - the FACE this _LayerEdge is inflated along
8256  *  \param [in] which - index of position
8257  *  \return gp_XY - result UV
8258  */
8259 //================================================================================
8260
8261 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8262 {
8263   if ( F.IsSame( eos._sWOL )) // F is my FACE
8264     return gp_XY( _pos.back().X(), _pos.back().Y() );
8265
8266   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8267     return gp_XY( 1e100, 1e100 );
8268
8269   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8270   double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8271   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8272   if ( !C2d.IsNull() && f <= u && u <= l )
8273     return C2d->Value( u ).XY();
8274
8275   return gp_XY( 1e100, 1e100 );
8276 }
8277
8278 //================================================================================
8279 /*!
8280  * \brief Test intersection of the last segment with a given triangle
8281  *   using Moller-Trumbore algorithm
8282  * Intersection is detected if distance to intersection is less than _LayerEdge._len
8283  */
8284 //================================================================================
8285
8286 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8287                                const gp_XYZ& vert0,
8288                                const gp_XYZ& vert1,
8289                                const gp_XYZ& vert2,
8290                                double&       t,
8291                                const double& EPSILON) const
8292 {
8293   const gp_Pnt& orig = lastSegment.Location();
8294   const gp_Dir& dir  = lastSegment.Direction();
8295
8296   /* calculate distance from vert0 to ray origin */
8297   //gp_XYZ tvec = orig.XYZ() - vert0;
8298
8299   //if ( tvec * dir > EPSILON )
8300     // intersected face is at back side of the temporary face this _LayerEdge belongs to
8301     //return false;
8302
8303   gp_XYZ edge1 = vert1 - vert0;
8304   gp_XYZ edge2 = vert2 - vert0;
8305
8306   /* begin calculating determinant - also used to calculate U parameter */
8307   gp_XYZ pvec = dir.XYZ() ^ edge2;
8308
8309   /* if determinant is near zero, ray lies in plane of triangle */
8310   double det = edge1 * pvec;
8311
8312   const double ANGL_EPSILON = 1e-12;
8313   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8314     return false;
8315
8316   /* calculate distance from vert0 to ray origin */
8317   gp_XYZ tvec = orig.XYZ() - vert0;
8318
8319   /* calculate U parameter and test bounds */
8320   double u = ( tvec * pvec ) / det;
8321   //if (u < 0.0 || u > 1.0)
8322   if ( u < -EPSILON || u > 1.0 + EPSILON )
8323     return false;
8324
8325   /* prepare to test V parameter */
8326   gp_XYZ qvec = tvec ^ edge1;
8327
8328   /* calculate V parameter and test bounds */
8329   double v = (dir.XYZ() * qvec) / det;
8330   //if ( v < 0.0 || u + v > 1.0 )
8331   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8332     return false;
8333
8334   /* calculate t, ray intersects triangle */
8335   t = (edge2 * qvec) / det;
8336
8337   //return true;
8338   return t > 0.;
8339 }
8340
8341 //================================================================================
8342 /*!
8343  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8344  *        neighbor _LayerEdge's by it's own inflation vector.
8345  *  \param [in] eov - EOS of the VERTEX
8346  *  \param [in] eos - EOS of the FACE
8347  *  \param [in] step - inflation step
8348  *  \param [in,out] badSmooEdges - tangled _LayerEdge's
8349  */
8350 //================================================================================
8351
8352 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
8353                                    const _EdgesOnShape*    eos,
8354                                    const int               step,
8355                                    vector< _LayerEdge* > & badSmooEdges )
8356 {
8357   // check if any of _neibors is in badSmooEdges
8358   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8359                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8360     return;
8361
8362   // get all edges to move
8363
8364   set< _LayerEdge* > edges;
8365
8366   // find a distance between _LayerEdge on VERTEX and its neighbors
8367   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
8368   double dist2 = 0;
8369   for ( size_t i = 0; i < _neibors.size(); ++i )
8370   {
8371     _LayerEdge* nEdge = _neibors[i];
8372     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8373     {
8374       edges.insert( nEdge );
8375       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8376     }
8377   }
8378   // add _LayerEdge's close to curPosV
8379   size_t nbE;
8380   do {
8381     nbE = edges.size();
8382     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8383     {
8384       _LayerEdge* edgeF = *e;
8385       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8386       {
8387         _LayerEdge* nEdge = edgeF->_neibors[i];
8388         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8389              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8390           edges.insert( nEdge );
8391       }
8392     }
8393   }
8394   while ( nbE < edges.size() );
8395
8396   // move the target node of the got edges
8397
8398   gp_XYZ prevPosV = PrevPos();
8399   if ( eov->SWOLType() == TopAbs_EDGE )
8400   {
8401     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8402     prevPosV = curve.Value( prevPosV.X() ).XYZ();
8403   }
8404   else if ( eov->SWOLType() == TopAbs_FACE )
8405   {
8406     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8407     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8408   }
8409
8410   SMDS_FacePositionPtr fPos;
8411   //double r = 1. - Min( 0.9, step / 10. );
8412   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8413   {
8414     _LayerEdge*       edgeF = *e;
8415     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
8416     const gp_XYZ    newPosF = curPosV + prevVF;
8417     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8418     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8419     edgeF->_pos.back() = newPosF;
8420     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8421
8422     // set _curvature to make edgeF updated by putOnOffsetSurface()
8423     if ( !edgeF->_curvature )
8424       if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8425       {
8426         edgeF->_curvature = _Factory::NewCurvature();
8427         edgeF->_curvature->_r = 0;
8428         edgeF->_curvature->_k = 0;
8429         edgeF->_curvature->_h2lenRatio = 0;
8430         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8431       }
8432   }
8433   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8434   //                      SMESH_TNodeXYZ( _nodes[0]    ));
8435   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8436   // {
8437   //   _LayerEdge*      edgeF = *e;
8438   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8439   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8440   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8441   //   edgeF->_pos.back() = newPosF;
8442   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8443   // }
8444
8445   // smooth _LayerEdge's around moved nodes
8446   //size_t nbBadBefore = badSmooEdges.size();
8447   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8448   {
8449     _LayerEdge* edgeF = *e;
8450     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8451       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8452         //&& !edges.count( edgeF->_neibors[j] ))
8453       {
8454         _LayerEdge* edgeFN = edgeF->_neibors[j];
8455         edgeFN->Unset( SMOOTHED );
8456         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8457         // if ( nbBad > 0 )
8458         // {
8459         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8460         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8461         //   int        nbBadAfter = edgeFN->_simplices.size();
8462         //   double vol;
8463         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8464         //   {
8465         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8466         //   }
8467         //   if ( nbBadAfter <= nbBad )
8468         //   {
8469         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8470         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8471         //     edgeF->_pos.back() = newPosF;
8472         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8473         //     nbBad = nbBadAfter;
8474         //   }
8475         // }
8476         if ( nbBad > 0 )
8477           badSmooEdges.push_back( edgeFN );
8478       }
8479   }
8480     // move a bit not smoothed around moved nodes
8481   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8482   //   {
8483   //   _LayerEdge*      edgeF = badSmooEdges[i];
8484   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8485   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8486   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8487   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8488   //   edgeF->_pos.back() = newPosF;
8489   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8490   // }
8491 }
8492
8493 //================================================================================
8494 /*!
8495  * \brief Perform smooth of _LayerEdge's based on EDGE's
8496  *  \retval bool - true if node has been moved
8497  */
8498 //================================================================================
8499
8500 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8501                               const TopoDS_Face&             F,
8502                               SMESH_MesherHelper&            helper)
8503 {
8504   ASSERT( IsOnEdge() );
8505
8506   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8507   SMESH_TNodeXYZ oldPos( tgtNode );
8508   double dist01, distNewOld;
8509   
8510   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8511   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8512   dist01 = p0.Distance( _2neibors->tgtNode(1) );
8513
8514   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8515   double lenDelta = 0;
8516   if ( _curvature )
8517   {
8518     //lenDelta = _curvature->lenDelta( _len );
8519     lenDelta = _curvature->lenDeltaByDist( dist01 );
8520     newPos.ChangeCoord() += _normal * lenDelta;
8521   }
8522
8523   distNewOld = newPos.Distance( oldPos );
8524
8525   if ( F.IsNull() )
8526   {
8527     if ( _2neibors->_plnNorm )
8528     {
8529       // put newPos on the plane defined by source node and _plnNorm
8530       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8531       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8532       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8533     }
8534     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8535     _pos.back() = newPos.XYZ();
8536   }
8537   else
8538   {
8539     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8540     gp_XY uv( Precision::Infinite(), 0 );
8541     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8542     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8543
8544     newPos = surface->Value( uv );
8545     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8546   }
8547
8548   // commented for IPAL0052478
8549   // if ( _curvature && lenDelta < 0 )
8550   // {
8551   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8552   //   _len -= prevPos.Distance( oldPos );
8553   //   _len += prevPos.Distance( newPos );
8554   // }
8555   bool moved = distNewOld > dist01/50;
8556   //if ( moved )
8557   dumpMove( tgtNode ); // debug
8558
8559   return moved;
8560 }
8561
8562 //================================================================================
8563 /*!
8564  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8565  */
8566 //================================================================================
8567
8568 void _LayerEdge::SmoothWoCheck()
8569 {
8570   if ( Is( DIFFICULT ))
8571     return;
8572
8573   bool moved = Is( SMOOTHED );
8574   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
8575     moved = _neibors[i]->Is( SMOOTHED );
8576   if ( !moved )
8577     return;
8578
8579   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8580
8581   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8582   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8583   _pos.back() = newPos;
8584
8585   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8586 }
8587
8588 //================================================================================
8589 /*!
8590  * \brief Checks validity of _neibors on EDGEs and VERTEXes
8591  */
8592 //================================================================================
8593
8594 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8595 {
8596   if ( ! Is( NEAR_BOUNDARY ))
8597     return 0;
8598
8599   int nbBad = 0;
8600   double vol;
8601   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8602   {
8603     _LayerEdge* eN = _neibors[iN];
8604     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8605       continue;
8606     if ( needSmooth )
8607       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8608                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8609                        eN->_pos.size() != _pos.size() );
8610
8611     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8612     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8613     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8614       if ( eN->_nodes.size() > 1 &&
8615            eN->_simplices[i].Includes( _nodes.back() ) &&
8616            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8617       {
8618         ++nbBad;
8619         if ( badNeibors )
8620         {
8621           badNeibors->push_back( eN );
8622           debugMsg("Bad boundary simplex ( "
8623                    << " "<< eN->_nodes[0]->GetID()
8624                    << " "<< eN->_nodes.back()->GetID()
8625                    << " "<< eN->_simplices[i]._nPrev->GetID()
8626                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8627         }
8628         else
8629         {
8630           break;
8631         }
8632       }
8633   }
8634   return nbBad;
8635 }
8636
8637 //================================================================================
8638 /*!
8639  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8640  *  \retval int - nb of bad simplices around this _LayerEdge
8641  */
8642 //================================================================================
8643
8644 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8645 {
8646   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8647     return 0; // shape of simplices not changed
8648   if ( _simplices.size() < 2 )
8649     return 0; // _LayerEdge inflated along EDGE or FACE
8650
8651   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8652     findBest = true;
8653
8654   const gp_XYZ& curPos  = _pos.back();
8655   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8656
8657   // quality metrics (orientation) of tetras around _tgtNode
8658   int nbOkBefore = 0;
8659   double vol, minVolBefore = 1e100;
8660   for ( size_t i = 0; i < _simplices.size(); ++i )
8661   {
8662     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8663     minVolBefore = Min( minVolBefore, vol );
8664   }
8665   int nbBad = _simplices.size() - nbOkBefore;
8666
8667   bool bndNeedSmooth = false;
8668   if ( nbBad == 0 )
8669     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8670   if ( nbBad > 0 )
8671     Set( DISTORTED );
8672
8673   // evaluate min angle
8674   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8675   {
8676     size_t nbGoodAngles = _simplices.size();
8677     double angle;
8678     for ( size_t i = 0; i < _simplices.size(); ++i )
8679     {
8680       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8681         --nbGoodAngles;
8682     }
8683     if ( nbGoodAngles == _simplices.size() )
8684     {
8685       Unset( MOVED );
8686       return 0;
8687     }
8688   }
8689   if ( Is( ON_CONCAVE_FACE ))
8690     findBest = true;
8691
8692   if ( step % 2 == 0 )
8693     findBest = false;
8694
8695   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8696   {
8697     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8698       _smooFunction = _funs[ FUN_CENTROIDAL ];
8699     else
8700       _smooFunction = _funs[ FUN_LAPLACIAN ];
8701   }
8702
8703   // compute new position for the last _pos using different _funs
8704   gp_XYZ newPos;
8705   bool moved = false;
8706   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8707   {
8708     if ( iFun < 0 )
8709       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8710     else if ( _funs[ iFun ] == _smooFunction )
8711       continue; // _smooFunction again
8712     else if ( step > 1 )
8713       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8714     else
8715       break; // let "easy" functions improve elements around distorted ones
8716
8717     if ( _curvature )
8718     {
8719       double delta  = _curvature->lenDelta( _len );
8720       if ( delta > 0 )
8721         newPos += _normal * delta;
8722       else
8723       {
8724         double segLen = _normal * ( newPos - prevPos );
8725         if ( segLen + delta > 0 )
8726           newPos += _normal * delta;
8727       }
8728       // double segLenChange = _normal * ( curPos - newPos );
8729       // newPos += 0.5 * _normal * segLenChange;
8730     }
8731
8732     int nbOkAfter = 0;
8733     double minVolAfter = 1e100;
8734     for ( size_t i = 0; i < _simplices.size(); ++i )
8735     {
8736       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8737       minVolAfter = Min( minVolAfter, vol );
8738     }
8739     // get worse?
8740     if ( nbOkAfter < nbOkBefore )
8741       continue;
8742
8743     if (( findBest ) &&
8744         ( nbOkAfter == nbOkBefore ) &&
8745         ( minVolAfter <= minVolBefore ))
8746       continue;
8747
8748     nbBad        = _simplices.size() - nbOkAfter;
8749     minVolBefore = minVolAfter;
8750     nbOkBefore   = nbOkAfter;
8751     moved        = true;
8752
8753     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8754     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8755     _pos.back() = newPos;
8756
8757     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8758                   << (nbBad ? " --BAD" : ""));
8759
8760     if ( iFun > -1 )
8761     {
8762       continue; // look for a better function
8763     }
8764
8765     if ( !findBest )
8766       break;
8767
8768   } // loop on smoothing functions
8769
8770   if ( moved ) // notify _neibors
8771   {
8772     Set( SMOOTHED );
8773     for ( size_t i = 0; i < _neibors.size(); ++i )
8774       if ( !_neibors[i]->Is( MOVED ))
8775       {
8776         _neibors[i]->Set( MOVED );
8777         toSmooth.push_back( _neibors[i] );
8778       }
8779   }
8780
8781   return nbBad;
8782 }
8783
8784 //================================================================================
8785 /*!
8786  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8787  *  \retval int - nb of bad simplices around this _LayerEdge
8788  */
8789 //================================================================================
8790
8791 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8792 {
8793   if ( !_smooFunction )
8794     return 0; // _LayerEdge inflated along EDGE or FACE
8795   if ( Is( BLOCKED ))
8796     return 0; // not inflated
8797
8798   const gp_XYZ& curPos  = _pos.back();
8799   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8800
8801   // quality metrics (orientation) of tetras around _tgtNode
8802   int nbOkBefore = 0;
8803   double vol, minVolBefore = 1e100;
8804   for ( size_t i = 0; i < _simplices.size(); ++i )
8805   {
8806     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8807     minVolBefore = Min( minVolBefore, vol );
8808   }
8809   int nbBad = _simplices.size() - nbOkBefore;
8810
8811   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8812   {
8813     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8814       _smooFunction = _funs[ FUN_LAPLACIAN ];
8815     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8816       _smooFunction = _funs[ FUN_CENTROIDAL ];
8817   }
8818
8819   // compute new position for the last _pos using different _funs
8820   gp_XYZ newPos;
8821   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8822   {
8823     if ( iFun < 0 )
8824       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8825     else if ( _funs[ iFun ] == _smooFunction )
8826       continue; // _smooFunction again
8827     else if ( step > 1 )
8828       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8829     else
8830       break; // let "easy" functions improve elements around distorted ones
8831
8832     if ( _curvature )
8833     {
8834       double delta  = _curvature->lenDelta( _len );
8835       if ( delta > 0 )
8836         newPos += _normal * delta;
8837       else
8838       {
8839         double segLen = _normal * ( newPos - prevPos );
8840         if ( segLen + delta > 0 )
8841           newPos += _normal * delta;
8842       }
8843       // double segLenChange = _normal * ( curPos - newPos );
8844       // newPos += 0.5 * _normal * segLenChange;
8845     }
8846
8847     int nbOkAfter = 0;
8848     double minVolAfter = 1e100;
8849     for ( size_t i = 0; i < _simplices.size(); ++i )
8850     {
8851       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8852       minVolAfter = Min( minVolAfter, vol );
8853     }
8854     // get worse?
8855     if ( nbOkAfter < nbOkBefore )
8856       continue;
8857     if (( isConcaveFace || findBest ) &&
8858         ( nbOkAfter == nbOkBefore ) &&
8859         ( minVolAfter <= minVolBefore )
8860         )
8861       continue;
8862
8863     nbBad        = _simplices.size() - nbOkAfter;
8864     minVolBefore = minVolAfter;
8865     nbOkBefore   = nbOkAfter;
8866
8867     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8868     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8869     _pos.back() = newPos;
8870
8871     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8872                   << ( nbBad ? "--BAD" : ""));
8873
8874     // commented for IPAL0052478
8875     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8876     // _len += prevPos.Distance(newPos);
8877
8878     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8879     {
8880       //_smooFunction = _funs[ iFun ];
8881       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8882       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8883       // << " minVol: " << minVolAfter
8884       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8885       // << endl;
8886       continue; // look for a better function
8887     }
8888
8889     if ( !findBest )
8890       break;
8891
8892   } // loop on smoothing functions
8893
8894   return nbBad;
8895 }
8896
8897 //================================================================================
8898 /*!
8899  * \brief Chooses a smoothing technique giving a position most close to an initial one.
8900  *        For a correct result, _simplices must contain nodes lying on geometry.
8901  */
8902 //================================================================================
8903
8904 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8905                                      const TNode2Edge&     n2eMap)
8906 {
8907   if ( _smooFunction ) return;
8908
8909   // use smoothNefPolygon() near concaveVertices
8910   if ( !concaveVertices.empty() )
8911   {
8912     _smooFunction = _funs[ FUN_CENTROIDAL ];
8913
8914     Set( ON_CONCAVE_FACE );
8915
8916     for ( size_t i = 0; i < _simplices.size(); ++i )
8917     {
8918       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8919       {
8920         _smooFunction = _funs[ FUN_NEFPOLY ];
8921
8922         // set FUN_CENTROIDAL to neighbor edges
8923         for ( i = 0; i < _neibors.size(); ++i )
8924         {
8925           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8926           {
8927             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8928           }
8929         }
8930         return;
8931       }
8932     }
8933
8934     // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8935     // // where the nodes are smoothed too far along a sphere thus creating
8936     // // inverted _simplices
8937     // double dist[theNbSmooFuns];
8938     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8939     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8940
8941     // double minDist = Precision::Infinite();
8942     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8943     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8944     // {
8945     //   gp_Pnt newP = (this->*_funs[i])();
8946     //   dist[i] = p.SquareDistance( newP );
8947     //   if ( dist[i]*coef[i] < minDist )
8948     //   {
8949     //     _smooFunction = _funs[i];
8950     //     minDist = dist[i]*coef[i];
8951     //   }
8952     // }
8953   }
8954   else
8955   {
8956     _smooFunction = _funs[ FUN_LAPLACIAN ];
8957   }
8958   // int minDim = 3;
8959   // for ( size_t i = 0; i < _simplices.size(); ++i )
8960   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8961   // if ( minDim == 0 )
8962   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8963   // else if ( minDim == 1 )
8964   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8965
8966
8967   // int iMin;
8968   // for ( int i = 0; i < FUN_NB; ++i )
8969   // {
8970   //   //cout << dist[i] << " ";
8971   //   if ( _smooFunction == _funs[i] ) {
8972   //     iMin = i;
8973   //     //debugMsg( fNames[i] );
8974   //     break;
8975   //   }
8976   // }
8977   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8978 }
8979
8980 //================================================================================
8981 /*!
8982  * \brief Returns a name of _SmooFunction
8983  */
8984 //================================================================================
8985
8986 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8987 {
8988   if ( !fun )
8989     fun = _smooFunction;
8990   for ( int i = 0; i < theNbSmooFuns; ++i )
8991     if ( fun == _funs[i] )
8992       return i;
8993
8994   return theNbSmooFuns;
8995 }
8996
8997 //================================================================================
8998 /*!
8999  * \brief Computes a new node position using Laplacian smoothing
9000  */
9001 //================================================================================
9002
9003 gp_XYZ _LayerEdge::smoothLaplacian()
9004 {
9005   gp_XYZ newPos (0,0,0);
9006   for ( size_t i = 0; i < _simplices.size(); ++i )
9007     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9008   newPos /= _simplices.size();
9009
9010   return newPos;
9011 }
9012
9013 //================================================================================
9014 /*!
9015  * \brief Computes a new node position using angular-based smoothing
9016  */
9017 //================================================================================
9018
9019 gp_XYZ _LayerEdge::smoothAngular()
9020 {
9021   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
9022   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
9023   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
9024
9025   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9026   gp_XYZ pN( 0,0,0 );
9027   for ( size_t i = 0; i < _simplices.size(); ++i )
9028   {
9029     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9030     edgeDir.push_back( p - pPrev );
9031     edgeSize.push_back( edgeDir.back().Magnitude() );
9032     if ( edgeSize.back() < numeric_limits<double>::min() )
9033     {
9034       edgeDir.pop_back();
9035       edgeSize.pop_back();
9036     }
9037     else
9038     {
9039       edgeDir.back() /= edgeSize.back();
9040       points.push_back( p );
9041       pN += p;
9042     }
9043     pPrev = p;
9044   }
9045   edgeDir.push_back ( edgeDir[0] );
9046   edgeSize.push_back( edgeSize[0] );
9047   pN /= points.size();
9048
9049   gp_XYZ newPos(0,0,0);
9050   double sumSize = 0;
9051   for ( size_t i = 0; i < points.size(); ++i )
9052   {
9053     gp_Vec toN    = pN - points[i];
9054     double toNLen = toN.Magnitude();
9055     if ( toNLen < numeric_limits<double>::min() )
9056     {
9057       newPos += pN;
9058       continue;
9059     }
9060     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
9061     double bisecLen = bisec.SquareMagnitude();
9062     if ( bisecLen < numeric_limits<double>::min() )
9063     {
9064       gp_Vec norm = edgeDir[i] ^ toN;
9065       bisec = norm ^ edgeDir[i];
9066       bisecLen = bisec.SquareMagnitude();
9067     }
9068     bisecLen = Sqrt( bisecLen );
9069     bisec /= bisecLen;
9070
9071 #if 1
9072     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
9073     sumSize += bisecLen;
9074 #else
9075     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
9076     sumSize += ( edgeSize[i] + edgeSize[i+1] );
9077 #endif
9078     newPos += pNew;
9079   }
9080   newPos /= sumSize;
9081
9082   // project newPos to an average plane
9083
9084   gp_XYZ norm(0,0,0); // plane normal
9085   points.push_back( points[0] );
9086   for ( size_t i = 1; i < points.size(); ++i )
9087   {
9088     gp_XYZ vec1 = points[ i-1 ] - pN;
9089     gp_XYZ vec2 = points[ i   ] - pN;
9090     gp_XYZ cross = vec1 ^ vec2;
9091     try {
9092       cross.Normalize();
9093       if ( cross * norm < numeric_limits<double>::min() )
9094         norm += cross.Reversed();
9095       else
9096         norm += cross;
9097     }
9098     catch (Standard_Failure) { // if |cross| == 0.
9099     }
9100   }
9101   gp_XYZ vec = newPos - pN;
9102   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
9103   newPos     = newPos - r * norm;
9104
9105   return newPos;
9106 }
9107
9108 //================================================================================
9109 /*!
9110  * \brief Computes a new node position using weighted node positions
9111  */
9112 //================================================================================
9113
9114 gp_XYZ _LayerEdge::smoothLengthWeighted()
9115 {
9116   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
9117   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
9118
9119   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9120   for ( size_t i = 0; i < _simplices.size(); ++i )
9121   {
9122     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9123     edgeSize.push_back( ( p - pPrev ).Modulus() );
9124     if ( edgeSize.back() < numeric_limits<double>::min() )
9125     {
9126       edgeSize.pop_back();
9127     }
9128     else
9129     {
9130       points.push_back( p );
9131     }
9132     pPrev = p;
9133   }
9134   edgeSize.push_back( edgeSize[0] );
9135
9136   gp_XYZ newPos(0,0,0);
9137   double sumSize = 0;
9138   for ( size_t i = 0; i < points.size(); ++i )
9139   {
9140     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
9141     sumSize += edgeSize[i] + edgeSize[i+1];
9142   }
9143   newPos /= sumSize;
9144   return newPos;
9145 }
9146
9147 //================================================================================
9148 /*!
9149  * \brief Computes a new node position using angular-based smoothing
9150  */
9151 //================================================================================
9152
9153 gp_XYZ _LayerEdge::smoothCentroidal()
9154 {
9155   gp_XYZ newPos(0,0,0);
9156   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9157   double sumSize = 0;
9158   for ( size_t i = 0; i < _simplices.size(); ++i )
9159   {
9160     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9161     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9162     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9163     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9164
9165     sumSize += size;
9166     newPos += gc * size;
9167   }
9168   newPos /= sumSize;
9169
9170   return newPos;
9171 }
9172
9173 //================================================================================
9174 /*!
9175  * \brief Computes a new node position located inside a Nef polygon
9176  */
9177 //================================================================================
9178
9179 gp_XYZ _LayerEdge::smoothNefPolygon()
9180 #ifdef OLD_NEF_POLYGON
9181 {
9182   gp_XYZ newPos(0,0,0);
9183
9184   // get a plane to search a solution on
9185
9186   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9187   size_t i;
9188   const double tol = numeric_limits<double>::min();
9189   gp_XYZ center(0,0,0);
9190   for ( i = 0; i < _simplices.size(); ++i )
9191   {
9192     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9193                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9194     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9195   }
9196   vecs.back() = vecs[0];
9197   center /= _simplices.size();
9198
9199   gp_XYZ zAxis(0,0,0);
9200   for ( i = 0; i < _simplices.size(); ++i )
9201     zAxis += vecs[i] ^ vecs[i+1];
9202
9203   gp_XYZ yAxis;
9204   for ( i = 0; i < _simplices.size(); ++i )
9205   {
9206     yAxis = vecs[i];
9207     if ( yAxis.SquareModulus() > tol )
9208       break;
9209   }
9210   gp_XYZ xAxis = yAxis ^ zAxis;
9211   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9212   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9213   //                             p0.Distance( _simplices[2]._nPrev ));
9214   // gp_XYZ center = smoothLaplacian();
9215   // gp_XYZ xAxis, yAxis, zAxis;
9216   // for ( i = 0; i < _simplices.size(); ++i )
9217   // {
9218   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9219   //   if ( xAxis.SquareModulus() > tol*tol )
9220   //     break;
9221   // }
9222   // for ( i = 1; i < _simplices.size(); ++i )
9223   // {
9224   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9225   //   zAxis = xAxis ^ yAxis;
9226   //   if ( zAxis.SquareModulus() > tol*tol )
9227   //     break;
9228   // }
9229   // if ( i == _simplices.size() ) return newPos;
9230
9231   yAxis = zAxis ^ xAxis;
9232   xAxis /= xAxis.Modulus();
9233   yAxis /= yAxis.Modulus();
9234
9235   // get half-planes of _simplices
9236
9237   vector< _halfPlane > halfPlns( _simplices.size() );
9238   int nbHP = 0;
9239   for ( size_t i = 0; i < _simplices.size(); ++i )
9240   {
9241     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9242     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9243     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9244     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9245     gp_XY  vec12 = p2 - p1;
9246     double dist12 = vec12.Modulus();
9247     if ( dist12 < tol )
9248       continue;
9249     vec12 /= dist12;
9250     halfPlns[ nbHP ]._pos = p1;
9251     halfPlns[ nbHP ]._dir = vec12;
9252     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9253     ++nbHP;
9254   }
9255
9256   // intersect boundaries of half-planes, define state of intersection points
9257   // in relation to all half-planes and calculate internal point of a 2D polygon
9258
9259   double sumLen = 0;
9260   gp_XY newPos2D (0,0);
9261
9262   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9263   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9264   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9265
9266   vector< vector< TIntPntState > > allIntPnts( nbHP );
9267   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9268   {
9269     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9270     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9271
9272     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9273     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9274
9275     int nbNotOut = 0;
9276     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9277
9278     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9279     {
9280       if ( iHP1 == iHP2 ) continue;
9281
9282       TIntPntState & ips1 = intPnts1[ iHP2 ];
9283       if ( ips1.second == UNDEF )
9284       {
9285         // find an intersection point of boundaries of iHP1 and iHP2
9286
9287         if ( iHP2 == iPrev ) // intersection with neighbors is known
9288           ips1.first = halfPlns[ iHP1 ]._pos;
9289         else if ( iHP2 == iNext )
9290           ips1.first = halfPlns[ iHP2 ]._pos;
9291         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9292           ips1.second = NO_INT;
9293
9294         // classify the found intersection point
9295         if ( ips1.second != NO_INT )
9296         {
9297           ips1.second = NOT_OUT;
9298           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9299             if ( i != iHP1 && i != iHP2 &&
9300                  halfPlns[ i ].IsOut( ips1.first, tol ))
9301               ips1.second = IS_OUT;
9302         }
9303         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9304         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9305         TIntPntState & ips2 = intPnts2[ iHP1 ];
9306         ips2 = ips1;
9307       }
9308       if ( ips1.second == NOT_OUT )
9309       {
9310         ++nbNotOut;
9311         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9312       }
9313     }
9314
9315     // find a NOT_OUT segment of boundary which is located between
9316     // two NOT_OUT int points
9317
9318     if ( nbNotOut < 2 )
9319       continue; // no such a segment
9320
9321     if ( nbNotOut > 2 )
9322     {
9323       // sort points along the boundary
9324       map< double, TIntPntState* > ipsByParam;
9325       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9326       {
9327         TIntPntState & ips1 = intPnts1[ iHP2 ];
9328         if ( ips1.second != NO_INT )
9329         {
9330           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9331           double param = op * halfPlns[ iHP1 ]._dir;
9332           ipsByParam.insert( make_pair( param, & ips1 ));
9333         }
9334       }
9335       // look for two neighboring NOT_OUT points
9336       nbNotOut = 0;
9337       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9338       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9339       {
9340         TIntPntState & ips1 = *(u2ips->second);
9341         if ( ips1.second == NOT_OUT )
9342           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9343         else if ( nbNotOut >= 2 )
9344           break;
9345         else
9346           nbNotOut = 0;
9347       }
9348     }
9349
9350     if ( nbNotOut >= 2 )
9351     {
9352       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9353       sumLen += len;
9354
9355       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9356     }
9357   }
9358
9359   if ( sumLen > 0 )
9360   {
9361     newPos2D /= sumLen;
9362     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9363   }
9364   else
9365   {
9366     newPos = center;
9367   }
9368
9369   return newPos;
9370 }
9371 #else // OLD_NEF_POLYGON
9372 { ////////////////////////////////// NEW
9373   gp_XYZ newPos(0,0,0);
9374
9375   // get a plane to search a solution on
9376
9377   size_t i;
9378   gp_XYZ center(0,0,0);
9379   for ( i = 0; i < _simplices.size(); ++i )
9380     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9381   center /= _simplices.size();
9382
9383   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9384   for ( i = 0; i < _simplices.size(); ++i )
9385     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9386   vecs.back() = vecs[0];
9387
9388   const double tol = numeric_limits<double>::min();
9389   gp_XYZ zAxis(0,0,0);
9390   for ( i = 0; i < _simplices.size(); ++i )
9391   {
9392     gp_XYZ cross = vecs[i] ^ vecs[i+1];
9393     try {
9394       cross.Normalize();
9395       if ( cross * zAxis < tol )
9396         zAxis += cross.Reversed();
9397       else
9398         zAxis += cross;
9399     }
9400     catch (Standard_Failure) { // if |cross| == 0.
9401     }
9402   }
9403
9404   gp_XYZ yAxis;
9405   for ( i = 0; i < _simplices.size(); ++i )
9406   {
9407     yAxis = vecs[i];
9408     if ( yAxis.SquareModulus() > tol )
9409       break;
9410   }
9411   gp_XYZ xAxis = yAxis ^ zAxis;
9412   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9413   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9414   //                             p0.Distance( _simplices[2]._nPrev ));
9415   // gp_XYZ center = smoothLaplacian();
9416   // gp_XYZ xAxis, yAxis, zAxis;
9417   // for ( i = 0; i < _simplices.size(); ++i )
9418   // {
9419   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9420   //   if ( xAxis.SquareModulus() > tol*tol )
9421   //     break;
9422   // }
9423   // for ( i = 1; i < _simplices.size(); ++i )
9424   // {
9425   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9426   //   zAxis = xAxis ^ yAxis;
9427   //   if ( zAxis.SquareModulus() > tol*tol )
9428   //     break;
9429   // }
9430   // if ( i == _simplices.size() ) return newPos;
9431
9432   yAxis = zAxis ^ xAxis;
9433   xAxis /= xAxis.Modulus();
9434   yAxis /= yAxis.Modulus();
9435
9436   // get half-planes of _simplices
9437
9438   vector< _halfPlane > halfPlns( _simplices.size() );
9439   int nbHP = 0;
9440   for ( size_t i = 0; i < _simplices.size(); ++i )
9441   {
9442     const gp_XYZ& OP1 = vecs[ i   ];
9443     const gp_XYZ& OP2 = vecs[ i+1 ];
9444     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9445     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9446     gp_XY  vec12 = p2 - p1;
9447     double dist12 = vec12.Modulus();
9448     if ( dist12 < tol )
9449       continue;
9450     vec12 /= dist12;
9451     halfPlns[ nbHP ]._pos = p1;
9452     halfPlns[ nbHP ]._dir = vec12;
9453     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9454     ++nbHP;
9455   }
9456
9457   // intersect boundaries of half-planes, define state of intersection points
9458   // in relation to all half-planes and calculate internal point of a 2D polygon
9459
9460   double sumLen = 0;
9461   gp_XY newPos2D (0,0);
9462
9463   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9464   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9465   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9466
9467   vector< vector< TIntPntState > > allIntPnts( nbHP );
9468   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9469   {
9470     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9471     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9472
9473     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9474     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9475
9476     int nbNotOut = 0;
9477     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9478
9479     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9480     {
9481       if ( iHP1 == iHP2 ) continue;
9482
9483       TIntPntState & ips1 = intPnts1[ iHP2 ];
9484       if ( ips1.second == UNDEF )
9485       {
9486         // find an intersection point of boundaries of iHP1 and iHP2
9487
9488         if ( iHP2 == iPrev ) // intersection with neighbors is known
9489           ips1.first = halfPlns[ iHP1 ]._pos;
9490         else if ( iHP2 == iNext )
9491           ips1.first = halfPlns[ iHP2 ]._pos;
9492         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9493           ips1.second = NO_INT;
9494
9495         // classify the found intersection point
9496         if ( ips1.second != NO_INT )
9497         {
9498           ips1.second = NOT_OUT;
9499           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9500             if ( i != iHP1 && i != iHP2 &&
9501                  halfPlns[ i ].IsOut( ips1.first, tol ))
9502               ips1.second = IS_OUT;
9503         }
9504         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9505         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9506         TIntPntState & ips2 = intPnts2[ iHP1 ];
9507         ips2 = ips1;
9508       }
9509       if ( ips1.second == NOT_OUT )
9510       {
9511         ++nbNotOut;
9512         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9513       }
9514     }
9515
9516     // find a NOT_OUT segment of boundary which is located between
9517     // two NOT_OUT int points
9518
9519     if ( nbNotOut < 2 )
9520       continue; // no such a segment
9521
9522     if ( nbNotOut > 2 )
9523     {
9524       // sort points along the boundary
9525       map< double, TIntPntState* > ipsByParam;
9526       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9527       {
9528         TIntPntState & ips1 = intPnts1[ iHP2 ];
9529         if ( ips1.second != NO_INT )
9530         {
9531           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9532           double param = op * halfPlns[ iHP1 ]._dir;
9533           ipsByParam.insert( make_pair( param, & ips1 ));
9534         }
9535       }
9536       // look for two neighboring NOT_OUT points
9537       nbNotOut = 0;
9538       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9539       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9540       {
9541         TIntPntState & ips1 = *(u2ips->second);
9542         if ( ips1.second == NOT_OUT )
9543           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9544         else if ( nbNotOut >= 2 )
9545           break;
9546         else
9547           nbNotOut = 0;
9548       }
9549     }
9550
9551     if ( nbNotOut >= 2 )
9552     {
9553       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9554       sumLen += len;
9555
9556       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9557     }
9558   }
9559
9560   if ( sumLen > 0 )
9561   {
9562     newPos2D /= sumLen;
9563     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9564   }
9565   else
9566   {
9567     newPos = center;
9568   }
9569
9570   return newPos;
9571 }
9572 #endif // OLD_NEF_POLYGON
9573
9574 //================================================================================
9575 /*!
9576  * \brief Add a new segment to _LayerEdge during inflation
9577  */
9578 //================================================================================
9579
9580 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9581 {
9582   if ( Is( BLOCKED ))
9583     return;
9584
9585   if ( len > _maxLen )
9586   {
9587     len = _maxLen;
9588     Block( eos.GetData() );
9589   }
9590   const double lenDelta = len - _len;
9591   if ( lenDelta < len * 1e-3  )
9592   {
9593     Block( eos.GetData() );
9594     return;
9595   }
9596
9597   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9598   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9599   gp_XYZ newXYZ;
9600   if ( eos._hyp.IsOffsetMethod() )
9601   {
9602     newXYZ = oldXYZ;
9603     gp_Vec faceNorm;
9604     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9605     while ( faceIt->more() )
9606     {
9607       const SMDS_MeshElement* face = faceIt->next();
9608       if ( !eos.GetNormal( face, faceNorm ))
9609         continue;
9610
9611       // translate plane of a face
9612       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9613
9614       // find point of intersection of the face plane located at baryCenter
9615       // and _normal located at newXYZ
9616       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9617       double dot =  ( faceNorm.XYZ() * _normal );
9618       if ( dot < std::numeric_limits<double>::min() )
9619         dot = lenDelta * 1e-3;
9620       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9621       newXYZ += step * _normal;
9622     }
9623     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9624   }
9625   else
9626   {
9627     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9628   }
9629
9630   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9631   _pos.push_back( newXYZ );
9632
9633   if ( !eos._sWOL.IsNull() )
9634   {
9635     double distXYZ[4];
9636     bool uvOK = false;
9637     if ( eos.SWOLType() == TopAbs_EDGE )
9638     {
9639       double u = Precision::Infinite(); // to force projection w/o distance check
9640       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9641                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9642       _pos.back().SetCoord( u, 0, 0 );
9643       if ( _nodes.size() > 1 && uvOK )
9644       {
9645         SMDS_EdgePositionPtr pos = n->GetPosition();
9646         pos->SetUParameter( u );
9647       }
9648     }
9649     else //  TopAbs_FACE
9650     {
9651       gp_XY uv( Precision::Infinite(), 0 );
9652       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9653                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9654       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9655       if ( _nodes.size() > 1 && uvOK )
9656       {
9657         SMDS_FacePositionPtr pos = n->GetPosition();
9658         pos->SetUParameter( uv.X() );
9659         pos->SetVParameter( uv.Y() );
9660       }
9661     }
9662     if ( uvOK )
9663     {
9664       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9665     }
9666     else
9667     {
9668       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9669       _pos.pop_back();
9670       Block( eos.GetData() );
9671       return;
9672     }
9673   }
9674
9675   _len = len;
9676
9677   // notify _neibors
9678   if ( eos.ShapeType() != TopAbs_FACE )
9679   {
9680     for ( size_t i = 0; i < _neibors.size(); ++i )
9681       //if (  _len > _neibors[i]->GetSmooLen() )
9682         _neibors[i]->Set( MOVED );
9683
9684     Set( MOVED );
9685   }
9686   dumpMove( n ); //debug
9687 }
9688
9689 //================================================================================
9690 /*!
9691  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9692  */
9693 //================================================================================
9694
9695 void _LayerEdge::Block( _SolidData& data )
9696 {
9697   //if ( Is( BLOCKED )) return;
9698   Set( BLOCKED );
9699
9700   SMESH_Comment msg( "#BLOCK shape=");
9701   msg << data.GetShapeEdges( this )->_shapeID
9702       << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9703   dumpCmd( msg + " -- BEGIN");
9704
9705   SetMaxLen( _len );
9706   std::queue<_LayerEdge*> queue;
9707   queue.push( this );
9708
9709   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9710   while ( !queue.empty() )
9711   {
9712     _LayerEdge* edge = queue.front(); queue.pop();
9713     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9714     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9715     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9716     {
9717       _LayerEdge* neibor = edge->_neibors[iN];
9718       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9719         continue;
9720       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9721       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9722       double minDist = pSrc.SquareDistance( pSrcN );
9723       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9724       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9725       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9726       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9727       //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9728       {
9729         //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9730         // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9731         //                   neibor->_lenFactor / edge->_lenFactor );
9732       }
9733       if ( neibor->_maxLen > newMaxLen )
9734       {
9735         neibor->SetMaxLen( newMaxLen );
9736         if ( neibor->_maxLen < neibor->_len )
9737         {
9738           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9739           int       lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
9740           while ( neibor->_len > neibor->_maxLen &&
9741                   neibor->NbSteps() > lastStep )
9742             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9743           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9744           //neibor->Block( data );
9745         }
9746         queue.push( neibor );
9747       }
9748     }
9749   }
9750   dumpCmd( msg + " -- END");
9751 }
9752
9753 //================================================================================
9754 /*!
9755  * \brief Remove last inflation step
9756  */
9757 //================================================================================
9758
9759 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9760 {
9761   if ( _pos.size() > curStep && _nodes.size() > 1 )
9762   {
9763     _pos.resize( curStep );
9764
9765     gp_Pnt      nXYZ = _pos.back();
9766     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9767     SMESH_TNodeXYZ curXYZ( n );
9768     if ( !eos._sWOL.IsNull() )
9769     {
9770       TopLoc_Location loc;
9771       if ( eos.SWOLType() == TopAbs_EDGE )
9772       {
9773         SMDS_EdgePositionPtr pos = n->GetPosition();
9774         pos->SetUParameter( nXYZ.X() );
9775         double f,l;
9776         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9777         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9778       }
9779       else
9780       {
9781         SMDS_FacePositionPtr pos = n->GetPosition();
9782         pos->SetUParameter( nXYZ.X() );
9783         pos->SetVParameter( nXYZ.Y() );
9784         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9785         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9786       }
9787     }
9788     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9789     dumpMove( n );
9790
9791     if ( restoreLength )
9792     {
9793       if ( NbSteps() == 0 )
9794         _len = 0.;
9795       else if ( IsOnFace() && Is( MOVED ))
9796         _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
9797       else
9798         _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9799     }
9800   }
9801   return;
9802 }
9803
9804 //================================================================================
9805 /*!
9806  * \brief Return index of a _pos distant from _normal
9807  */
9808 //================================================================================
9809
9810 int _LayerEdge::GetSmoothedPos( const double tol )
9811 {
9812   int iSmoothed = 0;
9813   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9814   {
9815     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9816     if ( normDist > tol * tol )
9817       iSmoothed = i;
9818   }
9819   return iSmoothed;
9820 }
9821
9822 //================================================================================
9823 /*!
9824  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9825  */
9826 //================================================================================
9827
9828 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9829 {
9830   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9831     return;
9832
9833   // find the 1st smoothed _pos
9834   int iSmoothed = GetSmoothedPos( tol );
9835   if ( !iSmoothed ) return;
9836
9837   gp_XYZ normal = _normal;
9838   if ( Is( NORMAL_UPDATED ))
9839   {
9840     double minDot = 1;
9841     for ( size_t i = 0; i < _neibors.size(); ++i )
9842     {
9843       if ( _neibors[i]->IsOnFace() )
9844       {
9845         double dot = _normal * _neibors[i]->_normal;
9846         if ( dot < minDot )
9847         {
9848           normal = _neibors[i]->_normal;
9849           minDot = dot;
9850         }
9851       }
9852     }
9853     if ( minDot == 1. )
9854       for ( size_t i = 1; i < _pos.size(); ++i )
9855       {
9856         normal = _pos[i] - _pos[0];
9857         double size = normal.Modulus();
9858         if ( size > RealSmall() )
9859         {
9860           normal /= size;
9861           break;
9862         }
9863       }
9864   }
9865   const double r = 0.2;
9866   for ( int iter = 0; iter < 50; ++iter )
9867   {
9868     double minDot = 1;
9869     for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9870     {
9871       gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9872       gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9873       _pos[i] = newPos;
9874       double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9875       double newLen = ( 1-r ) * midLen + r * segLen[i];
9876       const_cast< double& >( segLen[i] ) = newLen;
9877       // check angle between normal and (_pos[i+1], _pos[i] )
9878       gp_XYZ posDir = _pos[i+1] - _pos[i];
9879       double size   = posDir.SquareModulus();
9880       if ( size > RealSmall() )
9881         minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9882     }
9883     if ( minDot > 0.5 * 0.5 )
9884       break;
9885   }
9886   return;
9887 }
9888
9889 //================================================================================
9890 /*!
9891  * \brief Print flags
9892  */
9893 //================================================================================
9894
9895 std::string _LayerEdge::DumpFlags() const
9896 {
9897   SMESH_Comment dump;
9898   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9899     if ( _flags & flag )
9900     {
9901       EFlags f = (EFlags) flag;
9902       switch ( f ) {
9903       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
9904       case MOVED:           dump << "MOVED";           break;
9905       case SMOOTHED:        dump << "SMOOTHED";        break;
9906       case DIFFICULT:       dump << "DIFFICULT";       break;
9907       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9908       case BLOCKED:         dump << "BLOCKED";         break;
9909       case INTERSECTED:     dump << "INTERSECTED";     break;
9910       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
9911       case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9912       case MARKED:          dump << "MARKED";          break;
9913       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
9914       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
9915       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
9916       case DISTORTED:       dump << "DISTORTED";       break;
9917       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
9918       case SHRUNK:          dump << "SHRUNK";          break;
9919       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
9920       }
9921       dump << " ";
9922     }
9923   cout << dump << endl;
9924   return dump;
9925 }
9926
9927
9928 //================================================================================
9929 /*!
9930  * \brief Create layers of prisms
9931  */
9932 //================================================================================
9933
9934 bool _ViscousBuilder::refine(_SolidData& data)
9935 {
9936   SMESH_MesherHelper& helper = data.GetHelper();
9937   helper.SetElementsOnShape(false);
9938
9939   Handle(Geom_Curve) curve;
9940   Handle(ShapeAnalysis_Surface) surface;
9941   TopoDS_Edge geomEdge;
9942   TopoDS_Face geomFace;
9943   TopLoc_Location loc;
9944   double f,l, u = 0;
9945   gp_XY uv;
9946   vector< gp_XYZ > pos3D;
9947   bool isOnEdge, isTooConvexFace = false;
9948   TGeomID prevBaseId = -1;
9949   TNode2Edge* n2eMap = 0;
9950   TNode2Edge::iterator n2e;
9951
9952   // Create intermediate nodes on each _LayerEdge
9953
9954   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9955   {
9956     _EdgesOnShape& eos = data._edgesOnShape[iS];
9957     if ( eos._edges.empty() ) continue;
9958
9959     if ( eos._edges[0]->_nodes.size() < 2 )
9960       continue; // on _noShrinkShapes
9961
9962     // get data of a shrink shape
9963     isOnEdge = false;
9964     geomEdge.Nullify(); geomFace.Nullify();
9965     curve.Nullify(); surface.Nullify();
9966     if ( !eos._sWOL.IsNull() )
9967     {
9968       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9969       if ( isOnEdge )
9970       {
9971         geomEdge = TopoDS::Edge( eos._sWOL );
9972         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9973       }
9974       else
9975       {
9976         geomFace = TopoDS::Face( eos._sWOL );
9977         surface  = helper.GetSurface( geomFace );
9978       }
9979     }
9980     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9981     {
9982       geomFace = TopoDS::Face( eos._shape );
9983       surface  = helper.GetSurface( geomFace );
9984       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9985       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9986         eos._eosC1[ i ]->_toSmooth = true;
9987
9988       isTooConvexFace = false;
9989       if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
9990         isTooConvexFace = cf->_isTooCurved;
9991     }
9992
9993     vector< double > segLen;
9994     for ( size_t i = 0; i < eos._edges.size(); ++i )
9995     {
9996       _LayerEdge& edge = *eos._edges[i];
9997       if ( edge._pos.size() < 2 )
9998         continue;
9999
10000       // get accumulated length of segments
10001       segLen.resize( edge._pos.size() );
10002       segLen[0] = 0.0;
10003       if ( eos._sWOL.IsNull() )
10004       {
10005         bool useNormal = true;
10006         bool    usePos = false;
10007         bool  smoothed = false;
10008         double   preci = 0.1 * edge._len;
10009         if ( eos._toSmooth && edge._pos.size() > 2 )
10010         {
10011           smoothed = edge.GetSmoothedPos( preci );
10012         }
10013         if ( smoothed )
10014         {
10015           if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
10016           {
10017             useNormal = usePos = false;
10018             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
10019             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
10020             {
10021               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
10022               if ( surface->Gap() < 2. * edge._len )
10023                 segLen[j] = surface->Gap();
10024               else
10025                 useNormal = true;
10026             }
10027           }
10028         }
10029         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
10030         {
10031 #ifndef __NODES_AT_POS
10032           useNormal = usePos = false;
10033           edge._pos[1] = edge._pos.back();
10034           edge._pos.resize( 2 );
10035           segLen.resize( 2 );
10036           segLen[ 1 ] = edge._len;
10037 #endif
10038         }
10039         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
10040         {
10041           useNormal = usePos = false;
10042           _LayerEdge tmpEdge; // get original _normal
10043           tmpEdge._nodes.push_back( edge._nodes[0] );
10044           if ( !setEdgeData( tmpEdge, eos, helper, data ))
10045             usePos = true;
10046           else
10047             for ( size_t j = 1; j < edge._pos.size(); ++j )
10048               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
10049         }
10050         if ( useNormal )
10051         {
10052           for ( size_t j = 1; j < edge._pos.size(); ++j )
10053             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
10054         }
10055         if ( usePos )
10056         {
10057           for ( size_t j = 1; j < edge._pos.size(); ++j )
10058             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
10059         }
10060         else
10061         {
10062           bool swapped = ( edge._pos.size() > 2 );
10063           while ( swapped )
10064           {
10065             swapped = false;
10066             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
10067               if ( segLen[j] > segLen.back() )
10068               {
10069                 segLen.erase( segLen.begin() + j );
10070                 edge._pos.erase( edge._pos.begin() + j );
10071                 --j;
10072               }
10073               else if ( segLen[j] < segLen[j-1] )
10074               {
10075                 std::swap( segLen[j], segLen[j-1] );
10076                 std::swap( edge._pos[j], edge._pos[j-1] );
10077                 swapped = true;
10078               }
10079           }
10080         }
10081         // smooth a path formed by edge._pos
10082 #ifndef __NODES_AT_POS
10083         if (( smoothed ) /*&&
10084             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
10085           edge.SmoothPos( segLen, preci );
10086 #endif
10087       }
10088       else if ( eos._isRegularSWOL ) // usual SWOL
10089       {
10090         if ( edge.Is( _LayerEdge::SMOOTHED ))
10091         {
10092           SMESH_NodeXYZ p0( edge._nodes[0] );
10093           for ( size_t j = 1; j < edge._pos.size(); ++j )
10094           {
10095             gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10096             segLen[j] = ( pj - p0 ) * edge._normal;
10097           }
10098         }
10099         else
10100         {
10101           for ( size_t j = 1; j < edge._pos.size(); ++j )
10102             segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
10103         }
10104       }
10105       else if ( !surface.IsNull() ) // SWOL surface with singularities
10106       {
10107         pos3D.resize( edge._pos.size() );
10108         for ( size_t j = 0; j < edge._pos.size(); ++j )
10109           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10110
10111         for ( size_t j = 1; j < edge._pos.size(); ++j )
10112           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
10113       }
10114
10115       // allocate memory for new nodes if it is not yet refined
10116       const SMDS_MeshNode* tgtNode = edge._nodes.back();
10117       if ( edge._nodes.size() == 2 )
10118       {
10119 #ifdef __NODES_AT_POS
10120         int nbNodes = edge._pos.size();
10121 #else
10122         int nbNodes = eos._hyp.GetNumberLayers() + 1;
10123 #endif
10124         edge._nodes.resize( nbNodes, 0 );
10125         edge._nodes[1] = 0;
10126         edge._nodes.back() = tgtNode;
10127       }
10128       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
10129       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
10130       if ( baseShapeId != prevBaseId )
10131       {
10132         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
10133         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
10134         prevBaseId = baseShapeId;
10135       }
10136       _LayerEdge* edgeOnSameNode = 0;
10137       bool        useExistingPos = false;
10138       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
10139       {
10140         edgeOnSameNode = n2e->second;
10141         useExistingPos = ( edgeOnSameNode->_len < edge._len );
10142         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
10143         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
10144         if ( isOnEdge )
10145         {
10146           SMDS_EdgePositionPtr epos = lastPos;
10147           epos->SetUParameter( otherTgtPos.X() );
10148         }
10149         else
10150         {
10151           SMDS_FacePositionPtr fpos = lastPos;
10152           fpos->SetUParameter( otherTgtPos.X() );
10153           fpos->SetVParameter( otherTgtPos.Y() );
10154         }
10155       }
10156       // calculate height of the first layer
10157       double h0;
10158       const double T = segLen.back(); //data._hyp.GetTotalThickness();
10159       const double f = eos._hyp.GetStretchFactor();
10160       const int    N = eos._hyp.GetNumberLayers();
10161       const double fPowN = pow( f, N );
10162       if ( fPowN - 1 <= numeric_limits<double>::min() )
10163         h0 = T / N;
10164       else
10165         h0 = T * ( f - 1 )/( fPowN - 1 );
10166
10167       const double zeroLen = std::numeric_limits<double>::min();
10168
10169       // create intermediate nodes
10170       double hSum = 0, hi = h0/f;
10171       size_t iSeg = 1;
10172       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10173       {
10174         // compute an intermediate position
10175         hi *= f;
10176         hSum += hi;
10177         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10178           ++iSeg;
10179         int iPrevSeg = iSeg-1;
10180         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10181           --iPrevSeg;
10182         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10183         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10184 #ifdef __NODES_AT_POS
10185         pos = edge._pos[ iStep ];
10186 #endif
10187         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10188         if ( !eos._sWOL.IsNull() )
10189         {
10190           // compute XYZ by parameters <pos>
10191           if ( isOnEdge )
10192           {
10193             u = pos.X();
10194             if ( !node )
10195               pos = curve->Value( u ).Transformed(loc);
10196           }
10197           else if ( eos._isRegularSWOL )
10198           {
10199             uv.SetCoord( pos.X(), pos.Y() );
10200             if ( !node )
10201               pos = surface->Value( pos.X(), pos.Y() );
10202           }
10203           else
10204           {
10205             uv.SetCoord( pos.X(), pos.Y() );
10206             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10207             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10208             if ( !node )
10209               pos = surface->Value( uv );
10210           }
10211         }
10212         // create or update the node
10213         if ( !node )
10214         {
10215           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10216           if ( !eos._sWOL.IsNull() )
10217           {
10218             if ( isOnEdge )
10219               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10220             else
10221               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10222           }
10223           else
10224           {
10225             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10226           }
10227         }
10228         else
10229         {
10230           if ( !eos._sWOL.IsNull() )
10231           {
10232             // make average pos from new and current parameters
10233             if ( isOnEdge )
10234             {
10235               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10236               if ( useExistingPos )
10237                 u = helper.GetNodeU( geomEdge, node );
10238               pos = curve->Value( u ).Transformed(loc);
10239
10240               SMDS_EdgePositionPtr epos = node->GetPosition();
10241               epos->SetUParameter( u );
10242             }
10243             else
10244             {
10245               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10246               if ( useExistingPos )
10247                 uv = helper.GetNodeUV( geomFace, node );
10248               pos = surface->Value( uv );
10249
10250               SMDS_FacePositionPtr fpos = node->GetPosition();
10251               fpos->SetUParameter( uv.X() );
10252               fpos->SetVParameter( uv.Y() );
10253             }
10254           }
10255           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10256         }
10257       } // loop on edge._nodes
10258
10259       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10260       {
10261         if ( isOnEdge )
10262           edge._pos.back().SetCoord( u, 0,0);
10263         else
10264           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10265
10266         if ( edgeOnSameNode )
10267           edgeOnSameNode->_pos.back() = edge._pos.back();
10268       }
10269
10270     } // loop on eos._edges to create nodes
10271
10272
10273     if ( !getMeshDS()->IsEmbeddedMode() )
10274       // Log node movement
10275       for ( size_t i = 0; i < eos._edges.size(); ++i )
10276       {
10277         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10278         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10279       }
10280   }
10281
10282
10283   // Create volumes
10284
10285   helper.SetElementsOnShape(true);
10286
10287   vector< vector<const SMDS_MeshNode*>* > nnVec;
10288   set< vector<const SMDS_MeshNode*>* >    nnSet;
10289   set< int >                       degenEdgeInd;
10290   vector<const SMDS_MeshElement*>     degenVols;
10291
10292   TopExp_Explorer exp( data._solid, TopAbs_FACE );
10293   for ( ; exp.More(); exp.Next() )
10294   {
10295     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10296     if ( data._ignoreFaceIds.count( faceID ))
10297       continue;
10298     _EdgesOnShape*    eos = data.GetShapeEdges( faceID );
10299     SMDS_MeshGroup* group = StdMeshers_ViscousLayers::CreateGroup( eos->_hyp.GetGroupName(),
10300                                                                    *helper.GetMesh(),
10301                                                                    SMDSAbs_Volume );
10302     std::vector< const SMDS_MeshElement* > vols;
10303     const bool isReversedFace = data._reversedFaceIds.count( faceID );
10304     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
10305     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
10306     while ( fIt->more() )
10307     {
10308       const SMDS_MeshElement* face = fIt->next();
10309       const int            nbNodes = face->NbCornerNodes();
10310       nnVec.resize( nbNodes );
10311       nnSet.clear();
10312       degenEdgeInd.clear();
10313       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10314       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10315       for ( int iN = 0; iN < nbNodes; ++iN )
10316       {
10317         const SMDS_MeshNode* n = nIt->next();
10318         _LayerEdge*       edge = data._n2eMap[ n ];
10319         const int i = isReversedFace ? nbNodes-1-iN : iN;
10320         nnVec[ i ] = & edge->_nodes;
10321         maxZ = std::max( maxZ, nnVec[ i ]->size() );
10322         minZ = std::min( minZ, nnVec[ i ]->size() );
10323
10324         if ( helper.HasDegeneratedEdges() )
10325           nnSet.insert( nnVec[ i ]);
10326       }
10327
10328       if ( maxZ == 0 )
10329         continue;
10330       if ( 0 < nnSet.size() && nnSet.size() < 3 )
10331         continue;
10332
10333       vols.clear();
10334       const SMDS_MeshElement* vol;
10335
10336       switch ( nbNodes )
10337       {
10338       case 3: // TRIA
10339       {
10340         // PENTA
10341         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10342         {
10343           vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10344                                   (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
10345           vols.push_back( vol );
10346         }
10347
10348         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10349         {
10350           for ( int iN = 0; iN < nbNodes; ++iN )
10351             if ( nnVec[ iN ]->size() < iZ+1 )
10352               degenEdgeInd.insert( iN );
10353
10354           if ( degenEdgeInd.size() == 1 )  // PYRAM
10355           {
10356             int i2 = *degenEdgeInd.begin();
10357             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10358             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10359             vol = helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10360                                     (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
10361             vols.push_back( vol );
10362           }
10363           else  // TETRA
10364           {
10365             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10366             vol = helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10367                                     (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10368                                     (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10369                                     (*nnVec[ i3 ])[ iZ ]);
10370             vols.push_back( vol );
10371           }
10372         }
10373         break; // TRIA
10374       }
10375       case 4: // QUAD
10376       {
10377         // HEX
10378         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10379         {
10380           vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10381                                   (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10382                                   (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
10383                                   (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
10384           vols.push_back( vol );
10385         }
10386
10387         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10388         {
10389           for ( int iN = 0; iN < nbNodes; ++iN )
10390             if ( nnVec[ iN ]->size() < iZ+1 )
10391               degenEdgeInd.insert( iN );
10392
10393           switch ( degenEdgeInd.size() )
10394           {
10395           case 2: // PENTA
10396           {
10397             int i2 = *degenEdgeInd.begin();
10398             int i3 = *degenEdgeInd.rbegin();
10399             bool ok = ( i3 - i2 == 1 );
10400             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10401             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10402             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10403
10404             vol = helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10405                                     nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10406             vols.push_back( vol );
10407             if ( !ok && vol )
10408               degenVols.push_back( vol );
10409           }
10410           break;
10411
10412           default: // degen HEX
10413           {
10414             vol = helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10415                                     nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10416                                     nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10417                                     nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10418                                     nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
10419                                     nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
10420                                     nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
10421                                     nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
10422             vols.push_back( vol );
10423             degenVols.push_back( vol );
10424           }
10425           }
10426         }
10427         break; // HEX
10428       }
10429       default:
10430         return error("Not supported type of element", data._index);
10431
10432       } // switch ( nbNodes )
10433
10434       if ( group )
10435         for ( size_t i = 0; i < vols.size(); ++i )
10436           group->Add( vols[ i ]);
10437
10438     } // while ( fIt->more() )
10439   } // loop on FACEs
10440
10441   if ( !degenVols.empty() )
10442   {
10443     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10444     if ( !err || err->IsOK() )
10445     {
10446       SMESH_BadInputElements* badElems =
10447         new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10448       badElems->myBadElements.insert( badElems->myBadElements.end(),
10449                                       degenVols.begin(),degenVols.end() );
10450       err.reset( badElems );
10451     }
10452   }
10453
10454   return true;
10455 }
10456
10457 namespace VISCOUS_3D
10458 {
10459   struct ShrinkFace;
10460   //--------------------------------------------------------------------------------
10461   /*!
10462    * \brief Pair of periodic FACEs
10463    */
10464   struct PeriodicFaces
10465   {
10466     typedef StdMeshers_ProjectionUtils::TrsfFinder3D Trsf;
10467
10468     ShrinkFace*  _shriFace[2];
10469     TNodeNodeMap _nnMap;
10470     Trsf         _trsf;
10471
10472     PeriodicFaces( ShrinkFace* sf1, ShrinkFace* sf2 ): _shriFace{ sf1, sf2 } {}
10473     bool IncludeShrunk( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces ) const;
10474     bool MoveNodes( const TopoDS_Face& tgtFace );
10475     void Clear() { _nnMap.clear(); }
10476     bool IsEmpty() const { return _nnMap.empty(); }
10477   };
10478
10479   //--------------------------------------------------------------------------------
10480   /*!
10481    * \brief Shrink FACE data used to find periodic FACEs
10482    */
10483   struct ShrinkFace
10484   {
10485     // ................................................................................
10486     struct BndPart //!< part of FACE boundary, either shrink or no-shrink
10487     {
10488       bool                         _isShrink, _isReverse;
10489       int                          _nbSegments;
10490       AverageHyp*                  _hyp;
10491       std::vector< SMESH_NodeXYZ > _nodes;
10492       TopAbs_ShapeEnum             _vertSWOLType[2]; // shrink part includes VERTEXes
10493       AverageHyp*                  _vertHyp[2];
10494
10495       BndPart():
10496         _isShrink(0), _isReverse(0), _nbSegments(0), _hyp(0),
10497         _vertSWOLType{ TopAbs_WIRE, TopAbs_WIRE }, _vertHyp{ 0, 0 }
10498       {}
10499
10500       bool operator==( const BndPart& other ) const
10501       {
10502         return ( _isShrink       == other._isShrink &&
10503                  _nbSegments     == other._nbSegments &&
10504                  _nodes.size()   == other._nodes.size() &&
10505                  vertSWOLType1() == other.vertSWOLType1() &&
10506                  vertSWOLType2() == other.vertSWOLType2() &&
10507                  (( !_isShrink ) ||
10508                   ( *_hyp        == *other._hyp &&
10509                     vertHyp1()   == other.vertHyp1() &&
10510                     vertHyp2()   == other.vertHyp2() ))
10511                  );
10512       }
10513       bool CanAppend( const BndPart& other )
10514       {
10515         return ( _isShrink  == other._isShrink  &&
10516                  (( !_isShrink ) ||
10517                   ( *_hyp        == *other._hyp &&
10518                     *_hyp        == vertHyp2()  &&
10519                     vertHyp2()   == other.vertHyp1() ))
10520                  );
10521       }
10522       void Append( const BndPart& other )
10523       {
10524         _nbSegments += other._nbSegments;
10525         bool hasCommonNode = ( _nodes.back()->GetID() == other._nodes.front()->GetID() );
10526         _nodes.insert( _nodes.end(), other._nodes.begin() + hasCommonNode, other._nodes.end() );
10527         _vertSWOLType[1] = other._vertSWOLType[1];
10528         if ( _isShrink )
10529           _vertHyp[1] = other._vertHyp[1];
10530       }
10531       const SMDS_MeshNode*    Node(size_t i)  const
10532       {
10533         return _nodes[ _isReverse ? ( _nodes.size() - 1 - i ) : i ]._node;
10534       }
10535       void Reverse() { _isReverse = !_isReverse; }
10536       const TopAbs_ShapeEnum& vertSWOLType1() const { return _vertSWOLType[ _isReverse  ]; }
10537       const TopAbs_ShapeEnum& vertSWOLType2() const { return _vertSWOLType[ !_isReverse ]; }
10538       const AverageHyp&       vertHyp1()      const { return *(_vertHyp[ _isReverse  ]); }
10539       const AverageHyp&       vertHyp2()      const { return *(_vertHyp[ !_isReverse ]); }
10540     };
10541     // ................................................................................
10542
10543     SMESH_subMesh*       _subMesh;
10544     _SolidData*          _data1;
10545     _SolidData*          _data2;
10546     //bool                 _isPeriodic;
10547
10548     std::list< BndPart > _boundary;
10549     int                  _boundarySize, _nbBoundaryParts;
10550
10551     void Init( SMESH_subMesh* sm, _SolidData* sd1, _SolidData* sd2 )
10552     {
10553       _subMesh = sm; _data1 = sd1; _data2 = sd2; //_isPeriodic = false;
10554     }
10555     bool IsSame( const TopoDS_Face& face ) const
10556     {
10557       return _subMesh->GetSubShape().IsSame( face );
10558     }
10559     bool IsShrunk( const TopTools_MapOfShape& shrunkFaces ) const
10560     {
10561       return shrunkFaces.Contains( _subMesh->GetSubShape() );
10562     }
10563
10564     //================================================================================
10565     /*!
10566      * Check if meshes on two FACEs are equal
10567      */
10568     bool IsPeriodic( ShrinkFace& other, PeriodicFaces& periodic )
10569     {
10570       if ( !IsSameNbElements( other ))
10571         return false;
10572
10573       this->SetBoundary();
10574       other.SetBoundary();
10575       if ( this->_boundarySize    != other._boundarySize ||
10576            this->_nbBoundaryParts != other._nbBoundaryParts )
10577         return false;
10578
10579       for ( int isReverse = 0; isReverse < 2; ++isReverse )
10580       {
10581         if ( isReverse )
10582           Reverse( _boundary );
10583
10584         // check boundaries
10585         bool equalBoundary = false;
10586         for ( int iP = 0; iP < _nbBoundaryParts &&  !equalBoundary; ++iP )
10587         {
10588           if ( ! ( equalBoundary = ( this->_boundary == other._boundary )))
10589             // set first part at end
10590             _boundary.splice( _boundary.end(), _boundary, _boundary.begin() );
10591         }
10592         if ( !equalBoundary )
10593           continue;
10594
10595         // check connectivity
10596         std::set<const SMDS_MeshElement*> elemsThis, elemsOther;
10597         this->GetElements( elemsThis  );
10598         other.GetElements( elemsOther );
10599         SMESH_MeshEditor::Sew_Error err =
10600           SMESH_MeshEditor::FindMatchingNodes( elemsThis, elemsOther,
10601                                                this->_boundary.front().Node(0),
10602                                                other._boundary.front().Node(0),
10603                                                this->_boundary.front().Node(1),
10604                                                other._boundary.front().Node(1),
10605                                                periodic._nnMap );
10606         if ( err != SMESH_MeshEditor::SEW_OK )
10607           continue;
10608
10609         // check node positions
10610         std::vector< gp_XYZ > srcPnts, tgtPnts;
10611         this->GetBoundaryPoints( srcPnts );
10612         other.GetBoundaryPoints( tgtPnts );
10613         if ( !periodic._trsf.Solve( srcPnts, tgtPnts )) {
10614           continue;
10615         }
10616         double tol = std::numeric_limits<double>::max();
10617         for ( size_t i = 1; i < srcPnts.size(); ++i ) {
10618           tol = Min( tol, ( srcPnts[i-1] - srcPnts[i] ).SquareModulus() );
10619         }
10620         tol = 0.01 * Sqrt( tol );
10621         bool nodeCoincide = true;
10622         TNodeNodeMap::iterator n2n = periodic._nnMap.begin();
10623         for ( ; n2n != periodic._nnMap.end() &&  nodeCoincide; ++n2n )
10624         {
10625           SMESH_NodeXYZ nSrc = n2n->first;
10626           SMESH_NodeXYZ nTgt = n2n->second;
10627           gp_XYZ pTgt = periodic._trsf.Transform( nSrc );
10628           nodeCoincide = (( pTgt - nTgt ).SquareModulus() < tol );
10629         }
10630         if ( nodeCoincide )
10631           return true;
10632       }
10633       return false;
10634     }
10635
10636     bool IsSameNbElements( ShrinkFace& other ) // check number of mesh faces
10637     {
10638       SMESHDS_SubMesh* sm1 = this->_subMesh->GetSubMeshDS();
10639       SMESHDS_SubMesh* sm2 = other._subMesh->GetSubMeshDS();
10640       return ( sm1->NbElements() == sm2->NbElements() &&
10641                sm1->NbNodes()    == sm2->NbNodes() );
10642     }
10643
10644     void Reverse( std::list< BndPart >& boundary )
10645     {
10646       boundary.reverse();
10647       for ( std::list< BndPart >::iterator part = boundary.begin(); part != boundary.end(); ++part )
10648         part->Reverse();
10649     }
10650
10651     void SetBoundary()
10652     {
10653       if ( !_boundary.empty() )
10654         return;
10655
10656       TopoDS_Face F = TopoDS::Face( _subMesh->GetSubShape() );
10657       if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
10658       std::list< TopoDS_Edge > edges;
10659       std::list< int > nbEdgesInWire;
10660       /*int nbWires =*/ SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
10661
10662       // std::list< TopoDS_Edge >::iterator edgesEnd = edges.end();
10663       // if ( nbWires > 1 ) {
10664       //   edgesEnd = edges.begin();
10665       //   std::advance( edgesEnd, nbEdgesInWire.front() );
10666       // }
10667       StdMeshers_FaceSide fSide( F, edges, _subMesh->GetFather(),
10668                                  /*fwd=*/true, /*skipMedium=*/true );
10669       _boundarySize = fSide.NbSegments();
10670
10671       //TopoDS_Vertex vv[2];
10672       //std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
10673       for ( int iE = 0; iE < nbEdgesInWire.front(); ++iE )
10674       {
10675         BndPart bndPart;
10676         _EdgesOnShape*  eos = _data1->GetShapeEdges( fSide.EdgeID( iE ));
10677
10678         bndPart._isShrink = ( eos->SWOLType() == TopAbs_FACE );
10679         if ( bndPart._isShrink )
10680           if ((           _data1->_noShrinkShapes.count( eos->_shapeID )) ||
10681               ( _data2 && _data2->_noShrinkShapes.count( eos->_shapeID )))
10682             bndPart._isShrink = false;
10683
10684         if ( bndPart._isShrink )
10685         {
10686           bndPart._hyp = & eos->_hyp;
10687           _EdgesOnShape* eov[2] = { _data1->GetShapeEdges( fSide.FirstVertex( iE )),
10688                                     _data1->GetShapeEdges( fSide.LastVertex ( iE )) };
10689           for ( int iV = 0; iV < 2; ++iV )
10690           {
10691             bndPart._vertHyp     [iV] = & eov[iV]->_hyp;
10692             bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
10693             if ( _data1->_noShrinkShapes.count( eov[iV]->_shapeID ))
10694               bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
10695             if ( _data2 && bndPart._vertSWOLType[iV] != TopAbs_SHAPE )
10696             {
10697               eov[iV] = _data2->GetShapeEdges( iV ? fSide.LastVertex(iE) : fSide.FirstVertex(iE ));
10698               if ( _data2->_noShrinkShapes.count( eov[iV]->_shapeID ))
10699                 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
10700               else if ( eov[iV]->SWOLType() > bndPart._vertSWOLType[iV] )
10701                 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
10702             }
10703           }
10704         }
10705         std::vector<const SMDS_MeshNode*> nodes = fSide.GetOrderedNodes( iE );
10706         bndPart._nodes.assign( nodes.begin(), nodes.end() );
10707         bndPart._nbSegments = bndPart._nodes.size() - 1;
10708
10709         if ( _boundary.empty() || ! _boundary.back().CanAppend( bndPart ))
10710           _boundary.push_back( bndPart );
10711         else
10712           _boundary.back().Append( bndPart );
10713       }
10714
10715       _nbBoundaryParts = _boundary.size();
10716       if ( _nbBoundaryParts > 1 && _boundary.front()._isShrink == _boundary.back()._isShrink )
10717       {
10718         _boundary.back().Append( _boundary.front() );
10719         _boundary.pop_front();
10720         --_nbBoundaryParts;
10721       }
10722     }
10723
10724     void GetElements( std::set<const SMDS_MeshElement*>& theElems)
10725     {
10726       if ( SMESHDS_SubMesh* sm = _subMesh->GetSubMeshDS() )
10727         for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
10728           theElems.insert( theElems.end(), fIt->next() );
10729
10730       return ;
10731     }
10732
10733     void GetBoundaryPoints( std::vector< gp_XYZ >& points )
10734     {
10735       points.reserve( _boundarySize );
10736       size_t  nb = _boundary.rbegin()->_nodes.size();
10737       int lastID = _boundary.rbegin()->Node( nb - 1 )->GetID();
10738       std::list< BndPart >::const_iterator part = _boundary.begin();
10739       for ( ; part != _boundary.end(); ++part )
10740       {
10741         size_t nb = part->_nodes.size();
10742         size_t iF = 0;
10743         size_t iR = nb - 1;
10744         size_t* i = part->_isReverse ? &iR : &iF;
10745         if ( part->_nodes[ *i ]->GetID() == lastID )
10746           ++iF, --iR;
10747         for ( ; iF < nb; ++iF, --iR )
10748           points.push_back( part->_nodes[ *i ]);
10749         --iF, ++iR;
10750         lastID = part->_nodes[ *i ]->GetID();
10751       }
10752     }
10753   }; // struct ShrinkFace
10754
10755   //--------------------------------------------------------------------------------
10756   /*!
10757    * \brief Periodic FACEs
10758    */
10759   struct Periodicity
10760   {
10761     std::vector< ShrinkFace >    _shrinkFaces;
10762     std::vector< PeriodicFaces > _periodicFaces;
10763
10764     PeriodicFaces* GetPeriodic( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces )
10765     {
10766       for ( size_t i = 0; i < _periodicFaces.size(); ++i )
10767         if ( _periodicFaces[ i ].IncludeShrunk( face, shrunkFaces ))
10768           return & _periodicFaces[ i ];
10769       return 0;
10770     }
10771     void ClearPeriodic( const TopoDS_Face& face )
10772     {
10773       for ( size_t i = 0; i < _periodicFaces.size(); ++i )
10774         if ( _periodicFaces[ i ]._shriFace[0]->IsSame( face ) ||
10775              _periodicFaces[ i ]._shriFace[1]->IsSame( face ))
10776           _periodicFaces[ i ].Clear();
10777     }
10778   };
10779
10780   //================================================================================
10781   /*!
10782    * Check if a pair includes the given FACE and the other FACE is already shrunk
10783    */
10784   bool PeriodicFaces::IncludeShrunk( const TopoDS_Face&         face,
10785                                      const TopTools_MapOfShape& shrunkFaces ) const
10786   {
10787     if ( IsEmpty() ) return false;
10788     return (( _shriFace[0]->IsSame( face ) && _shriFace[1]->IsShrunk( shrunkFaces )) ||
10789             ( _shriFace[1]->IsSame( face ) && _shriFace[0]->IsShrunk( shrunkFaces )));
10790   }
10791
10792   //================================================================================
10793   /*!
10794    * Make equal meshes on periodic faces by moving corresponding nodes
10795    */
10796   bool PeriodicFaces::MoveNodes( const TopoDS_Face& tgtFace )
10797   {
10798     int iTgt = _shriFace[1]->IsSame( tgtFace );
10799     int iSrc = 1 - iTgt;
10800
10801     _SolidData* dataSrc = _shriFace[iSrc]->_data1;
10802     _SolidData* dataTgt = _shriFace[iTgt]->_data1;
10803
10804     Trsf * trsf = & _trsf, trsfInverse;
10805     if ( iSrc != 0 )
10806     {
10807       trsfInverse = _trsf;
10808       if ( !trsfInverse.Invert())
10809         return false;
10810       trsf = &trsfInverse;
10811     }
10812     SMESHDS_Mesh* meshDS = dataSrc->GetHelper().GetMeshDS();
10813
10814     TNode2Edge::iterator n2e;
10815     TNodeNodeMap::iterator n2n = _nnMap.begin();
10816     for ( ; n2n != _nnMap.end(); ++n2n )
10817     {
10818       const SMDS_MeshNode* const* nn = & n2n->first;
10819       const SMDS_MeshNode*      nSrc = nn[ iSrc ];
10820       const SMDS_MeshNode*      nTgt = nn[ iTgt ];
10821
10822       if (( nSrc->GetPosition()->GetDim() == 2 ) ||
10823           (( n2e = dataSrc->_n2eMap.find( nSrc )) == dataSrc->_n2eMap.end() ))
10824       {
10825         SMESH_NodeXYZ pSrc = nSrc;
10826         gp_XYZ pTgt = trsf->Transform( pSrc );
10827         meshDS->MoveNode( nTgt, pTgt.X(), pTgt.Y(), pTgt.Z() );
10828       }
10829       else
10830       {
10831         _LayerEdge* leSrc = n2e->second;
10832         n2e = dataTgt->_n2eMap.find( nTgt );
10833         if ( n2e == dataTgt->_n2eMap.end() )
10834           break;
10835         _LayerEdge* leTgt = n2e->second;
10836         if ( leSrc->_nodes.size() != leTgt->_nodes.size() )
10837           break;
10838         for ( size_t iN = 1; iN < leSrc->_nodes.size(); ++iN )
10839         {
10840           SMESH_NodeXYZ pSrc = leSrc->_nodes[ iN ];
10841           gp_XYZ pTgt = trsf->Transform( pSrc );
10842           meshDS->MoveNode( leTgt->_nodes[ iN ], pTgt.X(), pTgt.Y(), pTgt.Z() );
10843         }
10844       }
10845     }
10846     bool done = ( n2n == _nnMap.end() );
10847     debugMsg( "PeriodicFaces::MoveNodes "
10848               << _shriFace[iSrc]->_subMesh->GetId() << " -> "
10849               << _shriFace[iTgt]->_subMesh->GetId() << " -- "
10850               << ( done ? "DONE" : "FAIL"));
10851
10852     return done;
10853   }
10854 } // namespace VISCOUS_3D; Periodicity part
10855
10856
10857 //================================================================================
10858 /*!
10859  * \brief Find FACEs to shrink, that are equally meshed before shrink (i.e. periodic)
10860  *        and should remain equal after shrink
10861  */
10862 //================================================================================
10863
10864 void _ViscousBuilder::findPeriodicFaces()
10865 {
10866   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10867   // _LayerEdge's inflated along FACE or EDGE)
10868   std::map< TGeomID, std::list< _SolidData* > > id2sdMap;
10869   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10870   {
10871     _SolidData& data = _sdVec[i];
10872     std::map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10873     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10874       if ( s2s->second.ShapeType() == TopAbs_FACE )
10875         id2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10876   }
10877
10878   _periodicity.reset( new Periodicity );
10879   _periodicity->_shrinkFaces.resize( id2sdMap.size() );
10880
10881   std::map< TGeomID, std::list< _SolidData* > >::iterator id2sdIt = id2sdMap.begin();
10882   for ( size_t i = 0; i < id2sdMap.size(); ++i, ++id2sdIt )
10883   {
10884     _SolidData* sd1 = id2sdIt->second.front();
10885     _SolidData* sd2 = id2sdIt->second.back();
10886     _periodicity->_shrinkFaces[ i ].Init( _mesh->GetSubMeshContaining( id2sdIt->first ), sd1, sd2 );
10887   }
10888
10889   for (   size_t i1 = 0;      i1 < _periodicity->_shrinkFaces.size(); ++i1 )
10890     for ( size_t i2 = i1 + 1; i2 < _periodicity->_shrinkFaces.size(); ++i2 )
10891     {
10892       PeriodicFaces pf( & _periodicity->_shrinkFaces[ i1 ],
10893                         & _periodicity->_shrinkFaces[ i2 ]);
10894       if ( pf._shriFace[0]->IsPeriodic( *pf._shriFace[1], pf ))
10895       {
10896         _periodicity->_periodicFaces.push_back( pf );
10897       }
10898     }
10899   return;
10900 }
10901
10902 //================================================================================
10903 /*!
10904  * \brief Shrink 2D mesh on faces to let space for inflated layers
10905  */
10906 //================================================================================
10907
10908 bool _ViscousBuilder::shrink(_SolidData& theData)
10909 {
10910   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10911   // _LayerEdge's inflated along FACE or EDGE)
10912   map< TGeomID, list< _SolidData* > > f2sdMap;
10913   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10914   {
10915     _SolidData& data = _sdVec[i];
10916     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10917     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10918       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrunkFaces.Contains( s2s->second ))
10919       {
10920         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10921
10922         // Put mesh faces on the shrunk FACE to the proxy sub-mesh to avoid
10923         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10924         // by StdMeshers_QuadToTriaAdaptor
10925         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10926         {
10927           SMESH_ProxyMesh::SubMesh* proxySub =
10928             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10929           if ( proxySub->NbElements() == 0 )
10930           {
10931             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10932             while ( fIt->more() )
10933             {
10934               const SMDS_MeshElement* f = fIt->next();
10935               // as a result 3D algo will use elements from proxySub and not from smDS
10936               proxySub->AddElement( f );
10937               f->setIsMarked( true );
10938
10939               // Mark nodes on the FACE to discriminate them from nodes
10940               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10941               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10942               {
10943                 const SMDS_MeshNode* n = f->GetNode( iN );
10944                 if ( n->GetPosition()->GetDim() == 2 )
10945                   n->setIsMarked( true );
10946               }
10947             }
10948           }
10949         }
10950       }
10951   }
10952
10953   SMESH_MesherHelper helper( *_mesh );
10954   helper.ToFixNodeParameters( true );
10955
10956   // EDGEs to shrink
10957   map< TGeomID, _Shrinker1D > e2shrMap;
10958   vector< _EdgesOnShape* > subEOS;
10959   vector< _LayerEdge* > lEdges;
10960
10961   // loop on FACEs to shrink mesh on
10962   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10963   for ( ; f2sd != f2sdMap.end(); ++f2sd )
10964   {
10965     list< _SolidData* > & dataList = f2sd->second;
10966     if ( dataList.front()->_n2eMap.empty() ||
10967          dataList.back() ->_n2eMap.empty() )
10968       continue; // not yet computed
10969     if ( dataList.front() != &theData &&
10970          dataList.back()  != &theData )
10971       continue;
10972
10973     _SolidData&      data = *dataList.front();
10974     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
10975     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10976     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
10977     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10978
10979     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10980
10981     _shrunkFaces.Add( F );
10982     helper.SetSubShape( F );
10983
10984     // ==============================
10985     // Use periodicity to move nodes
10986     // ==============================
10987
10988     PeriodicFaces* periodic = _periodicity->GetPeriodic( F, _shrunkFaces );
10989     bool movedByPeriod = ( periodic && periodic->MoveNodes( F ));
10990
10991     // ===========================
10992     // Prepare data for shrinking
10993     // ===========================
10994
10995     // Collect nodes to smooth (they are marked at the beginning of this method)
10996     vector < const SMDS_MeshNode* > smoothNodes;
10997
10998     if ( !movedByPeriod )
10999     {
11000       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
11001       while ( nIt->more() )
11002       {
11003         const SMDS_MeshNode* n = nIt->next();
11004         if ( n->isMarked() )
11005           smoothNodes.push_back( n );
11006       }
11007     }
11008     // Find out face orientation
11009     double refSign = 1;
11010     const set<TGeomID> ignoreShapes;
11011     bool isOkUV;
11012     if ( !smoothNodes.empty() )
11013     {
11014       vector<_Simplex> simplices;
11015       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
11016       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
11017       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
11018       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
11019       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
11020         refSign = -1;
11021     }
11022
11023     // Find _LayerEdge's inflated along F
11024     subEOS.clear();
11025     lEdges.clear();
11026     {
11027       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
11028                                                                 /*complexFirst=*/true); //!!!
11029       while ( subIt->more() )
11030       {
11031         const TGeomID subID = subIt->next()->GetId();
11032         if ( data._noShrinkShapes.count( subID ))
11033           continue;
11034         _EdgesOnShape* eos = data.GetShapeEdges( subID );
11035         if ( !eos || eos->_sWOL.IsNull() )
11036           if ( data2 ) // check in adjacent SOLID
11037           {
11038             eos = data2->GetShapeEdges( subID );
11039             if ( !eos || eos->_sWOL.IsNull() )
11040               continue;
11041           }
11042         subEOS.push_back( eos );
11043
11044         if ( !movedByPeriod )
11045           for ( size_t i = 0; i < eos->_edges.size(); ++i )
11046           {
11047             lEdges.push_back( eos->_edges[ i ] );
11048             prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
11049           }
11050       }
11051     }
11052
11053     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
11054     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11055     while ( fIt->more() )
11056       if ( const SMDS_MeshElement* f = fIt->next() )
11057         dumpChangeNodes( f );
11058     dumpFunctionEnd();
11059
11060     // Replace source nodes by target nodes in mesh faces to shrink
11061     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
11062     const SMDS_MeshNode* nodes[20];
11063     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11064     {
11065       _EdgesOnShape& eos = * subEOS[ iS ];
11066       for ( size_t i = 0; i < eos._edges.size(); ++i )
11067       {
11068         _LayerEdge& edge = *eos._edges[i];
11069         const SMDS_MeshNode* srcNode = edge._nodes[0];
11070         const SMDS_MeshNode* tgtNode = edge._nodes.back();
11071         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
11072         while ( fIt->more() )
11073         {
11074           const SMDS_MeshElement* f = fIt->next();
11075           if ( !smDS->Contains( f ) || !f->isMarked() )
11076             continue;
11077           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
11078           for ( int iN = 0; nIt->more(); ++iN )
11079           {
11080             const SMDS_MeshNode* n = nIt->next();
11081             nodes[iN] = ( n == srcNode ? tgtNode : n );
11082           }
11083           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
11084           dumpChangeNodes( f );
11085         }
11086       }
11087     }
11088     dumpFunctionEnd();
11089
11090     // find out if a FACE is concave
11091     const bool isConcaveFace = isConcave( F, helper );
11092
11093     // Create _SmoothNode's on face F
11094     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
11095     {
11096       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
11097       const bool sortSimplices = isConcaveFace;
11098       for ( size_t i = 0; i < smoothNodes.size(); ++i )
11099       {
11100         const SMDS_MeshNode* n = smoothNodes[i];
11101         nodesToSmooth[ i ]._node = n;
11102         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
11103         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
11104         // fix up incorrect uv of nodes on the FACE
11105         helper.GetNodeUV( F, n, 0, &isOkUV);
11106         dumpMove( n );
11107       }
11108       dumpFunctionEnd();
11109     }
11110     //if ( nodesToSmooth.empty() ) continue;
11111
11112     // Find EDGE's to shrink and set simpices to LayerEdge's
11113     set< _Shrinker1D* > eShri1D;
11114     {
11115       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11116       {
11117         _EdgesOnShape& eos = * subEOS[ iS ];
11118         if ( eos.SWOLType() == TopAbs_EDGE )
11119         {
11120           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
11121           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
11122           if ( !movedByPeriod )
11123           {
11124             _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
11125             eShri1D.insert( & shrinker );
11126             shrinker.AddEdge( eos._edges[0], eos, helper );
11127             // restore params of nodes on EDGE if the EDGE has been already
11128             // shrunk while shrinking other FACE
11129             shrinker.RestoreParams();
11130           }
11131         }
11132         for ( size_t i = 0; i < eos._edges.size(); ++i )
11133         {
11134           _LayerEdge& edge = * eos._edges[i];
11135           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
11136
11137           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
11138           // not-marked nodes are those added by refine()
11139           edge._nodes.back()->setIsMarked( true );
11140         }
11141       }
11142     }
11143
11144     bool toFixTria = false; // to improve quality of trias by diagonal swap
11145     if ( isConcaveFace && !movedByPeriod )
11146     {
11147       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
11148       if ( hasTria != hasQuad ) {
11149         toFixTria = hasTria;
11150       }
11151       else {
11152         set<int> nbNodesSet;
11153         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11154         while ( fIt->more() && nbNodesSet.size() < 2 )
11155           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
11156         toFixTria = ( *nbNodesSet.begin() == 3 );
11157       }
11158     }
11159
11160     // ==================
11161     // Perform shrinking
11162     // ==================
11163
11164     bool shrunk = !movedByPeriod;
11165     int nbBad, shriStep=0, smooStep=0;
11166     _SmoothNode::SmoothType smoothType
11167       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
11168     SMESH_Comment errMsg;
11169     while ( shrunk )
11170     {
11171       shriStep++;
11172       // Move boundary nodes (actually just set new UV)
11173       // -----------------------------------------------
11174       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
11175       shrunk = false;
11176       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11177       {
11178         _EdgesOnShape& eos = * subEOS[ iS ];
11179         for ( size_t i = 0; i < eos._edges.size(); ++i )
11180         {
11181           shrunk |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
11182         }
11183       }
11184       dumpFunctionEnd();
11185
11186       // Move nodes on EDGE's
11187       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
11188       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
11189       for ( ; shr != eShri1D.end(); ++shr )
11190         (*shr)->Compute( /*set3D=*/false, helper );
11191
11192       // Smoothing in 2D
11193       // -----------------
11194       int nbNoImpSteps = 0;
11195       bool       moved = true;
11196       nbBad = 1;
11197       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
11198       {
11199         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11200
11201         int oldBadNb = nbBad;
11202         nbBad = 0;
11203         moved = false;
11204         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
11205         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
11206         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11207         {
11208           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
11209                                             smooTy, /*set3D=*/isConcaveFace);
11210         }
11211         if ( nbBad < oldBadNb )
11212           nbNoImpSteps = 0;
11213         else
11214           nbNoImpSteps++;
11215
11216         dumpFunctionEnd();
11217       }
11218
11219       errMsg.clear();
11220       if ( nbBad > 0 )
11221         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
11222       if ( shriStep > 200 )
11223         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
11224       if ( !errMsg.empty() )
11225         break;
11226
11227       // Fix narrow triangles by swapping diagonals
11228       // ---------------------------------------
11229       if ( toFixTria )
11230       {
11231         set<const SMDS_MeshNode*> usedNodes;
11232         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
11233
11234         // update working data
11235         set<const SMDS_MeshNode*>::iterator n;
11236         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
11237         {
11238           n = usedNodes.find( nodesToSmooth[ i ]._node );
11239           if ( n != usedNodes.end())
11240           {
11241             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
11242                                     nodesToSmooth[ i ]._simplices,
11243                                     ignoreShapes, NULL,
11244                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
11245             usedNodes.erase( n );
11246           }
11247         }
11248         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
11249         {
11250           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
11251           if ( n != usedNodes.end())
11252           {
11253             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
11254                                     lEdges[i]->_simplices,
11255                                     ignoreShapes );
11256             usedNodes.erase( n );
11257           }
11258         }
11259       }
11260       // TODO: check effect of this additional smooth
11261       // additional laplacian smooth to increase allowed shrink step
11262       // for ( int st = 1; st; --st )
11263       // {
11264       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11265       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11266       //   {
11267       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11268       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
11269       //   }
11270       // }
11271
11272     } // while ( shrunk )
11273
11274     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
11275     {
11276       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
11277
11278       // remove faces
11279       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
11280       {
11281         vector< const SMDS_MeshElement* > facesToRm;
11282         if ( psm )
11283         {
11284           facesToRm.reserve( psm->NbElements() );
11285           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
11286             facesToRm.push_back( ite->next() );
11287
11288           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11289             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11290               psm->Clear();
11291         }
11292         for ( size_t i = 0; i < facesToRm.size(); ++i )
11293           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
11294       }
11295       // remove nodes
11296       {
11297         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
11298         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
11299           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11300             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
11301                                 subEOS[iS]->_edges[i]->_nodes.end() );
11302         }
11303         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
11304         while ( itn->more() ) {
11305           const SMDS_MeshNode* n = itn->next();
11306           if ( !nodesToKeep.count( n ))
11307             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
11308         }
11309       }
11310       _periodicity->ClearPeriodic( F );
11311
11312       // restore position and UV of target nodes
11313       gp_Pnt p;
11314       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11315         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11316         {
11317           _LayerEdge*       edge = subEOS[iS]->_edges[i];
11318           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
11319           if ( edge->_pos.empty() ||
11320                edge->Is( _LayerEdge::SHRUNK )) continue;
11321           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
11322           {
11323             SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11324             pos->SetUParameter( edge->_pos[0].X() );
11325             pos->SetVParameter( edge->_pos[0].Y() );
11326             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
11327           }
11328           else
11329           {
11330             SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11331             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
11332             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
11333           }
11334           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11335           dumpMove( tgtNode );
11336         }
11337       // shrink EDGE sub-meshes and set proxy sub-meshes
11338       UVPtStructVec uvPtVec;
11339       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
11340       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
11341       {
11342         _Shrinker1D* shr = (*shrIt);
11343         shr->Compute( /*set3D=*/true, helper );
11344
11345         // set proxy mesh of EDGEs w/o layers
11346         map< double, const SMDS_MeshNode* > nodes;
11347         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
11348         // remove refinement nodes
11349         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
11350         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
11351         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
11352         if ( u2n->second == sn0 || u2n->second == sn1 )
11353         {
11354           while ( u2n->second != tn0 && u2n->second != tn1 )
11355             ++u2n;
11356           nodes.erase( nodes.begin(), u2n );
11357         }
11358         u2n = --nodes.end();
11359         if ( u2n->second == sn0 || u2n->second == sn1 )
11360         {
11361           while ( u2n->second != tn0 && u2n->second != tn1 )
11362             --u2n;
11363           nodes.erase( ++u2n, nodes.end() );
11364         }
11365         // set proxy sub-mesh
11366         uvPtVec.resize( nodes.size() );
11367         u2n = nodes.begin();
11368         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
11369         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
11370         {
11371           uvPtVec[ i ].node = u2n->second;
11372           uvPtVec[ i ].param = u2n->first;
11373           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
11374         }
11375         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
11376         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11377       }
11378
11379       // set proxy mesh of EDGEs with layers
11380       vector< _LayerEdge* > edges;
11381       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11382       {
11383         _EdgesOnShape& eos = * subEOS[ iS ];
11384         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
11385
11386         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
11387         data.SortOnEdge( E, eos._edges );
11388
11389         edges.clear();
11390         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
11391           if ( !eov->_edges.empty() )
11392             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
11393
11394         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
11395
11396         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
11397           if ( !eov->_edges.empty() )
11398             edges.push_back( eov->_edges[0] ); // on last VERTEX
11399
11400         uvPtVec.resize( edges.size() );
11401         for ( size_t i = 0; i < edges.size(); ++i )
11402         {
11403           uvPtVec[ i ].node = edges[i]->_nodes.back();
11404           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
11405           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
11406         }
11407         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
11408         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
11409         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11410       }
11411       // temporary clear the FACE sub-mesh from faces made by refine()
11412       vector< const SMDS_MeshElement* > elems;
11413       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
11414       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11415         elems.push_back( ite->next() );
11416       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
11417         elems.push_back( ite->next() );
11418       smDS->Clear();
11419
11420       // compute the mesh on the FACE
11421       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
11422       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
11423
11424       // re-fill proxy sub-meshes of the FACE
11425       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11426         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11427           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11428             psm->AddElement( ite->next() );
11429
11430       // re-fill smDS
11431       for ( size_t i = 0; i < elems.size(); ++i )
11432         smDS->AddElement( elems[i] );
11433
11434       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
11435         return error( errMsg );
11436
11437     } // end of re-meshing in case of failed smoothing
11438     else if ( !movedByPeriod )
11439     {
11440       // No wrongly shaped faces remain; final smooth. Set node XYZ.
11441       bool isStructuredFixed = false;
11442       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
11443         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
11444       if ( !isStructuredFixed )
11445       {
11446         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
11447           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
11448
11449         for ( int st = 3; st; --st )
11450         {
11451           switch( st ) {
11452           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
11453           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
11454           case 3: smoothType = _SmoothNode::ANGULAR; break;
11455           }
11456           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11457           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11458           {
11459             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11460                                      smoothType,/*set3D=*/st==1 );
11461           }
11462           dumpFunctionEnd();
11463         }
11464       }
11465       if ( !getMeshDS()->IsEmbeddedMode() )
11466         // Log node movement
11467         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11468         {
11469           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
11470           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
11471         }
11472     }
11473
11474     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
11475     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
11476     if ( data2 )
11477       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
11478
11479   } // loop on FACES to shrink mesh on
11480
11481
11482   // Replace source nodes by target nodes in shrunk mesh edges
11483
11484   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
11485   for ( ; e2shr != e2shrMap.end(); ++e2shr )
11486     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
11487
11488   return true;
11489 }
11490
11491 //================================================================================
11492 /*!
11493  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
11494  */
11495 //================================================================================
11496
11497 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
11498                                            _EdgesOnShape&         eos,
11499                                            SMESH_MesherHelper&    helper,
11500                                            const SMESHDS_SubMesh* faceSubMesh)
11501 {
11502   const SMDS_MeshNode* srcNode = edge._nodes[0];
11503   const SMDS_MeshNode* tgtNode = edge._nodes.back();
11504
11505   if ( eos.SWOLType() == TopAbs_FACE )
11506   {
11507     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
11508     {
11509       edge._pos.clear();
11510       edge.Set( _LayerEdge::SHRUNK );
11511       return srcNode == tgtNode;
11512     }
11513     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
11514     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
11515     gp_Vec2d uvDir( srcUV, tgtUV );
11516     double uvLen = uvDir.Magnitude();
11517     uvDir /= uvLen;
11518     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
11519     edge._len = uvLen;
11520
11521     //edge._pos.resize(1);
11522     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
11523
11524     // set UV of source node to target node
11525     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11526     pos->SetUParameter( srcUV.X() );
11527     pos->SetVParameter( srcUV.Y() );
11528   }
11529   else // _sWOL is TopAbs_EDGE
11530   {
11531     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
11532     {
11533       edge._pos.clear();
11534       edge.Set( _LayerEdge::SHRUNK );
11535       return srcNode == tgtNode;
11536     }
11537     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
11538     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
11539     if ( !edgeSM || edgeSM->NbElements() == 0 )
11540       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11541
11542     const SMDS_MeshNode* n2 = 0;
11543     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11544     while ( eIt->more() && !n2 )
11545     {
11546       const SMDS_MeshElement* e = eIt->next();
11547       if ( !edgeSM->Contains(e)) continue;
11548       n2 = e->GetNode( 0 );
11549       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
11550     }
11551     if ( !n2 )
11552       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11553
11554     if ( n2 == tgtNode ) // for 3D_mesh_GHS3D_01/B1
11555     {
11556       // shrunk by other SOLID
11557       edge.Set( _LayerEdge::SHRUNK ); // ???
11558       return true;
11559     }
11560
11561     double uSrc = helper.GetNodeU( E, srcNode, n2 );
11562     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
11563     double u2   = helper.GetNodeU( E, n2,      srcNode );
11564
11565     //edge._pos.clear();
11566
11567     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
11568     {
11569       // tgtNode is located so that it does not make faces with wrong orientation
11570       edge.Set( _LayerEdge::SHRUNK );
11571       return true;
11572     }
11573     //edge._pos.resize(1);
11574     edge._pos[0].SetCoord( U_TGT, uTgt );
11575     edge._pos[0].SetCoord( U_SRC, uSrc );
11576     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
11577
11578     edge._simplices.resize( 1 );
11579     edge._simplices[0]._nPrev = n2;
11580
11581     // set U of source node to the target node
11582     SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11583     pos->SetUParameter( uSrc );
11584   }
11585   return true;
11586 }
11587
11588 //================================================================================
11589 /*!
11590  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
11591  */
11592 //================================================================================
11593
11594 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
11595 {
11596   if ( edge._nodes.size() == 1 )
11597   {
11598     edge._pos.clear();
11599     edge._len = 0;
11600
11601     const SMDS_MeshNode* srcNode = edge._nodes[0];
11602     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
11603     if ( S.IsNull() ) return;
11604
11605     gp_Pnt p;
11606
11607     switch ( S.ShapeType() )
11608     {
11609     case TopAbs_EDGE:
11610     {
11611       double f,l;
11612       TopLoc_Location loc;
11613       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
11614       if ( curve.IsNull() ) return;
11615       SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
11616       p = curve->Value( ePos->GetUParameter() );
11617       break;
11618     }
11619     case TopAbs_VERTEX:
11620     {
11621       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
11622       break;
11623     }
11624     default: return;
11625     }
11626     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
11627     dumpMove( srcNode );
11628   }
11629 }
11630
11631 //================================================================================
11632 /*!
11633  * \brief Try to fix triangles with high aspect ratio by swapping diagonals
11634  */
11635 //================================================================================
11636
11637 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
11638                                   SMESH_MesherHelper&         helper,
11639                                   const bool                  is2D,
11640                                   const int                   step,
11641                                   set<const SMDS_MeshNode*> * involvedNodes)
11642 {
11643   SMESH::Controls::AspectRatio qualifier;
11644   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
11645   const double maxAspectRatio = is2D ? 4. : 2;
11646   _NodeCoordHelper xyz( F, helper, is2D );
11647
11648   // find bad triangles
11649
11650   vector< const SMDS_MeshElement* > badTrias;
11651   vector< double >                  badAspects;
11652   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
11653   SMDS_ElemIteratorPtr fIt = sm->GetElements();
11654   while ( fIt->more() )
11655   {
11656     const SMDS_MeshElement * f = fIt->next();
11657     if ( f->NbCornerNodes() != 3 ) continue;
11658     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
11659     double aspect = qualifier.GetValue( points );
11660     if ( aspect > maxAspectRatio )
11661     {
11662       badTrias.push_back( f );
11663       badAspects.push_back( aspect );
11664     }
11665   }
11666   if ( step == 1 )
11667   {
11668     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
11669     SMDS_ElemIteratorPtr fIt = sm->GetElements();
11670     while ( fIt->more() )
11671     {
11672       const SMDS_MeshElement * f = fIt->next();
11673       if ( f->NbCornerNodes() == 3 )
11674         dumpChangeNodes( f );
11675     }
11676     dumpFunctionEnd();
11677   }
11678   if ( badTrias.empty() )
11679     return;
11680
11681   // find couples of faces to swap diagonal
11682
11683   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
11684   vector< T2Trias > triaCouples; 
11685
11686   TIDSortedElemSet involvedFaces, emptySet;
11687   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
11688   {
11689     T2Trias trias    [3];
11690     double  aspRatio [3];
11691     int i1, i2, i3;
11692
11693     if ( !involvedFaces.insert( badTrias[iTia] ).second )
11694       continue;
11695     for ( int iP = 0; iP < 3; ++iP )
11696       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
11697
11698     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
11699     int bestCouple = -1;
11700     for ( int iSide = 0; iSide < 3; ++iSide )
11701     {
11702       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
11703       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
11704       trias [iSide].first  = badTrias[iTia];
11705       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
11706                                                              & i1, & i2 );
11707       if (( ! trias[iSide].second ) ||
11708           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
11709           ( ! sm->Contains( trias[iSide].second )))
11710         continue;
11711
11712       // aspect ratio of an adjacent tria
11713       for ( int iP = 0; iP < 3; ++iP )
11714         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
11715       double aspectInit = qualifier.GetValue( points2 );
11716
11717       // arrange nodes as after diag-swaping
11718       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
11719         i3 = helper.WrapIndex( i1-1, 3 );
11720       else
11721         i3 = helper.WrapIndex( i1+1, 3 );
11722       points1 = points;
11723       points1( 1+ iSide ) = points2( 1+ i3 );
11724       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
11725
11726       // aspect ratio after diag-swaping
11727       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
11728       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
11729         continue;
11730
11731       // prevent inversion of a triangle
11732       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
11733       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
11734       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
11735         continue;
11736
11737       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
11738         bestCouple = iSide;
11739     }
11740
11741     if ( bestCouple >= 0 )
11742     {
11743       triaCouples.push_back( trias[bestCouple] );
11744       involvedFaces.insert ( trias[bestCouple].second );
11745     }
11746     else
11747     {
11748       involvedFaces.erase( badTrias[iTia] );
11749     }
11750   }
11751   if ( triaCouples.empty() )
11752     return;
11753
11754   // swap diagonals
11755
11756   SMESH_MeshEditor editor( helper.GetMesh() );
11757   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11758   for ( size_t i = 0; i < triaCouples.size(); ++i )
11759   {
11760     dumpChangeNodes( triaCouples[i].first );
11761     dumpChangeNodes( triaCouples[i].second );
11762     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11763   }
11764
11765   if ( involvedNodes )
11766     for ( size_t i = 0; i < triaCouples.size(); ++i )
11767     {
11768       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11769                              triaCouples[i].first->end_nodes() );
11770       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11771                              triaCouples[i].second->end_nodes() );
11772     }
11773
11774   // just for debug dump resulting triangles
11775   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11776   for ( size_t i = 0; i < triaCouples.size(); ++i )
11777   {
11778     dumpChangeNodes( triaCouples[i].first );
11779     dumpChangeNodes( triaCouples[i].second );
11780   }
11781 }
11782
11783 //================================================================================
11784 /*!
11785  * \brief Move target node to it's final position on the FACE during shrinking
11786  */
11787 //================================================================================
11788
11789 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
11790                                  const TopoDS_Face&    F,
11791                                  _EdgesOnShape&        eos,
11792                                  SMESH_MesherHelper&   helper )
11793 {
11794   if ( Is( SHRUNK ))
11795     return false; // already at the target position
11796
11797   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11798
11799   if ( eos.SWOLType() == TopAbs_FACE )
11800   {
11801     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
11802     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11803     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11804     const double uvLen = tgtUV.Distance( curUV );
11805     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11806
11807     // Select shrinking step such that not to make faces with wrong orientation.
11808     double stepSize = 1e100;
11809     for ( size_t i = 0; i < _simplices.size(); ++i )
11810     {
11811       if ( !_simplices[i]._nPrev->isMarked() ||
11812            !_simplices[i]._nNext->isMarked() )
11813         continue; // simplex of quadrangle created by addBoundaryElements()
11814
11815       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11816       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11817       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11818       gp_XY dirN = uvN2 - uvN1;
11819       double det = uvDir.Crossed( dirN );
11820       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
11821       gp_XY dirN2Cur = curUV - uvN1;
11822       double step = dirN.Crossed( dirN2Cur ) / det;
11823       if ( step > 0 )
11824         stepSize = Min( step, stepSize );
11825     }
11826     gp_Pnt2d newUV;
11827     if ( uvLen <= stepSize )
11828     {
11829       newUV = tgtUV;
11830       Set( SHRUNK );
11831       //_pos.clear();
11832     }
11833     else if ( stepSize > 0 )
11834     {
11835       newUV = curUV + uvDir.XY() * stepSize * kSafe;
11836     }
11837     else
11838     {
11839       return true;
11840     }
11841     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11842     pos->SetUParameter( newUV.X() );
11843     pos->SetVParameter( newUV.Y() );
11844
11845 #ifdef __myDEBUG
11846     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11847     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11848     dumpMove( tgtNode );
11849 #endif
11850   }
11851   else // _sWOL is TopAbs_EDGE
11852   {
11853     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
11854     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
11855     SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
11856
11857     const double u2     = helper.GetNodeU( E, n2, tgtNode );
11858     const double uSrc   = _pos[0].Coord( U_SRC );
11859     const double lenTgt = _pos[0].Coord( LEN_TGT );
11860
11861     double newU = _pos[0].Coord( U_TGT );
11862     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11863     {
11864       Set( _LayerEdge::SHRUNK );
11865       //_pos.clear();
11866     }
11867     else
11868     {
11869       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11870     }
11871     tgtPos->SetUParameter( newU );
11872 #ifdef __myDEBUG
11873     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11874     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11875     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11876     dumpMove( tgtNode );
11877 #endif
11878   }
11879
11880   return true;
11881 }
11882
11883 //================================================================================
11884 /*!
11885  * \brief Perform smooth on the FACE
11886  *  \retval bool - true if the node has been moved
11887  */
11888 //================================================================================
11889
11890 bool _SmoothNode::Smooth(int&                  nbBad,
11891                          Handle(Geom_Surface)& surface,
11892                          SMESH_MesherHelper&   helper,
11893                          const double          refSign,
11894                          SmoothType            how,
11895                          bool                  set3D)
11896 {
11897   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11898
11899   // get uv of surrounding nodes
11900   vector<gp_XY> uv( _simplices.size() );
11901   for ( size_t i = 0; i < _simplices.size(); ++i )
11902     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11903
11904   // compute new UV for the node
11905   gp_XY newPos (0,0);
11906   if ( how == TFI && _simplices.size() == 4 )
11907   {
11908     gp_XY corners[4];
11909     for ( size_t i = 0; i < _simplices.size(); ++i )
11910       if ( _simplices[i]._nOpp )
11911         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11912       else
11913         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11914
11915     newPos = helper.calcTFI ( 0.5, 0.5,
11916                               corners[0], corners[1], corners[2], corners[3],
11917                               uv[1], uv[2], uv[3], uv[0] );
11918   }
11919   else if ( how == ANGULAR )
11920   {
11921     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11922   }
11923   else if ( how == CENTROIDAL && _simplices.size() > 3 )
11924   {
11925     // average centers of diagonals wieghted with their reciprocal lengths
11926     if ( _simplices.size() == 4 )
11927     {
11928       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11929       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11930       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11931     }
11932     else
11933     {
11934       double sumWeight = 0;
11935       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11936       for ( int i = 0; i < nb; ++i )
11937       {
11938         int iFrom = i + 2;
11939         int iTo   = i + _simplices.size() - 1;
11940         for ( int j = iFrom; j < iTo; ++j )
11941         {
11942           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11943           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11944           sumWeight += w;
11945           newPos += w * ( uv[i]+uv[i2] );
11946         }
11947       }
11948       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11949     }
11950   }
11951   else
11952   {
11953     // Laplacian smooth
11954     for ( size_t i = 0; i < _simplices.size(); ++i )
11955       newPos += uv[i];
11956     newPos /= _simplices.size();
11957   }
11958
11959   // count quality metrics (orientation) of triangles around the node
11960   int nbOkBefore = 0;
11961   gp_XY tgtUV = helper.GetNodeUV( face, _node );
11962   for ( size_t i = 0; i < _simplices.size(); ++i )
11963     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11964
11965   int nbOkAfter = 0;
11966   for ( size_t i = 0; i < _simplices.size(); ++i )
11967     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11968
11969   if ( nbOkAfter < nbOkBefore )
11970   {
11971     nbBad += _simplices.size() - nbOkBefore;
11972     return false;
11973   }
11974
11975   SMDS_FacePositionPtr pos = _node->GetPosition();
11976   pos->SetUParameter( newPos.X() );
11977   pos->SetVParameter( newPos.Y() );
11978
11979 #ifdef __myDEBUG
11980   set3D = true;
11981 #endif
11982   if ( set3D )
11983   {
11984     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
11985     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
11986     dumpMove( _node );
11987   }
11988
11989   nbBad += _simplices.size() - nbOkAfter;
11990   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
11991 }
11992
11993 //================================================================================
11994 /*!
11995  * \brief Computes new UV using angle based smoothing technique
11996  */
11997 //================================================================================
11998
11999 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
12000                                      const gp_XY&   uvToFix,
12001                                      const double   refSign)
12002 {
12003   uv.push_back( uv.front() );
12004
12005   vector< gp_XY >  edgeDir ( uv.size() );
12006   vector< double > edgeSize( uv.size() );
12007   for ( size_t i = 1; i < edgeDir.size(); ++i )
12008   {
12009     edgeDir [i-1] = uv[i] - uv[i-1];
12010     edgeSize[i-1] = edgeDir[i-1].Modulus();
12011     if ( edgeSize[i-1] < numeric_limits<double>::min() )
12012       edgeDir[i-1].SetX( 100 );
12013     else
12014       edgeDir[i-1] /= edgeSize[i-1] * refSign;
12015   }
12016   edgeDir.back()  = edgeDir.front();
12017   edgeSize.back() = edgeSize.front();
12018
12019   gp_XY  newPos(0,0);
12020   //int    nbEdges = 0;
12021   double sumSize = 0;
12022   for ( size_t i = 1; i < edgeDir.size(); ++i )
12023   {
12024     if ( edgeDir[i-1].X() > 1. ) continue;
12025     int i1 = i-1;
12026     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
12027     if ( i == edgeDir.size() ) break;
12028     gp_XY p = uv[i];
12029     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
12030     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
12031     gp_XY bisec = norm1 + norm2;
12032     double bisecSize = bisec.Modulus();
12033     if ( bisecSize < numeric_limits<double>::min() )
12034     {
12035       bisec = -edgeDir[i1] + edgeDir[i];
12036       bisecSize = bisec.Modulus();
12037     }
12038     bisec /= bisecSize;
12039
12040     gp_XY  dirToN  = uvToFix - p;
12041     double distToN = dirToN.Modulus();
12042     if ( bisec * dirToN < 0 )
12043       distToN = -distToN;
12044
12045     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
12046     //++nbEdges;
12047     sumSize += edgeSize[i1] + edgeSize[i];
12048   }
12049   newPos /= /*nbEdges * */sumSize;
12050   return newPos;
12051 }
12052
12053 //================================================================================
12054 /*!
12055  * \brief Keep a _LayerEdge inflated along the EDGE
12056  */
12057 //================================================================================
12058
12059 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
12060                            _EdgesOnShape&      eos,
12061                            SMESH_MesherHelper& helper )
12062 {
12063   // init
12064   if ( _nodes.empty() )
12065   {
12066     _edges[0] = _edges[1] = 0;
12067     _done = false;
12068   }
12069   // check _LayerEdge
12070   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
12071     return;
12072   if ( eos.SWOLType() != TopAbs_EDGE )
12073     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12074   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
12075     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12076
12077   // store _LayerEdge
12078   _geomEdge = TopoDS::Edge( eos._sWOL );
12079   double f,l;
12080   BRep_Tool::Range( _geomEdge, f,l );
12081   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
12082   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
12083
12084   // Update _nodes
12085
12086   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
12087   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
12088
12089   if ( _nodes.empty() )
12090   {
12091     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
12092     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
12093       return;
12094     TopLoc_Location loc;
12095     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
12096     GeomAdaptor_Curve aCurve(C, f,l);
12097     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
12098
12099     int nbExpectNodes = eSubMesh->NbNodes();
12100     _initU  .reserve( nbExpectNodes );
12101     _normPar.reserve( nbExpectNodes );
12102     _nodes  .reserve( nbExpectNodes );
12103     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
12104     while ( nIt->more() )
12105     {
12106       const SMDS_MeshNode* node = nIt->next();
12107
12108       // skip refinement nodes
12109       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
12110            node == tgtNode0 || node == tgtNode1 )
12111         continue;
12112       bool hasMarkedFace = false;
12113       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
12114       while ( fIt->more() && !hasMarkedFace )
12115         hasMarkedFace = fIt->next()->isMarked();
12116       if ( !hasMarkedFace )
12117         continue;
12118
12119       _nodes.push_back( node );
12120       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
12121       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
12122       _normPar.push_back(  len / totLen );
12123     }
12124   }
12125   else
12126   {
12127     // remove target node of the _LayerEdge from _nodes
12128     size_t nbFound = 0;
12129     for ( size_t i = 0; i < _nodes.size(); ++i )
12130       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
12131         _nodes[i] = 0, nbFound++;
12132     if ( nbFound == _nodes.size() )
12133       _nodes.clear();
12134   }
12135 }
12136
12137 //================================================================================
12138 /*!
12139  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
12140  */
12141 //================================================================================
12142
12143 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
12144 {
12145   if ( _done || _nodes.empty())
12146     return;
12147   const _LayerEdge* e = _edges[0];
12148   if ( !e ) e = _edges[1];
12149   if ( !e ) return;
12150
12151   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
12152             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
12153
12154   double f,l;
12155   if ( set3D || _done )
12156   {
12157     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
12158     GeomAdaptor_Curve aCurve(C, f,l);
12159
12160     if ( _edges[0] )
12161       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12162     if ( _edges[1] )
12163       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12164     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
12165
12166     for ( size_t i = 0; i < _nodes.size(); ++i )
12167     {
12168       if ( !_nodes[i] ) continue;
12169       double len = totLen * _normPar[i];
12170       GCPnts_AbscissaPoint discret( aCurve, len, f );
12171       if ( !discret.IsDone() )
12172         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
12173       double u = discret.Parameter();
12174       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12175       pos->SetUParameter( u );
12176       gp_Pnt p = C->Value( u );
12177       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
12178     }
12179   }
12180   else
12181   {
12182     BRep_Tool::Range( _geomEdge, f,l );
12183     if ( _edges[0] )
12184       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12185     if ( _edges[1] )
12186       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12187     
12188     for ( size_t i = 0; i < _nodes.size(); ++i )
12189     {
12190       if ( !_nodes[i] ) continue;
12191       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
12192       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12193       pos->SetUParameter( u );
12194     }
12195   }
12196 }
12197
12198 //================================================================================
12199 /*!
12200  * \brief Restore initial parameters of nodes on EDGE
12201  */
12202 //================================================================================
12203
12204 void _Shrinker1D::RestoreParams()
12205 {
12206   if ( _done )
12207     for ( size_t i = 0; i < _nodes.size(); ++i )
12208     {
12209       if ( !_nodes[i] ) continue;
12210       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12211       pos->SetUParameter( _initU[i] );
12212     }
12213   _done = false;
12214 }
12215
12216 //================================================================================
12217 /*!
12218  * \brief Replace source nodes by target nodes in shrunk mesh edges
12219  */
12220 //================================================================================
12221
12222 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
12223 {
12224   const SMDS_MeshNode* nodes[3];
12225   for ( int i = 0; i < 2; ++i )
12226   {
12227     if ( !_edges[i] ) continue;
12228
12229     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
12230     if ( !eSubMesh ) return;
12231     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
12232     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
12233     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
12234     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
12235     while ( eIt->more() )
12236     {
12237       const SMDS_MeshElement* e = eIt->next();
12238       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
12239           continue;
12240       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
12241       for ( int iN = 0; iN < e->NbNodes(); ++iN )
12242       {
12243         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
12244         nodes[iN] = ( n == srcNode ? tgtNode : n );
12245       }
12246       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
12247     }
12248   }
12249 }
12250
12251 //================================================================================
12252 /*!
12253  * \brief Creates 2D and 1D elements on boundaries of new prisms
12254  */
12255 //================================================================================
12256
12257 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
12258 {
12259   SMESH_MesherHelper helper( *_mesh );
12260
12261   vector< const SMDS_MeshNode* > faceNodes;
12262
12263   //for ( size_t i = 0; i < _sdVec.size(); ++i )
12264   {
12265     //_SolidData& data = _sdVec[i];
12266     TopTools_IndexedMapOfShape geomEdges;
12267     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
12268     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
12269     {
12270       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
12271       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
12272       if ( data._noShrinkShapes.count( edgeID ))
12273         continue;
12274
12275       // Get _LayerEdge's based on E
12276
12277       map< double, const SMDS_MeshNode* > u2nodes;
12278       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
12279         continue;
12280
12281       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
12282       TNode2Edge & n2eMap = data._n2eMap;
12283       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
12284       {
12285         //check if 2D elements are needed on E
12286         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
12287         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
12288         ledges.push_back( n2e->second );
12289         u2n++;
12290         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
12291           continue; // no layers on E
12292         ledges.push_back( n2eMap[ u2n->second ]);
12293
12294         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
12295         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
12296         int nbSharedPyram = 0;
12297         SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
12298         while ( vIt->more() )
12299         {
12300           const SMDS_MeshElement* v = vIt->next();
12301           nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
12302         }
12303         if ( nbSharedPyram > 1 )
12304           continue; // not free border of the pyramid
12305
12306         faceNodes.clear();
12307         faceNodes.push_back( ledges[0]->_nodes[0] );
12308         faceNodes.push_back( ledges[1]->_nodes[0] );
12309         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
12310         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
12311
12312         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
12313           continue; // faces already created
12314       }
12315       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
12316         ledges.push_back( n2eMap[ u2n->second ]);
12317
12318       // Find out orientation and type of face to create
12319
12320       bool reverse = false, isOnFace;
12321       TopoDS_Shape F;
12322
12323       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
12324       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
12325       {
12326         F = e2f->second.Oriented( TopAbs_FORWARD );
12327         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
12328         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
12329           reverse = !reverse, F.Reverse();
12330         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
12331           reverse = !reverse;
12332       }
12333       else if ( !data._ignoreFaceIds.count( e2f->first ))
12334       {
12335         // find FACE with layers sharing E
12336         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
12337         if ( fIt->more() )
12338           F = *( fIt->next() );
12339       }
12340       // Find the sub-mesh to add new faces
12341       SMESHDS_SubMesh* sm = 0;
12342       if ( isOnFace )
12343         sm = getMeshDS()->MeshElements( F );
12344       else
12345         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
12346       if ( !sm )
12347         return error("error in addBoundaryElements()", data._index);
12348
12349       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
12350       // faces for 3D meshing (PAL23414)
12351       SMESHDS_SubMesh* adjSM = 0;
12352       if ( isOnFace )
12353       {
12354         const TGeomID   faceID = sm->GetID();
12355         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
12356         while ( const TopoDS_Shape* solid = soIt->next() )
12357           if ( !solid->IsSame( data._solid ))
12358           {
12359             size_t iData = _solids.FindIndex( *solid ) - 1;
12360             if ( iData < _sdVec.size() &&
12361                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
12362                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
12363             {
12364               SMESH_ProxyMesh::SubMesh* proxySub =
12365                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
12366               if ( proxySub && proxySub->NbElements() > 0 )
12367                 adjSM = proxySub;
12368             }
12369           }
12370       }
12371
12372       // Make faces
12373       const int dj1 = reverse ? 0 : 1;
12374       const int dj2 = reverse ? 1 : 0;
12375       vector< const SMDS_MeshElement*> ff; // new faces row
12376       SMESHDS_Mesh* m = getMeshDS();
12377       for ( size_t j = 1; j < ledges.size(); ++j )
12378       {
12379         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
12380         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
12381         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
12382         if ( nn1.size() == nn2.size() )
12383         {
12384           if ( isOnFace )
12385             for ( size_t z = 1; z < nn1.size(); ++z )
12386               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12387           else
12388             for ( size_t z = 1; z < nn1.size(); ++z )
12389               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12390         }
12391         else if ( nn1.size() == 1 )
12392         {
12393           if ( isOnFace )
12394             for ( size_t z = 1; z < nn2.size(); ++z )
12395               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
12396           else
12397             for ( size_t z = 1; z < nn2.size(); ++z )
12398               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
12399         }
12400         else
12401         {
12402           if ( isOnFace )
12403             for ( size_t z = 1; z < nn1.size(); ++z )
12404               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
12405           else
12406             for ( size_t z = 1; z < nn1.size(); ++z )
12407               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
12408         }
12409
12410         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
12411         {
12412           for ( size_t z = 0; z < ff.size(); ++z )
12413             if ( ff[ z ])
12414               adjSM->AddElement( ff[ z ]);
12415           ff.clear();
12416         }
12417       }
12418
12419       // Make edges
12420       for ( int isFirst = 0; isFirst < 2; ++isFirst )
12421       {
12422         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
12423         _EdgesOnShape* eos = data.GetShapeEdges( edge );
12424         if ( eos && eos->SWOLType() == TopAbs_EDGE )
12425         {
12426           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
12427           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
12428             continue;
12429           helper.SetSubShape( eos->_sWOL );
12430           helper.SetElementsOnShape( true );
12431           for ( size_t z = 1; z < nn.size(); ++z )
12432             helper.AddEdge( nn[z-1], nn[z] );
12433         }
12434       }
12435
12436     } // loop on EDGE's
12437   } // loop on _SolidData's
12438
12439   return true;
12440 }