Salome HOME
23620: EDF 10301 - Completing Extrusion along a path
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_PolygonalFaceOfNodes.hxx"
31 #include "SMDS_SetIterator.hxx"
32 #include "SMESHDS_Group.hxx"
33 #include "SMESHDS_Hypothesis.hxx"
34 #include "SMESHDS_Mesh.hxx"
35 #include "SMESH_Algo.hxx"
36 #include "SMESH_ComputeError.hxx"
37 #include "SMESH_ControlsDef.hxx"
38 #include "SMESH_Gen.hxx"
39 #include "SMESH_Group.hxx"
40 #include "SMESH_HypoFilter.hxx"
41 #include "SMESH_Mesh.hxx"
42 #include "SMESH_MeshAlgos.hxx"
43 #include "SMESH_MesherHelper.hxx"
44 #include "SMESH_ProxyMesh.hxx"
45 #include "SMESH_subMesh.hxx"
46 #include "SMESH_MeshEditor.hxx"
47 #include "SMESH_subMeshEventListener.hxx"
48 #include "StdMeshers_FaceSide.hxx"
49 #include "StdMeshers_ViscousLayers2D.hxx"
50
51 #include <Adaptor3d_HSurface.hxx>
52 #include <BRepAdaptor_Curve.hxx>
53 #include <BRepAdaptor_Curve2d.hxx>
54 #include <BRepAdaptor_Surface.hxx>
55 //#include <BRepLProp_CLProps.hxx>
56 #include <BRepLProp_SLProps.hxx>
57 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
58 #include <BRep_Tool.hxx>
59 #include <Bnd_B2d.hxx>
60 #include <Bnd_B3d.hxx>
61 #include <ElCLib.hxx>
62 #include <GCPnts_AbscissaPoint.hxx>
63 #include <GCPnts_TangentialDeflection.hxx>
64 #include <Geom2d_Circle.hxx>
65 #include <Geom2d_Line.hxx>
66 #include <Geom2d_TrimmedCurve.hxx>
67 #include <GeomAdaptor_Curve.hxx>
68 #include <GeomLib.hxx>
69 #include <Geom_Circle.hxx>
70 #include <Geom_Curve.hxx>
71 #include <Geom_Line.hxx>
72 #include <Geom_TrimmedCurve.hxx>
73 #include <Precision.hxx>
74 #include <Standard_ErrorHandler.hxx>
75 #include <Standard_Failure.hxx>
76 #include <TColStd_Array1OfReal.hxx>
77 #include <TopExp.hxx>
78 #include <TopExp_Explorer.hxx>
79 #include <TopTools_IndexedMapOfShape.hxx>
80 #include <TopTools_ListOfShape.hxx>
81 #include <TopTools_MapIteratorOfMapOfShape.hxx>
82 #include <TopTools_MapOfShape.hxx>
83 #include <TopoDS.hxx>
84 #include <TopoDS_Edge.hxx>
85 #include <TopoDS_Face.hxx>
86 #include <TopoDS_Vertex.hxx>
87 #include <gp_Ax1.hxx>
88 #include <gp_Cone.hxx>
89 #include <gp_Sphere.hxx>
90 #include <gp_Vec.hxx>
91 #include <gp_XY.hxx>
92
93 #include <cmath>
94 #include <limits>
95 #include <list>
96 #include <queue>
97 #include <string>
98 #include <unordered_map>
99
100 #ifdef _DEBUG_
101 //#define __myDEBUG
102 //#define __NOT_INVALIDATE_BAD_SMOOTH
103 //#define __NODES_AT_POS
104 #endif
105
106 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
107 #define BLOCK_INFLATION // of individual _LayerEdge's
108 #define OLD_NEF_POLYGON
109
110 using namespace std;
111
112 //================================================================================
113 namespace VISCOUS_3D
114 {
115   typedef int TGeomID;
116
117   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
118
119   const double theMinSmoothCosin = 0.1;
120   const double theSmoothThickToElemSizeRatio = 0.6;
121   const double theMinSmoothTriaAngle = 30;
122   const double theMinSmoothQuadAngle = 45;
123
124   // what part of thickness is allowed till intersection
125   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
126   const double theThickToIntersection = 1.5;
127
128   bool needSmoothing( double cosin, double tgtThick, double elemSize )
129   {
130     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
131   }
132   double getSmoothingThickness( double cosin, double elemSize )
133   {
134     return theSmoothThickToElemSizeRatio * elemSize / cosin;
135   }
136
137   /*!
138    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
139    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
140    */
141   struct _MeshOfSolid : public SMESH_ProxyMesh,
142                         public SMESH_subMeshEventListenerData
143   {
144     bool                  _n2nMapComputed;
145     SMESH_ComputeErrorPtr _warning;
146
147     _MeshOfSolid( SMESH_Mesh* mesh)
148       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
149     {
150       SMESH_ProxyMesh::setMesh( *mesh );
151     }
152
153     // returns submesh for a geom face
154     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
155     {
156       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
157       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
158     }
159     void setNode2Node(const SMDS_MeshNode*                 srcNode,
160                       const SMDS_MeshNode*                 proxyNode,
161                       const SMESH_ProxyMesh::SubMesh* subMesh)
162     {
163       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
164     }
165   };
166   //--------------------------------------------------------------------------------
167   /*!
168    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
169    * It is used to clear an inferior dim sub-meshes modified by viscous layers
170    */
171   class _ShrinkShapeListener : SMESH_subMeshEventListener
172   {
173     _ShrinkShapeListener()
174       : SMESH_subMeshEventListener(/*isDeletable=*/false,
175                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
176   public:
177     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
178     virtual void ProcessEvent(const int                       event,
179                               const int                       eventType,
180                               SMESH_subMesh*                  solidSM,
181                               SMESH_subMeshEventListenerData* data,
182                               const SMESH_Hypothesis*         hyp)
183     {
184       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
185       {
186         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
187       }
188     }
189   };
190   //--------------------------------------------------------------------------------
191   /*!
192    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
193    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
194    * delete the data as soon as it has been used
195    */
196   class _ViscousListener : SMESH_subMeshEventListener
197   {
198     _ViscousListener():
199       SMESH_subMeshEventListener(/*isDeletable=*/false,
200                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
201     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
202   public:
203     virtual void ProcessEvent(const int                       event,
204                               const int                       eventType,
205                               SMESH_subMesh*                  subMesh,
206                               SMESH_subMeshEventListenerData* data,
207                               const SMESH_Hypothesis*         hyp)
208     {
209       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
210           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
211             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
212       {
213         // delete SMESH_ProxyMesh containing temporary faces
214         subMesh->DeleteEventListener( this );
215       }
216     }
217     // Finds or creates proxy mesh of the solid
218     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
219                                       const TopoDS_Shape& solid,
220                                       bool                toCreate=false)
221     {
222       if ( !mesh ) return 0;
223       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
224       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
225       if ( !data && toCreate )
226       {
227         data = new _MeshOfSolid(mesh);
228         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
229         sm->SetEventListener( Get(), data, sm );
230       }
231       return data;
232     }
233     // Removes proxy mesh of the solid
234     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
235     {
236       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
237     }
238   };
239   
240   //================================================================================
241   /*!
242    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
243    * the main shape when sub-mesh of the main shape is cleared,
244    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
245    * is cleared
246    */
247   //================================================================================
248
249   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
250   {
251     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
252     SMESH_subMeshEventListenerData* data =
253       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
254     if ( data )
255     {
256       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
257            data->mySubMeshes.end())
258         data->mySubMeshes.push_back( sub );
259     }
260     else
261     {
262       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
263       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
264     }
265   }
266   struct _SolidData;
267   //--------------------------------------------------------------------------------
268   /*!
269    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
270    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
271    * The class is used to check validity of face or volumes around a smoothed node;
272    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
273    */
274   struct _Simplex
275   {
276     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
277     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
278     _Simplex(const SMDS_MeshNode* nPrev=0,
279              const SMDS_MeshNode* nNext=0,
280              const SMDS_MeshNode* nOpp=0)
281       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
282     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
283     {
284       const double M[3][3] =
285         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
286          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
287          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
288       vol = ( + M[0][0] * M[1][1] * M[2][2]
289               + M[0][1] * M[1][2] * M[2][0]
290               + M[0][2] * M[1][0] * M[2][1]
291               - M[0][0] * M[1][2] * M[2][1]
292               - M[0][1] * M[1][0] * M[2][2]
293               - M[0][2] * M[1][1] * M[2][0]);
294       return vol > 1e-100;
295     }
296     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
297     {
298       SMESH_TNodeXYZ pSrc( nSrc );
299       return IsForward( &pSrc, &pTgt, vol );
300     }
301     bool IsForward(const gp_XY&         tgtUV,
302                    const SMDS_MeshNode* smoothedNode,
303                    const TopoDS_Face&   face,
304                    SMESH_MesherHelper&  helper,
305                    const double         refSign) const
306     {
307       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
308       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
309       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
310       double d = v1 ^ v2;
311       return d*refSign > 1e-100;
312     }
313     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
314     {
315       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
316       if ( !_nOpp ) // triangle
317       {
318         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
319         double tp2 = tp.SquareMagnitude();
320         double pn2 = pn.SquareMagnitude();
321         double nt2 = nt.SquareMagnitude();
322
323         if ( tp2 < pn2 && tp2 < nt2 )
324           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
325         else if ( pn2 < nt2 )
326           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
327         else
328           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
329
330         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
331                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
332         return minAngle < theMaxCos2;
333       }
334       else // quadrangle
335       {
336         SMESH_TNodeXYZ pOpp( _nOpp );
337         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
338         double tp2 = tp.SquareMagnitude();
339         double po2 = po.SquareMagnitude();
340         double on2 = on.SquareMagnitude();
341         double nt2 = nt.SquareMagnitude();
342         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
343                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
344                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
345                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
346
347         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
348                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
349         return minAngle < theMaxCos2;
350       }
351     }
352     bool IsNeighbour(const _Simplex& other) const
353     {
354       return _nPrev == other._nNext || _nNext == other._nPrev;
355     }
356     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
357     static void GetSimplices( const SMDS_MeshNode* node,
358                               vector<_Simplex>&   simplices,
359                               const set<TGeomID>& ingnoreShapes,
360                               const _SolidData*   dataToCheckOri = 0,
361                               const bool          toSort = false);
362     static void SortSimplices(vector<_Simplex>& simplices);
363   };
364   //--------------------------------------------------------------------------------
365   /*!
366    * Structure used to take into account surface curvature while smoothing
367    */
368   struct _Curvature
369   {
370     double   _r; // radius
371     double   _k; // factor to correct node smoothed position
372     double   _h2lenRatio; // avgNormProj / (2*avgDist)
373     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
374   public:
375     static _Curvature* New( double avgNormProj, double avgDist )
376     {
377       _Curvature* c = 0;
378       if ( fabs( avgNormProj / avgDist ) > 1./200 )
379       {
380         c = new _Curvature;
381         c->_r = avgDist * avgDist / avgNormProj;
382         c->_k = avgDist * avgDist / c->_r / c->_r;
383         //c->_k = avgNormProj / c->_r;
384         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
385         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
386
387         c->_uv.SetCoord( 0., 0. );
388       }
389       return c;
390     }
391     double lenDelta(double len) const { return _k * ( _r + len ); }
392     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
393   };
394   //--------------------------------------------------------------------------------
395
396   struct _2NearEdges;
397   struct _LayerEdge;
398   struct _EdgesOnShape;
399   struct _Smoother1D;
400   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
401
402   //--------------------------------------------------------------------------------
403   /*!
404    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
405    * and a node of the most internal layer (_nodes.back())
406    */
407   struct _LayerEdge
408   {
409     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
410
411     vector< const SMDS_MeshNode*> _nodes;
412
413     gp_XYZ              _normal;    // to boundary of solid
414     vector<gp_XYZ>      _pos;       // points computed during inflation
415     double              _len;       // length achieved with the last inflation step
416     double              _maxLen;    // maximal possible length
417     double              _cosin;     // of angle (_normal ^ surface)
418     double              _minAngle;  // of _simplices
419     double              _lenFactor; // to compute _len taking _cosin into account
420     int                 _flags;
421
422     // simplices connected to the source node (_nodes[0]);
423     // used for smoothing and quality check of _LayerEdge's based on the FACE
424     vector<_Simplex>    _simplices;
425     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
426     PSmooFun            _smooFunction; // smoothing function
427     _Curvature*         _curvature;
428     // data for smoothing of _LayerEdge's based on the EDGE
429     _2NearEdges*        _2neibors;
430
431     enum EFlags { TO_SMOOTH       = 0x0000001,
432                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
433                   SMOOTHED        = 0x0000004, // set by _LayerEdge::Smooth()
434                   DIFFICULT       = 0x0000008, // near concave VERTEX
435                   ON_CONCAVE_FACE = 0x0000010,
436                   BLOCKED         = 0x0000020, // not to inflate any more
437                   INTERSECTED     = 0x0000040, // close intersection with a face found
438                   NORMAL_UPDATED  = 0x0000080,
439                   UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
440                   MARKED          = 0x0000200, // local usage
441                   MULTI_NORMAL    = 0x0000400, // a normal is invisible by some of surrounding faces
442                   NEAR_BOUNDARY   = 0x0000800, // is near FACE boundary forcing smooth
443                   SMOOTHED_C1     = 0x0001000, // is on _eosC1
444                   DISTORTED       = 0x0002000, // was bad before smoothing
445                   RISKY_SWOL      = 0x0004000, // SWOL is parallel to a source FACE
446                   SHRUNK          = 0x0008000, // target node reached a tgt position while shrink()
447                   UNUSED_FLAG     = 0x0100000  // to add user flags after
448     };
449     bool Is   ( int flag ) const { return _flags & flag; }
450     void Set  ( int flag ) { _flags |= flag; }
451     void Unset( int flag ) { _flags &= ~flag; }
452     std::string DumpFlags() const; // debug
453
454     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
455     bool SetNewLength2d( Handle(Geom_Surface)& surface,
456                          const TopoDS_Face&    F,
457                          _EdgesOnShape&        eos,
458                          SMESH_MesherHelper&   helper );
459     void SetDataByNeighbors( const SMDS_MeshNode* n1,
460                              const SMDS_MeshNode* n2,
461                              const _EdgesOnShape& eos,
462                              SMESH_MesherHelper&  helper);
463     void Block( _SolidData& data );
464     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
465     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
466                             const TNode2Edge&     n2eMap);
467     void SmoothPos( const vector< double >& segLen, const double tol );
468     int  GetSmoothedPos( const double tol );
469     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
470     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
471     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
472     void SmoothWoCheck();
473     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
474                       const TopoDS_Face&             F,
475                       SMESH_MesherHelper&            helper);
476     void MoveNearConcaVer( const _EdgesOnShape*    eov,
477                            const _EdgesOnShape*    eos,
478                            const int               step,
479                            vector< _LayerEdge* > & badSmooEdges);
480     bool FindIntersection( SMESH_ElementSearcher&   searcher,
481                            double &                 distance,
482                            const double&            epsilon,
483                            _EdgesOnShape&           eos,
484                            const SMDS_MeshElement** face = 0);
485     bool SegTriaInter( const gp_Ax1&        lastSegment,
486                        const gp_XYZ&        p0,
487                        const gp_XYZ&        p1,
488                        const gp_XYZ&        p2,
489                        double&              dist,
490                        const double&        epsilon) const;
491     bool SegTriaInter( const gp_Ax1&        lastSegment,
492                        const SMDS_MeshNode* n0,
493                        const SMDS_MeshNode* n1,
494                        const SMDS_MeshNode* n2,
495                        double&              dist,
496                        const double&        epsilon) const
497     { return SegTriaInter( lastSegment,
498                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
499                            dist, epsilon );
500     }
501     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
502     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
503     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
504     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
505     bool   IsOnEdge() const { return _2neibors; }
506     bool   IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
507     int    BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
508     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
509     void   SetCosin( double cosin );
510     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
511     void   SetMaxLen( double l ) { _maxLen = l; }
512     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
513     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
514     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
515       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
516     }
517     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
518
519     gp_XYZ smoothLaplacian();
520     gp_XYZ smoothAngular();
521     gp_XYZ smoothLengthWeighted();
522     gp_XYZ smoothCentroidal();
523     gp_XYZ smoothNefPolygon();
524
525     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
526     static const int theNbSmooFuns = FUN_NB;
527     static PSmooFun _funs[theNbSmooFuns];
528     static const char* _funNames[theNbSmooFuns+1];
529     int smooFunID( PSmooFun fun=0) const;
530   };
531   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
532                                                             &_LayerEdge::smoothLengthWeighted,
533                                                             &_LayerEdge::smoothCentroidal,
534                                                             &_LayerEdge::smoothNefPolygon,
535                                                             &_LayerEdge::smoothAngular };
536   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
537                                                          "LengthWeighted",
538                                                          "Centroidal",
539                                                          "NefPolygon",
540                                                          "Angular",
541                                                          "None"};
542   struct _LayerEdgeCmp
543   {
544     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
545     {
546       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
547       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
548     }
549   };
550   //--------------------------------------------------------------------------------
551   /*!
552    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
553    */
554   struct _halfPlane
555   {
556     gp_XY _pos, _dir, _inNorm;
557     bool IsOut( const gp_XY p, const double tol ) const
558     {
559       return _inNorm * ( p - _pos ) < -tol;
560     }
561     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
562     {
563       //const double eps = 1e-10;
564       double D = _dir.Crossed( hp._dir );
565       if ( fabs(D) < std::numeric_limits<double>::min())
566         return false;
567       gp_XY vec21 = _pos - hp._pos; 
568       double u = hp._dir.Crossed( vec21 ) / D; 
569       intPnt = _pos + _dir * u;
570       return true;
571     }
572   };
573   //--------------------------------------------------------------------------------
574   /*!
575    * Structure used to smooth a _LayerEdge based on an EDGE.
576    */
577   struct _2NearEdges
578   {
579     double               _wgt  [2]; // weights of _nodes
580     _LayerEdge*          _edges[2];
581
582      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
583     gp_XYZ*              _plnNorm;
584
585     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
586     const SMDS_MeshNode* tgtNode(bool is2nd) {
587       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
588     }
589     const SMDS_MeshNode* srcNode(bool is2nd) {
590       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
591     }
592     void reverse() {
593       std::swap( _wgt  [0], _wgt  [1] );
594       std::swap( _edges[0], _edges[1] );
595     }
596     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
597       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
598     }
599     bool include( const _LayerEdge* e ) {
600       return ( _edges[0] == e || _edges[1] == e );
601     }
602   };
603
604
605   //--------------------------------------------------------------------------------
606   /*!
607    * \brief Layers parameters got by averaging several hypotheses
608    */
609   struct AverageHyp
610   {
611     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
612       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
613     {
614       Add( hyp );
615     }
616     void Add( const StdMeshers_ViscousLayers* hyp )
617     {
618       if ( hyp )
619       {
620         _nbHyps++;
621         _nbLayers       = hyp->GetNumberLayers();
622         //_thickness     += hyp->GetTotalThickness();
623         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
624         _stretchFactor += hyp->GetStretchFactor();
625         _method         = hyp->GetMethod();
626       }
627     }
628     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
629     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
630     int    GetNumberLayers()   const { return _nbLayers; }
631     int    GetMethod()         const { return _method; }
632
633     bool   UseSurfaceNormal()  const
634     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
635     bool   ToSmooth()          const
636     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
637     bool   IsOffsetMethod()    const
638     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
639
640   private:
641     int     _nbLayers, _nbHyps, _method;
642     double  _thickness, _stretchFactor;
643   };
644
645   //--------------------------------------------------------------------------------
646   /*!
647    * \brief _LayerEdge's on a shape and other shape data
648    */
649   struct _EdgesOnShape
650   {
651     vector< _LayerEdge* > _edges;
652
653     TopoDS_Shape          _shape;
654     TGeomID               _shapeID;
655     SMESH_subMesh *       _subMesh;
656     // face or edge w/o layer along or near which _edges are inflated
657     TopoDS_Shape          _sWOL;
658     bool                  _isRegularSWOL; // w/o singularities
659     // averaged StdMeshers_ViscousLayers parameters
660     AverageHyp            _hyp;
661     bool                  _toSmooth;
662     _Smoother1D*          _edgeSmoother;
663     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
664     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
665
666     typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
667     TFace2NormMap            _faceNormals; // if _shape is FACE
668     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
669
670     Handle(ShapeAnalysis_Surface) _offsetSurf;
671     _LayerEdge*                   _edgeForOffset;
672
673     _SolidData*            _data; // parent SOLID
674
675     _LayerEdge*      operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
676     size_t           size() const { return _edges.size(); }
677     TopAbs_ShapeEnum ShapeType() const
678     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
679     TopAbs_ShapeEnum SWOLType() const
680     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
681     bool             HasC1( const _EdgesOnShape* other ) const
682     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
683     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
684     _SolidData&      GetData() const { return *_data; }
685
686     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
687   };
688
689   //--------------------------------------------------------------------------------
690   /*!
691    * \brief Convex FACE whose radius of curvature is less than the thickness of
692    *        layers. It is used to detect distortion of prisms based on a convex
693    *        FACE and to update normals to enable further increasing the thickness
694    */
695   struct _ConvexFace
696   {
697     TopoDS_Face                     _face;
698
699     // edges whose _simplices are used to detect prism distortion
700     vector< _LayerEdge* >           _simplexTestEdges;
701
702     // map a sub-shape to _SolidData::_edgesOnShape
703     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
704
705     bool                            _isTooCurved;
706     bool                            _normalsFixed;
707     bool                            _normalsFixedOnBorders; // used in putOnOffsetSurface()
708
709     double GetMaxCurvature( _SolidData&         data,
710                             _EdgesOnShape&      eof,
711                             BRepLProp_SLProps&  surfProp,
712                             SMESH_MesherHelper& helper);
713
714     bool GetCenterOfCurvature( _LayerEdge*         ledge,
715                                BRepLProp_SLProps&  surfProp,
716                                SMESH_MesherHelper& helper,
717                                gp_Pnt &            center ) const;
718     bool CheckPrisms() const;
719   };
720
721   //--------------------------------------------------------------------------------
722   /*!
723    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
724    *        at inflation up to the full thickness. A detected collision
725    *        is fixed in updateNormals()
726    */
727   struct _CollisionEdges
728   {
729     _LayerEdge*           _edge;
730     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
731     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
732     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
733   };
734
735   //--------------------------------------------------------------------------------
736   /*!
737    * \brief Data of a SOLID
738    */
739   struct _SolidData
740   {
741     typedef const StdMeshers_ViscousLayers* THyp;
742     TopoDS_Shape                    _solid;
743     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
744     TGeomID                         _index; // SOLID id
745     _MeshOfSolid*                   _proxyMesh;
746     list< THyp >                    _hyps;
747     list< TopoDS_Shape >            _hypShapes;
748     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
749     set< TGeomID >                  _reversedFaceIds;
750     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
751
752     double                          _stepSize, _stepSizeCoeff, _geomSize;
753     const SMDS_MeshNode*            _stepSizeNodes[2];
754
755     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
756
757     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
758     map< TGeomID, TNode2Edge* >     _s2neMap;
759     // _LayerEdge's with underlying shapes
760     vector< _EdgesOnShape >         _edgesOnShape;
761
762     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
763     //        layers and a FACE w/o layers
764     // value: the shape (FACE or EDGE) to shrink mesh on.
765     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
766     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
767
768     // Convex FACEs whose radius of curvature is less than the thickness of layers
769     map< TGeomID, _ConvexFace >      _convexFaces;
770
771     // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
772     // the adjacent SOLID
773     set< TGeomID >                   _noShrinkShapes;
774
775     int                              _nbShapesToSmooth;
776
777     vector< _CollisionEdges >        _collisionEdges;
778     set< TGeomID >                   _concaveFaces;
779
780     double                           _maxThickness; // of all _hyps
781     double                           _minThickness; // of all _hyps
782
783     double                           _epsilon; // precision for SegTriaInter()
784
785     SMESH_MesherHelper*              _helper;
786
787     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
788                _MeshOfSolid*       m=0)
789       :_solid(s), _proxyMesh(m), _helper(0) {}
790     ~_SolidData();
791
792     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
793     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
794
795     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
796       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
797       return id2face == _convexFaces.end() ? 0 : & id2face->second;
798     }
799     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
800     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
801     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
802     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
803
804     SMESH_MesherHelper& GetHelper() const { return *_helper; }
805
806     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
807       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
808         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
809           _edgesOnShape[i]._edges[j]->Unset( flag );
810     }
811     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
812                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
813
814     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
815   };
816   //--------------------------------------------------------------------------------
817   /*!
818    * \brief Offset plane used in getNormalByOffset()
819    */
820   struct _OffsetPlane
821   {
822     gp_Pln _plane;
823     int    _faceIndex;
824     int    _faceIndexNext[2];
825     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
826     bool   _isLineOK[2];
827     _OffsetPlane() {
828       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
829     }
830     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
831                                     const TopoDS_Edge&   E,
832                                     const TopoDS_Vertex& V );
833     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
834     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
835   };
836   //--------------------------------------------------------------------------------
837   /*!
838    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
839    */
840   struct _CentralCurveOnEdge
841   {
842     bool                  _isDegenerated;
843     vector< gp_Pnt >      _curvaCenters;
844     vector< _LayerEdge* > _ledges;
845     vector< gp_XYZ >      _normals; // new normal for each of _ledges
846     vector< double >      _segLength2;
847
848     TopoDS_Edge           _edge;
849     TopoDS_Face           _adjFace;
850     bool                  _adjFaceToSmooth;
851
852     void Append( const gp_Pnt& center, _LayerEdge* ledge )
853     {
854       if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
855         return;
856       if ( _curvaCenters.size() > 0 )
857         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
858       _curvaCenters.push_back( center );
859       _ledges.push_back( ledge );
860       _normals.push_back( ledge->_normal );
861     }
862     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
863     void SetShapes( const TopoDS_Edge&  edge,
864                     const _ConvexFace&  convFace,
865                     _SolidData&         data,
866                     SMESH_MesherHelper& helper);
867   };
868   //--------------------------------------------------------------------------------
869   /*!
870    * \brief Data of node on a shrinked FACE
871    */
872   struct _SmoothNode
873   {
874     const SMDS_MeshNode*         _node;
875     vector<_Simplex>             _simplices; // for quality check
876
877     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
878
879     bool Smooth(int&                  badNb,
880                 Handle(Geom_Surface)& surface,
881                 SMESH_MesherHelper&   helper,
882                 const double          refSign,
883                 SmoothType            how,
884                 bool                  set3D);
885
886     gp_XY computeAngularPos(vector<gp_XY>& uv,
887                             const gp_XY&   uvToFix,
888                             const double   refSign );
889   };
890   struct PyDump;
891   //--------------------------------------------------------------------------------
892   /*!
893    * \brief Builder of viscous layers
894    */
895   class _ViscousBuilder
896   {
897   public:
898     _ViscousBuilder();
899     // does it's job
900     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
901                                   const TopoDS_Shape& shape);
902     // check validity of hypotheses
903     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
904                                            const TopoDS_Shape& shape );
905
906     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
907     void RestoreListeners();
908
909     // computes SMESH_ProxyMesh::SubMesh::_n2n;
910     bool MakeN2NMap( _MeshOfSolid* pm );
911
912   private:
913
914     bool findSolidsWithLayers();
915     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
916     bool findFacesWithLayers(const bool onlyWith=false);
917     void getIgnoreFaces(const TopoDS_Shape&             solid,
918                         const StdMeshers_ViscousLayers* hyp,
919                         const TopoDS_Shape&             hypShape,
920                         set<TGeomID>&                   ignoreFaces);
921     bool makeLayer(_SolidData& data);
922     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
923     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
924                       SMESH_MesherHelper& helper, _SolidData& data);
925     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
926                          const TopoDS_Face&   face,
927                          SMESH_MesherHelper&  helper,
928                          bool&                isOK,
929                          bool                 shiftInside=false);
930     bool getFaceNormalAtSingularity(const gp_XY&        uv,
931                                     const TopoDS_Face&  face,
932                                     SMESH_MesherHelper& helper,
933                                     gp_Dir&             normal );
934     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
935     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
936                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
937                               int                              nbFaces,
938                               bool                             lastNoOffset = false);
939     bool findNeiborsOnEdge(const _LayerEdge*     edge,
940                            const SMDS_MeshNode*& n1,
941                            const SMDS_MeshNode*& n2,
942                            _EdgesOnShape&        eos,
943                            _SolidData&           data);
944     void findSimplexTestEdges( _SolidData&                    data,
945                                vector< vector<_LayerEdge*> >& edgesByGeom);
946     void computeGeomSize( _SolidData& data );
947     bool findShapesToSmooth( _SolidData& data);
948     void limitStepSizeByCurvature( _SolidData&  data );
949     void limitStepSize( _SolidData&             data,
950                         const SMDS_MeshElement* face,
951                         const _LayerEdge*       maxCosinEdge );
952     void limitStepSize( _SolidData& data, const double minSize);
953     bool inflate(_SolidData& data);
954     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
955     int  invalidateBadSmooth( _SolidData&               data,
956                               SMESH_MesherHelper&       helper,
957                               vector< _LayerEdge* >&    badSmooEdges,
958                               vector< _EdgesOnShape* >& eosC1,
959                               const int                 infStep );
960     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
961     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
962                              vector< _EdgesOnShape* >& eosC1,
963                              int smooStep=0, int moveAll=false );
964     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
965     void findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
966                                                 _SolidData&         data,
967                                                 SMESH_MesherHelper& helper );
968     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
969     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
970                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
971                                  const bool isSmoothable );
972     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
973     bool updateNormalsOfConvexFaces( _SolidData&         data,
974                                      SMESH_MesherHelper& helper,
975                                      int                 stepNb );
976     void updateNormalsOfC1Vertices( _SolidData& data );
977     bool updateNormalsOfSmoothed( _SolidData&         data,
978                                   SMESH_MesherHelper& helper,
979                                   const int           nbSteps,
980                                   const double        stepSize );
981     bool isNewNormalOk( _SolidData&   data,
982                         _LayerEdge&   edge,
983                         const gp_XYZ& newNormal);
984     bool refine(_SolidData& data);
985     bool shrink(_SolidData& data);
986     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
987                               SMESH_MesherHelper& helper,
988                               const SMESHDS_SubMesh* faceSubMesh );
989     void restoreNoShrink( _LayerEdge& edge ) const;
990     void fixBadFaces(const TopoDS_Face&          F,
991                      SMESH_MesherHelper&         helper,
992                      const bool                  is2D,
993                      const int                   step,
994                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
995     bool addBoundaryElements(_SolidData& data);
996
997     bool error( const string& text, int solidID=-1 );
998     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
999
1000     // debug
1001     void makeGroupOfLE();
1002
1003     SMESH_Mesh*                _mesh;
1004     SMESH_ComputeErrorPtr      _error;
1005
1006     vector<                    _SolidData >  _sdVec;
1007     TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
1008     TopTools_MapOfShape        _shrinkedFaces;
1009
1010     int                        _tmpFaceID;
1011     PyDump*                    _pyDump;
1012   };
1013   //--------------------------------------------------------------------------------
1014   /*!
1015    * \brief Shrinker of nodes on the EDGE
1016    */
1017   class _Shrinker1D
1018   {
1019     TopoDS_Edge                   _geomEdge;
1020     vector<double>                _initU;
1021     vector<double>                _normPar;
1022     vector<const SMDS_MeshNode*>  _nodes;
1023     const _LayerEdge*             _edges[2];
1024     bool                          _done;
1025   public:
1026     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1027     void Compute(bool set3D, SMESH_MesherHelper& helper);
1028     void RestoreParams();
1029     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1030     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1031     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1032     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1033     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1034     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1035   };
1036   //--------------------------------------------------------------------------------
1037   /*!
1038    * \brief Smoother of _LayerEdge's on EDGE.
1039    */
1040   struct _Smoother1D
1041   {
1042     struct OffPnt // point of the offsetted EDGE
1043     {
1044       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1045       double      _len;    // length reached at previous inflation step
1046       double      _param;  // on EDGE
1047       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1048       gp_XYZ      _edgeDir;// EDGE tangent at _param
1049       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1050     };
1051     vector< OffPnt >   _offPoints;
1052     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1053     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1054     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1055     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1056     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1057     _EdgesOnShape&     _eos;
1058     double             _curveLen; // length of the EDGE
1059     std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1060
1061     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1062                                               _EdgesOnShape&      eos,
1063                                               SMESH_MesherHelper& helper);
1064
1065     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1066                  _EdgesOnShape&     eos )
1067       : _anaCurve( curveForSmooth ), _eos( eos )
1068     {
1069     }
1070     bool Perform(_SolidData&                    data,
1071                  Handle(ShapeAnalysis_Surface)& surface,
1072                  const TopoDS_Face&             F,
1073                  SMESH_MesherHelper&            helper );
1074
1075     void prepare(_SolidData& data );
1076
1077     void findEdgesToSmooth();
1078
1079     bool isToSmooth( int iE );
1080
1081     bool smoothAnalyticEdge( _SolidData&                    data,
1082                              Handle(ShapeAnalysis_Surface)& surface,
1083                              const TopoDS_Face&             F,
1084                              SMESH_MesherHelper&            helper);
1085     bool smoothComplexEdge( _SolidData&                    data,
1086                             Handle(ShapeAnalysis_Surface)& surface,
1087                             const TopoDS_Face&             F,
1088                             SMESH_MesherHelper&            helper);
1089     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1090                             const gp_XYZ&  edgeDir);
1091     _LayerEdge* getLEdgeOnV( bool is2nd )
1092     {
1093       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1094     }
1095     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1096
1097     void offPointsToPython() const; // debug
1098   };
1099   //--------------------------------------------------------------------------------
1100   /*!
1101    * \brief Class of temporary mesh face.
1102    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1103    * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1104    */
1105   struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1106   {
1107     const SMDS_MeshElement* _srcFace;
1108
1109     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1110                   int                                 ID,
1111                   int                                 faceID=-1,
1112                   const SMDS_MeshElement*             srcFace=0 ):
1113       SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1114     virtual SMDSAbs_EntityType  GetEntityType() const
1115     { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1116     virtual SMDSAbs_GeometryType GetGeomType()  const
1117     { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1118   };
1119   //--------------------------------------------------------------------------------
1120   /*!
1121    * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1122    */
1123   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1124   {
1125     _LayerEdge *_le1, *_le2;
1126     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1127       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1128     {
1129       myNodes[0]=_le1->_nodes[0];
1130       myNodes[1]=_le1->_nodes.back();
1131       myNodes[2]=_le2->_nodes.back();
1132       myNodes[3]=_le2->_nodes[0];
1133     }
1134     const SMDS_MeshNode* n( size_t i ) const
1135     {
1136       return myNodes[ i ];
1137     }
1138     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1139     {
1140       SMESH_TNodeXYZ p0s( myNodes[0] );
1141       SMESH_TNodeXYZ p0t( myNodes[1] );
1142       SMESH_TNodeXYZ p1t( myNodes[2] );
1143       SMESH_TNodeXYZ p1s( myNodes[3] );
1144       gp_XYZ  v0 = p0t - p0s;
1145       gp_XYZ  v1 = p1t - p1s;
1146       gp_XYZ v01 = p1s - p0s;
1147       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1148       gp_XYZ   d = v01 ^ n;
1149       d.Normalize();
1150       return d;
1151     }
1152     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1153     {
1154       myNodes[0]=le1->_nodes[0];
1155       myNodes[1]=le1->_nodes.back();
1156       myNodes[2]=le2->_nodes.back();
1157       myNodes[3]=le2->_nodes[0];
1158       return GetDir();
1159     }
1160   };
1161   //--------------------------------------------------------------------------------
1162   /*!
1163    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1164    * \warning Location of a surface is ignored
1165    */
1166   struct _NodeCoordHelper
1167   {
1168     SMESH_MesherHelper&        _helper;
1169     const TopoDS_Face&         _face;
1170     Handle(Geom_Surface)       _surface;
1171     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1172
1173     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1174       : _helper( helper ), _face( F )
1175     {
1176       if ( is2D )
1177       {
1178         TopLoc_Location loc;
1179         _surface = BRep_Tool::Surface( _face, loc );
1180       }
1181       if ( _surface.IsNull() )
1182         _fun = & _NodeCoordHelper::direct;
1183       else
1184         _fun = & _NodeCoordHelper::byUV;
1185     }
1186     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1187
1188   private:
1189     gp_XYZ direct(const SMDS_MeshNode* n) const
1190     {
1191       return SMESH_TNodeXYZ( n );
1192     }
1193     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1194     {
1195       gp_XY uv = _helper.GetNodeUV( _face, n );
1196       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1197     }
1198   };
1199
1200   //================================================================================
1201   /*!
1202    * \brief Check angle between vectors 
1203    */
1204   //================================================================================
1205
1206   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1207   {
1208     double dot = v1 * v2; // cos * |v1| * |v2|
1209     double l1  = v1.SquareMagnitude();
1210     double l2  = v2.SquareMagnitude();
1211     return (( dot * cos >= 0 ) && 
1212             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1213   }
1214
1215 } // namespace VISCOUS_3D
1216
1217
1218
1219 //================================================================================
1220 // StdMeshers_ViscousLayers hypothesis
1221 //
1222 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1223   :SMESH_Hypothesis(hypId, gen),
1224    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1225    _method( SURF_OFFSET_SMOOTH )
1226 {
1227   _name = StdMeshers_ViscousLayers::GetHypType();
1228   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1229 } // --------------------------------------------------------------------------------
1230 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1231 {
1232   if ( faceIds != _shapeIds )
1233     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1234   if ( _isToIgnoreShapes != toIgnore )
1235     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1236 } // --------------------------------------------------------------------------------
1237 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1238 {
1239   if ( thickness != _thickness )
1240     _thickness = thickness, NotifySubMeshesHypothesisModification();
1241 } // --------------------------------------------------------------------------------
1242 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1243 {
1244   if ( _nbLayers != nb )
1245     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1246 } // --------------------------------------------------------------------------------
1247 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1248 {
1249   if ( _stretchFactor != factor )
1250     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1251 } // --------------------------------------------------------------------------------
1252 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1253 {
1254   if ( _method != method )
1255     _method = method, NotifySubMeshesHypothesisModification();
1256 } // --------------------------------------------------------------------------------
1257 SMESH_ProxyMesh::Ptr
1258 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1259                                   const TopoDS_Shape& theShape,
1260                                   const bool          toMakeN2NMap) const
1261 {
1262   using namespace VISCOUS_3D;
1263   _ViscousBuilder builder;
1264   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1265   if ( err && !err->IsOK() )
1266     return SMESH_ProxyMesh::Ptr();
1267
1268   vector<SMESH_ProxyMesh::Ptr> components;
1269   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1270   for ( ; exp.More(); exp.Next() )
1271   {
1272     if ( _MeshOfSolid* pm =
1273          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1274     {
1275       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1276         if ( !builder.MakeN2NMap( pm ))
1277           return SMESH_ProxyMesh::Ptr();
1278       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1279       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1280
1281       if ( pm->_warning && !pm->_warning->IsOK() )
1282       {
1283         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1284         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1285         if ( !smError || smError->IsOK() )
1286           smError = pm->_warning;
1287       }
1288     }
1289     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1290   }
1291   switch ( components.size() )
1292   {
1293   case 0: break;
1294
1295   case 1: return components[0];
1296
1297   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1298   }
1299   return SMESH_ProxyMesh::Ptr();
1300 } // --------------------------------------------------------------------------------
1301 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1302 {
1303   save << " " << _nbLayers
1304        << " " << _thickness
1305        << " " << _stretchFactor
1306        << " " << _shapeIds.size();
1307   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1308     save << " " << _shapeIds[i];
1309   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1310   save << " " << _method;
1311   return save;
1312 } // --------------------------------------------------------------------------------
1313 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1314 {
1315   int nbFaces, faceID, shapeToTreat, method;
1316   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1317   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1318     _shapeIds.push_back( faceID );
1319   if ( load >> shapeToTreat ) {
1320     _isToIgnoreShapes = !shapeToTreat;
1321     if ( load >> method )
1322       _method = (ExtrusionMethod) method;
1323   }
1324   else {
1325     _isToIgnoreShapes = true; // old behavior
1326   }
1327   return load;
1328 } // --------------------------------------------------------------------------------
1329 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1330                                                    const TopoDS_Shape& theShape)
1331 {
1332   // TODO
1333   return false;
1334 } // --------------------------------------------------------------------------------
1335 SMESH_ComputeErrorPtr
1336 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1337                                           const TopoDS_Shape&                  theShape,
1338                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1339 {
1340   VISCOUS_3D::_ViscousBuilder builder;
1341   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1342   if ( err && !err->IsOK() )
1343     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1344   else
1345     theStatus = SMESH_Hypothesis::HYP_OK;
1346
1347   return err;
1348 }
1349 // --------------------------------------------------------------------------------
1350 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1351 {
1352   bool isIn =
1353     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1354   return IsToIgnoreShapes() ? !isIn : isIn;
1355 }
1356 // END StdMeshers_ViscousLayers hypothesis
1357 //================================================================================
1358
1359 namespace VISCOUS_3D
1360 {
1361   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1362   {
1363     gp_Vec dir;
1364     double f,l;
1365     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1366     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1367     gp_Pnt p = BRep_Tool::Pnt( fromV );
1368     double distF = p.SquareDistance( c->Value( f ));
1369     double distL = p.SquareDistance( c->Value( l ));
1370     c->D1(( distF < distL ? f : l), p, dir );
1371     if ( distL < distF ) dir.Reverse();
1372     return dir.XYZ();
1373   }
1374   //--------------------------------------------------------------------------------
1375   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1376                      SMESH_MesherHelper& helper)
1377   {
1378     gp_Vec dir;
1379     double f,l; gp_Pnt p;
1380     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1381     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1382     double u = helper.GetNodeU( E, atNode );
1383     c->D1( u, p, dir );
1384     return dir.XYZ();
1385   }
1386   //--------------------------------------------------------------------------------
1387   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1388                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1389                      double* cosin=0);
1390   //--------------------------------------------------------------------------------
1391   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1392                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1393   {
1394     double f,l;
1395     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1396     if ( c.IsNull() )
1397     {
1398       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1399       return getFaceDir( F, v, node, helper, ok );
1400     }
1401     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1402     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1403     gp_Pnt p; gp_Vec du, dv, norm;
1404     surface->D1( uv.X(),uv.Y(), p, du,dv );
1405     norm = du ^ dv;
1406
1407     double u = helper.GetNodeU( fromE, node, 0, &ok );
1408     c->D1( u, p, du );
1409     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1410     if ( o == TopAbs_REVERSED )
1411       du.Reverse();
1412
1413     gp_Vec dir = norm ^ du;
1414
1415     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1416          helper.IsClosedEdge( fromE ))
1417     {
1418       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1419       else                        c->D1( f, p, dv );
1420       if ( o == TopAbs_REVERSED )
1421         dv.Reverse();
1422       gp_Vec dir2 = norm ^ dv;
1423       dir = dir.Normalized() + dir2.Normalized();
1424     }
1425     return dir.XYZ();
1426   }
1427   //--------------------------------------------------------------------------------
1428   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1429                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1430                      bool& ok, double* cosin)
1431   {
1432     TopoDS_Face faceFrw = F;
1433     faceFrw.Orientation( TopAbs_FORWARD );
1434     //double f,l; TopLoc_Location loc;
1435     TopoDS_Edge edges[2]; // sharing a vertex
1436     size_t nbEdges = 0;
1437     {
1438       TopoDS_Vertex VV[2];
1439       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1440       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1441       {
1442         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1443         if ( SMESH_Algo::isDegenerated( e )) continue;
1444         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1445         if ( VV[1].IsSame( fromV )) {
1446           nbEdges += edges[ 0 ].IsNull();
1447           edges[ 0 ] = e;
1448         }
1449         else if ( VV[0].IsSame( fromV )) {
1450           nbEdges += edges[ 1 ].IsNull();
1451           edges[ 1 ] = e;
1452         }
1453       }
1454     }
1455     gp_XYZ dir(0,0,0), edgeDir[2];
1456     if ( nbEdges == 2 )
1457     {
1458       // get dirs of edges going fromV
1459       ok = true;
1460       for ( size_t i = 0; i < nbEdges && ok; ++i )
1461       {
1462         edgeDir[i] = getEdgeDir( edges[i], fromV );
1463         double size2 = edgeDir[i].SquareModulus();
1464         if (( ok = size2 > numeric_limits<double>::min() ))
1465           edgeDir[i] /= sqrt( size2 );
1466       }
1467       if ( !ok ) return dir;
1468
1469       // get angle between the 2 edges
1470       gp_Vec faceNormal;
1471       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1472       if ( Abs( angle ) < 5 * M_PI/180 )
1473       {
1474         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1475       }
1476       else
1477       {
1478         dir = edgeDir[0] + edgeDir[1];
1479         if ( angle < 0 )
1480           dir.Reverse();
1481       }
1482       if ( cosin ) {
1483         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1484         *cosin = Cos( angle );
1485       }
1486     }
1487     else if ( nbEdges == 1 )
1488     {
1489       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1490       if ( cosin ) *cosin = 1.;
1491     }
1492     else
1493     {
1494       ok = false;
1495     }
1496
1497     return dir;
1498   }
1499
1500   //================================================================================
1501   /*!
1502    * \brief Finds concave VERTEXes of a FACE
1503    */
1504   //================================================================================
1505
1506   bool getConcaveVertices( const TopoDS_Face&  F,
1507                            SMESH_MesherHelper& helper,
1508                            set< TGeomID >*     vertices = 0)
1509   {
1510     // check angles at VERTEXes
1511     TError error;
1512     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1513     for ( size_t iW = 0; iW < wires.size(); ++iW )
1514     {
1515       const int nbEdges = wires[iW]->NbEdges();
1516       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1517         continue;
1518       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1519       {
1520         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1521         int iE2 = ( iE1 + 1 ) % nbEdges;
1522         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1523           iE2 = ( iE2 + 1 ) % nbEdges;
1524         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1525         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1526                                         wires[iW]->Edge( iE2 ), F, V );
1527         if ( angle < -5. * M_PI / 180. )
1528         {
1529           if ( !vertices )
1530             return true;
1531           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1532         }
1533       }
1534     }
1535     return vertices ? !vertices->empty() : false;
1536   }
1537
1538   //================================================================================
1539   /*!
1540    * \brief Returns true if a FACE is bound by a concave EDGE
1541    */
1542   //================================================================================
1543
1544   bool isConcave( const TopoDS_Face&  F,
1545                   SMESH_MesherHelper& helper,
1546                   set< TGeomID >*     vertices = 0 )
1547   {
1548     bool isConcv = false;
1549     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1550     //   return true;
1551     gp_Vec2d drv1, drv2;
1552     gp_Pnt2d p;
1553     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1554     for ( ; eExp.More(); eExp.Next() )
1555     {
1556       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1557       if ( SMESH_Algo::isDegenerated( E )) continue;
1558       // check if 2D curve is concave
1559       BRepAdaptor_Curve2d curve( E, F );
1560       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1561       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1562       curve.Intervals( intervals, GeomAbs_C2 );
1563       bool isConvex = true;
1564       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1565       {
1566         double u1 = intervals( i );
1567         double u2 = intervals( i+1 );
1568         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1569         double cross = drv1 ^ drv2;
1570         if ( E.Orientation() == TopAbs_REVERSED )
1571           cross = -cross;
1572         isConvex = ( cross > -1e-9 ); // 0.1 );
1573       }
1574       if ( !isConvex )
1575       {
1576         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1577         isConcv = true;
1578         if ( vertices )
1579           break;
1580         else
1581           return true;
1582       }
1583     }
1584
1585     // check angles at VERTEXes
1586     if ( getConcaveVertices( F, helper, vertices ))
1587       isConcv = true;
1588
1589     return isConcv;
1590   }
1591
1592   //================================================================================
1593   /*!
1594    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1595    *  \param [in] face - the mesh face to treat
1596    *  \param [in] nodeOnEdge - a node on the EDGE
1597    *  \param [out] faceSize - the computed distance
1598    *  \return bool - true if faceSize computed
1599    */
1600   //================================================================================
1601
1602   bool getDistFromEdge( const SMDS_MeshElement* face,
1603                         const SMDS_MeshNode*    nodeOnEdge,
1604                         double &                faceSize )
1605   {
1606     faceSize = Precision::Infinite();
1607     bool done = false;
1608
1609     int nbN  = face->NbCornerNodes();
1610     int iOnE = face->GetNodeIndex( nodeOnEdge );
1611     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1612                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1613     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1614                                       face->GetNode( iNext[1] ) };
1615     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1616     double segLen = -1.;
1617     // look for two neighbor not in-FACE nodes of face
1618     for ( int i = 0; i < 2; ++i )
1619     {
1620       if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1621           ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1622       {
1623         // look for an in-FACE node
1624         for ( int iN = 0; iN < nbN; ++iN )
1625         {
1626           if ( iN == iOnE || iN == iNext[i] )
1627             continue;
1628           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1629           gp_XYZ v = pInFace - segEnd;
1630           if ( segLen < 0 )
1631           {
1632             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1633             segLen = segVec.Modulus();
1634           }
1635           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1636           faceSize = Min( faceSize, distToSeg );
1637           done = true;
1638         }
1639         segLen = -1;
1640       }
1641     }
1642     return done;
1643   }
1644   //================================================================================
1645   /*!
1646    * \brief Return direction of axis or revolution of a surface
1647    */
1648   //================================================================================
1649
1650   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1651                           gp_Dir &                 axis )
1652   {
1653     switch ( surface.GetType() ) {
1654     case GeomAbs_Cone:
1655     {
1656       gp_Cone cone = surface.Cone();
1657       axis = cone.Axis().Direction();
1658       break;
1659     }
1660     case GeomAbs_Sphere:
1661     {
1662       gp_Sphere sphere = surface.Sphere();
1663       axis = sphere.Position().Direction();
1664       break;
1665     }
1666     case GeomAbs_SurfaceOfRevolution:
1667     {
1668       axis = surface.AxeOfRevolution().Direction();
1669       break;
1670     }
1671     //case GeomAbs_SurfaceOfExtrusion:
1672     case GeomAbs_OffsetSurface:
1673     {
1674       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1675       return getRovolutionAxis( base->Surface(), axis );
1676     }
1677     default: return false;
1678     }
1679     return true;
1680   }
1681
1682   //--------------------------------------------------------------------------------
1683   // DEBUG. Dump intermediate node positions into a python script
1684   // HOWTO use: run python commands written in a console to see
1685   //  construction steps of viscous layers
1686 #ifdef __myDEBUG
1687   ostream* py;
1688   int      theNbPyFunc;
1689   struct PyDump
1690   {
1691     PyDump(SMESH_Mesh& m) {
1692       int tag = 3 + m.GetId();
1693       const char* fname = "/tmp/viscous.py";
1694       cout << "execfile('"<<fname<<"')"<<endl;
1695       py = _pyStream = new ofstream(fname);
1696       *py << "import SMESH" << endl
1697           << "from salome.smesh import smeshBuilder" << endl
1698           << "smesh  = smeshBuilder.New()" << endl
1699           << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1700           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1701       theNbPyFunc = 0;
1702     }
1703     void Finish() {
1704       if (py) {
1705         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1706           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1707         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1708           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1709       }
1710       delete py; py=0;
1711     }
1712     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1713     struct MyStream : public ostream
1714     {
1715       template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1716     };
1717     void Pause() { py = &_mystream; }
1718     void Resume() { py = _pyStream; }
1719     MyStream _mystream;
1720     ostream* _pyStream;
1721   };
1722 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1723 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1724 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1725 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1726   void _dumpFunction(const string& fun, int ln)
1727   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1728   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1729   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1730                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1731   void _dumpCmd(const string& txt, int ln)
1732   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1733   void dumpFunctionEnd()
1734   { if (py) *py<< "  return"<< endl; }
1735   void dumpChangeNodes( const SMDS_MeshElement* f )
1736   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1737       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1738       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1739 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1740
1741 #else
1742
1743   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1744 #define dumpFunction(f) f
1745 #define dumpMove(n)
1746 #define dumpMoveComm(n,txt)
1747 #define dumpCmd(txt)
1748 #define dumpFunctionEnd()
1749 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1750 #define debugMsg( txt ) {}
1751
1752 #endif
1753 }
1754
1755 using namespace VISCOUS_3D;
1756
1757 //================================================================================
1758 /*!
1759  * \brief Constructor of _ViscousBuilder
1760  */
1761 //================================================================================
1762
1763 _ViscousBuilder::_ViscousBuilder()
1764 {
1765   _error = SMESH_ComputeError::New(COMPERR_OK);
1766   _tmpFaceID = 0;
1767 }
1768
1769 //================================================================================
1770 /*!
1771  * \brief Stores error description and returns false
1772  */
1773 //================================================================================
1774
1775 bool _ViscousBuilder::error(const string& text, int solidId )
1776 {
1777   const string prefix = string("Viscous layers builder: ");
1778   _error->myName    = COMPERR_ALGO_FAILED;
1779   _error->myComment = prefix + text;
1780   if ( _mesh )
1781   {
1782     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1783     if ( !sm && !_sdVec.empty() )
1784       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1785     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1786     {
1787       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1788       if ( smError && smError->myAlgo )
1789         _error->myAlgo = smError->myAlgo;
1790       smError = _error;
1791       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1792     }
1793     // set KO to all solids
1794     for ( size_t i = 0; i < _sdVec.size(); ++i )
1795     {
1796       if ( _sdVec[i]._index == solidId )
1797         continue;
1798       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1799       if ( !sm->IsEmpty() )
1800         continue;
1801       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1802       if ( !smError || smError->IsOK() )
1803       {
1804         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1805         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1806       }
1807     }
1808   }
1809   makeGroupOfLE(); // debug
1810
1811   return false;
1812 }
1813
1814 //================================================================================
1815 /*!
1816  * \brief At study restoration, restore event listeners used to clear an inferior
1817  *  dim sub-mesh modified by viscous layers
1818  */
1819 //================================================================================
1820
1821 void _ViscousBuilder::RestoreListeners()
1822 {
1823   // TODO
1824 }
1825
1826 //================================================================================
1827 /*!
1828  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1829  */
1830 //================================================================================
1831
1832 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1833 {
1834   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1835   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1836   for ( ; fExp.More(); fExp.Next() )
1837   {
1838     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1839     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1840
1841     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1842       continue;
1843     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1844       continue;
1845
1846     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1847       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1848
1849     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1850     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1851     while( prxIt->more() )
1852     {
1853       const SMDS_MeshElement* fSrc = srcIt->next();
1854       const SMDS_MeshElement* fPrx = prxIt->next();
1855       if ( fSrc->NbNodes() != fPrx->NbNodes())
1856         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1857       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1858         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1859     }
1860   }
1861   pm->_n2nMapComputed = true;
1862   return true;
1863 }
1864
1865 //================================================================================
1866 /*!
1867  * \brief Does its job
1868  */
1869 //================================================================================
1870
1871 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1872                                                const TopoDS_Shape& theShape)
1873 {
1874   _mesh = & theMesh;
1875
1876   // check if proxy mesh already computed
1877   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1878   if ( !exp.More() )
1879     return error("No SOLID's in theShape"), _error;
1880
1881   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1882     return SMESH_ComputeErrorPtr(); // everything already computed
1883
1884   PyDump debugDump( theMesh );
1885   _pyDump = &debugDump;
1886
1887   // TODO: ignore already computed SOLIDs 
1888   if ( !findSolidsWithLayers())
1889     return _error;
1890
1891   if ( !findFacesWithLayers() )
1892     return _error;
1893
1894   for ( size_t i = 0; i < _sdVec.size(); ++i )
1895   {
1896     size_t iSD = 0;
1897     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1898       if ( _sdVec[iSD]._before.IsEmpty() &&
1899            !_sdVec[iSD]._solid.IsNull() &&
1900            _sdVec[iSD]._n2eMap.empty() )
1901         break;
1902
1903     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1904       return _error;
1905
1906     if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1907     {
1908       _sdVec[iSD]._solid.Nullify();
1909       continue;
1910     }
1911
1912     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
1913       return _error;
1914
1915     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
1916       return _error;
1917
1918     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
1919       return _error;
1920
1921     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1922
1923     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1924     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1925       _sdVec[iSD]._before.Remove( solid );
1926   }
1927
1928   makeGroupOfLE(); // debug
1929   debugDump.Finish();
1930
1931   return _error;
1932 }
1933
1934 //================================================================================
1935 /*!
1936  * \brief Check validity of hypotheses
1937  */
1938 //================================================================================
1939
1940 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1941                                                         const TopoDS_Shape& shape )
1942 {
1943   _mesh = & mesh;
1944
1945   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1946     return SMESH_ComputeErrorPtr(); // everything already computed
1947
1948
1949   findSolidsWithLayers();
1950   bool ok = findFacesWithLayers( true );
1951
1952   // remove _MeshOfSolid's of _SolidData's
1953   for ( size_t i = 0; i < _sdVec.size(); ++i )
1954     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1955
1956   if ( !ok )
1957     return _error;
1958
1959   return SMESH_ComputeErrorPtr();
1960 }
1961
1962 //================================================================================
1963 /*!
1964  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1965  */
1966 //================================================================================
1967
1968 bool _ViscousBuilder::findSolidsWithLayers()
1969 {
1970   // get all solids
1971   TopTools_IndexedMapOfShape allSolids;
1972   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1973   _sdVec.reserve( allSolids.Extent());
1974
1975   SMESH_HypoFilter filter;
1976   for ( int i = 1; i <= allSolids.Extent(); ++i )
1977   {
1978     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1979     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1980     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1981       continue; // solid is already meshed
1982     SMESH_Algo* algo = sm->GetAlgo();
1983     if ( !algo ) continue;
1984     // TODO: check if algo is hidden
1985     const list <const SMESHDS_Hypothesis *> & allHyps =
1986       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1987     _SolidData* soData = 0;
1988     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1989     const StdMeshers_ViscousLayers* viscHyp = 0;
1990     for ( ; hyp != allHyps.end(); ++hyp )
1991       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1992       {
1993         TopoDS_Shape hypShape;
1994         filter.Init( filter.Is( viscHyp ));
1995         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1996
1997         if ( !soData )
1998         {
1999           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2000                                                                     allSolids(i),
2001                                                                     /*toCreate=*/true);
2002           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2003           soData = & _sdVec.back();
2004           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2005           soData->_helper = new SMESH_MesherHelper( *_mesh );
2006           soData->_helper->SetSubShape( allSolids(i) );
2007           _solids.Add( allSolids(i) );
2008         }
2009         soData->_hyps.push_back( viscHyp );
2010         soData->_hypShapes.push_back( hypShape );
2011       }
2012   }
2013   if ( _sdVec.empty() )
2014     return error
2015       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2016
2017   return true;
2018 }
2019
2020 //================================================================================
2021 /*!
2022  * \brief Set a _SolidData to be computed before another
2023  */
2024 //================================================================================
2025
2026 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2027 {
2028   // check possibility to set this order; get all solids before solidBefore
2029   TopTools_IndexedMapOfShape allSolidsBefore;
2030   allSolidsBefore.Add( solidBefore._solid );
2031   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2032   {
2033     int iSD = _solids.FindIndex( allSolidsBefore(i) );
2034     if ( iSD )
2035     {
2036       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2037       for ( ; soIt.More(); soIt.Next() )
2038         allSolidsBefore.Add( soIt.Value() );
2039     }
2040   }
2041   if ( allSolidsBefore.Contains( solidAfter._solid ))
2042     return false;
2043
2044   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2045     solidAfter._before.Add( allSolidsBefore(i) );
2046
2047   return true;
2048 }
2049
2050 //================================================================================
2051 /*!
2052  * \brief
2053  */
2054 //================================================================================
2055
2056 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2057 {
2058   SMESH_MesherHelper helper( *_mesh );
2059   TopExp_Explorer exp;
2060
2061   // collect all faces-to-ignore defined by hyp
2062   for ( size_t i = 0; i < _sdVec.size(); ++i )
2063   {
2064     // get faces-to-ignore defined by each hyp
2065     typedef const StdMeshers_ViscousLayers* THyp;
2066     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2067     list< TFacesOfHyp > ignoreFacesOfHyps;
2068     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2069     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2070     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2071     {
2072       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2073       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2074     }
2075
2076     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2077     const int nbHyps = _sdVec[i]._hyps.size();
2078     if ( nbHyps > 1 )
2079     {
2080       // check if two hypotheses define different parameters for the same FACE
2081       list< TFacesOfHyp >::iterator igFacesOfHyp;
2082       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2083       {
2084         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2085         THyp hyp = 0;
2086         igFacesOfHyp = ignoreFacesOfHyps.begin();
2087         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2088           if ( ! igFacesOfHyp->first.count( faceID ))
2089           {
2090             if ( hyp )
2091               return error(SMESH_Comment("Several hypotheses define "
2092                                          "Viscous Layers on the face #") << faceID );
2093             hyp = igFacesOfHyp->second;
2094           }
2095         if ( hyp )
2096           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2097         else
2098           _sdVec[i]._ignoreFaceIds.insert( faceID );
2099       }
2100
2101       // check if two hypotheses define different number of viscous layers for
2102       // adjacent faces of a solid
2103       set< int > nbLayersSet;
2104       igFacesOfHyp = ignoreFacesOfHyps.begin();
2105       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2106       {
2107         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2108       }
2109       if ( nbLayersSet.size() > 1 )
2110       {
2111         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2112         {
2113           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2114           THyp hyp1 = 0, hyp2 = 0;
2115           while( const TopoDS_Shape* face = fIt->next() )
2116           {
2117             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2118             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2119             if ( f2h != _sdVec[i]._face2hyp.end() )
2120             {
2121               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2122             }
2123           }
2124           if ( hyp1 && hyp2 &&
2125                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2126           {
2127             return error("Two hypotheses define different number of "
2128                          "viscous layers on adjacent faces");
2129           }
2130         }
2131       }
2132     } // if ( nbHyps > 1 )
2133     else
2134     {
2135       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2136     }
2137   } // loop on _sdVec
2138
2139   if ( onlyWith ) // is called to check hypotheses compatibility only
2140     return true;
2141
2142   // fill _SolidData::_reversedFaceIds
2143   for ( size_t i = 0; i < _sdVec.size(); ++i )
2144   {
2145     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2146     for ( ; exp.More(); exp.Next() )
2147     {
2148       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2149       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2150       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2151           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2152           helper.IsReversedSubMesh( face ))
2153       {
2154         _sdVec[i]._reversedFaceIds.insert( faceID );
2155       }
2156     }
2157   }
2158
2159   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2160   TopTools_IndexedMapOfShape shapes;
2161   std::string structAlgoName = "Hexa_3D";
2162   for ( size_t i = 0; i < _sdVec.size(); ++i )
2163   {
2164     shapes.Clear();
2165     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2166     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2167     {
2168       const TopoDS_Shape& edge = shapes(iE);
2169       // find 2 FACEs sharing an EDGE
2170       TopoDS_Shape FF[2];
2171       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2172       while ( fIt->more())
2173       {
2174         const TopoDS_Shape* f = fIt->next();
2175         FF[ int( !FF[0].IsNull()) ] = *f;
2176       }
2177       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2178
2179       // check presence of layers on them
2180       int ignore[2];
2181       for ( int j = 0; j < 2; ++j )
2182         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2183       if ( ignore[0] == ignore[1] )
2184         continue; // nothing interesting
2185       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2186
2187       // add EDGE to maps
2188       if ( !fWOL.IsNull())
2189       {
2190         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2191         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2192       }
2193     }
2194   }
2195
2196   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2197
2198   for ( size_t i = 0; i < _sdVec.size(); ++i )
2199   {
2200     shapes.Clear();
2201     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2202     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2203     {
2204       const TopoDS_Shape& vertex = shapes(iV);
2205       // find faces WOL sharing the vertex
2206       vector< TopoDS_Shape > facesWOL;
2207       size_t totalNbFaces = 0;
2208       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2209       while ( fIt->more())
2210       {
2211         const TopoDS_Shape* f = fIt->next();
2212         totalNbFaces++;
2213         const int fID = getMeshDS()->ShapeToIndex( *f );
2214         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2215           facesWOL.push_back( *f );
2216       }
2217       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2218         continue; // no layers at this vertex or no WOL
2219       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2220       switch ( facesWOL.size() )
2221       {
2222       case 1:
2223       {
2224         helper.SetSubShape( facesWOL[0] );
2225         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2226         {
2227           TopoDS_Shape seamEdge;
2228           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2229           while ( eIt->more() && seamEdge.IsNull() )
2230           {
2231             const TopoDS_Shape* e = eIt->next();
2232             if ( helper.IsRealSeam( *e ) )
2233               seamEdge = *e;
2234           }
2235           if ( !seamEdge.IsNull() )
2236           {
2237             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2238             break;
2239           }
2240         }
2241         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2242         break;
2243       }
2244       case 2:
2245       {
2246         // find an edge shared by 2 faces
2247         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2248         while ( eIt->more())
2249         {
2250           const TopoDS_Shape* e = eIt->next();
2251           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2252                helper.IsSubShape( *e, facesWOL[1]))
2253           {
2254             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2255           }
2256         }
2257         break;
2258       }
2259       default:
2260         return error("Not yet supported case", _sdVec[i]._index);
2261       }
2262     }
2263   }
2264
2265   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2266   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2267   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2268   for ( size_t i = 0; i < _sdVec.size(); ++i )
2269   {
2270     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2271     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2272     {
2273       const TopoDS_Shape& fWOL = e2f->second;
2274       const TGeomID     edgeID = e2f->first;
2275       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2276       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2277       if ( edge.ShapeType() != TopAbs_EDGE )
2278         continue; // shrink shape is VERTEX
2279
2280       TopoDS_Shape solid;
2281       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2282       while ( soIt->more() && solid.IsNull() )
2283       {
2284         const TopoDS_Shape* so = soIt->next();
2285         if ( !so->IsSame( _sdVec[i]._solid ))
2286           solid = *so;
2287       }
2288       if ( solid.IsNull() )
2289         continue;
2290
2291       bool noShrinkE = false;
2292       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2293       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2294       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2295       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2296       {
2297         // the adjacent SOLID has NO layers on fWOL;
2298         // shrink allowed if
2299         // - there are layers on the EDGE in the adjacent SOLID
2300         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2301         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2302         bool shrinkAllowed = (( hasWLAdj ) ||
2303                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2304         noShrinkE = !shrinkAllowed;
2305       }
2306       else if ( iSolid < _sdVec.size() )
2307       {
2308         // the adjacent SOLID has layers on fWOL;
2309         // check if SOLID's mesh is unstructured and then try to set it
2310         // to be computed after the i-th solid
2311         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2312           noShrinkE = true; // don't shrink fWOL
2313       }
2314       else
2315       {
2316         // the adjacent SOLID has NO layers at all
2317         noShrinkE = isStructured;
2318       }
2319
2320       if ( noShrinkE )
2321       {
2322         _sdVec[i]._noShrinkShapes.insert( edgeID );
2323
2324         // check if there is a collision with to-shrink-from EDGEs in iSolid
2325         // if ( iSolid < _sdVec.size() )
2326         // {
2327         //   shapes.Clear();
2328         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2329         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2330         //   {
2331         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2332         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2333         //     if ( eID == edgeID ||
2334         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2335         //          _sdVec[i]._noShrinkShapes.count( eID ))
2336         //       continue;
2337         //     for ( int is1st = 0; is1st < 2; ++is1st )
2338         //     {
2339         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2340         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2341         //       {
2342         //         return error("No way to make a conformal mesh with "
2343         //                      "the given set of faces with layers", _sdVec[i]._index);
2344         //       }
2345         //     }
2346         //   }
2347         // }
2348       }
2349
2350       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2351       // _shrinkShape2Shape is different in the adjacent SOLID
2352       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2353       {
2354         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2355         bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2356
2357         if ( iSolid < _sdVec.size() )
2358         {
2359           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2360           {
2361             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2362             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2363             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2364             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2365               noShrinkV = (( isStructured ) ||
2366                            ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2367             else
2368               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2369           }
2370           else
2371           {
2372             noShrinkV = noShrinkE;
2373           }
2374         }
2375         else
2376         {
2377           // the adjacent SOLID has NO layers at all
2378           if ( isStructured )
2379           {
2380             noShrinkV = true;
2381           }
2382           else
2383           {
2384             noShrinkV = noShrinkIfAdjMeshed =
2385               ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2386           }
2387         }
2388
2389         if ( noShrinkV && noShrinkIfAdjMeshed )
2390         {
2391           // noShrinkV if FACEs in the adjacent SOLID are meshed
2392           PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2393                                                        *_mesh, TopAbs_FACE, &solid );
2394           while ( fIt->more() )
2395           {
2396             const TopoDS_Shape* f = fIt->next();
2397             if ( !f->IsSame( fWOL ))
2398             {
2399               noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2400               break;
2401             }
2402           }
2403         }
2404         if ( noShrinkV )
2405           _sdVec[i]._noShrinkShapes.insert( vID );
2406       }
2407
2408     } // loop on _sdVec[i]._shrinkShape2Shape
2409   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2410
2411
2412     // add FACEs of other SOLIDs to _ignoreFaceIds
2413   for ( size_t i = 0; i < _sdVec.size(); ++i )
2414   {
2415     shapes.Clear();
2416     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2417
2418     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2419     {
2420       if ( !shapes.Contains( exp.Current() ))
2421         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2422     }
2423   }
2424
2425   return true;
2426 }
2427
2428 //================================================================================
2429 /*!
2430  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2431  */
2432 //================================================================================
2433
2434 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2435                                      const StdMeshers_ViscousLayers* hyp,
2436                                      const TopoDS_Shape&             hypShape,
2437                                      set<TGeomID>&                   ignoreFaceIds)
2438 {
2439   TopExp_Explorer exp;
2440
2441   vector<TGeomID> ids = hyp->GetBndShapes();
2442   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2443   {
2444     for ( size_t ii = 0; ii < ids.size(); ++ii )
2445     {
2446       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2447       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2448         ignoreFaceIds.insert( ids[ii] );
2449     }
2450   }
2451   else // FACEs with layers are given
2452   {
2453     exp.Init( solid, TopAbs_FACE );
2454     for ( ; exp.More(); exp.Next() )
2455     {
2456       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2457       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2458         ignoreFaceIds.insert( faceInd );
2459     }
2460   }
2461
2462   // ignore internal FACEs if inlets and outlets are specified
2463   if ( hyp->IsToIgnoreShapes() )
2464   {
2465     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2466     TopExp::MapShapesAndAncestors( hypShape,
2467                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2468
2469     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2470     {
2471       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2472       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2473         continue;
2474
2475       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2476       if ( nbSolids > 1 )
2477         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2478     }
2479   }
2480 }
2481
2482 //================================================================================
2483 /*!
2484  * \brief Create the inner surface of the viscous layer and prepare data for infation
2485  */
2486 //================================================================================
2487
2488 bool _ViscousBuilder::makeLayer(_SolidData& data)
2489 {
2490   // get all sub-shapes to make layers on
2491   set<TGeomID> subIds, faceIds;
2492   subIds = data._noShrinkShapes;
2493   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2494   for ( ; exp.More(); exp.Next() )
2495   {
2496     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2497     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2498       faceIds.insert( fSubM->GetId() );
2499   }
2500
2501   // make a map to find new nodes on sub-shapes shared with other SOLID
2502   map< TGeomID, TNode2Edge* >::iterator s2ne;
2503   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2504   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2505   {
2506     TGeomID shapeInd = s2s->first;
2507     for ( size_t i = 0; i < _sdVec.size(); ++i )
2508     {
2509       if ( _sdVec[i]._index == data._index ) continue;
2510       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2511       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2512            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2513       {
2514         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2515         break;
2516       }
2517     }
2518   }
2519
2520   // Create temporary faces and _LayerEdge's
2521
2522   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2523
2524   data._stepSize = Precision::Infinite();
2525   data._stepSizeNodes[0] = 0;
2526
2527   SMESH_MesherHelper helper( *_mesh );
2528   helper.SetSubShape( data._solid );
2529   helper.SetElementsOnShape( true );
2530
2531   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2532   TNode2Edge::iterator n2e2;
2533
2534   // collect _LayerEdge's of shapes they are based on
2535   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2536   const int nbShapes = getMeshDS()->MaxShapeIndex();
2537   edgesByGeom.resize( nbShapes+1 );
2538
2539   // set data of _EdgesOnShape's
2540   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2541   {
2542     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2543     while ( smIt->more() )
2544     {
2545       sm = smIt->next();
2546       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2547            !faceIds.count( sm->GetId() ))
2548         continue;
2549       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2550     }
2551   }
2552   // make _LayerEdge's
2553   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2554   {
2555     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2556     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2557     SMESH_ProxyMesh::SubMesh* proxySub =
2558       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2559
2560     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2561     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2562
2563     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2564     while ( eIt->more() )
2565     {
2566       const SMDS_MeshElement* face = eIt->next();
2567       double          faceMaxCosin = -1;
2568       _LayerEdge*     maxCosinEdge = 0;
2569       int             nbDegenNodes = 0;
2570
2571       newNodes.resize( face->NbCornerNodes() );
2572       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2573       {
2574         const SMDS_MeshNode* n = face->GetNode( i );
2575         const int      shapeID = n->getshapeId();
2576         const bool onDegenShap = helper.IsDegenShape( shapeID );
2577         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2578         if ( onDegenShap )
2579         {
2580           if ( onDegenEdge )
2581           {
2582             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2583             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2584             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2585             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2586               n = vN;
2587               nbDegenNodes++;
2588             }
2589           }
2590           else
2591           {
2592             nbDegenNodes++;
2593           }
2594         }
2595         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2596         if ( !(*n2e).second )
2597         {
2598           // add a _LayerEdge
2599           _LayerEdge* edge = new _LayerEdge();
2600           edge->_nodes.push_back( n );
2601           n2e->second = edge;
2602           edgesByGeom[ shapeID ]._edges.push_back( edge );
2603           const bool noShrink = data._noShrinkShapes.count( shapeID );
2604
2605           SMESH_TNodeXYZ xyz( n );
2606
2607           // set edge data or find already refined _LayerEdge and get data from it
2608           if (( !noShrink                                                     ) &&
2609               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2610               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2611               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2612           {
2613             _LayerEdge* foundEdge = (*n2e2).second;
2614             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2615             foundEdge->_pos.push_back( lastPos );
2616             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2617             const_cast< SMDS_MeshNode* >
2618               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2619           }
2620           else
2621           {
2622             if ( !noShrink )
2623             {
2624               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2625             }
2626             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2627               return false;
2628
2629             if ( edge->_nodes.size() < 2 )
2630               edge->Block( data );
2631               //data._noShrinkShapes.insert( shapeID );
2632           }
2633           dumpMove(edge->_nodes.back());
2634
2635           if ( edge->_cosin > faceMaxCosin )
2636           {
2637             faceMaxCosin = edge->_cosin;
2638             maxCosinEdge = edge;
2639           }
2640         }
2641         newNodes[ i ] = n2e->second->_nodes.back();
2642
2643         if ( onDegenEdge )
2644           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2645       }
2646       if ( newNodes.size() - nbDegenNodes < 2 )
2647         continue;
2648
2649       // create a temporary face
2650       const SMDS_MeshElement* newFace =
2651         new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2652       proxySub->AddElement( newFace );
2653
2654       // compute inflation step size by min size of element on a convex surface
2655       if ( faceMaxCosin > theMinSmoothCosin )
2656         limitStepSize( data, face, maxCosinEdge );
2657
2658     } // loop on 2D elements on a FACE
2659   } // loop on FACEs of a SOLID to create _LayerEdge's
2660
2661
2662   // Set _LayerEdge::_neibors
2663   TNode2Edge::iterator n2e;
2664   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2665   {
2666     _EdgesOnShape& eos = data._edgesOnShape[iS];
2667     for ( size_t i = 0; i < eos._edges.size(); ++i )
2668     {
2669       _LayerEdge* edge = eos._edges[i];
2670       TIDSortedNodeSet nearNodes;
2671       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2672       while ( fIt->more() )
2673       {
2674         const SMDS_MeshElement* f = fIt->next();
2675         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2676           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2677       }
2678       nearNodes.erase( edge->_nodes[0] );
2679       edge->_neibors.reserve( nearNodes.size() );
2680       TIDSortedNodeSet::iterator node = nearNodes.begin();
2681       for ( ; node != nearNodes.end(); ++node )
2682         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2683           edge->_neibors.push_back( n2e->second );
2684     }
2685   }
2686
2687   data._epsilon = 1e-7;
2688   if ( data._stepSize < 1. )
2689     data._epsilon *= data._stepSize;
2690
2691   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2692     return false;
2693
2694   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2695   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2696
2697   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2698   const SMDS_MeshNode* nn[2];
2699   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2700   {
2701     _EdgesOnShape& eos = data._edgesOnShape[iS];
2702     for ( size_t i = 0; i < eos._edges.size(); ++i )
2703     {
2704       _LayerEdge* edge = eos._edges[i];
2705       if ( edge->IsOnEdge() )
2706       {
2707         // get neighbor nodes
2708         bool hasData = ( edge->_2neibors->_edges[0] );
2709         if ( hasData ) // _LayerEdge is a copy of another one
2710         {
2711           nn[0] = edge->_2neibors->srcNode(0);
2712           nn[1] = edge->_2neibors->srcNode(1);
2713         }
2714         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2715         {
2716           return false;
2717         }
2718         // set neighbor _LayerEdge's
2719         for ( int j = 0; j < 2; ++j )
2720         {
2721           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2722             return error("_LayerEdge not found by src node", data._index);
2723           edge->_2neibors->_edges[j] = n2e->second;
2724         }
2725         if ( !hasData )
2726           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2727       }
2728
2729       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2730       {
2731         _Simplex& s = edge->_simplices[j];
2732         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2733         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2734       }
2735
2736       // For an _LayerEdge on a degenerated EDGE, copy some data from
2737       // a corresponding _LayerEdge on a VERTEX
2738       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2739       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2740       {
2741         // Generally we should not get here
2742         if ( eos.ShapeType() != TopAbs_EDGE )
2743           continue;
2744         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2745         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2746         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2747           continue;
2748         const _LayerEdge* vEdge = n2e->second;
2749         edge->_normal    = vEdge->_normal;
2750         edge->_lenFactor = vEdge->_lenFactor;
2751         edge->_cosin     = vEdge->_cosin;
2752       }
2753
2754     } // loop on data._edgesOnShape._edges
2755   } // loop on data._edgesOnShape
2756
2757   // fix _LayerEdge::_2neibors on EDGEs to smooth
2758   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2759   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2760   //   if ( !e2c->second.IsNull() )
2761   //   {
2762   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2763   //       data.Sort2NeiborsOnEdge( eos->_edges );
2764   //   }
2765
2766   dumpFunctionEnd();
2767   return true;
2768 }
2769
2770 //================================================================================
2771 /*!
2772  * \brief Compute inflation step size by min size of element on a convex surface
2773  */
2774 //================================================================================
2775
2776 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2777                                      const SMDS_MeshElement* face,
2778                                      const _LayerEdge*       maxCosinEdge )
2779 {
2780   int iN = 0;
2781   double minSize = 10 * data._stepSize;
2782   const int nbNodes = face->NbCornerNodes();
2783   for ( int i = 0; i < nbNodes; ++i )
2784   {
2785     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2786     const SMDS_MeshNode*  curN = face->GetNode( i );
2787     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2788          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2789     {
2790       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2791       if ( dist < minSize )
2792         minSize = dist, iN = i;
2793     }
2794   }
2795   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2796   if ( newStep < data._stepSize )
2797   {
2798     data._stepSize = newStep;
2799     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2800     data._stepSizeNodes[0] = face->GetNode( iN );
2801     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2802   }
2803 }
2804
2805 //================================================================================
2806 /*!
2807  * \brief Compute inflation step size by min size of element on a convex surface
2808  */
2809 //================================================================================
2810
2811 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2812 {
2813   if ( minSize < data._stepSize )
2814   {
2815     data._stepSize = minSize;
2816     if ( data._stepSizeNodes[0] )
2817     {
2818       double dist =
2819         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2820       data._stepSizeCoeff = data._stepSize / dist;
2821     }
2822   }
2823 }
2824
2825 //================================================================================
2826 /*!
2827  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2828  */
2829 //================================================================================
2830
2831 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2832 {
2833   SMESH_MesherHelper helper( *_mesh );
2834
2835   BRepLProp_SLProps surfProp( 2, 1e-6 );
2836   data._convexFaces.clear();
2837
2838   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2839   {
2840     _EdgesOnShape& eof = data._edgesOnShape[iS];
2841     if ( eof.ShapeType() != TopAbs_FACE ||
2842          data._ignoreFaceIds.count( eof._shapeID ))
2843       continue;
2844
2845     TopoDS_Face        F = TopoDS::Face( eof._shape );
2846     const TGeomID faceID = eof._shapeID;
2847
2848     BRepAdaptor_Surface surface( F, false );
2849     surfProp.SetSurface( surface );
2850
2851     _ConvexFace cnvFace;
2852     cnvFace._face = F;
2853     cnvFace._normalsFixed = false;
2854     cnvFace._isTooCurved = false;
2855
2856     double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2857     if ( maxCurvature > 0 )
2858     {
2859       limitStepSize( data, 0.9 / maxCurvature );
2860       findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2861     }
2862     if ( !cnvFace._isTooCurved ) continue;
2863
2864     _ConvexFace & convFace =
2865       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2866
2867     // skip a closed surface (data._convexFaces is useful anyway)
2868     bool isClosedF = false;
2869     helper.SetSubShape( F );
2870     if ( helper.HasRealSeam() )
2871     {
2872       // in the closed surface there must be a closed EDGE
2873       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2874         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2875     }
2876     if ( isClosedF )
2877     {
2878       // limit _LayerEdge::_maxLen on the FACE
2879       const double oriFactor    = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2880       const double minCurvature =
2881         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2882       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2883       if ( id2eos != cnvFace._subIdToEOS.end() )
2884       {
2885         _EdgesOnShape& eos = * id2eos->second;
2886         for ( size_t i = 0; i < eos._edges.size(); ++i )
2887         {
2888           _LayerEdge* ledge = eos._edges[ i ];
2889           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2890           surfProp.SetParameters( uv.X(), uv.Y() );
2891           if ( surfProp.IsCurvatureDefined() )
2892           {
2893             double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2894                                     surfProp.MinCurvature() * oriFactor );
2895             if ( curvature > minCurvature )
2896               ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
2897           }
2898         }
2899       }
2900       continue;
2901     }
2902
2903     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2904     // prism distortion.
2905     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2906     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2907     {
2908       // there are _LayerEdge's on the FACE it-self;
2909       // select _LayerEdge's near EDGEs
2910       _EdgesOnShape& eos = * id2eos->second;
2911       for ( size_t i = 0; i < eos._edges.size(); ++i )
2912       {
2913         _LayerEdge* ledge = eos._edges[ i ];
2914         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2915           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2916           {
2917             // do not select _LayerEdge's neighboring sharp EDGEs
2918             bool sharpNbr = false;
2919             for ( size_t iN = 0; iN < ledge->_neibors.size()  && !sharpNbr; ++iN )
2920               sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
2921             if ( !sharpNbr )
2922               convFace._simplexTestEdges.push_back( ledge );
2923             break;
2924           }
2925       }
2926     }
2927     else
2928     {
2929       // where there are no _LayerEdge's on a _ConvexFace,
2930       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2931       // so that collision of viscous internal faces is not detected by check of
2932       // intersection of _LayerEdge's with the viscous internal faces.
2933
2934       set< const SMDS_MeshNode* > usedNodes;
2935
2936       // look for _LayerEdge's with null _sWOL
2937       id2eos = convFace._subIdToEOS.begin();
2938       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2939       {
2940         _EdgesOnShape& eos = * id2eos->second;
2941         if ( !eos._sWOL.IsNull() )
2942           continue;
2943         for ( size_t i = 0; i < eos._edges.size(); ++i )
2944         {
2945           _LayerEdge* ledge = eos._edges[ i ];
2946           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2947           if ( !usedNodes.insert( srcNode ).second ) continue;
2948
2949           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2950           {
2951             usedNodes.insert( ledge->_simplices[i]._nPrev );
2952             usedNodes.insert( ledge->_simplices[i]._nNext );
2953           }
2954           convFace._simplexTestEdges.push_back( ledge );
2955         }
2956       }
2957     }
2958   } // loop on FACEs of data._solid
2959 }
2960
2961 //================================================================================
2962 /*!
2963  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2964  */
2965 //================================================================================
2966
2967 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2968 {
2969   // define allowed thickness
2970   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2971
2972
2973   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2974   // boundary inclined to the shape at a sharp angle
2975
2976   TopTools_MapOfShape edgesOfSmooFaces;
2977   SMESH_MesherHelper helper( *_mesh );
2978   bool ok = true;
2979
2980   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2981   data._nbShapesToSmooth = 0;
2982
2983   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2984   {
2985     _EdgesOnShape& eos = edgesByGeom[iS];
2986     eos._toSmooth = false;
2987     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2988       continue;
2989
2990     double tgtThick = eos._hyp.GetTotalThickness();
2991     SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
2992     while ( subIt->more() && !eos._toSmooth )
2993     {
2994       TGeomID iSub = subIt->next()->GetId();
2995       const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
2996       if ( eSub.empty() ) continue;
2997
2998       double faceSize;
2999       for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3000         if ( eSub[i]->_cosin > theMinSmoothCosin )
3001         {
3002           SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3003           while ( fIt->more() && !eos._toSmooth )
3004           {
3005             const SMDS_MeshElement* face = fIt->next();
3006             if ( face->getshapeId() == eos._shapeID &&
3007                  getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3008             {
3009               eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3010                                              tgtThick * eSub[i]->_lenFactor,
3011                                              faceSize);
3012             }
3013           }
3014         }
3015     }
3016     if ( eos._toSmooth )
3017     {
3018       for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3019         edgesOfSmooFaces.Add( eExp.Current() );
3020
3021       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3022     }
3023     data._nbShapesToSmooth += eos._toSmooth;
3024
3025   }  // check FACEs
3026
3027   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3028   {
3029     _EdgesOnShape& eos = edgesByGeom[iS];
3030     eos._edgeSmoother = NULL;
3031     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3032     if ( !eos._hyp.ToSmooth() ) continue;
3033
3034     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3035     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3036       continue;
3037
3038     double tgtThick = eos._hyp.GetTotalThickness();
3039     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3040     {
3041       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3042       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3043       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3044       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3045       double angle    = eDir.Angle( eV[0]->_normal );
3046       double cosin    = Cos( angle );
3047       double cosinAbs = Abs( cosin );
3048       if ( cosinAbs > theMinSmoothCosin )
3049       {
3050         // always smooth analytic EDGEs
3051         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3052         eos._toSmooth = ! curve.IsNull();
3053
3054         // compare tgtThick with the length of an end segment
3055         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3056         while ( eIt->more() && !eos._toSmooth )
3057         {
3058           const SMDS_MeshElement* endSeg = eIt->next();
3059           if ( endSeg->getshapeId() == (int) iS )
3060           {
3061             double segLen =
3062               SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3063             eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3064           }
3065         }
3066         if ( eos._toSmooth )
3067         {
3068           eos._edgeSmoother = new _Smoother1D( curve, eos );
3069
3070           // for ( size_t i = 0; i < eos._edges.size(); ++i )
3071           //   eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3072         }
3073       }
3074     }
3075     data._nbShapesToSmooth += eos._toSmooth;
3076
3077   } // check EDGEs
3078
3079   // Reset _cosin if no smooth is allowed by the user
3080   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3081   {
3082     _EdgesOnShape& eos = edgesByGeom[iS];
3083     if ( eos._edges.empty() ) continue;
3084
3085     if ( !eos._hyp.ToSmooth() )
3086       for ( size_t i = 0; i < eos._edges.size(); ++i )
3087         //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3088         eos._edges[i]->_lenFactor = 1;
3089   }
3090
3091
3092   // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3093
3094   TopTools_MapOfShape c1VV;
3095
3096   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3097   {
3098     _EdgesOnShape& eos = edgesByGeom[iS];
3099     if ( eos._edges.empty() ||
3100          eos.ShapeType() != TopAbs_FACE ||
3101          !eos._toSmooth )
3102       continue;
3103
3104     // check EDGEs of a FACE
3105     TopTools_MapOfShape checkedEE, allVV;
3106     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3107     while ( !smQueue.empty() )
3108     {
3109       SMESH_subMesh* sm = smQueue.front();
3110       smQueue.pop_front();
3111       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3112       while ( smIt->more() )
3113       {
3114         sm = smIt->next();
3115         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3116           allVV.Add( sm->GetSubShape() );
3117         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3118              !checkedEE.Add( sm->GetSubShape() ))
3119           continue;
3120
3121         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3122         vector<_LayerEdge*>& eE = eoe->_edges;
3123         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3124           continue;
3125
3126         bool isC1 = true; // check continuity along an EDGE
3127         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3128           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3129         if ( !isC1 )
3130           continue;
3131
3132         // check that mesh faces are C1 as well
3133         {
3134           gp_XYZ norm1, norm2;
3135           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3136           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3137           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3138             continue;
3139           while ( fIt->more() && isC1 )
3140             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3141                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3142           if ( !isC1 )
3143             continue;
3144         }
3145
3146         // add the EDGE and an adjacent FACE to _eosC1
3147         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3148         while ( const TopoDS_Shape* face = fIt->next() )
3149         {
3150           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3151           if ( !eof ) continue; // other solid
3152           if ( eos._shapeID == eof->_shapeID ) continue;
3153           if ( !eos.HasC1( eof ))
3154           {
3155             // check the FACEs
3156             eos._eosC1.push_back( eof );
3157             eof->_toSmooth = false;
3158             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3159             smQueue.push_back( eof->_subMesh );
3160           }
3161           if ( !eos.HasC1( eoe ))
3162           {
3163             eos._eosC1.push_back( eoe );
3164             eoe->_toSmooth = false;
3165             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3166           }
3167         }
3168       }
3169     }
3170     if ( eos._eosC1.empty() )
3171       continue;
3172
3173     // check VERTEXes of C1 FACEs
3174     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3175     for ( ; vIt.More(); vIt.Next() )
3176     {
3177       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3178       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3179         continue;
3180
3181       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3182       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3183       while ( const TopoDS_Shape* face = fIt->next() )
3184       {
3185         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3186         if ( !eof ) continue; // other solid
3187         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3188         if ( !isC1 )
3189           break;
3190       }
3191       if ( isC1 )
3192       {
3193         eos._eosC1.push_back( eov );
3194         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3195         c1VV.Add( eov->_shape );
3196       }
3197     }
3198
3199   } // fill _eosC1 of FACEs
3200
3201
3202   // Find C1 EDGEs
3203
3204   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3205
3206   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3207   {
3208     _EdgesOnShape& eov = edgesByGeom[iS];
3209     if ( eov._edges.empty() ||
3210          eov.ShapeType() != TopAbs_VERTEX ||
3211          c1VV.Contains( eov._shape ))
3212       continue;
3213     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3214
3215     // get directions of surrounding EDGEs
3216     dirOfEdges.clear();
3217     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3218     while ( const TopoDS_Shape* e = fIt->next() )
3219     {
3220       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3221       if ( !eoe ) continue; // other solid
3222       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3223       if ( !Precision::IsInfinite( eDir.X() ))
3224         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3225     }
3226
3227     // find EDGEs with C1 directions
3228     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3229       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3230         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3231         {
3232           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3233           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3234           if ( isC1 )
3235           {
3236             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3237             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3238             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3239             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3240             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3241             dirOfEdges[i].first = 0;
3242             dirOfEdges[j].first = 0;
3243           }
3244         }
3245   } // fill _eosC1 of VERTEXes
3246
3247
3248
3249   return ok;
3250 }
3251
3252 //================================================================================
3253 /*!
3254  * \brief initialize data of _EdgesOnShape
3255  */
3256 //================================================================================
3257
3258 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3259                                     SMESH_subMesh* sm,
3260                                     _SolidData&    data )
3261 {
3262   if ( !eos._shape.IsNull() ||
3263        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3264     return;
3265
3266   SMESH_MesherHelper helper( *_mesh );
3267
3268   eos._subMesh = sm;
3269   eos._shapeID = sm->GetId();
3270   eos._shape   = sm->GetSubShape();
3271   if ( eos.ShapeType() == TopAbs_FACE )
3272     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3273   eos._toSmooth = false;
3274   eos._data = &data;
3275
3276   // set _SWOL
3277   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3278     data._shrinkShape2Shape.find( eos._shapeID );
3279   if ( s2s != data._shrinkShape2Shape.end() )
3280     eos._sWOL = s2s->second;
3281
3282   eos._isRegularSWOL = true;
3283   if ( eos.SWOLType() == TopAbs_FACE )
3284   {
3285     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3286     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3287     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3288   }
3289
3290   // set _hyp
3291   if ( data._hyps.size() == 1 )
3292   {
3293     eos._hyp = data._hyps.back();
3294   }
3295   else
3296   {
3297     // compute average StdMeshers_ViscousLayers parameters
3298     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3299     if ( eos.ShapeType() == TopAbs_FACE )
3300     {
3301       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3302         eos._hyp = f2hyp->second;
3303     }
3304     else
3305     {
3306       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3307       while ( const TopoDS_Shape* face = fIt->next() )
3308       {
3309         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3310         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3311           eos._hyp.Add( f2hyp->second );
3312       }
3313     }
3314   }
3315
3316   // set _faceNormals
3317   if ( ! eos._hyp.UseSurfaceNormal() )
3318   {
3319     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3320     {
3321       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3322       if ( !smDS ) return;
3323       eos._faceNormals.reserve( smDS->NbElements() );
3324
3325       double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3326       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3327       for ( ; eIt->more(); )
3328       {
3329         const SMDS_MeshElement* face = eIt->next();
3330         gp_XYZ&                 norm = eos._faceNormals[face];
3331         if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3332           norm.SetCoord( 0,0,0 );
3333         norm *= oriFactor;
3334       }
3335     }
3336     else // find EOS of adjacent FACEs
3337     {
3338       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3339       while ( const TopoDS_Shape* face = fIt->next() )
3340       {
3341         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3342         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3343         if ( eos._faceEOS.back()->_shape.IsNull() )
3344           // avoid using uninitialised _shapeID in GetNormal()
3345           eos._faceEOS.back()->_shapeID = faceID;
3346       }
3347     }
3348   }
3349 }
3350
3351 //================================================================================
3352 /*!
3353  * \brief Returns normal of a face
3354  */
3355 //================================================================================
3356
3357 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3358 {
3359   bool ok = false;
3360   _EdgesOnShape* eos = 0;
3361
3362   if ( face->getshapeId() == _shapeID )
3363   {
3364     eos = this;
3365   }
3366   else
3367   {
3368     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3369       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3370         eos = _faceEOS[ iF ];
3371   }
3372
3373   if (( eos ) &&
3374       ( ok = ( eos->_faceNormals.count( face ) )))
3375   {
3376     norm = eos->_faceNormals[ face ];
3377   }
3378   else if ( !eos )
3379   {
3380     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3381               << " on _shape #" << _shapeID );
3382   }
3383   return ok;
3384 }
3385
3386
3387 //================================================================================
3388 /*!
3389  * \brief Set data of _LayerEdge needed for smoothing
3390  */
3391 //================================================================================
3392
3393 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3394                                   _EdgesOnShape&      eos,
3395                                   SMESH_MesherHelper& helper,
3396                                   _SolidData&         data)
3397 {
3398   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3399
3400   edge._len       = 0;
3401   edge._maxLen    = Precision::Infinite();
3402   edge._minAngle  = 0;
3403   edge._2neibors  = 0;
3404   edge._curvature = 0;
3405   edge._flags     = 0;
3406
3407   // --------------------------
3408   // Compute _normal and _cosin
3409   // --------------------------
3410
3411   edge._cosin     = 0;
3412   edge._lenFactor = 1.;
3413   edge._normal.SetCoord(0,0,0);
3414   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3415
3416   int totalNbFaces = 0;
3417   TopoDS_Face F;
3418   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3419   gp_Vec geomNorm;
3420   bool normOK = true;
3421
3422   const bool onShrinkShape = !eos._sWOL.IsNull();
3423   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3424                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3425
3426   // get geom FACEs the node lies on
3427   //if ( useGeometry )
3428   {
3429     set<TGeomID> faceIds;
3430     if  ( eos.ShapeType() == TopAbs_FACE )
3431     {
3432       faceIds.insert( eos._shapeID );
3433     }
3434     else
3435     {
3436       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3437       while ( fIt->more() )
3438         faceIds.insert( fIt->next()->getshapeId() );
3439     }
3440     set<TGeomID>::iterator id = faceIds.begin();
3441     for ( ; id != faceIds.end(); ++id )
3442     {
3443       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3444       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3445         continue;
3446       F = TopoDS::Face( s );
3447       face2Norm[ totalNbFaces ].first = F;
3448       totalNbFaces++;
3449     }
3450   }
3451
3452   // find _normal
3453   bool fromVonF = false;
3454   if ( useGeometry )
3455   {
3456     fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3457                  eos.SWOLType()  == TopAbs_FACE  &&
3458                  totalNbFaces > 1 );
3459
3460     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3461     {
3462       if ( eos.SWOLType() == TopAbs_EDGE )
3463       {
3464         // inflate from VERTEX along EDGE
3465         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3466       }
3467       else if ( eos.ShapeType() == TopAbs_VERTEX )
3468       {
3469         // inflate from VERTEX along FACE
3470         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3471                                    node, helper, normOK, &edge._cosin);
3472       }
3473       else
3474       {
3475         // inflate from EDGE along FACE
3476         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3477                                    node, helper, normOK);
3478       }
3479     }
3480     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3481     {
3482       if ( fromVonF )
3483         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3484
3485       int nbOkNorms = 0;
3486       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3487       {
3488         F = face2Norm[ iF ].first;
3489         geomNorm = getFaceNormal( node, F, helper, normOK );
3490         if ( !normOK ) continue;
3491         nbOkNorms++;
3492
3493         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3494           geomNorm.Reverse();
3495         face2Norm[ iF ].second = geomNorm.XYZ();
3496         edge._normal += geomNorm.XYZ();
3497       }
3498       if ( nbOkNorms == 0 )
3499         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3500
3501       if ( totalNbFaces >= 3 )
3502       {
3503         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3504       }
3505
3506       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3507       {
3508         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3509         edge._normal.SetCoord( 0,0,0 );
3510         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3511         {
3512           const TopoDS_Face& F = face2Norm[iF].first;
3513           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3514           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3515             geomNorm.Reverse();
3516           if ( normOK )
3517             face2Norm[ iF ].second = geomNorm.XYZ();
3518           edge._normal += face2Norm[ iF ].second;
3519         }
3520       }
3521     }
3522   }
3523   else // !useGeometry - get _normal using surrounding mesh faces
3524   {
3525     edge._normal = getWeigthedNormal( &edge );
3526
3527     // set<TGeomID> faceIds;
3528     //
3529     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3530     // while ( fIt->more() )
3531     // {
3532     //   const SMDS_MeshElement* face = fIt->next();
3533     //   if ( eos.GetNormal( face, geomNorm ))
3534     //   {
3535     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3536     //       continue; // use only one mesh face on FACE
3537     //     edge._normal += geomNorm.XYZ();
3538     //     totalNbFaces++;
3539     //   }
3540     // }
3541   }
3542
3543   // compute _cosin
3544   //if ( eos._hyp.UseSurfaceNormal() )
3545   {
3546     switch ( eos.ShapeType() )
3547     {
3548     case TopAbs_FACE: {
3549       edge._cosin = 0;
3550       break;
3551     }
3552     case TopAbs_EDGE: {
3553       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3554       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3555       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3556       edge._cosin      = Cos( angle );
3557       break;
3558     }
3559     case TopAbs_VERTEX: {
3560       if ( fromVonF )
3561       {
3562         getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3563                     node, helper, normOK, &edge._cosin );
3564       }
3565       else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3566       {
3567         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3568         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3569         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3570         edge._cosin      = Cos( angle );
3571         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3572           for ( int iF = 1; iF < totalNbFaces; ++iF )
3573           {
3574             F = face2Norm[ iF ].first;
3575             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3576             if ( normOK ) {
3577               double angle = inFaceDir.Angle( edge._normal );
3578               double cosin = Cos( angle );
3579               if ( Abs( cosin ) > Abs( edge._cosin ))
3580                 edge._cosin = cosin;
3581             }
3582           }
3583       }
3584       break;
3585     }
3586     default:
3587       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3588     }
3589   }
3590
3591   double normSize = edge._normal.SquareModulus();
3592   if ( normSize < numeric_limits<double>::min() )
3593     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3594
3595   edge._normal /= sqrt( normSize );
3596
3597   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3598   {
3599     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3600     edge._nodes.resize( 1 );
3601     edge._normal.SetCoord( 0,0,0 );
3602     edge.SetMaxLen( 0 );
3603   }
3604
3605   // Set the rest data
3606   // --------------------
3607
3608   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3609
3610   if ( onShrinkShape )
3611   {
3612     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3613     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3614       sm->RemoveNode( tgtNode );
3615
3616     // set initial position which is parameters on _sWOL in this case
3617     if ( eos.SWOLType() == TopAbs_EDGE )
3618     {
3619       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3620       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3621       if ( edge._nodes.size() > 1 )
3622         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3623     }
3624     else // eos.SWOLType() == TopAbs_FACE
3625     {
3626       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3627       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3628       if ( edge._nodes.size() > 1 )
3629         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3630     }
3631
3632     if ( edge._nodes.size() > 1 )
3633     {
3634       // check if an angle between a FACE with layers and SWOL is sharp,
3635       // else the edge should not inflate
3636       F.Nullify();
3637       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3638         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3639           F = face2Norm[iF].first;
3640       if ( !F.IsNull())
3641       {
3642         geomNorm = getFaceNormal( node, F, helper, normOK );
3643         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3644           geomNorm.Reverse(); // inside the SOLID
3645         if ( geomNorm * edge._normal < -0.001 )
3646         {
3647           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3648           edge._nodes.resize( 1 );
3649         }
3650         else if ( edge._lenFactor > 3 )
3651         {
3652           edge._lenFactor = 2;
3653           edge.Set( _LayerEdge::RISKY_SWOL );
3654         }
3655       }
3656     }
3657   }
3658   else
3659   {
3660     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3661
3662     if ( eos.ShapeType() == TopAbs_FACE )
3663     {
3664       double angle;
3665       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3666       {
3667         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3668         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3669       }
3670     }
3671   }
3672
3673   // Set neighbor nodes for a _LayerEdge based on EDGE
3674
3675   if ( eos.ShapeType() == TopAbs_EDGE /*||
3676        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3677   {
3678     edge._2neibors = new _2NearEdges;
3679     // target nodes instead of source ones will be set later
3680   }
3681
3682   return true;
3683 }
3684
3685 //================================================================================
3686 /*!
3687  * \brief Return normal to a FACE at a node
3688  *  \param [in] n - node
3689  *  \param [in] face - FACE
3690  *  \param [in] helper - helper
3691  *  \param [out] isOK - true or false
3692  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3693  *  \return gp_XYZ - normal
3694  */
3695 //================================================================================
3696
3697 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3698                                       const TopoDS_Face&   face,
3699                                       SMESH_MesherHelper&  helper,
3700                                       bool&                isOK,
3701                                       bool                 shiftInside)
3702 {
3703   gp_XY uv;
3704   if ( shiftInside )
3705   {
3706     // get a shifted position
3707     gp_Pnt p = SMESH_TNodeXYZ( node );
3708     gp_XYZ shift( 0,0,0 );
3709     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3710     switch ( S.ShapeType() ) {
3711     case TopAbs_VERTEX:
3712     {
3713       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3714       break;
3715     }
3716     case TopAbs_EDGE:
3717     {
3718       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3719       break;
3720     }
3721     default:
3722       isOK = false;
3723     }
3724     if ( isOK )
3725       shift.Normalize();
3726     p.Translate( shift * 1e-5 );
3727
3728     TopLoc_Location loc;
3729     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3730
3731     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3732     
3733     projector.Perform( p );
3734     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3735     {
3736       isOK = false;
3737       return p.XYZ();
3738     }
3739     Standard_Real U,V;
3740     projector.LowerDistanceParameters(U,V);
3741     uv.SetCoord( U,V );
3742   }
3743   else
3744   {
3745     uv = helper.GetNodeUV( face, node, 0, &isOK );
3746   }
3747
3748   gp_Dir normal;
3749   isOK = false;
3750
3751   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3752
3753   if ( !shiftInside &&
3754        helper.IsDegenShape( node->getshapeId() ) &&
3755        getFaceNormalAtSingularity( uv, face, helper, normal ))
3756   {
3757     isOK = true;
3758     return normal.XYZ();
3759   }
3760
3761   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3762   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3763
3764   if ( pointKind == IMPOSSIBLE &&
3765        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3766   {
3767     // probably NormEstim() failed due to a too high tolerance
3768     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3769     isOK = ( pointKind < IMPOSSIBLE );
3770   }
3771   if ( pointKind < IMPOSSIBLE )
3772   {
3773     if ( pointKind != REGULAR &&
3774          !shiftInside &&
3775          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3776     {
3777       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3778       if ( normShift * normal.XYZ() < 0. )
3779         normal = normShift;
3780     }
3781     isOK = true;
3782   }
3783
3784   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3785   {
3786     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3787
3788     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3789     while ( fIt->more() )
3790     {
3791       const SMDS_MeshElement* f = fIt->next();
3792       if ( f->getshapeId() == faceID )
3793       {
3794         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3795         if ( isOK )
3796         {
3797           TopoDS_Face ff = face;
3798           ff.Orientation( TopAbs_FORWARD );
3799           if ( helper.IsReversedSubMesh( ff ))
3800             normal.Reverse();
3801           break;
3802         }
3803       }
3804     }
3805   }
3806   return normal.XYZ();
3807 }
3808
3809 //================================================================================
3810 /*!
3811  * \brief Try to get normal at a singularity of a surface basing on it's nature
3812  */
3813 //================================================================================
3814
3815 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3816                                                   const TopoDS_Face&  face,
3817                                                   SMESH_MesherHelper& helper,
3818                                                   gp_Dir&             normal )
3819 {
3820   BRepAdaptor_Surface surface( face );
3821   gp_Dir axis;
3822   if ( !getRovolutionAxis( surface, axis ))
3823     return false;
3824
3825   double f,l, d, du, dv;
3826   f = surface.FirstUParameter();
3827   l = surface.LastUParameter();
3828   d = ( uv.X() - f ) / ( l - f );
3829   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3830   f = surface.FirstVParameter();
3831   l = surface.LastVParameter();
3832   d = ( uv.Y() - f ) / ( l - f );
3833   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3834
3835   gp_Dir refDir;
3836   gp_Pnt2d testUV = uv;
3837   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3838   double tol = 1e-5;
3839   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3840   for ( int iLoop = 0; true ; ++iLoop )
3841   {
3842     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3843     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3844       break;
3845     if ( iLoop > 20 )
3846       return false;
3847     tol /= 10.;
3848   }
3849
3850   if ( axis * refDir < 0. )
3851     axis.Reverse();
3852
3853   normal = axis;
3854
3855   return true;
3856 }
3857
3858 //================================================================================
3859 /*!
3860  * \brief Return a normal at a node weighted with angles taken by faces
3861  */
3862 //================================================================================
3863
3864 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3865 {
3866   const SMDS_MeshNode* n = edge->_nodes[0];
3867
3868   gp_XYZ resNorm(0,0,0);
3869   SMESH_TNodeXYZ p0( n ), pP, pN;
3870   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3871   {
3872     pP.Set( edge->_simplices[i]._nPrev );
3873     pN.Set( edge->_simplices[i]._nNext );
3874     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3875     double l0P = v0P.SquareMagnitude();
3876     double l0N = v0N.SquareMagnitude();
3877     double lPN = vPN.SquareMagnitude();
3878     if ( l0P < std::numeric_limits<double>::min() ||
3879          l0N < std::numeric_limits<double>::min() ||
3880          lPN < std::numeric_limits<double>::min() )
3881       continue;
3882     double lNorm = norm.SquareMagnitude();
3883     double  sin2 = lNorm / l0P / l0N;
3884     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3885
3886     double weight = sin2 * angle / lPN;
3887     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3888   }
3889
3890   return resNorm;
3891 }
3892
3893 //================================================================================
3894 /*!
3895  * \brief Return a normal at a node by getting a common point of offset planes
3896  *        defined by the FACE normals
3897  */
3898 //================================================================================
3899
3900 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3901                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3902                                            int                              nbFaces,
3903                                            bool                             lastNoOffset)
3904 {
3905   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3906
3907   gp_XYZ resNorm(0,0,0);
3908   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3909   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3910   {
3911     for ( int i = 0; i < nbFaces; ++i )
3912       resNorm += f2Normal[i].second;
3913     return resNorm;
3914   }
3915
3916   // prepare _OffsetPlane's
3917   vector< _OffsetPlane > pln( nbFaces );
3918   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3919   {
3920     pln[i]._faceIndex = i;
3921     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3922   }
3923   if ( lastNoOffset )
3924   {
3925     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3926     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3927   }
3928
3929   // intersect neighboring OffsetPlane's
3930   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3931   while ( const TopoDS_Shape* edge = edgeIt->next() )
3932   {
3933     int f1 = -1, f2 = -1;
3934     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3935       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3936         (( f1 < 0 ) ? f1 : f2 ) = i;
3937
3938     if ( f2 >= 0 )
3939       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3940   }
3941
3942   // get a common point
3943   gp_XYZ commonPnt( 0, 0, 0 );
3944   int nbPoints = 0;
3945   bool isPointFound;
3946   for ( int i = 0; i < nbFaces; ++i )
3947   {
3948     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3949     nbPoints  += isPointFound;
3950   }
3951   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3952   if ( nbPoints == 0 )
3953     return wgtNorm;
3954
3955   commonPnt /= nbPoints;
3956   resNorm = commonPnt - p0;
3957   if ( lastNoOffset )
3958     return resNorm;
3959
3960   // choose the best among resNorm and wgtNorm
3961   resNorm.Normalize();
3962   wgtNorm.Normalize();
3963   double resMinDot = std::numeric_limits<double>::max();
3964   double wgtMinDot = std::numeric_limits<double>::max();
3965   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3966   {
3967     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3968     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3969   }
3970
3971   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3972   {
3973     edge->Set( _LayerEdge::MULTI_NORMAL );
3974   }
3975
3976   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3977 }
3978
3979 //================================================================================
3980 /*!
3981  * \brief Compute line of intersection of 2 planes
3982  */
3983 //================================================================================
3984
3985 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3986                                             const TopoDS_Edge&   E,
3987                                             const TopoDS_Vertex& V )
3988 {
3989   int iNext = bool( _faceIndexNext[0] >= 0 );
3990   _faceIndexNext[ iNext ] = pln._faceIndex;
3991
3992   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3993   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3994
3995   gp_XYZ lineDir = n1 ^ n2;
3996
3997   double x = Abs( lineDir.X() );
3998   double y = Abs( lineDir.Y() );
3999   double z = Abs( lineDir.Z() );
4000
4001   int cooMax; // max coordinate
4002   if (x > y) {
4003     if (x > z) cooMax = 1;
4004     else       cooMax = 3;
4005   }
4006   else {
4007     if (y > z) cooMax = 2;
4008     else       cooMax = 3;
4009   }
4010
4011   gp_Pnt linePos;
4012   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4013   {
4014     // parallel planes - intersection is an offset of the common EDGE
4015     gp_Pnt p = BRep_Tool::Pnt( V );
4016     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4017     lineDir  = getEdgeDir( E, V );
4018   }
4019   else
4020   {
4021     // the constants in the 2 plane equations
4022     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
4023     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4024
4025     switch ( cooMax ) {
4026     case 1:
4027       linePos.SetX(  0 );
4028       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4029       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4030       break;
4031     case 2:
4032       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4033       linePos.SetY(  0 );
4034       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4035       break;
4036     case 3:
4037       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4038       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4039       linePos.SetZ(  0 );
4040     }
4041   }
4042   gp_Lin& line = _lines[ iNext ];
4043   line.SetDirection( lineDir );
4044   line.SetLocation ( linePos );
4045
4046   _isLineOK[ iNext ] = true;
4047
4048
4049   iNext = bool( pln._faceIndexNext[0] >= 0 );
4050   pln._lines        [ iNext ] = line;
4051   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4052   pln._isLineOK     [ iNext ] = true;
4053 }
4054
4055 //================================================================================
4056 /*!
4057  * \brief Computes intersection point of two _lines
4058  */
4059 //================================================================================
4060
4061 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4062                                     const TopoDS_Vertex & V) const
4063 {
4064   gp_XYZ p( 0,0,0 );
4065   isFound = false;
4066
4067   if ( NbLines() == 2 )
4068   {
4069     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4070     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4071     if ( Abs( dot01 ) > 0.05 )
4072     {
4073       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4074       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4075       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4076       isFound = true;
4077     }
4078     else
4079     {
4080       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4081       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4082       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4083       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4084       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4085       isFound = true;
4086     }
4087   }
4088
4089   return p;
4090 }
4091
4092 //================================================================================
4093 /*!
4094  * \brief Find 2 neigbor nodes of a node on EDGE
4095  */
4096 //================================================================================
4097
4098 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4099                                         const SMDS_MeshNode*& n1,
4100                                         const SMDS_MeshNode*& n2,
4101                                         _EdgesOnShape&        eos,
4102                                         _SolidData&           data)
4103 {
4104   const SMDS_MeshNode* node = edge->_nodes[0];
4105   const int        shapeInd = eos._shapeID;
4106   SMESHDS_SubMesh*   edgeSM = 0;
4107   if ( eos.ShapeType() == TopAbs_EDGE )
4108   {
4109     edgeSM = eos._subMesh->GetSubMeshDS();
4110     if ( !edgeSM || edgeSM->NbElements() == 0 )
4111       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4112   }
4113   int iN = 0;
4114   n2 = 0;
4115   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4116   while ( eIt->more() && !n2 )
4117   {
4118     const SMDS_MeshElement* e = eIt->next();
4119     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4120     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4121     if ( edgeSM )
4122     {
4123       if (!edgeSM->Contains(e)) continue;
4124     }
4125     else
4126     {
4127       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4128       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4129     }
4130     ( iN++ ? n2 : n1 ) = nNeibor;
4131   }
4132   if ( !n2 )
4133     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4134   return true;
4135 }
4136
4137 //================================================================================
4138 /*!
4139  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4140  */
4141 //================================================================================
4142
4143 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4144                                      const SMDS_MeshNode* n2,
4145                                      const _EdgesOnShape& eos,
4146                                      SMESH_MesherHelper&  helper)
4147 {
4148   if ( eos.ShapeType() != TopAbs_EDGE )
4149     return;
4150   if ( _curvature && Is( SMOOTHED_C1 ))
4151     return;
4152
4153   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4154   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4155   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4156
4157   // Set _curvature
4158
4159   double      sumLen = vec1.Modulus() + vec2.Modulus();
4160   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4161   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4162   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4163   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4164   if ( _curvature ) delete _curvature;
4165   _curvature = _Curvature::New( avgNormProj, avgLen );
4166   // if ( _curvature )
4167   //   debugMsg( _nodes[0]->GetID()
4168   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4169   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4170   //             << _curvature->lenDelta(0) );
4171
4172   // Set _plnNorm
4173
4174   if ( eos._sWOL.IsNull() )
4175   {
4176     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4177     // if ( SMESH_Algo::isDegenerated( E ))
4178     //   return;
4179     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4180     gp_XYZ plnNorm = dirE ^ _normal;
4181     double proj0   = plnNorm * vec1;
4182     double proj1   = plnNorm * vec2;
4183     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4184     {
4185       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4186       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4187     }
4188   }
4189 }
4190
4191 //================================================================================
4192 /*!
4193  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4194  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4195  */
4196 //================================================================================
4197
4198 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4199                          _EdgesOnShape&      eos,
4200                          SMESH_MesherHelper& helper )
4201 {
4202   _nodes     = other._nodes;
4203   _normal    = other._normal;
4204   _len       = 0;
4205   _lenFactor = other._lenFactor;
4206   _cosin     = other._cosin;
4207   _2neibors  = other._2neibors;
4208   _curvature = 0; std::swap( _curvature, other._curvature );
4209   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4210
4211   gp_XYZ lastPos( 0,0,0 );
4212   if ( eos.SWOLType() == TopAbs_EDGE )
4213   {
4214     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4215     _pos.push_back( gp_XYZ( u, 0, 0));
4216
4217     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4218     lastPos.SetX( u );
4219   }
4220   else // TopAbs_FACE
4221   {
4222     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4223     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4224
4225     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4226     lastPos.SetX( uv.X() );
4227     lastPos.SetY( uv.Y() );
4228   }
4229   return lastPos;
4230 }
4231
4232 //================================================================================
4233 /*!
4234  * \brief Set _cosin and _lenFactor
4235  */
4236 //================================================================================
4237
4238 void _LayerEdge::SetCosin( double cosin )
4239 {
4240   _cosin = cosin;
4241   cosin = Abs( _cosin );
4242   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4243   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4244 }
4245
4246 //================================================================================
4247 /*!
4248  * \brief Check if another _LayerEdge is a neighbor on EDGE
4249  */
4250 //================================================================================
4251
4252 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4253 {
4254   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4255           ( edge->_2neibors && edge->_2neibors->include( this )));
4256 }
4257
4258 //================================================================================
4259 /*!
4260  * \brief Fills a vector<_Simplex > 
4261  */
4262 //================================================================================
4263
4264 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4265                              vector<_Simplex>&    simplices,
4266                              const set<TGeomID>&  ingnoreShapes,
4267                              const _SolidData*    dataToCheckOri,
4268                              const bool           toSort)
4269 {
4270   simplices.clear();
4271   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4272   while ( fIt->more() )
4273   {
4274     const SMDS_MeshElement* f = fIt->next();
4275     const TGeomID    shapeInd = f->getshapeId();
4276     if ( ingnoreShapes.count( shapeInd )) continue;
4277     const int nbNodes = f->NbCornerNodes();
4278     const int  srcInd = f->GetNodeIndex( node );
4279     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4280     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4281     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4282     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4283       std::swap( nPrev, nNext );
4284     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4285   }
4286
4287   if ( toSort )
4288     SortSimplices( simplices );
4289 }
4290
4291 //================================================================================
4292 /*!
4293  * \brief Set neighbor simplices side by side
4294  */
4295 //================================================================================
4296
4297 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4298 {
4299   vector<_Simplex> sortedSimplices( simplices.size() );
4300   sortedSimplices[0] = simplices[0];
4301   size_t nbFound = 0;
4302   for ( size_t i = 1; i < simplices.size(); ++i )
4303   {
4304     for ( size_t j = 1; j < simplices.size(); ++j )
4305       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4306       {
4307         sortedSimplices[i] = simplices[j];
4308         nbFound++;
4309         break;
4310       }
4311   }
4312   if ( nbFound == simplices.size() - 1 )
4313     simplices.swap( sortedSimplices );
4314 }
4315
4316 //================================================================================
4317 /*!
4318  * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4319  */
4320 //================================================================================
4321
4322 void _ViscousBuilder::makeGroupOfLE()
4323 {
4324 #ifdef _DEBUG_
4325   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4326   {
4327     if ( _sdVec[i]._n2eMap.empty() ) continue;
4328
4329     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4330     TNode2Edge::iterator n2e;
4331     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4332     {
4333       _LayerEdge* le = n2e->second;
4334       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4335       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4336       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4337       if ( le ) {
4338         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4339                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4340       }
4341     }
4342     dumpFunctionEnd();
4343
4344     dumpFunction( SMESH_Comment("makeNormals") << i );
4345     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4346     {
4347       _LayerEdge* edge = n2e->second;
4348       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4349       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4350       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4351               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4352     }
4353     dumpFunctionEnd();
4354
4355     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4356     dumpCmd( "faceId1 = mesh.NbElements()" );
4357     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4358     for ( ; fExp.More(); fExp.Next() )
4359     {
4360       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4361       {
4362         if ( sm->NbElements() == 0 ) continue;
4363         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4364         while ( fIt->more())
4365         {
4366           const SMDS_MeshElement* e = fIt->next();
4367           SMESH_Comment cmd("mesh.AddFace([");
4368           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4369             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4370           dumpCmd( cmd );
4371         }
4372       }
4373     }
4374     dumpCmd( "faceId2 = mesh.NbElements()" );
4375     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4376              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4377              << "'%s-%s' % (faceId1+1, faceId2))");
4378     dumpFunctionEnd();
4379   }
4380 #endif
4381 }
4382
4383 //================================================================================
4384 /*!
4385  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4386  */
4387 //================================================================================
4388
4389 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4390 {
4391   data._geomSize = Precision::Infinite();
4392   double intersecDist;
4393   const SMDS_MeshElement* face;
4394   SMESH_MesherHelper helper( *_mesh );
4395
4396   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4397     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4398                                            data._proxyMesh->GetFaces( data._solid )));
4399
4400   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4401   {
4402     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4403     if ( eos._edges.empty() )
4404       continue;
4405     // get neighbor faces, intersection with which should not be considered since
4406     // collisions are avoided by means of smoothing
4407     set< TGeomID > neighborFaces;
4408     if ( eos._hyp.ToSmooth() )
4409     {
4410       SMESH_subMeshIteratorPtr subIt =
4411         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4412       while ( subIt->more() )
4413       {
4414         SMESH_subMesh* sm = subIt->next();
4415         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4416         while ( const TopoDS_Shape* face = fIt->next() )
4417           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4418       }
4419     }
4420     // find intersections
4421     double thinkness = eos._hyp.GetTotalThickness();
4422     for ( size_t i = 0; i < eos._edges.size(); ++i )
4423     {
4424       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4425       eos._edges[i]->SetMaxLen( thinkness );
4426       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4427       if ( intersecDist > 0 && face )
4428       {
4429         data._geomSize = Min( data._geomSize, intersecDist );
4430         if ( !neighborFaces.count( face->getshapeId() ))
4431           eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4432       }
4433     }
4434   }
4435
4436   data._maxThickness = 0;
4437   data._minThickness = 1e100;
4438   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4439   for ( ; hyp != data._hyps.end(); ++hyp )
4440   {
4441     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4442     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4443   }
4444
4445   // Limit inflation step size by geometry size found by intersecting
4446   // normals of _LayerEdge's with mesh faces
4447   if ( data._stepSize > 0.3 * data._geomSize )
4448     limitStepSize( data, 0.3 * data._geomSize );
4449
4450   if ( data._stepSize > data._minThickness )
4451     limitStepSize( data, data._minThickness );
4452
4453
4454   // -------------------------------------------------------------------------
4455   // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4456   // so no need in detecting intersection at each inflation step
4457   // -------------------------------------------------------------------------
4458
4459   int nbSteps = data._maxThickness / data._stepSize;
4460   if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4461     return;
4462
4463   vector< const SMDS_MeshElement* > closeFaces;
4464   int nbDetected = 0;
4465
4466   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4467   {
4468     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4469     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4470       continue;
4471
4472     for ( size_t i = 0; i < eos.size(); ++i )
4473     {
4474       SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4475       double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4476       closeFaces.clear();
4477       searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4478
4479       bool toIgnore = true;
4480       for ( size_t iF = 0; iF < closeFaces.size()  && toIgnore; ++iF )
4481         if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4482                              data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4483         {
4484           // check if a _LayerEdge will inflate in a direction opposite to a direction
4485           // toward a close face
4486           bool allBehind = true;
4487           for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes()  && allBehind; ++iN )
4488           {
4489             SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4490             allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4491           }
4492           toIgnore = allBehind;
4493         }
4494
4495
4496       if ( toIgnore ) // no need to detect intersection
4497       {
4498         eos[i]->Set( _LayerEdge::INTERSECTED );
4499         ++nbDetected;
4500       }
4501     }
4502   }
4503
4504   debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4505
4506   return;
4507 }
4508
4509 //================================================================================
4510 /*!
4511  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4512  */
4513 //================================================================================
4514
4515 bool _ViscousBuilder::inflate(_SolidData& data)
4516 {
4517   SMESH_MesherHelper helper( *_mesh );
4518
4519   const double tgtThick = data._maxThickness;
4520
4521   if ( data._stepSize < 1. )
4522     data._epsilon = data._stepSize * 1e-7;
4523
4524   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4525   _pyDump->Pause();
4526
4527   findCollisionEdges( data, helper );
4528
4529   limitMaxLenByCurvature( data, helper );
4530
4531   _pyDump->Resume();
4532
4533   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4534   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4535     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4536          data._edgesOnShape[i]._edges.size() > 0 &&
4537          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4538     {
4539       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4540       data._edgesOnShape[i]._edges[0]->Block( data );
4541     }
4542
4543   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4544
4545   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4546   int nbSteps = 0, nbRepeats = 0;
4547   while ( avgThick < 0.99 )
4548   {
4549     // new target length
4550     double prevThick = curThick;
4551     curThick += data._stepSize;
4552     if ( curThick > tgtThick )
4553     {
4554       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4555       nbRepeats++;
4556     }
4557
4558     double stepSize = curThick - prevThick;
4559     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4560
4561     // Elongate _LayerEdge's
4562     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4563     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4564     {
4565       _EdgesOnShape& eos = data._edgesOnShape[iS];
4566       if ( eos._edges.empty() ) continue;
4567
4568       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4569       for ( size_t i = 0; i < eos._edges.size(); ++i )
4570       {
4571         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4572       }
4573     }
4574     dumpFunctionEnd();
4575
4576     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4577       return false;
4578
4579     // Improve and check quality
4580     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4581     {
4582       if ( nbSteps > 0 )
4583       {
4584 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4585         debugMsg("NOT INVALIDATED STEP!");
4586         return error("Smoothing failed", data._index);
4587 #endif
4588         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4589         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4590         {
4591           _EdgesOnShape& eos = data._edgesOnShape[iS];
4592           for ( size_t i = 0; i < eos._edges.size(); ++i )
4593             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4594         }
4595         dumpFunctionEnd();
4596       }
4597       break; // no more inflating possible
4598     }
4599     nbSteps++;
4600
4601     // Evaluate achieved thickness
4602     avgThick = 0;
4603     int nbActiveEdges = 0;
4604     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4605     {
4606       _EdgesOnShape& eos = data._edgesOnShape[iS];
4607       if ( eos._edges.empty() ) continue;
4608
4609       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4610       for ( size_t i = 0; i < eos._edges.size(); ++i )
4611       {
4612         if ( eos._edges[i]->_nodes.size() > 1 )
4613           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4614         else
4615           avgThick    += shapeTgtThick;
4616         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4617       }
4618     }
4619     avgThick /= data._n2eMap.size();
4620     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4621
4622 #ifdef BLOCK_INFLATION
4623     if ( nbActiveEdges == 0 )
4624     {
4625       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4626       break;
4627     }
4628 #else
4629     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4630     {
4631       debugMsg( "-- Stop inflation since "
4632                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4633                 << tgtThick * avgThick << " ) * " << safeFactor );
4634       break;
4635     }
4636 #endif
4637
4638     // new step size
4639     limitStepSize( data, 0.25 * distToIntersection );
4640     if ( data._stepSizeNodes[0] )
4641       data._stepSize = data._stepSizeCoeff *
4642         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4643
4644   } // while ( avgThick < 0.99 )
4645
4646   if ( nbSteps == 0 )
4647     return error("failed at the very first inflation step", data._index);
4648
4649   if ( avgThick < 0.99 )
4650   {
4651     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4652     {
4653       data._proxyMesh->_warning.reset
4654         ( new SMESH_ComputeError (COMPERR_WARNING,
4655                                   SMESH_Comment("Thickness ") << tgtThick <<
4656                                   " of viscous layers not reached,"
4657                                   " average reached thickness is " << avgThick*tgtThick));
4658     }
4659   }
4660
4661   // Restore position of src nodes moved by inflation on _noShrinkShapes
4662   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4663   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4664   {
4665     _EdgesOnShape& eos = data._edgesOnShape[iS];
4666     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4667       for ( size_t i = 0; i < eos._edges.size(); ++i )
4668       {
4669         restoreNoShrink( *eos._edges[ i ] );
4670       }
4671   }
4672   dumpFunctionEnd();
4673
4674   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4675 }
4676
4677 //================================================================================
4678 /*!
4679  * \brief Improve quality of layer inner surface and check intersection
4680  */
4681 //================================================================================
4682
4683 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4684                                      const int   infStep,
4685                                      double &    distToIntersection)
4686 {
4687   if ( data._nbShapesToSmooth == 0 )
4688     return true; // no shapes needing smoothing
4689
4690   bool moved, improved;
4691   double vol;
4692   vector< _LayerEdge* >    movedEdges, badEdges;
4693   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4694   vector< bool >           isConcaveFace;
4695
4696   SMESH_MesherHelper helper(*_mesh);
4697   Handle(ShapeAnalysis_Surface) surface;
4698   TopoDS_Face F;
4699
4700   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4701   {
4702     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4703
4704     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4705     {
4706       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4707       if ( !eos._toSmooth ||
4708            eos.ShapeType() != shapeType ||
4709            eos._edges.empty() )
4710         continue;
4711
4712       // already smoothed?
4713       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4714       // if ( !toSmooth ) continue;
4715
4716       if ( !eos._hyp.ToSmooth() )
4717       {
4718         // smooth disabled by the user; check validy only
4719         if ( !isFace ) continue;
4720         badEdges.clear();
4721         for ( size_t i = 0; i < eos._edges.size(); ++i )
4722         {
4723           _LayerEdge* edge = eos._edges[i];
4724           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4725             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4726             {
4727               // debugMsg( "-- Stop inflation. Bad simplex ("
4728               //           << " "<< edge->_nodes[0]->GetID()
4729               //           << " "<< edge->_nodes.back()->GetID()
4730               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4731               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4732               // return false;
4733               badEdges.push_back( edge );
4734             }
4735         }
4736         if ( !badEdges.empty() )
4737         {
4738           eosC1.resize(1);
4739           eosC1[0] = &eos;
4740           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4741           if ( nbBad > 0 )
4742             return false;
4743         }
4744         continue; // goto the next EDGE or FACE
4745       }
4746
4747       // prepare data
4748       if ( eos.SWOLType() == TopAbs_FACE )
4749       {
4750         if ( !F.IsSame( eos._sWOL )) {
4751           F = TopoDS::Face( eos._sWOL );
4752           helper.SetSubShape( F );
4753           surface = helper.GetSurface( F );
4754         }
4755       }
4756       else
4757       {
4758         F.Nullify(); surface.Nullify();
4759       }
4760       const TGeomID sInd = eos._shapeID;
4761
4762       // perform smoothing
4763
4764       if ( eos.ShapeType() == TopAbs_EDGE )
4765       {
4766         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4767
4768         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4769         {
4770           // smooth on EDGE's (normally we should not get here)
4771           int step = 0;
4772           do {
4773             moved = false;
4774             for ( size_t i = 0; i < eos._edges.size(); ++i )
4775             {
4776               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4777             }
4778             dumpCmd( SMESH_Comment("# end step ")<<step);
4779           }
4780           while ( moved && step++ < 5 );
4781         }
4782         dumpFunctionEnd();
4783       }
4784
4785       else // smooth on FACE
4786       {
4787         eosC1.clear();
4788         eosC1.push_back( & eos );
4789         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4790
4791         movedEdges.clear();
4792         isConcaveFace.resize( eosC1.size() );
4793         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4794         {
4795           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4796           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4797           for ( size_t i = 0; i < edges.size(); ++i )
4798             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4799                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4800               movedEdges.push_back( edges[i] );
4801
4802           makeOffsetSurface( *eosC1[ iEOS ], helper );
4803         }
4804
4805         int step = 0, stepLimit = 5, nbBad = 0;
4806         while (( ++step <= stepLimit ) || improved )
4807         {
4808           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4809                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4810           int oldBadNb = nbBad;
4811           badEdges.clear();
4812
4813 #ifdef INCREMENTAL_SMOOTH
4814           bool findBest = false; // ( step == stepLimit );
4815           for ( size_t i = 0; i < movedEdges.size(); ++i )
4816           {
4817             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4818             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4819               badEdges.push_back( movedEdges[i] );
4820           }
4821 #else
4822           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4823           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4824           {
4825             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4826             for ( size_t i = 0; i < edges.size(); ++i )
4827             {
4828               edges[i]->Unset( _LayerEdge::SMOOTHED );
4829               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4830                 badEdges.push_back( eos._edges[i] );
4831             }
4832           }
4833 #endif
4834           nbBad = badEdges.size();
4835
4836           if ( nbBad > 0 )
4837             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4838
4839           if ( !badEdges.empty() && step >= stepLimit / 2 )
4840           {
4841             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4842               stepLimit = 9;
4843
4844             // resolve hard smoothing situation around concave VERTEXes
4845             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4846             {
4847               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4848               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4849                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4850                                                          step, badEdges );
4851             }
4852             // look for the best smooth of _LayerEdge's neighboring badEdges
4853             nbBad = 0;
4854             for ( size_t i = 0; i < badEdges.size(); ++i )
4855             {
4856               _LayerEdge* ledge = badEdges[i];
4857               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4858               {
4859                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4860                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4861               }
4862               ledge->Unset( _LayerEdge::SMOOTHED );
4863               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4864             }
4865             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4866           }
4867
4868           if ( nbBad == oldBadNb  &&
4869                nbBad > 0 &&
4870                step < stepLimit ) // smooth w/o check of validity
4871           {
4872             dumpFunctionEnd();
4873             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4874                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4875             for ( size_t i = 0; i < movedEdges.size(); ++i )
4876             {
4877               movedEdges[i]->SmoothWoCheck();
4878             }
4879             if ( stepLimit < 9 )
4880               stepLimit++;
4881           }
4882
4883           improved = ( nbBad < oldBadNb );
4884
4885           dumpFunctionEnd();
4886
4887           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4888             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4889             {
4890               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4891             }
4892
4893         } // smoothing steps
4894
4895         // project -- to prevent intersections or fix bad simplices
4896         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4897         {
4898           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4899             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4900         }
4901
4902         //if ( !badEdges.empty() )
4903         {
4904           badEdges.clear();
4905           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4906           {
4907             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4908             {
4909               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4910
4911               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4912               edge->CheckNeiborsOnBoundary( & badEdges );
4913               if (( nbBad > 0 ) ||
4914                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4915               {
4916                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4917                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4918                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4919                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4920                   {
4921                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4922                              << " "<< tgtXYZ._node->GetID()
4923                              << " "<< edge->_simplices[j]._nPrev->GetID()
4924                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4925                     badEdges.push_back( edge );
4926                     break;
4927                   }
4928               }
4929             }
4930           }
4931
4932           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4933           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4934
4935           if ( nbBad > 0 )
4936             return false;
4937         }
4938
4939       } // // smooth on FACE's
4940     } // loop on shapes
4941   } // smooth on [ EDGEs, FACEs ]
4942
4943   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4944   eosC1.resize(1);
4945   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4946   {
4947     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4948     if ( eos.ShapeType() == TopAbs_FACE ||
4949          eos._edges.empty() ||
4950          !eos._sWOL.IsNull() )
4951       continue;
4952
4953     badEdges.clear();
4954     for ( size_t i = 0; i < eos._edges.size(); ++i )
4955     {
4956       _LayerEdge*      edge = eos._edges[i];
4957       if ( edge->_nodes.size() < 2 ) continue;
4958       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4959       //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
4960       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4961       //const gp_XYZ& prevXYZ = edge->PrevPos();
4962       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4963         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4964         {
4965           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4966                    << " "<< tgtXYZ._node->GetID()
4967                    << " "<< edge->_simplices[j]._nPrev->GetID()
4968                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4969           badEdges.push_back( edge );
4970           break;
4971         }
4972     }
4973
4974     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4975     eosC1[0] = &eos;
4976     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4977     if ( nbBad > 0 )
4978       return false;
4979   }
4980
4981
4982   // Check if the last segments of _LayerEdge intersects 2D elements;
4983   // checked elements are either temporary faces or faces on surfaces w/o the layers
4984
4985   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4986     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4987                                            data._proxyMesh->GetFaces( data._solid )) );
4988
4989 #ifdef BLOCK_INFLATION
4990   const bool toBlockInfaltion = true;
4991 #else
4992   const bool toBlockInfaltion = false;
4993 #endif
4994   distToIntersection = Precision::Infinite();
4995   double dist;
4996   const SMDS_MeshElement* intFace = 0;
4997   const SMDS_MeshElement* closestFace = 0;
4998   _LayerEdge* le = 0;
4999   bool is1stBlocked = true; // dbg
5000   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5001   {
5002     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5003     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5004       continue;
5005     for ( size_t i = 0; i < eos._edges.size(); ++i )
5006     {
5007       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5008            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5009         continue;
5010       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5011       {
5012         return false;
5013         // commented due to "Illegal hash-positionPosition" error in NETGEN
5014         // on Debian60 on viscous_layers_01/B2 case
5015         // Collision; try to deflate _LayerEdge's causing it
5016         // badEdges.clear();
5017         // badEdges.push_back( eos._edges[i] );
5018         // eosC1[0] = & eos;
5019         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5020         // if ( nbBad > 0 )
5021         //   return false;
5022
5023         // badEdges.clear();
5024         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5025         // {
5026         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5027         //   {
5028         //     const SMDS_MeshElement* srcFace =
5029         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5030         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5031         //     while ( nIt->more() )
5032         //     {
5033         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5034         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5035         //       if ( n2e != data._n2eMap.end() )
5036         //         badEdges.push_back( n2e->second );
5037         //     }
5038         //     eosC1[0] = eof;
5039         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5040         //     if ( nbBad > 0 )
5041         //       return false;
5042         //   }
5043         // }
5044         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5045         //   return false;
5046         // else
5047         //   continue;
5048       }
5049       if ( !intFace )
5050       {
5051         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5052         debugMsg( msg );
5053         continue;
5054       }
5055
5056       const bool isShorterDist = ( distToIntersection > dist );
5057       if ( toBlockInfaltion || isShorterDist )
5058       {
5059         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5060         // lying on this _ConvexFace
5061         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5062           if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5063             continue;
5064
5065         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5066         // ( avoid limiting the thickness on the case of issue 22576)
5067         if ( intFace->getshapeId() == eos._shapeID  )
5068           continue;
5069
5070         // ignore intersection with intFace of an adjacent FACE
5071         if ( dist > 0.1 * eos._edges[i]->_len )
5072         {
5073           bool toIgnore = false;
5074           if (  eos._toSmooth )
5075           {
5076             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5077             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5078             {
5079               TopExp_Explorer sub( eos._shape,
5080                                    eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5081               for ( ; !toIgnore && sub.More(); sub.Next() )
5082                 // is adjacent - has a common EDGE or VERTEX
5083                 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5084
5085               if ( toIgnore ) // check angle between normals
5086               {
5087                 gp_XYZ normal;
5088                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5089                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
5090               }
5091             }
5092           }
5093           if ( !toIgnore ) // check if the edge is a neighbor of intFace
5094           {
5095             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
5096             {
5097               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5098               toIgnore = ( nInd >= 0 );
5099             }
5100           }
5101           if ( toIgnore )
5102             continue;
5103         }
5104
5105         // intersection not ignored
5106
5107         if ( toBlockInfaltion &&
5108              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5109         {
5110           if ( is1stBlocked ) { is1stBlocked = false; // debug
5111             dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5112           }
5113           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5114           eos._edges[i]->Block( data );                  // not to inflate
5115
5116           //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5117           {
5118             // block _LayerEdge's, on top of which intFace is
5119             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5120             {
5121               const SMDS_MeshElement* srcFace = f->_srcFace;
5122               SMDS_ElemIteratorPtr        nIt = srcFace->nodesIterator();
5123               while ( nIt->more() )
5124               {
5125                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5126                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5127                 if ( n2e != data._n2eMap.end() )
5128                   n2e->second->Block( data );
5129               }
5130             }
5131           }
5132         }
5133
5134         if ( isShorterDist )
5135         {
5136           distToIntersection = dist;
5137           le = eos._edges[i];
5138           closestFace = intFace;
5139         }
5140
5141       } // if ( toBlockInfaltion || isShorterDist )
5142     } // loop on eos._edges
5143   } // loop on data._edgesOnShape
5144
5145   if ( !is1stBlocked )
5146     dumpFunctionEnd();
5147
5148   if ( closestFace && le )
5149   {
5150 #ifdef __myDEBUG
5151     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5152     cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5153          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5154          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5155          << ") distance = " << distToIntersection<< endl;
5156 #endif
5157   }
5158
5159   return true;
5160 }
5161
5162 //================================================================================
5163 /*!
5164  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5165  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5166  *  \return int - resulting nb of bad _LayerEdge's
5167  */
5168 //================================================================================
5169
5170 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5171                                           SMESH_MesherHelper&       helper,
5172                                           vector< _LayerEdge* >&    badSmooEdges,
5173                                           vector< _EdgesOnShape* >& eosC1,
5174                                           const int                 infStep )
5175 {
5176   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5177
5178   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5179
5180   enum {
5181     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5182     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5183     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5184   };
5185   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5186
5187   double vol;
5188   bool haveInvalidated = true;
5189   while ( haveInvalidated )
5190   {
5191     haveInvalidated = false;
5192     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5193     {
5194       _LayerEdge*   edge = badSmooEdges[i];
5195       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5196       edge->Set( ADDED );
5197       bool invalidated = false;
5198       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5199       {
5200         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5201         edge->Block( data );
5202         edge->Set( INVALIDATED );
5203         edge->Unset( TO_INVALIDATE );
5204         invalidated = true;
5205         haveInvalidated = true;
5206       }
5207
5208       // look for _LayerEdge's of bad _simplices
5209       int nbBad = 0;
5210       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5211       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5212       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5213       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5214       {
5215         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5216             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5217           continue;
5218
5219         bool isBad = true;
5220         _LayerEdge* ee[2] = { 0,0 };
5221         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5222           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5223             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5224
5225         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5226         while ( maxNbSteps > edge->NbSteps() && isBad )
5227         {
5228           --maxNbSteps;
5229           for ( int iE = 0; iE < 2; ++iE )
5230           {
5231             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5232                  ee[ iE ]->NbSteps() > 1 )
5233             {
5234               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5235               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5236               ee[ iE ]->Block( data );
5237               ee[ iE ]->Set( INVALIDATED );
5238               haveInvalidated = true;
5239             }
5240           }
5241           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5242               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5243             isBad = false;
5244         }
5245         nbBad += isBad;
5246         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5247         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5248         ee[0]->Set( ADDED );
5249         ee[1]->Set( ADDED );
5250         if ( isBad )
5251         {
5252           ee[0]->Set( TO_INVALIDATE );
5253           ee[1]->Set( TO_INVALIDATE );
5254         }
5255       }
5256
5257       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5258       {
5259         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5260         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5261         edge->Block( data );
5262         edge->Set( INVALIDATED );
5263         edge->Unset( TO_INVALIDATE );
5264         haveInvalidated = true;
5265       }
5266     } // loop on badSmooEdges
5267   } // while ( haveInvalidated )
5268
5269   // re-smooth on analytical EDGEs
5270   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5271   {
5272     _LayerEdge* edge = badSmooEdges[i];
5273     if ( !edge->Is( INVALIDATED )) continue;
5274
5275     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5276     if ( eos->ShapeType() == TopAbs_VERTEX )
5277     {
5278       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5279       while ( const TopoDS_Shape* e = eIt->next() )
5280         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5281           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5282           {
5283             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5284             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5285             //   F       = TopoDS::Face( eoe->_sWOL );
5286             //   surface = helper.GetSurface( F );
5287             // }
5288             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5289             eoe->_edgeSmoother->_anaCurve.Nullify();
5290           }
5291     }
5292   }
5293
5294
5295   // check result of invalidation
5296
5297   int nbBad = 0;
5298   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5299   {
5300     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5301     {
5302       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5303       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5304       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5305       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5306       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5307         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5308         {
5309           ++nbBad;
5310           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5311                    << " "<< tgtXYZ._node->GetID()
5312                    << " "<< edge->_simplices[j]._nPrev->GetID()
5313                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5314         }
5315     }
5316   }
5317   dumpFunctionEnd();
5318
5319   return nbBad;
5320 }
5321
5322 //================================================================================
5323 /*!
5324  * \brief Create an offset surface
5325  */
5326 //================================================================================
5327
5328 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5329 {
5330   if ( eos._offsetSurf.IsNull() ||
5331        eos._edgeForOffset == 0 ||
5332        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5333     return;
5334
5335   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5336
5337   // find offset
5338   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5339   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5340   double offset = baseSurface->Gap();
5341
5342   eos._offsetSurf.Nullify();
5343
5344   try
5345   {
5346     BRepOffsetAPI_MakeOffsetShape offsetMaker;
5347     offsetMaker.PerformByJoin( eos._shape, -offset, Precision::Confusion() );
5348     if ( !offsetMaker.IsDone() ) return;
5349
5350     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5351     if ( !fExp.More() ) return;
5352
5353     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5354     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5355     if ( surf.IsNull() ) return;
5356
5357     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5358   }
5359   catch ( Standard_Failure )
5360   {
5361   }
5362 }
5363
5364 //================================================================================
5365 /*!
5366  * \brief Put nodes of a curved FACE to its offset surface
5367  */
5368 //================================================================================
5369
5370 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5371                                           int                       infStep,
5372                                           vector< _EdgesOnShape* >& eosC1,
5373                                           int                       smooStep,
5374                                           int                       moveAll )
5375 {
5376   _EdgesOnShape * eof = & eos;
5377   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5378   {
5379     eof = 0;
5380     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5381     {
5382       if ( eosC1[i]->_offsetSurf.IsNull() ||
5383            eosC1[i]->ShapeType() != TopAbs_FACE ||
5384            eosC1[i]->_edgeForOffset == 0 ||
5385            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5386         continue;
5387       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5388         eof = eosC1[i];
5389     }
5390   }
5391   if ( !eof ||
5392        eof->_offsetSurf.IsNull() ||
5393        eof->ShapeType() != TopAbs_FACE ||
5394        eof->_edgeForOffset == 0 ||
5395        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5396     return;
5397
5398   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5399   for ( size_t i = 0; i < eos._edges.size(); ++i )
5400   {
5401     _LayerEdge* edge = eos._edges[i];
5402     edge->Unset( _LayerEdge::MARKED );
5403     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5404       continue;
5405     if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5406     {
5407       if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5408         continue;
5409     }
5410     else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5411       continue;
5412
5413     int nbBlockedAround = 0;
5414     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5415       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5416     if ( nbBlockedAround > 1 )
5417       continue;
5418
5419     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5420     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5421     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5422     edge->_curvature->_uv = uv;
5423     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5424
5425     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5426     gp_XYZ prevP = edge->PrevCheckPos();
5427     bool      ok = true;
5428     if ( !moveAll )
5429       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5430       {
5431         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5432       }
5433     if ( ok )
5434     {
5435       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5436       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5437       edge->_pos.back() = newP;
5438
5439       edge->Set( _LayerEdge::MARKED );
5440       if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5441       {
5442         edge->_normal = ( newP - prevP ).Normalized();
5443       }
5444     }
5445   }
5446
5447
5448
5449 #ifdef _DEBUG_
5450   // dumpMove() for debug
5451   size_t i = 0;
5452   for ( ; i < eos._edges.size(); ++i )
5453     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5454       break;
5455   if ( i < eos._edges.size() )
5456   {
5457     dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5458                  << "_InfStep" << infStep << "_" << smooStep );
5459     for ( ; i < eos._edges.size(); ++i )
5460     {
5461       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5462         dumpMove( eos._edges[i]->_nodes.back() );
5463     }
5464     dumpFunctionEnd();
5465   }
5466 #endif
5467
5468   _ConvexFace* cnvFace;
5469   if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5470        eos.ShapeType() == TopAbs_FACE &&
5471        (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5472        !cnvFace->_normalsFixedOnBorders )
5473   {
5474     // put on the surface nodes built on FACE boundaries
5475     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5476     while ( smIt->more() )
5477     {
5478       SMESH_subMesh* sm = smIt->next();
5479       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5480       if ( !subEOS->_sWOL.IsNull() ) continue;
5481       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5482
5483       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5484     }
5485     cnvFace->_normalsFixedOnBorders = true;
5486   }
5487 }
5488
5489 //================================================================================
5490 /*!
5491  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5492  *        _LayerEdge's to be in a consequent order
5493  */
5494 //================================================================================
5495
5496 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5497                                                 _EdgesOnShape&      eos,
5498                                                 SMESH_MesherHelper& helper)
5499 {
5500   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5501
5502   TopLoc_Location loc; double f,l;
5503
5504   Handle(Geom_Line)   line;
5505   Handle(Geom_Circle) circle;
5506   bool isLine, isCirc;
5507   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5508   {
5509     // check if the EDGE is a line
5510     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5511     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5512       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5513
5514     line   = Handle(Geom_Line)::DownCast( curve );
5515     circle = Handle(Geom_Circle)::DownCast( curve );
5516     isLine = (!line.IsNull());
5517     isCirc = (!circle.IsNull());
5518
5519     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5520     {
5521       isLine = SMESH_Algo::IsStraight( E );
5522
5523       if ( isLine )
5524         line = new Geom_Line( gp::OX() ); // only type does matter
5525     }
5526     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5527     {
5528       // TODO
5529     }
5530   }
5531   else //////////////////////////////////////////////////////////////////////// 2D case
5532   {
5533     if ( !eos._isRegularSWOL ) // 23190
5534       return NULL;
5535
5536     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5537
5538     // check if the EDGE is a line
5539     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5540     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5541       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5542
5543     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5544     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5545     isLine = (!line2d.IsNull());
5546     isCirc = (!circle2d.IsNull());
5547
5548     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5549     {
5550       Bnd_B2d bndBox;
5551       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5552       while ( nIt->more() )
5553         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5554       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5555
5556       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5557       for ( int i = 0; i < 2 && !isLine; ++i )
5558         isLine = ( size.Coord( i+1 ) <= lineTol );
5559     }
5560     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5561     {
5562       // TODO
5563     }
5564     if ( isLine )
5565     {
5566       line = new Geom_Line( gp::OX() ); // only type does matter
5567     }
5568     else if ( isCirc )
5569     {
5570       gp_Pnt2d p = circle2d->Location();
5571       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5572       circle = new Geom_Circle( ax, 1.); // only center position does matter
5573     }
5574   }
5575
5576   if ( isLine )
5577     return line;
5578   if ( isCirc )
5579     return circle;
5580
5581   return Handle(Geom_Curve)();
5582 }
5583
5584 //================================================================================
5585 /*!
5586  * \brief Smooth edges on EDGE
5587  */
5588 //================================================================================
5589
5590 bool _Smoother1D::Perform(_SolidData&                    data,
5591                           Handle(ShapeAnalysis_Surface)& surface,
5592                           const TopoDS_Face&             F,
5593                           SMESH_MesherHelper&            helper )
5594 {
5595   if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5596     prepare( data );
5597
5598   findEdgesToSmooth();
5599   if ( isAnalytic() )
5600     return smoothAnalyticEdge( data, surface, F, helper );
5601   else
5602     return smoothComplexEdge ( data, surface, F, helper );
5603 }
5604
5605 //================================================================================
5606 /*!
5607  * \brief Find edges to smooth
5608  */
5609 //================================================================================
5610
5611 void _Smoother1D::findEdgesToSmooth()
5612 {
5613   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5614   for ( int iEnd = 0; iEnd < 2; ++iEnd )
5615     if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5616       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5617
5618   _eToSmooth[0].first = _eToSmooth[0].second = 0;
5619
5620   for ( size_t i = 0; i < _eos.size(); ++i )
5621   {
5622     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5623     {
5624       if ( needSmoothing( _leOnV[0]._cosin,
5625                           _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
5626            isToSmooth( i )
5627            )
5628         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5629       else
5630         break;
5631     }
5632     _eToSmooth[0].second = i+1;
5633   }
5634
5635   _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5636
5637   for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5638   {
5639     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5640     {
5641       if ( needSmoothing( _leOnV[1]._cosin,
5642                           _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
5643            isToSmooth( i ))
5644         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5645       else
5646         break;
5647     }
5648     _eToSmooth[1].first = i;
5649   }
5650 }
5651
5652 //================================================================================
5653 /*!
5654  * \brief Check if iE-th _LayerEdge needs smoothing
5655  */
5656 //================================================================================
5657
5658 bool _Smoother1D::isToSmooth( int iE )
5659 {
5660   SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5661   SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5662   SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5663   gp_XYZ       seg0 = pi - p0;
5664   gp_XYZ       seg1 = p1 - pi;
5665   gp_XYZ    tangent =  seg0 + seg1;
5666   double tangentLen = tangent.Modulus();
5667   double  segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5668   if ( tangentLen < std::numeric_limits<double>::min() )
5669     return false;
5670   tangent /= tangentLen;
5671
5672   for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5673   {
5674     _LayerEdge* ne = _eos[iE]->_neibors[i];
5675     if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5676          ne->_nodes.size() < 2 ||
5677          ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5678       continue;
5679     gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5680     double    proj = edgeVec * tangent;
5681     if ( needSmoothing( 1., proj, segMinLen ))
5682       return true;
5683   }
5684   return false;
5685 }
5686
5687 //================================================================================
5688 /*!
5689  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5690  */
5691 //================================================================================
5692
5693 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5694                                       Handle(ShapeAnalysis_Surface)& surface,
5695                                       const TopoDS_Face&             F,
5696                                       SMESH_MesherHelper&            helper)
5697 {
5698   if ( !isAnalytic() ) return false;
5699
5700   size_t iFrom = 0, iTo = _eos._edges.size();
5701
5702   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5703   {
5704     if ( F.IsNull() ) // 3D
5705     {
5706       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5707       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5708       //const   gp_XYZ lineDir = pSrc1 - pSrc0;
5709       //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5710       //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5711       // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5712       //                    vLE0->Is( _LayerEdge::BLOCKED ) ||
5713       //                    vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5714       //                    vLE1->Is( _LayerEdge::BLOCKED ));
5715       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5716       {
5717         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5718         if ( iFrom >= iTo ) continue;
5719         SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5720         SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5721         double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5722         double param1 = _leParams[ iTo ];
5723         for ( size_t i = iFrom; i < iTo; ++i )
5724         {
5725           _LayerEdge*       edge = _eos[i];
5726           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5727           double           param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5728           gp_XYZ          newPos = p0 * ( 1. - param ) + p1 * param;
5729
5730           // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5731           // {
5732           //   gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5733           //   double  shift = ( lineDir * ( newPos - pSrc0 ) -
5734           //                     lineDir * ( curPos - pSrc0 ));
5735           //   newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5736           // }
5737           if ( edge->Is( _LayerEdge::BLOCKED ))
5738           {
5739             SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5740             double curThick = pSrc.SquareDistance( tgtNode );
5741             double newThink = ( pSrc - newPos ).SquareModulus();
5742             if ( newThink > curThick )
5743               continue;
5744           }
5745           edge->_pos.back() = newPos;
5746           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5747           dumpMove( tgtNode );
5748         }
5749       }
5750     }
5751     else // 2D
5752     {
5753       _LayerEdge* eV0 = getLEdgeOnV( 0 );
5754       _LayerEdge* eV1 = getLEdgeOnV( 1 );
5755       gp_XY      uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5756       gp_XY      uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5757       if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5758       {
5759         int iPeriodic = helper.GetPeriodicIndex();
5760         if ( iPeriodic == 1 || iPeriodic == 2 )
5761         {
5762           uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5763           if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5764             std::swap( uvV0, uvV1 );
5765         }
5766       }
5767       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5768       {
5769         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5770         if ( iFrom >= iTo ) continue;
5771         _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5772         _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5773         gp_XY      uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5774         gp_XY      uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5775         double  param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5776         double  param1 = _leParams[ iTo ];
5777         gp_XY  rangeUV = uv1 - uv0;
5778         for ( size_t i = iFrom; i < iTo; ++i )
5779         {
5780           if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5781           double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5782           gp_XY newUV = uv0 + param * rangeUV;
5783
5784           gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5785           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5786           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5787           dumpMove( tgtNode );
5788
5789           SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5790           pos->SetUParameter( newUV.X() );
5791           pos->SetVParameter( newUV.Y() );
5792
5793           gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5794
5795           if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5796           {
5797             _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5798             if ( _eos[i]->_pos.size() > 2 )
5799             {
5800               // modify previous positions to make _LayerEdge less sharply bent
5801               vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5802               const gp_XYZ  uvShift = newUV0 - uvVec.back();
5803               const double     len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5804               int iPrev = uvVec.size() - 2;
5805               while ( iPrev > 0 )
5806               {
5807                 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5808                 uvVec[ iPrev ] += uvShift * r;
5809                 --iPrev;
5810               }
5811             }
5812           }
5813           _eos[i]->_pos.back() = newUV0;
5814         }
5815       }
5816     }
5817     return true;
5818   }
5819
5820   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5821   {
5822     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5823     gp_Pnt center3D = circle->Location();
5824
5825     if ( F.IsNull() ) // 3D
5826     {
5827       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5828         return true; // closed EDGE - nothing to do
5829
5830       // circle is a real curve of EDGE
5831       gp_Circ circ = circle->Circ();
5832
5833       // new center is shifted along its axis
5834       const gp_Dir& axis = circ.Axis().Direction();
5835       _LayerEdge*     e0 = getLEdgeOnV(0);
5836       _LayerEdge*     e1 = getLEdgeOnV(1);
5837       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5838       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5839       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5840       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5841       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5842
5843       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5844
5845       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5846       gp_Circ newCirc( newAxis, newRadius );
5847       gp_Vec  vecC1  ( newCenter, p1 );
5848
5849       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5850       if ( uLast < 0 )
5851         uLast += 2 * M_PI;
5852       
5853       for ( size_t i = 0; i < _eos.size(); ++i )
5854       {
5855         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5856         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5857         double u = uLast * _leParams[i];
5858         gp_Pnt p = ElCLib::Value( u, newCirc );
5859         _eos._edges[i]->_pos.back() = p.XYZ();
5860
5861         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5862         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5863         dumpMove( tgtNode );
5864       }
5865       return true;
5866     }
5867     else // 2D
5868     {
5869       const gp_XY center( center3D.X(), center3D.Y() );
5870
5871       _LayerEdge* e0 = getLEdgeOnV(0);
5872       _LayerEdge* eM = _eos._edges[ 0 ];
5873       _LayerEdge* e1 = getLEdgeOnV(1);
5874       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5875       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5876       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5877       gp_Vec2d vec0( center, uv0 );
5878       gp_Vec2d vecM( center, uvM );
5879       gp_Vec2d vec1( center, uv1 );
5880       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5881       double uMidl = vec0.Angle( vecM );
5882       if ( uLast * uMidl <= 0. )
5883         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5884       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5885
5886       gp_Ax2d   axis( center, vec0 );
5887       gp_Circ2d circ( axis, radius );
5888       for ( size_t i = 0; i < _eos.size(); ++i )
5889       {
5890         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5891         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5892         double    newU = uLast * _leParams[i];
5893         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5894         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5895
5896         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5897         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5898         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5899         dumpMove( tgtNode );
5900
5901         SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5902         pos->SetUParameter( newUV.X() );
5903         pos->SetVParameter( newUV.Y() );
5904
5905         _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5906       }
5907     }
5908     return true;
5909   }
5910
5911   return false;
5912 }
5913
5914 //================================================================================
5915 /*!
5916  * \brief smooth _LayerEdge's on a an EDGE
5917  */
5918 //================================================================================
5919
5920 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5921                                      Handle(ShapeAnalysis_Surface)& surface,
5922                                      const TopoDS_Face&             F,
5923                                      SMESH_MesherHelper&            helper)
5924 {
5925   if ( _offPoints.empty() )
5926     return false;
5927
5928   // ----------------------------------------------
5929   // move _offPoints along normals of _LayerEdge's
5930   // ----------------------------------------------
5931
5932   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5933   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5934     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5935   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5936     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5937   _leOnV[0]._len = e[0]->_len;
5938   _leOnV[1]._len = e[1]->_len;
5939   for ( size_t i = 0; i < _offPoints.size(); i++ )
5940   {
5941     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5942     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5943     const double w0 = _offPoints[i]._2edges._wgt[0];
5944     const double w1 = _offPoints[i]._2edges._wgt[1];
5945     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5946     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5947     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5948     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5949          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5950       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5951
5952     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5953     _offPoints[i]._len  = avgLen;
5954   }
5955
5956   double fTol = 0;
5957   if ( !surface.IsNull() ) // project _offPoints to the FACE
5958   {
5959     fTol = 100 * BRep_Tool::Tolerance( F );
5960     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5961
5962     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5963     //if ( surface->Gap() < 0.5 * segLen )
5964       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5965
5966     for ( size_t i = 1; i < _offPoints.size(); ++i )
5967     {
5968       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5969       //if ( surface->Gap() < 0.5 * segLen )
5970         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5971     }
5972   }
5973
5974   // -----------------------------------------------------------------
5975   // project tgt nodes of extreme _LayerEdge's to the offset segments
5976   // -----------------------------------------------------------------
5977
5978   const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
5979   if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
5980   if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
5981
5982   gp_Pnt pExtreme[2], pProj[2];
5983   bool isProjected[2];
5984   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5985   {
5986     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5987     int  i = _iSeg[ is2nd ];
5988     int di = is2nd ? -1 : +1;
5989     bool & projected = isProjected[ is2nd ];
5990     projected = false;
5991     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5992     int nbWorse = 0;
5993     do {
5994       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5995       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5996       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5997       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5998       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5999       if ( dist < distMin || projected )
6000       {
6001         _iSeg[ is2nd ] = i;
6002         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6003         distMin = dist;
6004       }
6005       else if ( dist > distPrev )
6006       {
6007         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6008           break;
6009       }
6010       distPrev = dist;
6011       i += di;
6012     }
6013     while ( !projected &&
6014             i >= 0 && i+1 < (int)_offPoints.size() );
6015
6016     if ( !projected )
6017     {
6018       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6019       {
6020         _iSeg[0] = 0;
6021         _iSeg[1] = _offPoints.size()-2;
6022         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6023         return false;
6024       }
6025     }
6026   }
6027   if ( _iSeg[0] > _iSeg[1] )
6028   {
6029     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6030     return false;
6031   }
6032
6033   // adjust length of extreme LE (test viscous_layers_01/B7)
6034   gp_Vec vDiv0( pExtreme[0], pProj[0] );
6035   gp_Vec vDiv1( pExtreme[1], pProj[1] );
6036   double d0 = vDiv0.Magnitude();
6037   double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6038   if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6039     if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6040     else                                   e[0]->_len -= d0;
6041   }
6042   if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6043     if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6044     else                                   e[1]->_len -= d1;
6045   }
6046
6047   // ---------------------------------------------------------------------------------
6048   // compute normalized length of the offset segments located between the projections
6049   // ---------------------------------------------------------------------------------
6050
6051   // temporary replace extreme _offPoints by pExtreme
6052   gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0]   ]._xyz,
6053                       _offPoints[ _iSeg[1]+1 ]._xyz };
6054   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
6055   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6056
6057   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6058   vector< double > len( nbSeg + 1 );
6059   len[ iSeg++ ] = 0;
6060   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6061   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6062   {
6063     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6064   }
6065   // if ( isProjected[ 1 ])
6066   //   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6067   // else
6068   //   len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6069
6070   double fullLen = len.back() - d0 - d1;
6071   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6072     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6073
6074   // -------------------------------------------------------------
6075   // distribute tgt nodes of _LayerEdge's between the projections
6076   // -------------------------------------------------------------
6077
6078   iSeg = 0;
6079   for ( size_t i = 0; i < _eos.size(); ++i )
6080   {
6081     if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6082     //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6083     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6084       iSeg++;
6085     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6086     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
6087                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6088
6089     if ( surface.IsNull() )
6090     {
6091       _eos[i]->_pos.back() = p;
6092     }
6093     else // project a new node position to a FACE
6094     {
6095       gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6096       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6097
6098       p = surface->Value( uv2 ).XYZ();
6099       _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6100     }
6101     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6102     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6103     dumpMove( tgtNode );
6104   }
6105
6106   _offPoints[ _iSeg[0]   ]._xyz = opXYZ[0];
6107   _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6108
6109   return true;
6110 }
6111
6112 //================================================================================
6113 /*!
6114  * \brief Prepare for smoothing
6115  */
6116 //================================================================================
6117
6118 void _Smoother1D::prepare(_SolidData& data)
6119 {
6120   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6121   _curveLen = SMESH_Algo::EdgeLength( E );
6122
6123   // sort _LayerEdge's by position on the EDGE
6124   data.SortOnEdge( E, _eos._edges );
6125
6126   // compute normalized param of _eos._edges on EDGE
6127   _leParams.resize( _eos._edges.size() + 1 );
6128   {
6129     double curLen;
6130     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6131     _leParams[0] = 0;
6132     for ( size_t i = 0; i < _eos._edges.size(); ++i )
6133     {
6134       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6135       curLen         = p.Distance( pPrev );
6136       _leParams[i+1] = _leParams[i] + curLen;
6137       pPrev          = p;
6138     }
6139     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6140     for ( size_t i = 0; i < _leParams.size()-1; ++i )
6141       _leParams[i] = _leParams[i+1] / fullLen;
6142     _leParams.back() = 1.;
6143   }
6144
6145   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6146
6147   // get cosin to use in findEdgesToSmooth()
6148   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6149   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6150   _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6151   _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6152   if ( _eos._sWOL.IsNull() ) // 3D
6153     for ( int iEnd = 0; iEnd < 2; ++iEnd )
6154       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6155
6156   if ( isAnalytic() )
6157     return;
6158
6159   // divide E to have offset segments with low deflection
6160   BRepAdaptor_Curve c3dAdaptor( E );
6161   const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6162   const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6163   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6164   if ( discret.NbPoints() <= 2 )
6165   {
6166     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6167     return;
6168   }
6169
6170   const double u0 = c3dAdaptor.FirstParameter();
6171   gp_Pnt p; gp_Vec tangent;
6172   if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6173   {
6174     _offPoints.resize( discret.NbPoints() );
6175     for ( size_t i = 0; i < _offPoints.size(); i++ )
6176     {
6177       double u = discret.Parameter( i+1 );
6178       c3dAdaptor.D1( u, p, tangent );
6179       _offPoints[i]._xyz     = p.XYZ();
6180       _offPoints[i]._edgeDir = tangent.XYZ();
6181       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6182     }
6183   }
6184   else
6185   {
6186     std::vector< double > params( _eos.size() + 2 );
6187
6188     params[0]     = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6189     params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6190     for ( size_t i = 0; i < _eos.size(); i++ )
6191       params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6192
6193     if ( params[1] > params[ _eos.size() ] )
6194       std::reverse( params.begin() + 1, params.end() - 1 );
6195
6196     _offPoints.resize( _eos.size() + 2 );
6197     for ( size_t i = 0; i < _offPoints.size(); i++ )
6198     {
6199       const double u = params[i];
6200       c3dAdaptor.D1( u, p, tangent );
6201       _offPoints[i]._xyz     = p.XYZ();
6202       _offPoints[i]._edgeDir = tangent.XYZ();
6203       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6204     }
6205   }
6206
6207   // set _2edges
6208   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6209   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6210   _2NearEdges tmp2edges;
6211   tmp2edges._edges[1] = _eos._edges[0];
6212   _leOnV[0]._2neibors = & tmp2edges;
6213   _leOnV[0]._nodes    = leOnV[0]->_nodes;
6214   _leOnV[1]._nodes    = leOnV[1]->_nodes;
6215   _LayerEdge* eNext, *ePrev = & _leOnV[0];
6216   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6217   {
6218     // find _LayerEdge's located before and after an offset point
6219     // (_eos._edges[ iLE ] is next after ePrev)
6220     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6221       ePrev = _eos._edges[ iLE++ ];
6222     eNext = ePrev->_2neibors->_edges[1];
6223
6224     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6225     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6226     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6227     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6228   }
6229
6230   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6231   for ( size_t i = 0; i < _offPoints.size(); i++ )
6232     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6233       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6234     else break;
6235   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6236     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6237       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6238     else break;
6239
6240   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6241
6242   int iLBO = _offPoints.size() - 2; // last but one
6243
6244   if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6245     _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6246   else
6247     _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal,       _edgeDir[0] );
6248   if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6249     _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6250   else
6251     _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal,           _edgeDir[1] );
6252   _leOnV[ 0 ]._len = 0;
6253   _leOnV[ 1 ]._len = 0;
6254   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
6255   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6256
6257   _iSeg[0] = 0;
6258   _iSeg[1] = _offPoints.size()-2;
6259
6260   // initialize OffPnt::_len
6261   for ( size_t i = 0; i < _offPoints.size(); ++i )
6262     _offPoints[i]._len = 0;
6263
6264   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6265   {
6266     _leOnV[0]._len = leOnV[0]->_len;
6267     _leOnV[1]._len = leOnV[1]->_len;
6268     for ( size_t i = 0; i < _offPoints.size(); i++ )
6269     {
6270       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6271       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6272       const double w0 = _offPoints[i]._2edges._wgt[0];
6273       const double w1 = _offPoints[i]._2edges._wgt[1];
6274       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
6275       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6276                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6277       _offPoints[i]._xyz = avgXYZ;
6278       _offPoints[i]._len = avgLen;
6279     }
6280   }
6281 }
6282
6283 //================================================================================
6284 /*!
6285  * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6286  */
6287 //================================================================================
6288
6289 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6290                                      const gp_XYZ&  edgeDir)
6291 {
6292   gp_XYZ cross = normal ^ edgeDir;
6293   gp_XYZ  norm = edgeDir ^ cross;
6294   double  size = norm.Modulus();
6295
6296   // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6297   //   return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6298
6299   return norm / size;
6300 }
6301
6302 //================================================================================
6303 /*!
6304  * \brief Writes a script creating a mesh composed of _offPoints
6305  */
6306 //================================================================================
6307
6308 void _Smoother1D::offPointsToPython() const
6309 {
6310   const char* fname = "/tmp/offPoints.py";
6311   cout << "execfile('"<<fname<<"')"<<endl;
6312   ofstream py(fname);
6313   py << "import SMESH" << endl
6314      << "from salome.smesh import smeshBuilder" << endl
6315      << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
6316      << "mesh   = smesh.Mesh( 'offPoints' )"<<endl;
6317   for ( size_t i = 0; i < _offPoints.size(); i++ )
6318   {
6319     py << "mesh.AddNode( "
6320        << _offPoints[i]._xyz.X() << ", "
6321        << _offPoints[i]._xyz.Y() << ", "
6322        << _offPoints[i]._xyz.Z() << " )" << endl;
6323   }
6324 }
6325
6326 //================================================================================
6327 /*!
6328  * \brief Sort _LayerEdge's by a parameter on a given EDGE
6329  */
6330 //================================================================================
6331
6332 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
6333                              vector< _LayerEdge* >& edges)
6334 {
6335   map< double, _LayerEdge* > u2edge;
6336   for ( size_t i = 0; i < edges.size(); ++i )
6337     u2edge.insert( u2edge.end(),
6338                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6339
6340   ASSERT( u2edge.size() == edges.size() );
6341   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6342   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6343     edges[i] = u2e->second;
6344
6345   Sort2NeiborsOnEdge( edges );
6346 }
6347
6348 //================================================================================
6349 /*!
6350  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6351  */
6352 //================================================================================
6353
6354 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6355 {
6356   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6357
6358   for ( size_t i = 0; i < edges.size()-1; ++i )
6359     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6360       edges[i]->_2neibors->reverse();
6361
6362   const size_t iLast = edges.size() - 1;
6363   if ( edges.size() > 1 &&
6364        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6365     edges[iLast]->_2neibors->reverse();
6366 }
6367
6368 //================================================================================
6369 /*!
6370  * \brief Return _EdgesOnShape* corresponding to the shape
6371  */
6372 //================================================================================
6373
6374 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6375 {
6376   if ( shapeID < (int)_edgesOnShape.size() &&
6377        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6378     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6379
6380   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6381     if ( _edgesOnShape[i]._shapeID == shapeID )
6382       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6383
6384   return 0;
6385 }
6386
6387 //================================================================================
6388 /*!
6389  * \brief Return _EdgesOnShape* corresponding to the shape
6390  */
6391 //================================================================================
6392
6393 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6394 {
6395   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6396   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6397 }
6398
6399 //================================================================================
6400 /*!
6401  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6402  */
6403 //================================================================================
6404
6405 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6406 {
6407   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6408
6409   set< TGeomID > vertices;
6410   TopoDS_Face F;
6411   if ( eos->ShapeType() == TopAbs_FACE )
6412   {
6413     // check FACE concavity and get concave VERTEXes
6414     F = TopoDS::Face( eos->_shape );
6415     if ( isConcave( F, helper, &vertices ))
6416       _concaveFaces.insert( eos->_shapeID );
6417
6418     // set eos._eosConcaVer
6419     eos->_eosConcaVer.clear();
6420     eos->_eosConcaVer.reserve( vertices.size() );
6421     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6422     {
6423       _EdgesOnShape* eov = GetShapeEdges( *v );
6424       if ( eov && eov->_edges.size() == 1 )
6425       {
6426         eos->_eosConcaVer.push_back( eov );
6427         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6428           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6429       }
6430     }
6431
6432     // SetSmooLen() to _LayerEdge's on FACE
6433     // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6434     // {
6435     //   eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6436     // }
6437     // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6438     // while ( smIt->more() ) // loop on sub-shapes of the FACE
6439     // {
6440     //   _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6441     //   if ( !eoe ) continue;
6442
6443     //   vector<_LayerEdge*>& eE = eoe->_edges;
6444     //   for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6445     //   {
6446     //     if ( eE[iE]->_cosin <= theMinSmoothCosin )
6447     //       continue;
6448
6449     //     SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6450     //     while ( segIt->more() )
6451     //     {
6452     //       const SMDS_MeshElement* seg = segIt->next();
6453     //       if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6454     //         continue;
6455     //       if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6456     //         continue; // not to check a seg twice
6457     //       for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6458     //       {
6459     //         _LayerEdge* eN = eE[iE]->_neibors[iN];
6460     //         if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6461     //           continue;
6462     //         double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6463     //         double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6464     //         eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6465     //         eN->Set( _LayerEdge::NEAR_BOUNDARY );
6466     //       }
6467     //     }
6468     //   }
6469     // }
6470   } // if ( eos->ShapeType() == TopAbs_FACE )
6471
6472   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6473   {
6474     eos->_edges[i]->_smooFunction = 0;
6475     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6476   }
6477   bool isCurved = false;
6478   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6479   {
6480     _LayerEdge* edge = eos->_edges[i];
6481
6482     // get simplices sorted
6483     _Simplex::SortSimplices( edge->_simplices );
6484
6485     // smoothing function
6486     edge->ChooseSmooFunction( vertices, _n2eMap );
6487
6488     // set _curvature
6489     double avgNormProj = 0, avgLen = 0;
6490     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6491     {
6492       _Simplex& s = edge->_simplices[iS];
6493
6494       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6495       avgNormProj += edge->_normal * vec;
6496       avgLen      += vec.Modulus();
6497       if ( substituteSrcNodes )
6498       {
6499         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6500         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6501       }
6502     }
6503     avgNormProj /= edge->_simplices.size();
6504     avgLen      /= edge->_simplices.size();
6505     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6506     {
6507       edge->Set( _LayerEdge::SMOOTHED_C1 );
6508       isCurved = true;
6509       SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6510       if ( !fPos )
6511         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6512           fPos = edge->_simplices[iS]._nPrev->GetPosition();
6513       if ( fPos )
6514         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6515     }
6516   }
6517
6518   // prepare for putOnOffsetSurface()
6519   if (( eos->ShapeType() == TopAbs_FACE ) &&
6520       ( isCurved || !eos->_eosConcaVer.empty() ))
6521   {
6522     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6523     eos->_edgeForOffset = 0;
6524
6525     double maxCosin = -1;
6526     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6527     {
6528       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6529       if ( !eoe || eoe->_edges.empty() ) continue;
6530
6531       vector<_LayerEdge*>& eE = eoe->_edges;
6532       _LayerEdge* e = eE[ eE.size() / 2 ];
6533       if ( e->_cosin > maxCosin )
6534       {
6535         eos->_edgeForOffset = e;
6536         maxCosin = e->_cosin;
6537       }
6538     }
6539   }
6540 }
6541
6542 //================================================================================
6543 /*!
6544  * \brief Add faces for smoothing
6545  */
6546 //================================================================================
6547
6548 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6549                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6550 {
6551   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6552   for ( ; eos != eosToSmooth.end(); ++eos )
6553   {
6554     if ( !*eos || (*eos)->_toSmooth ) continue;
6555
6556     (*eos)->_toSmooth = true;
6557
6558     if ( (*eos)->ShapeType() == TopAbs_FACE )
6559     {
6560       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6561       (*eos)->_toSmooth = true;
6562     }
6563   }
6564
6565   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6566   if ( edgesNoAnaSmooth )
6567     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6568     {
6569       if ( (*eos)->_edgeSmoother )
6570         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6571     }
6572 }
6573
6574 //================================================================================
6575 /*!
6576  * \brief Limit _LayerEdge::_maxLen according to local curvature
6577  */
6578 //================================================================================
6579
6580 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6581 {
6582   // find intersection of neighbor _LayerEdge's to limit _maxLen
6583   // according to local curvature (IPAL52648)
6584
6585   // This method must be called after findCollisionEdges() where _LayerEdge's
6586   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6587
6588   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6589   {
6590     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6591     if ( eosI._edges.empty() ) continue;
6592     if ( !eosI._hyp.ToSmooth() )
6593     {
6594       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6595       {
6596         _LayerEdge* eI = eosI._edges[i];
6597         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6598         {
6599           _LayerEdge* eN = eI->_neibors[iN];
6600           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6601           {
6602             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6603             limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
6604           }
6605         }
6606       }
6607     }
6608     else if ( eosI.ShapeType() == TopAbs_EDGE )
6609     {
6610       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6611       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6612
6613       _LayerEdge* e0 = eosI._edges[0];
6614       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6615       {
6616         _LayerEdge* eI = eosI._edges[i];
6617         limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
6618         e0 = eI;
6619       }
6620     }
6621   }
6622 }
6623
6624 //================================================================================
6625 /*!
6626  * \brief Limit _LayerEdge::_maxLen according to local curvature
6627  */
6628 //================================================================================
6629
6630 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*    e1,
6631                                               _LayerEdge*    e2,
6632                                               _EdgesOnShape& eos1,
6633                                               _EdgesOnShape& eos2,
6634                                               const bool     isSmoothable )
6635 {
6636   if (( e1->_nodes[0]->GetPosition()->GetDim() !=
6637         e2->_nodes[0]->GetPosition()->GetDim() ) &&
6638       ( e1->_cosin < 0.75 ))
6639     return; // angle > 90 deg at e1
6640
6641   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6642   double norSize = plnNorm.SquareModulus();
6643   if ( norSize < std::numeric_limits<double>::min() )
6644     return; // parallel normals
6645
6646   // find closest points of skew _LayerEdge's
6647   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6648   gp_XYZ dir12 = src2 - src1;
6649   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6650   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6651   double  dot1 = perp2 * e1->_normal;
6652   double  dot2 = perp1 * e2->_normal;
6653   double    u1 =   ( perp2 * dir12 ) / dot1;
6654   double    u2 = - ( perp1 * dir12 ) / dot2;
6655   if ( u1 > 0 && u2 > 0 )
6656   {
6657     double ovl = ( u1 * e1->_normal * dir12 -
6658                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6659     if ( ovl > theSmoothThickToElemSizeRatio )
6660     {
6661       const double coef = 0.75;
6662       e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
6663       e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
6664     }
6665   }
6666 }
6667
6668 //================================================================================
6669 /*!
6670  * \brief Fill data._collisionEdges
6671  */
6672 //================================================================================
6673
6674 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6675 {
6676   data._collisionEdges.clear();
6677
6678   // set the full thickness of the layers to LEs
6679   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6680   {
6681     _EdgesOnShape& eos = data._edgesOnShape[iS];
6682     if ( eos._edges.empty() ) continue;
6683     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6684     if ( !eos._sWOL.IsNull() ) continue; // PAL23566
6685
6686     for ( size_t i = 0; i < eos._edges.size(); ++i )
6687     {
6688       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6689       double maxLen = eos._edges[i]->_maxLen;
6690       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6691       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6692       eos._edges[i]->_maxLen = maxLen;
6693     }
6694   }
6695
6696   // make temporary quadrangles got by extrusion of
6697   // mesh edges along _LayerEdge._normal's
6698
6699   vector< const SMDS_MeshElement* > tmpFaces;
6700
6701   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6702   {
6703     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6704     if ( eos.ShapeType() != TopAbs_EDGE )
6705       continue;
6706     if ( eos._edges.empty() )
6707     {
6708       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6709       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6710       while ( smIt->more() )
6711         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6712           if ( eov->_edges.size() == 1 )
6713             edge[ bool( edge[0]) ] = eov->_edges[0];
6714
6715       if ( edge[1] )
6716       {
6717         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6718         tmpFaces.push_back( f );
6719       }
6720     }
6721     for ( size_t i = 0; i < eos._edges.size(); ++i )
6722     {
6723       _LayerEdge* edge = eos._edges[i];
6724       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6725       {
6726         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6727         if ( src2->GetPosition()->GetDim() > 0 &&
6728              src2->GetID() < edge->_nodes[0]->GetID() )
6729           continue; // avoid using same segment twice
6730
6731         // a _LayerEdge containing tgt2
6732         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6733
6734         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6735         tmpFaces.push_back( f );
6736       }
6737     }
6738   }
6739
6740   // Find _LayerEdge's intersecting tmpFaces.
6741
6742   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6743                                                             tmpFaces.end()));
6744   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6745     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6746
6747   double dist1, dist2, segLen, eps = 0.5;
6748   _CollisionEdges collEdges;
6749   vector< const SMDS_MeshElement* > suspectFaces;
6750   const double angle45 = Cos( 45. * M_PI / 180. );
6751
6752   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6753   {
6754     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6755     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6756       continue;
6757     // find sub-shapes whose VL can influence VL on eos
6758     set< TGeomID > neighborShapes;
6759     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6760     while ( const TopoDS_Shape* face = fIt->next() )
6761     {
6762       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6763       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6764       {
6765         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6766         while ( subIt->more() )
6767           neighborShapes.insert( subIt->next()->GetId() );
6768       }
6769     }
6770     if ( eos.ShapeType() == TopAbs_VERTEX )
6771     {
6772       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6773       while ( const TopoDS_Shape* edge = eIt->next() )
6774         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6775     }
6776     // find intersecting _LayerEdge's
6777     for ( size_t i = 0; i < eos._edges.size(); ++i )
6778     {
6779       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6780       _LayerEdge*   edge = eos._edges[i];
6781       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6782       segLen *= 1.2;
6783
6784       gp_Vec eSegDir0, eSegDir1;
6785       if ( edge->IsOnEdge() )
6786       {
6787         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6788         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6789         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6790       }
6791       suspectFaces.clear();
6792       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6793                                      SMDSAbs_Face, suspectFaces );
6794       collEdges._intEdges.clear();
6795       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6796       {
6797         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6798         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6799         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6800         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6801         if ( edge->IsOnEdge() ) {
6802           if ( edge->_2neibors->include( f->_le1 ) ||
6803                edge->_2neibors->include( f->_le2 )) continue;
6804         }
6805         else {
6806           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6807               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6808         }
6809         dist1 = dist2 = Precision::Infinite();
6810         if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
6811           dist1 = Precision::Infinite();
6812         if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
6813           dist2 = Precision::Infinite();
6814         if (( dist1 > segLen ) && ( dist2 > segLen ))
6815           continue;
6816
6817         if ( edge->IsOnEdge() )
6818         {
6819           // skip perpendicular EDGEs
6820           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
6821           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6822                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6823                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6824                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6825           if ( !isParallel )
6826             continue;
6827         }
6828
6829         // either limit inflation of edges or remember them for updating _normal
6830         // double dot = edge->_normal * f->GetDir();
6831         // if ( dot > 0.1 )
6832         {
6833           collEdges._intEdges.push_back( f->_le1 );
6834           collEdges._intEdges.push_back( f->_le2 );
6835         }
6836         // else
6837         // {
6838         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6839         //   edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
6840         // }
6841       }
6842
6843       if ( !collEdges._intEdges.empty() )
6844       {
6845         collEdges._edge = edge;
6846         data._collisionEdges.push_back( collEdges );
6847       }
6848     }
6849   }
6850
6851   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6852     delete tmpFaces[i];
6853
6854   // restore the zero thickness
6855   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6856   {
6857     _EdgesOnShape& eos = data._edgesOnShape[iS];
6858     if ( eos._edges.empty() ) continue;
6859     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6860
6861     for ( size_t i = 0; i < eos._edges.size(); ++i )
6862     {
6863       eos._edges[i]->InvalidateStep( 1, eos );
6864       eos._edges[i]->_len = 0;
6865     }
6866   }
6867 }
6868
6869 //================================================================================
6870 /*!
6871  * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
6872  *        will be updated at each inflation step
6873  */
6874 //================================================================================
6875
6876 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
6877                                                              _SolidData&         data,
6878                                                              SMESH_MesherHelper& helper )
6879 {
6880   const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
6881   const double       preci = BRep_Tool::Tolerance( convFace._face );
6882   Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
6883
6884   bool edgesToUpdateFound = false;
6885
6886   map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6887   for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6888   {
6889     _EdgesOnShape& eos = * id2eos->second;
6890     if ( !eos._sWOL.IsNull() ) continue;
6891     if ( !eos._hyp.ToSmooth() ) continue;
6892     for ( size_t i = 0; i < eos._edges.size(); ++i )
6893     {
6894       _LayerEdge* ledge = eos._edges[ i ];
6895       if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
6896       if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
6897
6898       gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
6899                         ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
6900
6901       // the normal must be updated if distance from tgtPos to surface is less than
6902       // target thickness
6903
6904       // find an initial UV for search of a projection of tgtPos to surface
6905       const SMDS_MeshNode* nodeInFace = 0;
6906       SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6907       while ( fIt->more() && !nodeInFace )
6908       {
6909         const SMDS_MeshElement* f = fIt->next();
6910         if ( convFaceID != f->getshapeId() ) continue;
6911
6912         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
6913         while ( nIt->more() && !nodeInFace )
6914         {
6915           const SMDS_MeshElement* n = nIt->next();
6916           if ( n->getshapeId() == convFaceID )
6917             nodeInFace = static_cast< const SMDS_MeshNode* >( n );
6918         }
6919       }
6920       if ( !nodeInFace )
6921         continue;
6922       gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
6923
6924       // projection
6925       surface->NextValueOfUV( uv, tgtPos, preci );
6926       double  dist = surface->Gap();
6927       if ( dist < 0.95 * ledge->_maxLen )
6928       {
6929         ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
6930         if ( !ledge->_curvature ) ledge->_curvature = new _Curvature;
6931         ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
6932         edgesToUpdateFound = true;
6933       }
6934     }
6935   }
6936
6937   if ( !convFace._isTooCurved && edgesToUpdateFound )
6938   {
6939     data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
6940   }
6941 }
6942
6943 //================================================================================
6944 /*!
6945  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6946  * _LayerEdge's on neighbor EDGE's
6947  */
6948 //================================================================================
6949
6950 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6951                                      SMESH_MesherHelper& helper,
6952                                      int                 stepNb,
6953                                      double              stepSize)
6954 {
6955   updateNormalsOfC1Vertices( data );
6956
6957   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6958     return false;
6959
6960   // map to store new _normal and _cosin for each intersected edge
6961   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6962   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6963   _LayerEdge zeroEdge;
6964   zeroEdge._normal.SetCoord( 0,0,0 );
6965   zeroEdge._maxLen = Precision::Infinite();
6966   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6967
6968   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6969
6970   double segLen, dist1, dist2, dist;
6971   vector< pair< _LayerEdge*, double > > intEdgesDist;
6972   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6973
6974   for ( int iter = 0; iter < 5; ++iter )
6975   {
6976     edge2newEdge.clear();
6977
6978     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6979     {
6980       _CollisionEdges& ce = data._collisionEdges[iE];
6981       _LayerEdge*   edge1 = ce._edge;
6982       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6983       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6984       if ( !eos1 ) continue;
6985
6986       // detect intersections
6987       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6988       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6989       double     eps = 0.5;
6990       intEdgesDist.clear();
6991       double minIntDist = Precision::Infinite();
6992       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6993       {
6994         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6995              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6996              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6997           continue;
6998         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6999         double fact = ( 1.1 + dot * dot );
7000         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7001         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7002         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7003         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7004         dist1 = dist2 = Precision::Infinite();
7005         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
7006              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7007           continue;
7008         dist = dist1;
7009         if ( dist > testLen || dist <= 0 )
7010         {
7011           dist = dist2;
7012           if ( dist > testLen || dist <= 0 )
7013             continue;
7014         }
7015         // choose a closest edge
7016         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7017         double d1 = intP.SquareDistance( pSrc0 );
7018         double d2 = intP.SquareDistance( pSrc1 );
7019         int iClose = i + ( d2 < d1 );
7020         _LayerEdge* edge2 = ce._intEdges[iClose];
7021         edge2->Unset( _LayerEdge::MARKED );
7022
7023         // choose a closest edge among neighbors
7024         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7025         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7026         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7027         {
7028           _LayerEdge * edgeJ = intEdgesDist[j].first;
7029           if ( edge2->IsNeiborOnEdge( edgeJ ))
7030           {
7031             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7032             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7033           }
7034         }
7035         intEdgesDist.push_back( make_pair( edge2, dist ));
7036         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7037         // {
7038         //   iClose = i + !( d2 < d1 );
7039         //   intEdges.push_back( ce._intEdges[iClose] );
7040         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7041         // }
7042         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7043       }
7044
7045       //ce._edge = 0;
7046
7047       // compute new _normals
7048       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7049       {
7050         _LayerEdge* edge2   = intEdgesDist[i].first;
7051         double      distWgt = edge1->_len / intEdgesDist[i].second;
7052         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7053         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
7054         if ( edge2->Is( _LayerEdge::MARKED )) continue;
7055         edge2->Set( _LayerEdge::MARKED );
7056
7057         // get a new normal
7058         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7059
7060         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7061         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7062         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7063         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
7064         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7065         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7066         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7067         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7068         newNormal.Normalize();
7069
7070         // get new cosin
7071         double newCos;
7072         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7073         if ( cos1 < theMinSmoothCosin )
7074         {
7075           newCos = cos2 * sgn1;
7076         }
7077         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7078         {
7079           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7080         }
7081         else
7082         {
7083           newCos = edge1->_cosin;
7084         }
7085
7086         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7087         e2neIt->second._normal += distWgt * newNormal;
7088         e2neIt->second._cosin   = newCos;
7089         e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7090         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7091           e2neIt->second._normal += dir2;
7092
7093         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7094         e2neIt->second._normal += distWgt * newNormal;
7095         if ( Precision::IsInfinite( zeroEdge._maxLen ))
7096         {
7097           e2neIt->second._cosin  = edge2->_cosin;
7098           e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7099         }
7100         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7101           e2neIt->second._normal += dir1;
7102       }
7103     }
7104
7105     if ( edge2newEdge.empty() )
7106       break; //return true;
7107
7108     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7109
7110     // Update data of edges depending on a new _normal
7111
7112     data.UnmarkEdges();
7113     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7114     {
7115       _LayerEdge*    edge = e2neIt->first;
7116       _LayerEdge& newEdge = e2neIt->second;
7117       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
7118       if ( edge->Is( _LayerEdge::BLOCKED && newEdge._maxLen > edge->_len ))
7119         continue;
7120
7121       // Check if a new _normal is OK:
7122       newEdge._normal.Normalize();
7123       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7124       {
7125         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7126         {
7127           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7128           edge->SetMaxLen( newEdge._maxLen );
7129           edge->SetNewLength( newEdge._maxLen, *eos, helper );
7130         }
7131         continue; // the new _normal is bad
7132       }
7133       // the new _normal is OK
7134
7135       // find shapes that need smoothing due to change of _normal
7136       if ( edge->_cosin   < theMinSmoothCosin &&
7137            newEdge._cosin > theMinSmoothCosin )
7138       {
7139         if ( eos->_sWOL.IsNull() )
7140         {
7141           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7142           while ( fIt->more() )
7143             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7144         }
7145         else // edge inflates along a FACE
7146         {
7147           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7148           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7149           while ( const TopoDS_Shape* E = eIt->next() )
7150           {
7151             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7152             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7153             if ( angle < M_PI / 2 )
7154               shapesToSmooth.insert( data.GetShapeEdges( *E ));
7155           }
7156         }
7157       }
7158
7159       double len = edge->_len;
7160       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7161       edge->SetNormal( newEdge._normal );
7162       edge->SetCosin( newEdge._cosin );
7163       edge->SetNewLength( len, *eos, helper );
7164       edge->Set( _LayerEdge::MARKED );
7165       edge->Set( _LayerEdge::NORMAL_UPDATED );
7166       edgesNoAnaSmooth.insert( eos );
7167     }
7168
7169     // Update normals and other dependent data of not intersecting _LayerEdge's
7170     // neighboring the intersecting ones
7171
7172     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7173     {
7174       _LayerEdge*   edge1 = e2neIt->first;
7175       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7176       if ( !edge1->Is( _LayerEdge::MARKED ))
7177         continue;
7178
7179       if ( edge1->IsOnEdge() )
7180       {
7181         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7182         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7183         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7184       }
7185
7186       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7187         continue;
7188       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7189       {
7190         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7191         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7192           continue; // j-th neighbor is also intersected
7193         _LayerEdge* prevEdge = edge1;
7194         const int nbSteps = 10;
7195         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7196         {
7197           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7198                neighbor->Is( _LayerEdge::MARKED ))
7199             break;
7200           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7201           if ( !eos ) continue;
7202           _LayerEdge* nextEdge = neighbor;
7203           if ( neighbor->_2neibors )
7204           {
7205             int iNext = 0;
7206             nextEdge = neighbor->_2neibors->_edges[iNext];
7207             if ( nextEdge == prevEdge )
7208               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7209           }
7210           double r = double(step-1)/nbSteps/(iter+1);
7211           if ( !nextEdge->_2neibors )
7212             r = Min( r, 0.5 );
7213
7214           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7215           newNorm.Normalize();
7216           if ( !isNewNormalOk( data, *neighbor, newNorm ))
7217             break;
7218
7219           double len = neighbor->_len;
7220           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7221           neighbor->SetNormal( newNorm );
7222           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7223           if ( neighbor->_2neibors )
7224             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7225           neighbor->SetNewLength( len, *eos, helper );
7226           neighbor->Set( _LayerEdge::MARKED );
7227           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7228           edgesNoAnaSmooth.insert( eos );
7229
7230           if ( !neighbor->_2neibors )
7231             break; // neighbor is on VERTEX
7232
7233           // goto the next neighbor
7234           prevEdge = neighbor;
7235           neighbor = nextEdge;
7236         }
7237       }
7238     }
7239     dumpFunctionEnd();
7240   } // iterations
7241
7242   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7243
7244   return true;
7245 }
7246
7247 //================================================================================
7248 /*!
7249  * \brief Check if a new normal is OK
7250  */
7251 //================================================================================
7252
7253 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
7254                                      _LayerEdge&   edge,
7255                                      const gp_XYZ& newNormal)
7256 {
7257   // check a min angle between the newNormal and surrounding faces
7258   vector<_Simplex> simplices;
7259   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7260   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7261   double newMinDot = 1, curMinDot = 1;
7262   for ( size_t i = 0; i < simplices.size(); ++i )
7263   {
7264     n1.Set( simplices[i]._nPrev );
7265     n2.Set( simplices[i]._nNext );
7266     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7267     double normLen2 = normFace.SquareModulus();
7268     if ( normLen2 < std::numeric_limits<double>::min() )
7269       continue;
7270     normFace /= Sqrt( normLen2 );
7271     newMinDot = Min( newNormal    * normFace, newMinDot );
7272     curMinDot = Min( edge._normal * normFace, curMinDot );
7273   }
7274   bool ok = true;
7275   if ( newMinDot < 0.5 )
7276   {
7277     ok = ( newMinDot >= curMinDot * 0.9 );
7278     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7279     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7280     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7281   }
7282
7283   return ok;
7284 }
7285
7286 //================================================================================
7287 /*!
7288  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7289  */
7290 //================================================================================
7291
7292 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
7293                                                SMESH_MesherHelper& helper,
7294                                                const int           nbSteps,
7295                                                const double        stepSize )
7296 {
7297   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7298     return true; // no shapes needing smoothing
7299
7300   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7301   {
7302     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7303     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
7304          !eos._hyp.ToSmooth() ||
7305          eos.ShapeType() != TopAbs_FACE ||
7306          eos._edges.empty() )
7307       continue;
7308
7309     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7310     if ( !toSmooth ) continue;
7311
7312     for ( size_t i = 0; i < eos._edges.size(); ++i )
7313     {
7314       _LayerEdge* edge = eos._edges[i];
7315       if ( !edge->Is( _LayerEdge::SMOOTHED ))
7316         continue;
7317       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7318         continue;
7319
7320       const gp_XYZ& pPrev = edge->PrevPos();
7321       const gp_XYZ& pLast = edge->_pos.back();
7322       gp_XYZ      stepVec = pLast - pPrev;
7323       double realStepSize = stepVec.Modulus();
7324       if ( realStepSize < numeric_limits<double>::min() )
7325         continue;
7326
7327       edge->_lenFactor = realStepSize / stepSize;
7328       edge->_normal    = stepVec / realStepSize;
7329       edge->Set( _LayerEdge::NORMAL_UPDATED );
7330     }
7331   }
7332
7333   return true;
7334 }
7335
7336 //================================================================================
7337 /*!
7338  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7339  */
7340 //================================================================================
7341
7342 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7343 {
7344   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7345   {
7346     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7347     if ( eov._eosC1.empty() ||
7348          eov.ShapeType() != TopAbs_VERTEX ||
7349          eov._edges.empty() )
7350       continue;
7351
7352     gp_XYZ newNorm   = eov._edges[0]->_normal;
7353     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7354     bool normChanged = false;
7355
7356     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7357     {
7358       _EdgesOnShape*   eoe = eov._eosC1[i];
7359       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7360       const double    eLen = SMESH_Algo::EdgeLength( e );
7361       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
7362       if ( oppV.IsSame( eov._shape ))
7363         oppV = SMESH_MesherHelper::IthVertex( 1, e );
7364       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7365       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7366       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7367
7368       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7369       if ( curThickOpp + curThick < eLen )
7370         continue;
7371
7372       double wgt = 2. * curThick / eLen;
7373       newNorm += wgt * eovOpp->_edges[0]->_normal;
7374       normChanged = true;
7375     }
7376     if ( normChanged )
7377     {
7378       eov._edges[0]->SetNormal( newNorm.Normalized() );
7379       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7380     }
7381   }
7382 }
7383
7384 //================================================================================
7385 /*!
7386  * \brief Modify normals of _LayerEdge's on _ConvexFace's
7387  */
7388 //================================================================================
7389
7390 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
7391                                                   SMESH_MesherHelper& helper,
7392                                                   int                 stepNb )
7393 {
7394   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7395   bool isOK;
7396
7397   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7398   for ( ; id2face != data._convexFaces.end(); ++id2face )
7399   {
7400     _ConvexFace & convFace = (*id2face).second;
7401     convFace._normalsFixedOnBorders = false; // to update at each inflation step
7402
7403     if ( convFace._normalsFixed )
7404       continue; // already fixed
7405     if ( convFace.CheckPrisms() )
7406       continue; // nothing to fix
7407
7408     convFace._normalsFixed = true;
7409
7410     BRepAdaptor_Surface surface ( convFace._face, false );
7411     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
7412
7413     // check if the convex FACE is of spherical shape
7414
7415     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7416     Bnd_B3d nodesBox;
7417     gp_Pnt  center;
7418
7419     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7420     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7421     {
7422       _EdgesOnShape& eos = *(id2eos->second);
7423       if ( eos.ShapeType() == TopAbs_VERTEX )
7424       {
7425         _LayerEdge* ledge = eos._edges[ 0 ];
7426         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7427           centersBox.Add( center );
7428       }
7429       for ( size_t i = 0; i < eos._edges.size(); ++i )
7430         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7431     }
7432     if ( centersBox.IsVoid() )
7433     {
7434       debugMsg( "Error: centersBox.IsVoid()" );
7435       return false;
7436     }
7437     const bool isSpherical =
7438       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7439
7440     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7441     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7442
7443     if ( isSpherical )
7444     {
7445       // set _LayerEdge::_normal as average of all normals
7446
7447       // WARNING: different density of nodes on EDGEs is not taken into account that
7448       // can lead to an improper new normal
7449
7450       gp_XYZ avgNormal( 0,0,0 );
7451       nbEdges = 0;
7452       id2eos = convFace._subIdToEOS.begin();
7453       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7454       {
7455         _EdgesOnShape& eos = *(id2eos->second);
7456         // set data of _CentralCurveOnEdge
7457         if ( eos.ShapeType() == TopAbs_EDGE )
7458         {
7459           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7460           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7461           if ( !eos._sWOL.IsNull() )
7462             ceCurve._adjFace.Nullify();
7463           else
7464             ceCurve._ledges.insert( ceCurve._ledges.end(),
7465                                     eos._edges.begin(), eos._edges.end());
7466         }
7467         // summarize normals
7468         for ( size_t i = 0; i < eos._edges.size(); ++i )
7469           avgNormal += eos._edges[ i ]->_normal;
7470       }
7471       double normSize = avgNormal.SquareModulus();
7472       if ( normSize < 1e-200 )
7473       {
7474         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7475         return false;
7476       }
7477       avgNormal /= Sqrt( normSize );
7478
7479       // compute new _LayerEdge::_cosin on EDGEs
7480       double avgCosin = 0;
7481       int     nbCosin = 0;
7482       gp_Vec inFaceDir;
7483       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7484       {
7485         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7486         if ( ceCurve._adjFace.IsNull() )
7487           continue;
7488         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7489         {
7490           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7491           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7492           if ( isOK )
7493           {
7494             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7495             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7496             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7497             nbCosin++;
7498           }
7499         }
7500       }
7501       if ( nbCosin > 0 )
7502         avgCosin /= nbCosin;
7503
7504       // set _LayerEdge::_normal = avgNormal
7505       id2eos = convFace._subIdToEOS.begin();
7506       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7507       {
7508         _EdgesOnShape& eos = *(id2eos->second);
7509         if ( eos.ShapeType() != TopAbs_EDGE )
7510           for ( size_t i = 0; i < eos._edges.size(); ++i )
7511             eos._edges[ i ]->_cosin = avgCosin;
7512
7513         for ( size_t i = 0; i < eos._edges.size(); ++i )
7514         {
7515           eos._edges[ i ]->SetNormal( avgNormal );
7516           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7517         }
7518       }
7519     }
7520     else // if ( isSpherical )
7521     {
7522       // We suppose that centers of curvature at all points of the FACE
7523       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7524       // having a common center of curvature we define the same new normal
7525       // as a sum of normals of _LayerEdge's on EDGEs among them.
7526
7527       // get all centers of curvature for each EDGE
7528
7529       helper.SetSubShape( convFace._face );
7530       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7531
7532       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7533       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7534       {
7535         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7536
7537         // set adjacent FACE
7538         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7539
7540         // get _LayerEdge's of the EDGE
7541         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7542         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7543         if ( !eos || eos->_edges.empty() )
7544         {
7545           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7546           for ( int iV = 0; iV < 2; ++iV )
7547           {
7548             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7549             TGeomID     vID = meshDS->ShapeToIndex( v );
7550             eos = data.GetShapeEdges( vID );
7551             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7552           }
7553           edgeLEdge    = &vertexLEdges[0];
7554           edgeLEdgeEnd = edgeLEdge + 2;
7555
7556           centerCurves[ iE ]._adjFace.Nullify();
7557         }
7558         else
7559         {
7560           if ( ! eos->_toSmooth )
7561             data.SortOnEdge( edge, eos->_edges );
7562           edgeLEdge    = &eos->_edges[ 0 ];
7563           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7564           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7565           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7566
7567           if ( ! eos->_sWOL.IsNull() )
7568             centerCurves[ iE ]._adjFace.Nullify();
7569         }
7570
7571         // Get curvature centers
7572
7573         centersBox.Clear();
7574
7575         if ( edgeLEdge[0]->IsOnEdge() &&
7576              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7577         { // 1st VERTEX
7578           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7579           centersBox.Add( center );
7580         }
7581         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7582           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7583           { // EDGE or VERTEXes
7584             centerCurves[ iE ].Append( center, *edgeLEdge );
7585             centersBox.Add( center );
7586           }
7587         if ( edgeLEdge[-1]->IsOnEdge() &&
7588              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7589         { // 2nd VERTEX
7590           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7591           centersBox.Add( center );
7592         }
7593         centerCurves[ iE ]._isDegenerated =
7594           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7595
7596       } // loop on EDGES of convFace._face to set up data of centerCurves
7597
7598       // Compute new normals for _LayerEdge's on EDGEs
7599
7600       double avgCosin = 0;
7601       int     nbCosin = 0;
7602       gp_Vec inFaceDir;
7603       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7604       {
7605         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7606         if ( ceCurve._isDegenerated )
7607           continue;
7608         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7609         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7610         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7611         {
7612           isOK = false;
7613           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7614           {
7615             if ( iE1 != iE2 )
7616               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7617           }
7618           if ( isOK && !ceCurve._adjFace.IsNull() )
7619           {
7620             // compute new _LayerEdge::_cosin
7621             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7622             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7623             if ( isOK )
7624             {
7625               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7626               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7627               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7628               nbCosin++;
7629             }
7630           }
7631         }
7632       }
7633       // set new normals to _LayerEdge's of NOT degenerated central curves
7634       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7635       {
7636         if ( centerCurves[ iE ]._isDegenerated )
7637           continue;
7638         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7639         {
7640           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7641           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7642         }
7643       }
7644       // set new normals to _LayerEdge's of     degenerated central curves
7645       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7646       {
7647         if ( !centerCurves[ iE ]._isDegenerated ||
7648              centerCurves[ iE ]._ledges.size() < 3 )
7649           continue;
7650         // new normal is an average of new normals at VERTEXes that
7651         // was computed on non-degenerated _CentralCurveOnEdge's
7652         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7653                            centerCurves[ iE ]._ledges.back ()->_normal );
7654         double sz = newNorm.Modulus();
7655         if ( sz < 1e-200 )
7656           continue;
7657         newNorm /= sz;
7658         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7659                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7660         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7661         {
7662           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7663           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7664           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7665         }
7666       }
7667
7668       // Find new normals for _LayerEdge's based on FACE
7669
7670       if ( nbCosin > 0 )
7671         avgCosin /= nbCosin;
7672       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7673       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7674       if ( id2eos != convFace._subIdToEOS.end() )
7675       {
7676         int iE = 0;
7677         gp_XYZ newNorm;
7678         _EdgesOnShape& eos = * ( id2eos->second );
7679         for ( size_t i = 0; i < eos._edges.size(); ++i )
7680         {
7681           _LayerEdge* ledge = eos._edges[ i ];
7682           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7683             continue;
7684           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7685           {
7686             iE = iE % centerCurves.size();
7687             if ( centerCurves[ iE ]._isDegenerated )
7688               continue;
7689             newNorm.SetCoord( 0,0,0 );
7690             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7691             {
7692               ledge->SetNormal( newNorm );
7693               ledge->_cosin  = avgCosin;
7694               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7695               break;
7696             }
7697           }
7698         }
7699       }
7700
7701     } // not a quasi-spherical FACE
7702
7703     // Update _LayerEdge's data according to a new normal
7704
7705     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7706                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7707
7708     id2eos = convFace._subIdToEOS.begin();
7709     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7710     {
7711       _EdgesOnShape& eos = * ( id2eos->second );
7712       for ( size_t i = 0; i < eos._edges.size(); ++i )
7713       {
7714         _LayerEdge* & ledge = eos._edges[ i ];
7715         double len = ledge->_len;
7716         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7717         ledge->SetCosin( ledge->_cosin );
7718         ledge->SetNewLength( len, eos, helper );
7719       }
7720       if ( eos.ShapeType() != TopAbs_FACE )
7721         for ( size_t i = 0; i < eos._edges.size(); ++i )
7722         {
7723           _LayerEdge* ledge = eos._edges[ i ];
7724           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7725           {
7726             _LayerEdge* neibor = ledge->_neibors[iN];
7727             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7728             {
7729               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7730               neibor->Set( _LayerEdge::MOVED );
7731               neibor->SetSmooLen( neibor->_len );
7732             }
7733           }
7734         }
7735     } // loop on sub-shapes of convFace._face
7736
7737     // Find FACEs adjacent to convFace._face that got necessity to smooth
7738     // as a result of normals modification
7739
7740     set< _EdgesOnShape* > adjFacesToSmooth;
7741     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7742     {
7743       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7744            centerCurves[ iE ]._adjFaceToSmooth )
7745         continue;
7746       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7747       {
7748         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7749         {
7750           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7751           break;
7752         }
7753       }
7754     }
7755     data.AddShapesToSmooth( adjFacesToSmooth );
7756
7757     dumpFunctionEnd();
7758
7759
7760   } // loop on data._convexFaces
7761
7762   return true;
7763 }
7764
7765 //================================================================================
7766 /*!
7767  * \brief Return max curvature of a FACE
7768  */
7769 //================================================================================
7770
7771 double _ConvexFace::GetMaxCurvature( _SolidData&         data,
7772                                      _EdgesOnShape&      eof,
7773                                      BRepLProp_SLProps&  surfProp,
7774                                      SMESH_MesherHelper& helper)
7775 {
7776   double maxCurvature = 0;
7777
7778   TopoDS_Face F = TopoDS::Face( eof._shape );
7779
7780   const int           nbTestPnt = 5;
7781   const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7782   SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7783   while ( smIt->more() )
7784   {
7785     SMESH_subMesh* sm = smIt->next();
7786     const TGeomID subID = sm->GetId();
7787
7788     // find _LayerEdge's of a sub-shape
7789     _EdgesOnShape* eos;
7790     if (( eos = data.GetShapeEdges( subID )))
7791       this->_subIdToEOS.insert( make_pair( subID, eos ));
7792     else
7793       continue;
7794
7795     // check concavity and curvature and limit data._stepSize
7796     const double minCurvature =
7797       1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7798     size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7799     for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7800     {
7801       gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7802       surfProp.SetParameters( uv.X(), uv.Y() );
7803       if ( surfProp.IsCurvatureDefined() )
7804       {
7805         double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7806                                 surfProp.MinCurvature() * oriFactor );
7807         maxCurvature = Max( maxCurvature, curvature );
7808
7809         if ( curvature > minCurvature )
7810           this->_isTooCurved = true;
7811       }
7812     }
7813   } // loop on sub-shapes of the FACE
7814
7815   return maxCurvature;
7816 }
7817
7818 //================================================================================
7819 /*!
7820  * \brief Finds a center of curvature of a surface at a _LayerEdge
7821  */
7822 //================================================================================
7823
7824 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7825                                         BRepLProp_SLProps&  surfProp,
7826                                         SMESH_MesherHelper& helper,
7827                                         gp_Pnt &            center ) const
7828 {
7829   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7830   surfProp.SetParameters( uv.X(), uv.Y() );
7831   if ( !surfProp.IsCurvatureDefined() )
7832     return false;
7833
7834   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7835   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7836   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7837   if ( surfCurvatureMin > surfCurvatureMax )
7838     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7839   else
7840     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7841
7842   return true;
7843 }
7844
7845 //================================================================================
7846 /*!
7847  * \brief Check that prisms are not distorted
7848  */
7849 //================================================================================
7850
7851 bool _ConvexFace::CheckPrisms() const
7852 {
7853   double vol = 0;
7854   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7855   {
7856     const _LayerEdge* edge = _simplexTestEdges[i];
7857     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7858     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7859       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7860       {
7861         debugMsg( "Bad simplex of _simplexTestEdges ("
7862                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7863                   << " "<< edge->_simplices[j]._nPrev->GetID()
7864                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7865         return false;
7866       }
7867   }
7868   return true;
7869 }
7870
7871 //================================================================================
7872 /*!
7873  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7874  *        stored in this _CentralCurveOnEdge.
7875  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7876  *  \param [in,out] newNormal - current normal at this point, to be redefined
7877  *  \return bool - true if succeeded.
7878  */
7879 //================================================================================
7880
7881 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7882 {
7883   if ( this->_isDegenerated )
7884     return false;
7885
7886   // find two centers the given one lies between
7887
7888   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7889   {
7890     double sl2 = 1.001 * _segLength2[ i ];
7891
7892     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7893     if ( d1 > sl2 )
7894       continue;
7895     
7896     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7897     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7898       continue;
7899
7900     d1 = Sqrt( d1 );
7901     d2 = Sqrt( d2 );
7902     double r = d1 / ( d1 + d2 );
7903     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7904                    (      r ) * _ledges[ i+1 ]->_normal );
7905     norm.Normalize();
7906
7907     newNormal += norm;
7908     double sz = newNormal.Modulus();
7909     if ( sz < 1e-200 )
7910       break;
7911     newNormal /= sz;
7912     return true;
7913   }
7914   return false;
7915 }
7916
7917 //================================================================================
7918 /*!
7919  * \brief Set shape members
7920  */
7921 //================================================================================
7922
7923 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7924                                      const _ConvexFace&  convFace,
7925                                      _SolidData&         data,
7926                                      SMESH_MesherHelper& helper)
7927 {
7928   _edge = edge;
7929
7930   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7931   while ( const TopoDS_Shape* F = fIt->next())
7932     if ( !convFace._face.IsSame( *F ))
7933     {
7934       _adjFace = TopoDS::Face( *F );
7935       _adjFaceToSmooth = false;
7936       // _adjFace already in a smoothing queue ?
7937       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7938         _adjFaceToSmooth = eos->_toSmooth;
7939       break;
7940     }
7941 }
7942
7943 //================================================================================
7944 /*!
7945  * \brief Looks for intersection of it's last segment with faces
7946  *  \param distance - returns shortest distance from the last node to intersection
7947  */
7948 //================================================================================
7949
7950 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7951                                    double &                 distance,
7952                                    const double&            epsilon,
7953                                    _EdgesOnShape&           eos,
7954                                    const SMDS_MeshElement** intFace)
7955 {
7956   vector< const SMDS_MeshElement* > suspectFaces;
7957   double segLen;
7958   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7959   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7960
7961   bool segmentIntersected = false;
7962   distance = Precision::Infinite();
7963   int iFace = -1; // intersected face
7964   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7965   {
7966     const SMDS_MeshElement* face = suspectFaces[j];
7967     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7968          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7969       continue; // face sharing _LayerEdge node
7970     const int nbNodes = face->NbCornerNodes();
7971     bool intFound = false;
7972     double dist;
7973     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7974     if ( nbNodes == 3 )
7975     {
7976       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7977     }
7978     else
7979     {
7980       const SMDS_MeshNode* tria[3];
7981       tria[0] = *nIt++;
7982       tria[1] = *nIt++;
7983       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7984       {
7985         tria[2] = *nIt++;
7986         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7987         tria[1] = tria[2];
7988       }
7989     }
7990     if ( intFound )
7991     {
7992       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7993         segmentIntersected = true;
7994       if ( distance > dist )
7995         distance = dist, iFace = j;
7996     }
7997   }
7998   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7999
8000   distance -= segLen;
8001
8002   if ( segmentIntersected )
8003   {
8004 #ifdef __myDEBUG
8005     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8006     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8007     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8008          << ", intersection with face ("
8009          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8010          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8011          << ") distance = " << distance << endl;
8012 #endif
8013   }
8014
8015   return segmentIntersected;
8016 }
8017
8018 //================================================================================
8019 /*!
8020  * \brief Returns a point used to check orientation of _simplices
8021  */
8022 //================================================================================
8023
8024 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8025 {
8026   size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8027
8028   if ( !eos || eos->_sWOL.IsNull() )
8029     return _pos[ i ];
8030
8031   if ( eos->SWOLType() == TopAbs_EDGE )
8032   {
8033     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8034   }
8035   //else //  TopAbs_FACE
8036
8037   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8038 }
8039
8040 //================================================================================
8041 /*!
8042  * \brief Returns size and direction of the last segment
8043  */
8044 //================================================================================
8045
8046 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8047 {
8048   // find two non-coincident positions
8049   gp_XYZ orig = _pos.back();
8050   gp_XYZ vec;
8051   int iPrev = _pos.size() - 2;
8052   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8053   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8054   while ( iPrev >= 0 )
8055   {
8056     vec = orig - _pos[iPrev];
8057     if ( vec.SquareModulus() > tol*tol )
8058       break;
8059     else
8060       iPrev--;
8061   }
8062
8063   // make gp_Ax1
8064   gp_Ax1 segDir;
8065   if ( iPrev < 0 )
8066   {
8067     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8068     segDir.SetDirection( _normal );
8069     segLen = 0;
8070   }
8071   else
8072   {
8073     gp_Pnt pPrev = _pos[ iPrev ];
8074     if ( !eos._sWOL.IsNull() )
8075     {
8076       TopLoc_Location loc;
8077       if ( eos.SWOLType() == TopAbs_EDGE )
8078       {
8079         double f,l;
8080         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8081         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8082       }
8083       else
8084       {
8085         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8086         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8087       }
8088       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8089     }
8090     segDir.SetLocation( pPrev );
8091     segDir.SetDirection( vec );
8092     segLen = vec.Modulus();
8093   }
8094
8095   return segDir;
8096 }
8097
8098 //================================================================================
8099 /*!
8100  * \brief Return the last (or \a which) position of the target node on a FACE. 
8101  *  \param [in] F - the FACE this _LayerEdge is inflated along
8102  *  \param [in] which - index of position
8103  *  \return gp_XY - result UV
8104  */
8105 //================================================================================
8106
8107 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8108 {
8109   if ( F.IsSame( eos._sWOL )) // F is my FACE
8110     return gp_XY( _pos.back().X(), _pos.back().Y() );
8111
8112   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8113     return gp_XY( 1e100, 1e100 );
8114
8115   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8116   double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8117   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8118   if ( !C2d.IsNull() && f <= u && u <= l )
8119     return C2d->Value( u ).XY();
8120
8121   return gp_XY( 1e100, 1e100 );
8122 }
8123
8124 //================================================================================
8125 /*!
8126  * \brief Test intersection of the last segment with a given triangle
8127  *   using Moller-Trumbore algorithm
8128  * Intersection is detected if distance to intersection is less than _LayerEdge._len
8129  */
8130 //================================================================================
8131
8132 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8133                                const gp_XYZ& vert0,
8134                                const gp_XYZ& vert1,
8135                                const gp_XYZ& vert2,
8136                                double&       t,
8137                                const double& EPSILON) const
8138 {
8139   const gp_Pnt& orig = lastSegment.Location();
8140   const gp_Dir& dir  = lastSegment.Direction();
8141
8142   /* calculate distance from vert0 to ray origin */
8143   //gp_XYZ tvec = orig.XYZ() - vert0;
8144
8145   //if ( tvec * dir > EPSILON )
8146     // intersected face is at back side of the temporary face this _LayerEdge belongs to
8147     //return false;
8148
8149   gp_XYZ edge1 = vert1 - vert0;
8150   gp_XYZ edge2 = vert2 - vert0;
8151
8152   /* begin calculating determinant - also used to calculate U parameter */
8153   gp_XYZ pvec = dir.XYZ() ^ edge2;
8154
8155   /* if determinant is near zero, ray lies in plane of triangle */
8156   double det = edge1 * pvec;
8157
8158   const double ANGL_EPSILON = 1e-12;
8159   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8160     return false;
8161
8162   /* calculate distance from vert0 to ray origin */
8163   gp_XYZ tvec = orig.XYZ() - vert0;
8164
8165   /* calculate U parameter and test bounds */
8166   double u = ( tvec * pvec ) / det;
8167   //if (u < 0.0 || u > 1.0)
8168   if ( u < -EPSILON || u > 1.0 + EPSILON )
8169     return false;
8170
8171   /* prepare to test V parameter */
8172   gp_XYZ qvec = tvec ^ edge1;
8173
8174   /* calculate V parameter and test bounds */
8175   double v = (dir.XYZ() * qvec) / det;
8176   //if ( v < 0.0 || u + v > 1.0 )
8177   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8178     return false;
8179
8180   /* calculate t, ray intersects triangle */
8181   t = (edge2 * qvec) / det;
8182
8183   //return true;
8184   return t > 0.;
8185 }
8186
8187 //================================================================================
8188 /*!
8189  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8190  *        neighbor _LayerEdge's by it's own inflation vector.
8191  *  \param [in] eov - EOS of the VERTEX
8192  *  \param [in] eos - EOS of the FACE
8193  *  \param [in] step - inflation step
8194  *  \param [in,out] badSmooEdges - tangled _LayerEdge's
8195  */
8196 //================================================================================
8197
8198 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
8199                                    const _EdgesOnShape*    eos,
8200                                    const int               step,
8201                                    vector< _LayerEdge* > & badSmooEdges )
8202 {
8203   // check if any of _neibors is in badSmooEdges
8204   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8205                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8206     return;
8207
8208   // get all edges to move
8209
8210   set< _LayerEdge* > edges;
8211
8212   // find a distance between _LayerEdge on VERTEX and its neighbors
8213   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
8214   double dist2 = 0;
8215   for ( size_t i = 0; i < _neibors.size(); ++i )
8216   {
8217     _LayerEdge* nEdge = _neibors[i];
8218     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8219     {
8220       edges.insert( nEdge );
8221       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8222     }
8223   }
8224   // add _LayerEdge's close to curPosV
8225   size_t nbE;
8226   do {
8227     nbE = edges.size();
8228     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8229     {
8230       _LayerEdge* edgeF = *e;
8231       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8232       {
8233         _LayerEdge* nEdge = edgeF->_neibors[i];
8234         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8235              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8236           edges.insert( nEdge );
8237       }
8238     }
8239   }
8240   while ( nbE < edges.size() );
8241
8242   // move the target node of the got edges
8243
8244   gp_XYZ prevPosV = PrevPos();
8245   if ( eov->SWOLType() == TopAbs_EDGE )
8246   {
8247     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8248     prevPosV = curve.Value( prevPosV.X() ).XYZ();
8249   }
8250   else if ( eov->SWOLType() == TopAbs_FACE )
8251   {
8252     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8253     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8254   }
8255
8256   SMDS_FacePositionPtr fPos;
8257   //double r = 1. - Min( 0.9, step / 10. );
8258   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8259   {
8260     _LayerEdge*       edgeF = *e;
8261     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
8262     const gp_XYZ    newPosF = curPosV + prevVF;
8263     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8264     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8265     edgeF->_pos.back() = newPosF;
8266     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8267
8268     // set _curvature to make edgeF updated by putOnOffsetSurface()
8269     if ( !edgeF->_curvature )
8270       if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8271       {
8272         edgeF->_curvature = new _Curvature;
8273         edgeF->_curvature->_r = 0;
8274         edgeF->_curvature->_k = 0;
8275         edgeF->_curvature->_h2lenRatio = 0;
8276         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8277       }
8278   }
8279   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8280   //                      SMESH_TNodeXYZ( _nodes[0]    ));
8281   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8282   // {
8283   //   _LayerEdge*      edgeF = *e;
8284   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8285   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8286   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8287   //   edgeF->_pos.back() = newPosF;
8288   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8289   // }
8290
8291   // smooth _LayerEdge's around moved nodes
8292   //size_t nbBadBefore = badSmooEdges.size();
8293   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8294   {
8295     _LayerEdge* edgeF = *e;
8296     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8297       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8298         //&& !edges.count( edgeF->_neibors[j] ))
8299       {
8300         _LayerEdge* edgeFN = edgeF->_neibors[j];
8301         edgeFN->Unset( SMOOTHED );
8302         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8303         // if ( nbBad > 0 )
8304         // {
8305         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8306         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8307         //   int        nbBadAfter = edgeFN->_simplices.size();
8308         //   double vol;
8309         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8310         //   {
8311         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8312         //   }
8313         //   if ( nbBadAfter <= nbBad )
8314         //   {
8315         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8316         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8317         //     edgeF->_pos.back() = newPosF;
8318         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8319         //     nbBad = nbBadAfter;
8320         //   }
8321         // }
8322         if ( nbBad > 0 )
8323           badSmooEdges.push_back( edgeFN );
8324       }
8325   }
8326     // move a bit not smoothed around moved nodes
8327   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8328   //   {
8329   //   _LayerEdge*      edgeF = badSmooEdges[i];
8330   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8331   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8332   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8333   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8334   //   edgeF->_pos.back() = newPosF;
8335   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8336   // }
8337 }
8338
8339 //================================================================================
8340 /*!
8341  * \brief Perform smooth of _LayerEdge's based on EDGE's
8342  *  \retval bool - true if node has been moved
8343  */
8344 //================================================================================
8345
8346 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8347                               const TopoDS_Face&             F,
8348                               SMESH_MesherHelper&            helper)
8349 {
8350   ASSERT( IsOnEdge() );
8351
8352   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8353   SMESH_TNodeXYZ oldPos( tgtNode );
8354   double dist01, distNewOld;
8355   
8356   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8357   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8358   dist01 = p0.Distance( _2neibors->tgtNode(1) );
8359
8360   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8361   double lenDelta = 0;
8362   if ( _curvature )
8363   {
8364     //lenDelta = _curvature->lenDelta( _len );
8365     lenDelta = _curvature->lenDeltaByDist( dist01 );
8366     newPos.ChangeCoord() += _normal * lenDelta;
8367   }
8368
8369   distNewOld = newPos.Distance( oldPos );
8370
8371   if ( F.IsNull() )
8372   {
8373     if ( _2neibors->_plnNorm )
8374     {
8375       // put newPos on the plane defined by source node and _plnNorm
8376       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8377       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8378       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8379     }
8380     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8381     _pos.back() = newPos.XYZ();
8382   }
8383   else
8384   {
8385     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8386     gp_XY uv( Precision::Infinite(), 0 );
8387     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8388     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8389
8390     newPos = surface->Value( uv );
8391     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8392   }
8393
8394   // commented for IPAL0052478
8395   // if ( _curvature && lenDelta < 0 )
8396   // {
8397   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8398   //   _len -= prevPos.Distance( oldPos );
8399   //   _len += prevPos.Distance( newPos );
8400   // }
8401   bool moved = distNewOld > dist01/50;
8402   //if ( moved )
8403   dumpMove( tgtNode ); // debug
8404
8405   return moved;
8406 }
8407
8408 //================================================================================
8409 /*!
8410  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8411  */
8412 //================================================================================
8413
8414 void _LayerEdge::SmoothWoCheck()
8415 {
8416   if ( Is( DIFFICULT ))
8417     return;
8418
8419   bool moved = Is( SMOOTHED );
8420   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
8421     moved = _neibors[i]->Is( SMOOTHED );
8422   if ( !moved )
8423     return;
8424
8425   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8426
8427   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8428   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8429   _pos.back() = newPos;
8430
8431   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8432 }
8433
8434 //================================================================================
8435 /*!
8436  * \brief Checks validity of _neibors on EDGEs and VERTEXes
8437  */
8438 //================================================================================
8439
8440 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8441 {
8442   if ( ! Is( NEAR_BOUNDARY ))
8443     return 0;
8444
8445   int nbBad = 0;
8446   double vol;
8447   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8448   {
8449     _LayerEdge* eN = _neibors[iN];
8450     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8451       continue;
8452     if ( needSmooth )
8453       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8454                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8455                        eN->_pos.size() != _pos.size() );
8456
8457     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8458     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8459     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8460       if ( eN->_nodes.size() > 1 &&
8461            eN->_simplices[i].Includes( _nodes.back() ) &&
8462            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8463       {
8464         ++nbBad;
8465         if ( badNeibors )
8466         {
8467           badNeibors->push_back( eN );
8468           debugMsg("Bad boundary simplex ( "
8469                    << " "<< eN->_nodes[0]->GetID()
8470                    << " "<< eN->_nodes.back()->GetID()
8471                    << " "<< eN->_simplices[i]._nPrev->GetID()
8472                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8473         }
8474         else
8475         {
8476           break;
8477         }
8478       }
8479   }
8480   return nbBad;
8481 }
8482
8483 //================================================================================
8484 /*!
8485  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8486  *  \retval int - nb of bad simplices around this _LayerEdge
8487  */
8488 //================================================================================
8489
8490 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8491 {
8492   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8493     return 0; // shape of simplices not changed
8494   if ( _simplices.size() < 2 )
8495     return 0; // _LayerEdge inflated along EDGE or FACE
8496
8497   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8498     findBest = true;
8499
8500   const gp_XYZ& curPos  = _pos.back();
8501   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8502
8503   // quality metrics (orientation) of tetras around _tgtNode
8504   int nbOkBefore = 0;
8505   double vol, minVolBefore = 1e100;
8506   for ( size_t i = 0; i < _simplices.size(); ++i )
8507   {
8508     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8509     minVolBefore = Min( minVolBefore, vol );
8510   }
8511   int nbBad = _simplices.size() - nbOkBefore;
8512
8513   bool bndNeedSmooth = false;
8514   if ( nbBad == 0 )
8515     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8516   if ( nbBad > 0 )
8517     Set( DISTORTED );
8518
8519   // evaluate min angle
8520   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8521   {
8522     size_t nbGoodAngles = _simplices.size();
8523     double angle;
8524     for ( size_t i = 0; i < _simplices.size(); ++i )
8525     {
8526       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8527         --nbGoodAngles;
8528     }
8529     if ( nbGoodAngles == _simplices.size() )
8530     {
8531       Unset( MOVED );
8532       return 0;
8533     }
8534   }
8535   if ( Is( ON_CONCAVE_FACE ))
8536     findBest = true;
8537
8538   if ( step % 2 == 0 )
8539     findBest = false;
8540
8541   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8542   {
8543     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8544       _smooFunction = _funs[ FUN_CENTROIDAL ];
8545     else
8546       _smooFunction = _funs[ FUN_LAPLACIAN ];
8547   }
8548
8549   // compute new position for the last _pos using different _funs
8550   gp_XYZ newPos;
8551   bool moved = false;
8552   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8553   {
8554     if ( iFun < 0 )
8555       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8556     else if ( _funs[ iFun ] == _smooFunction )
8557       continue; // _smooFunction again
8558     else if ( step > 1 )
8559       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8560     else
8561       break; // let "easy" functions improve elements around distorted ones
8562
8563     if ( _curvature )
8564     {
8565       double delta  = _curvature->lenDelta( _len );
8566       if ( delta > 0 )
8567         newPos += _normal * delta;
8568       else
8569       {
8570         double segLen = _normal * ( newPos - prevPos );
8571         if ( segLen + delta > 0 )
8572           newPos += _normal * delta;
8573       }
8574       // double segLenChange = _normal * ( curPos - newPos );
8575       // newPos += 0.5 * _normal * segLenChange;
8576     }
8577
8578     int nbOkAfter = 0;
8579     double minVolAfter = 1e100;
8580     for ( size_t i = 0; i < _simplices.size(); ++i )
8581     {
8582       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8583       minVolAfter = Min( minVolAfter, vol );
8584     }
8585     // get worse?
8586     if ( nbOkAfter < nbOkBefore )
8587       continue;
8588
8589     if (( findBest ) &&
8590         ( nbOkAfter == nbOkBefore ) &&
8591         ( minVolAfter <= minVolBefore ))
8592       continue;
8593
8594     nbBad        = _simplices.size() - nbOkAfter;
8595     minVolBefore = minVolAfter;
8596     nbOkBefore   = nbOkAfter;
8597     moved        = true;
8598
8599     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8600     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8601     _pos.back() = newPos;
8602
8603     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8604                   << (nbBad ? " --BAD" : ""));
8605
8606     if ( iFun > -1 )
8607     {
8608       continue; // look for a better function
8609     }
8610
8611     if ( !findBest )
8612       break;
8613
8614   } // loop on smoothing functions
8615
8616   if ( moved ) // notify _neibors
8617   {
8618     Set( SMOOTHED );
8619     for ( size_t i = 0; i < _neibors.size(); ++i )
8620       if ( !_neibors[i]->Is( MOVED ))
8621       {
8622         _neibors[i]->Set( MOVED );
8623         toSmooth.push_back( _neibors[i] );
8624       }
8625   }
8626
8627   return nbBad;
8628 }
8629
8630 //================================================================================
8631 /*!
8632  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8633  *  \retval int - nb of bad simplices around this _LayerEdge
8634  */
8635 //================================================================================
8636
8637 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8638 {
8639   if ( !_smooFunction )
8640     return 0; // _LayerEdge inflated along EDGE or FACE
8641   if ( Is( BLOCKED ))
8642     return 0; // not inflated
8643
8644   const gp_XYZ& curPos  = _pos.back();
8645   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8646
8647   // quality metrics (orientation) of tetras around _tgtNode
8648   int nbOkBefore = 0;
8649   double vol, minVolBefore = 1e100;
8650   for ( size_t i = 0; i < _simplices.size(); ++i )
8651   {
8652     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8653     minVolBefore = Min( minVolBefore, vol );
8654   }
8655   int nbBad = _simplices.size() - nbOkBefore;
8656
8657   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8658   {
8659     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8660       _smooFunction = _funs[ FUN_LAPLACIAN ];
8661     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8662       _smooFunction = _funs[ FUN_CENTROIDAL ];
8663   }
8664
8665   // compute new position for the last _pos using different _funs
8666   gp_XYZ newPos;
8667   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8668   {
8669     if ( iFun < 0 )
8670       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8671     else if ( _funs[ iFun ] == _smooFunction )
8672       continue; // _smooFunction again
8673     else if ( step > 1 )
8674       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8675     else
8676       break; // let "easy" functions improve elements around distorted ones
8677
8678     if ( _curvature )
8679     {
8680       double delta  = _curvature->lenDelta( _len );
8681       if ( delta > 0 )
8682         newPos += _normal * delta;
8683       else
8684       {
8685         double segLen = _normal * ( newPos - prevPos );
8686         if ( segLen + delta > 0 )
8687           newPos += _normal * delta;
8688       }
8689       // double segLenChange = _normal * ( curPos - newPos );
8690       // newPos += 0.5 * _normal * segLenChange;
8691     }
8692
8693     int nbOkAfter = 0;
8694     double minVolAfter = 1e100;
8695     for ( size_t i = 0; i < _simplices.size(); ++i )
8696     {
8697       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8698       minVolAfter = Min( minVolAfter, vol );
8699     }
8700     // get worse?
8701     if ( nbOkAfter < nbOkBefore )
8702       continue;
8703     if (( isConcaveFace || findBest ) &&
8704         ( nbOkAfter == nbOkBefore ) &&
8705         ( minVolAfter <= minVolBefore )
8706         )
8707       continue;
8708
8709     nbBad        = _simplices.size() - nbOkAfter;
8710     minVolBefore = minVolAfter;
8711     nbOkBefore   = nbOkAfter;
8712
8713     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8714     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8715     _pos.back() = newPos;
8716
8717     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8718                   << ( nbBad ? "--BAD" : ""));
8719
8720     // commented for IPAL0052478
8721     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8722     // _len += prevPos.Distance(newPos);
8723
8724     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8725     {
8726       //_smooFunction = _funs[ iFun ];
8727       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8728       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8729       // << " minVol: " << minVolAfter
8730       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8731       // << endl;
8732       continue; // look for a better function
8733     }
8734
8735     if ( !findBest )
8736       break;
8737
8738   } // loop on smoothing functions
8739
8740   return nbBad;
8741 }
8742
8743 //================================================================================
8744 /*!
8745  * \brief Chooses a smoothing technique giving a position most close to an initial one.
8746  *        For a correct result, _simplices must contain nodes lying on geometry.
8747  */
8748 //================================================================================
8749
8750 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8751                                      const TNode2Edge&     n2eMap)
8752 {
8753   if ( _smooFunction ) return;
8754
8755   // use smoothNefPolygon() near concaveVertices
8756   if ( !concaveVertices.empty() )
8757   {
8758     _smooFunction = _funs[ FUN_CENTROIDAL ];
8759
8760     Set( ON_CONCAVE_FACE );
8761
8762     for ( size_t i = 0; i < _simplices.size(); ++i )
8763     {
8764       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8765       {
8766         _smooFunction = _funs[ FUN_NEFPOLY ];
8767
8768         // set FUN_CENTROIDAL to neighbor edges
8769         for ( i = 0; i < _neibors.size(); ++i )
8770         {
8771           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8772           {
8773             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8774           }
8775         }
8776         return;
8777       }
8778     }
8779
8780     // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8781     // // where the nodes are smoothed too far along a sphere thus creating
8782     // // inverted _simplices
8783     // double dist[theNbSmooFuns];
8784     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8785     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8786
8787     // double minDist = Precision::Infinite();
8788     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8789     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8790     // {
8791     //   gp_Pnt newP = (this->*_funs[i])();
8792     //   dist[i] = p.SquareDistance( newP );
8793     //   if ( dist[i]*coef[i] < minDist )
8794     //   {
8795     //     _smooFunction = _funs[i];
8796     //     minDist = dist[i]*coef[i];
8797     //   }
8798     // }
8799   }
8800   else
8801   {
8802     _smooFunction = _funs[ FUN_LAPLACIAN ];
8803   }
8804   // int minDim = 3;
8805   // for ( size_t i = 0; i < _simplices.size(); ++i )
8806   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8807   // if ( minDim == 0 )
8808   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8809   // else if ( minDim == 1 )
8810   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8811
8812
8813   // int iMin;
8814   // for ( int i = 0; i < FUN_NB; ++i )
8815   // {
8816   //   //cout << dist[i] << " ";
8817   //   if ( _smooFunction == _funs[i] ) {
8818   //     iMin = i;
8819   //     //debugMsg( fNames[i] );
8820   //     break;
8821   //   }
8822   // }
8823   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8824 }
8825
8826 //================================================================================
8827 /*!
8828  * \brief Returns a name of _SmooFunction
8829  */
8830 //================================================================================
8831
8832 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8833 {
8834   if ( !fun )
8835     fun = _smooFunction;
8836   for ( int i = 0; i < theNbSmooFuns; ++i )
8837     if ( fun == _funs[i] )
8838       return i;
8839
8840   return theNbSmooFuns;
8841 }
8842
8843 //================================================================================
8844 /*!
8845  * \brief Computes a new node position using Laplacian smoothing
8846  */
8847 //================================================================================
8848
8849 gp_XYZ _LayerEdge::smoothLaplacian()
8850 {
8851   gp_XYZ newPos (0,0,0);
8852   for ( size_t i = 0; i < _simplices.size(); ++i )
8853     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8854   newPos /= _simplices.size();
8855
8856   return newPos;
8857 }
8858
8859 //================================================================================
8860 /*!
8861  * \brief Computes a new node position using angular-based smoothing
8862  */
8863 //================================================================================
8864
8865 gp_XYZ _LayerEdge::smoothAngular()
8866 {
8867   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8868   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8869   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8870
8871   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8872   gp_XYZ pN( 0,0,0 );
8873   for ( size_t i = 0; i < _simplices.size(); ++i )
8874   {
8875     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8876     edgeDir.push_back( p - pPrev );
8877     edgeSize.push_back( edgeDir.back().Magnitude() );
8878     if ( edgeSize.back() < numeric_limits<double>::min() )
8879     {
8880       edgeDir.pop_back();
8881       edgeSize.pop_back();
8882     }
8883     else
8884     {
8885       edgeDir.back() /= edgeSize.back();
8886       points.push_back( p );
8887       pN += p;
8888     }
8889     pPrev = p;
8890   }
8891   edgeDir.push_back ( edgeDir[0] );
8892   edgeSize.push_back( edgeSize[0] );
8893   pN /= points.size();
8894
8895   gp_XYZ newPos(0,0,0);
8896   double sumSize = 0;
8897   for ( size_t i = 0; i < points.size(); ++i )
8898   {
8899     gp_Vec toN    = pN - points[i];
8900     double toNLen = toN.Magnitude();
8901     if ( toNLen < numeric_limits<double>::min() )
8902     {
8903       newPos += pN;
8904       continue;
8905     }
8906     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8907     double bisecLen = bisec.SquareMagnitude();
8908     if ( bisecLen < numeric_limits<double>::min() )
8909     {
8910       gp_Vec norm = edgeDir[i] ^ toN;
8911       bisec = norm ^ edgeDir[i];
8912       bisecLen = bisec.SquareMagnitude();
8913     }
8914     bisecLen = Sqrt( bisecLen );
8915     bisec /= bisecLen;
8916
8917 #if 1
8918     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8919     sumSize += bisecLen;
8920 #else
8921     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8922     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8923 #endif
8924     newPos += pNew;
8925   }
8926   newPos /= sumSize;
8927
8928   // project newPos to an average plane
8929
8930   gp_XYZ norm(0,0,0); // plane normal
8931   points.push_back( points[0] );
8932   for ( size_t i = 1; i < points.size(); ++i )
8933   {
8934     gp_XYZ vec1 = points[ i-1 ] - pN;
8935     gp_XYZ vec2 = points[ i   ] - pN;
8936     gp_XYZ cross = vec1 ^ vec2;
8937     try {
8938       cross.Normalize();
8939       if ( cross * norm < numeric_limits<double>::min() )
8940         norm += cross.Reversed();
8941       else
8942         norm += cross;
8943     }
8944     catch (Standard_Failure) { // if |cross| == 0.
8945     }
8946   }
8947   gp_XYZ vec = newPos - pN;
8948   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8949   newPos     = newPos - r * norm;
8950
8951   return newPos;
8952 }
8953
8954 //================================================================================
8955 /*!
8956  * \brief Computes a new node position using weigthed node positions
8957  */
8958 //================================================================================
8959
8960 gp_XYZ _LayerEdge::smoothLengthWeighted()
8961 {
8962   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8963   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8964
8965   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8966   for ( size_t i = 0; i < _simplices.size(); ++i )
8967   {
8968     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8969     edgeSize.push_back( ( p - pPrev ).Modulus() );
8970     if ( edgeSize.back() < numeric_limits<double>::min() )
8971     {
8972       edgeSize.pop_back();
8973     }
8974     else
8975     {
8976       points.push_back( p );
8977     }
8978     pPrev = p;
8979   }
8980   edgeSize.push_back( edgeSize[0] );
8981
8982   gp_XYZ newPos(0,0,0);
8983   double sumSize = 0;
8984   for ( size_t i = 0; i < points.size(); ++i )
8985   {
8986     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8987     sumSize += edgeSize[i] + edgeSize[i+1];
8988   }
8989   newPos /= sumSize;
8990   return newPos;
8991 }
8992
8993 //================================================================================
8994 /*!
8995  * \brief Computes a new node position using angular-based smoothing
8996  */
8997 //================================================================================
8998
8999 gp_XYZ _LayerEdge::smoothCentroidal()
9000 {
9001   gp_XYZ newPos(0,0,0);
9002   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9003   double sumSize = 0;
9004   for ( size_t i = 0; i < _simplices.size(); ++i )
9005   {
9006     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9007     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9008     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9009     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9010
9011     sumSize += size;
9012     newPos += gc * size;
9013   }
9014   newPos /= sumSize;
9015
9016   return newPos;
9017 }
9018
9019 //================================================================================
9020 /*!
9021  * \brief Computes a new node position located inside a Nef polygon
9022  */
9023 //================================================================================
9024
9025 gp_XYZ _LayerEdge::smoothNefPolygon()
9026 #ifdef OLD_NEF_POLYGON
9027 {
9028   gp_XYZ newPos(0,0,0);
9029
9030   // get a plane to search a solution on
9031
9032   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9033   size_t i;
9034   const double tol = numeric_limits<double>::min();
9035   gp_XYZ center(0,0,0);
9036   for ( i = 0; i < _simplices.size(); ++i )
9037   {
9038     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9039                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9040     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9041   }
9042   vecs.back() = vecs[0];
9043   center /= _simplices.size();
9044
9045   gp_XYZ zAxis(0,0,0);
9046   for ( i = 0; i < _simplices.size(); ++i )
9047     zAxis += vecs[i] ^ vecs[i+1];
9048
9049   gp_XYZ yAxis;
9050   for ( i = 0; i < _simplices.size(); ++i )
9051   {
9052     yAxis = vecs[i];
9053     if ( yAxis.SquareModulus() > tol )
9054       break;
9055   }
9056   gp_XYZ xAxis = yAxis ^ zAxis;
9057   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9058   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9059   //                             p0.Distance( _simplices[2]._nPrev ));
9060   // gp_XYZ center = smoothLaplacian();
9061   // gp_XYZ xAxis, yAxis, zAxis;
9062   // for ( i = 0; i < _simplices.size(); ++i )
9063   // {
9064   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9065   //   if ( xAxis.SquareModulus() > tol*tol )
9066   //     break;
9067   // }
9068   // for ( i = 1; i < _simplices.size(); ++i )
9069   // {
9070   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9071   //   zAxis = xAxis ^ yAxis;
9072   //   if ( zAxis.SquareModulus() > tol*tol )
9073   //     break;
9074   // }
9075   // if ( i == _simplices.size() ) return newPos;
9076
9077   yAxis = zAxis ^ xAxis;
9078   xAxis /= xAxis.Modulus();
9079   yAxis /= yAxis.Modulus();
9080
9081   // get half-planes of _simplices
9082
9083   vector< _halfPlane > halfPlns( _simplices.size() );
9084   int nbHP = 0;
9085   for ( size_t i = 0; i < _simplices.size(); ++i )
9086   {
9087     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9088     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9089     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9090     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9091     gp_XY  vec12 = p2 - p1;
9092     double dist12 = vec12.Modulus();
9093     if ( dist12 < tol )
9094       continue;
9095     vec12 /= dist12;
9096     halfPlns[ nbHP ]._pos = p1;
9097     halfPlns[ nbHP ]._dir = vec12;
9098     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9099     ++nbHP;
9100   }
9101
9102   // intersect boundaries of half-planes, define state of intersection points
9103   // in relation to all half-planes and calculate internal point of a 2D polygon
9104
9105   double sumLen = 0;
9106   gp_XY newPos2D (0,0);
9107
9108   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9109   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9110   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9111
9112   vector< vector< TIntPntState > > allIntPnts( nbHP );
9113   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9114   {
9115     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9116     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9117
9118     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9119     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9120
9121     int nbNotOut = 0;
9122     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9123
9124     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9125     {
9126       if ( iHP1 == iHP2 ) continue;
9127
9128       TIntPntState & ips1 = intPnts1[ iHP2 ];
9129       if ( ips1.second == UNDEF )
9130       {
9131         // find an intersection point of boundaries of iHP1 and iHP2
9132
9133         if ( iHP2 == iPrev ) // intersection with neighbors is known
9134           ips1.first = halfPlns[ iHP1 ]._pos;
9135         else if ( iHP2 == iNext )
9136           ips1.first = halfPlns[ iHP2 ]._pos;
9137         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9138           ips1.second = NO_INT;
9139
9140         // classify the found intersection point
9141         if ( ips1.second != NO_INT )
9142         {
9143           ips1.second = NOT_OUT;
9144           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9145             if ( i != iHP1 && i != iHP2 &&
9146                  halfPlns[ i ].IsOut( ips1.first, tol ))
9147               ips1.second = IS_OUT;
9148         }
9149         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9150         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9151         TIntPntState & ips2 = intPnts2[ iHP1 ];
9152         ips2 = ips1;
9153       }
9154       if ( ips1.second == NOT_OUT )
9155       {
9156         ++nbNotOut;
9157         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9158       }
9159     }
9160
9161     // find a NOT_OUT segment of boundary which is located between
9162     // two NOT_OUT int points
9163
9164     if ( nbNotOut < 2 )
9165       continue; // no such a segment
9166
9167     if ( nbNotOut > 2 )
9168     {
9169       // sort points along the boundary
9170       map< double, TIntPntState* > ipsByParam;
9171       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9172       {
9173         TIntPntState & ips1 = intPnts1[ iHP2 ];
9174         if ( ips1.second != NO_INT )
9175         {
9176           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9177           double param = op * halfPlns[ iHP1 ]._dir;
9178           ipsByParam.insert( make_pair( param, & ips1 ));
9179         }
9180       }
9181       // look for two neighboring NOT_OUT points
9182       nbNotOut = 0;
9183       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9184       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9185       {
9186         TIntPntState & ips1 = *(u2ips->second);
9187         if ( ips1.second == NOT_OUT )
9188           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9189         else if ( nbNotOut >= 2 )
9190           break;
9191         else
9192           nbNotOut = 0;
9193       }
9194     }
9195
9196     if ( nbNotOut >= 2 )
9197     {
9198       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9199       sumLen += len;
9200
9201       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9202     }
9203   }
9204
9205   if ( sumLen > 0 )
9206   {
9207     newPos2D /= sumLen;
9208     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9209   }
9210   else
9211   {
9212     newPos = center;
9213   }
9214
9215   return newPos;
9216 }
9217 #else // OLD_NEF_POLYGON
9218 { ////////////////////////////////// NEW
9219   gp_XYZ newPos(0,0,0);
9220
9221   // get a plane to search a solution on
9222
9223   size_t i;
9224   gp_XYZ center(0,0,0);
9225   for ( i = 0; i < _simplices.size(); ++i )
9226     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9227   center /= _simplices.size();
9228
9229   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9230   for ( i = 0; i < _simplices.size(); ++i )
9231     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9232   vecs.back() = vecs[0];
9233
9234   const double tol = numeric_limits<double>::min();
9235   gp_XYZ zAxis(0,0,0);
9236   for ( i = 0; i < _simplices.size(); ++i )
9237   {
9238     gp_XYZ cross = vecs[i] ^ vecs[i+1];
9239     try {
9240       cross.Normalize();
9241       if ( cross * zAxis < tol )
9242         zAxis += cross.Reversed();
9243       else
9244         zAxis += cross;
9245     }
9246     catch (Standard_Failure) { // if |cross| == 0.
9247     }
9248   }
9249
9250   gp_XYZ yAxis;
9251   for ( i = 0; i < _simplices.size(); ++i )
9252   {
9253     yAxis = vecs[i];
9254     if ( yAxis.SquareModulus() > tol )
9255       break;
9256   }
9257   gp_XYZ xAxis = yAxis ^ zAxis;
9258   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9259   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9260   //                             p0.Distance( _simplices[2]._nPrev ));
9261   // gp_XYZ center = smoothLaplacian();
9262   // gp_XYZ xAxis, yAxis, zAxis;
9263   // for ( i = 0; i < _simplices.size(); ++i )
9264   // {
9265   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9266   //   if ( xAxis.SquareModulus() > tol*tol )
9267   //     break;
9268   // }
9269   // for ( i = 1; i < _simplices.size(); ++i )
9270   // {
9271   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9272   //   zAxis = xAxis ^ yAxis;
9273   //   if ( zAxis.SquareModulus() > tol*tol )
9274   //     break;
9275   // }
9276   // if ( i == _simplices.size() ) return newPos;
9277
9278   yAxis = zAxis ^ xAxis;
9279   xAxis /= xAxis.Modulus();
9280   yAxis /= yAxis.Modulus();
9281
9282   // get half-planes of _simplices
9283
9284   vector< _halfPlane > halfPlns( _simplices.size() );
9285   int nbHP = 0;
9286   for ( size_t i = 0; i < _simplices.size(); ++i )
9287   {
9288     const gp_XYZ& OP1 = vecs[ i   ];
9289     const gp_XYZ& OP2 = vecs[ i+1 ];
9290     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9291     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9292     gp_XY  vec12 = p2 - p1;
9293     double dist12 = vec12.Modulus();
9294     if ( dist12 < tol )
9295       continue;
9296     vec12 /= dist12;
9297     halfPlns[ nbHP ]._pos = p1;
9298     halfPlns[ nbHP ]._dir = vec12;
9299     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9300     ++nbHP;
9301   }
9302
9303   // intersect boundaries of half-planes, define state of intersection points
9304   // in relation to all half-planes and calculate internal point of a 2D polygon
9305
9306   double sumLen = 0;
9307   gp_XY newPos2D (0,0);
9308
9309   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9310   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9311   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9312
9313   vector< vector< TIntPntState > > allIntPnts( nbHP );
9314   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9315   {
9316     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9317     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9318
9319     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9320     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9321
9322     int nbNotOut = 0;
9323     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9324
9325     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9326     {
9327       if ( iHP1 == iHP2 ) continue;
9328
9329       TIntPntState & ips1 = intPnts1[ iHP2 ];
9330       if ( ips1.second == UNDEF )
9331       {
9332         // find an intersection point of boundaries of iHP1 and iHP2
9333
9334         if ( iHP2 == iPrev ) // intersection with neighbors is known
9335           ips1.first = halfPlns[ iHP1 ]._pos;
9336         else if ( iHP2 == iNext )
9337           ips1.first = halfPlns[ iHP2 ]._pos;
9338         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9339           ips1.second = NO_INT;
9340
9341         // classify the found intersection point
9342         if ( ips1.second != NO_INT )
9343         {
9344           ips1.second = NOT_OUT;
9345           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9346             if ( i != iHP1 && i != iHP2 &&
9347                  halfPlns[ i ].IsOut( ips1.first, tol ))
9348               ips1.second = IS_OUT;
9349         }
9350         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9351         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9352         TIntPntState & ips2 = intPnts2[ iHP1 ];
9353         ips2 = ips1;
9354       }
9355       if ( ips1.second == NOT_OUT )
9356       {
9357         ++nbNotOut;
9358         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9359       }
9360     }
9361
9362     // find a NOT_OUT segment of boundary which is located between
9363     // two NOT_OUT int points
9364
9365     if ( nbNotOut < 2 )
9366       continue; // no such a segment
9367
9368     if ( nbNotOut > 2 )
9369     {
9370       // sort points along the boundary
9371       map< double, TIntPntState* > ipsByParam;
9372       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9373       {
9374         TIntPntState & ips1 = intPnts1[ iHP2 ];
9375         if ( ips1.second != NO_INT )
9376         {
9377           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9378           double param = op * halfPlns[ iHP1 ]._dir;
9379           ipsByParam.insert( make_pair( param, & ips1 ));
9380         }
9381       }
9382       // look for two neighboring NOT_OUT points
9383       nbNotOut = 0;
9384       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9385       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9386       {
9387         TIntPntState & ips1 = *(u2ips->second);
9388         if ( ips1.second == NOT_OUT )
9389           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9390         else if ( nbNotOut >= 2 )
9391           break;
9392         else
9393           nbNotOut = 0;
9394       }
9395     }
9396
9397     if ( nbNotOut >= 2 )
9398     {
9399       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9400       sumLen += len;
9401
9402       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9403     }
9404   }
9405
9406   if ( sumLen > 0 )
9407   {
9408     newPos2D /= sumLen;
9409     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9410   }
9411   else
9412   {
9413     newPos = center;
9414   }
9415
9416   return newPos;
9417 }
9418 #endif // OLD_NEF_POLYGON
9419
9420 //================================================================================
9421 /*!
9422  * \brief Add a new segment to _LayerEdge during inflation
9423  */
9424 //================================================================================
9425
9426 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9427 {
9428   if ( Is( BLOCKED ))
9429     return;
9430
9431   if ( len > _maxLen )
9432   {
9433     len = _maxLen;
9434     Block( eos.GetData() );
9435   }
9436   const double lenDelta = len - _len;
9437   if ( lenDelta < len * 1e-3  )
9438   {
9439     Block( eos.GetData() );
9440     return;
9441   }
9442
9443   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9444   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9445   gp_XYZ newXYZ;
9446   if ( eos._hyp.IsOffsetMethod() )
9447   {
9448     newXYZ = oldXYZ;
9449     gp_Vec faceNorm;
9450     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9451     while ( faceIt->more() )
9452     {
9453       const SMDS_MeshElement* face = faceIt->next();
9454       if ( !eos.GetNormal( face, faceNorm ))
9455         continue;
9456
9457       // translate plane of a face
9458       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9459
9460       // find point of intersection of the face plane located at baryCenter
9461       // and _normal located at newXYZ
9462       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9463       double dot =  ( faceNorm.XYZ() * _normal );
9464       if ( dot < std::numeric_limits<double>::min() )
9465         dot = lenDelta * 1e-3;
9466       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9467       newXYZ += step * _normal;
9468     }
9469     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9470   }
9471   else
9472   {
9473     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9474   }
9475
9476   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9477   _pos.push_back( newXYZ );
9478
9479   if ( !eos._sWOL.IsNull() )
9480   {
9481     double distXYZ[4];
9482     bool uvOK = false;
9483     if ( eos.SWOLType() == TopAbs_EDGE )
9484     {
9485       double u = Precision::Infinite(); // to force projection w/o distance check
9486       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9487                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9488       _pos.back().SetCoord( u, 0, 0 );
9489       if ( _nodes.size() > 1 && uvOK )
9490       {
9491         SMDS_EdgePositionPtr pos = n->GetPosition();
9492         pos->SetUParameter( u );
9493       }
9494     }
9495     else //  TopAbs_FACE
9496     {
9497       gp_XY uv( Precision::Infinite(), 0 );
9498       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9499                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9500       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9501       if ( _nodes.size() > 1 && uvOK )
9502       {
9503         SMDS_FacePositionPtr pos = n->GetPosition();
9504         pos->SetUParameter( uv.X() );
9505         pos->SetVParameter( uv.Y() );
9506       }
9507     }
9508     if ( uvOK )
9509     {
9510       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9511     }
9512     else
9513     {
9514       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9515       _pos.pop_back();
9516       Block( eos.GetData() );
9517       return;
9518     }
9519   }
9520
9521   _len = len;
9522
9523   // notify _neibors
9524   if ( eos.ShapeType() != TopAbs_FACE )
9525   {
9526     for ( size_t i = 0; i < _neibors.size(); ++i )
9527       //if (  _len > _neibors[i]->GetSmooLen() )
9528         _neibors[i]->Set( MOVED );
9529
9530     Set( MOVED );
9531   }
9532   dumpMove( n ); //debug
9533 }
9534
9535 //================================================================================
9536 /*!
9537  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9538  */
9539 //================================================================================
9540
9541 void _LayerEdge::Block( _SolidData& data )
9542 {
9543   //if ( Is( BLOCKED )) return;
9544   Set( BLOCKED );
9545
9546   SMESH_Comment msg( "#BLOCK shape=");
9547   msg << data.GetShapeEdges( this )->_shapeID
9548       << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9549   dumpCmd( msg + " -- BEGIN");
9550
9551   SetMaxLen( _len );
9552   std::queue<_LayerEdge*> queue;
9553   queue.push( this );
9554
9555   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9556   while ( !queue.empty() )
9557   {
9558     _LayerEdge* edge = queue.front(); queue.pop();
9559     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9560     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9561     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9562     {
9563       _LayerEdge* neibor = edge->_neibors[iN];
9564       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9565         continue;
9566       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9567       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9568       double minDist = pSrc.SquareDistance( pSrcN );
9569       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9570       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9571       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9572       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9573       //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9574       {
9575         //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9576         // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9577         //                   neibor->_lenFactor / edge->_lenFactor );
9578       }
9579       if ( neibor->_maxLen > newMaxLen )
9580       {
9581         neibor->SetMaxLen( newMaxLen );
9582         if ( neibor->_maxLen < neibor->_len )
9583         {
9584           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9585           int       lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
9586           while ( neibor->_len > neibor->_maxLen &&
9587                   neibor->NbSteps() > lastStep )
9588             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9589           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9590           //neibor->Block( data );
9591         }
9592         queue.push( neibor );
9593       }
9594     }
9595   }
9596   dumpCmd( msg + " -- END");
9597 }
9598
9599 //================================================================================
9600 /*!
9601  * \brief Remove last inflation step
9602  */
9603 //================================================================================
9604
9605 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9606 {
9607   if ( _pos.size() > curStep && _nodes.size() > 1 )
9608   {
9609     _pos.resize( curStep );
9610
9611     gp_Pnt      nXYZ = _pos.back();
9612     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9613     SMESH_TNodeXYZ curXYZ( n );
9614     if ( !eos._sWOL.IsNull() )
9615     {
9616       TopLoc_Location loc;
9617       if ( eos.SWOLType() == TopAbs_EDGE )
9618       {
9619         SMDS_EdgePositionPtr pos = n->GetPosition();
9620         pos->SetUParameter( nXYZ.X() );
9621         double f,l;
9622         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9623         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9624       }
9625       else
9626       {
9627         SMDS_FacePositionPtr pos = n->GetPosition();
9628         pos->SetUParameter( nXYZ.X() );
9629         pos->SetVParameter( nXYZ.Y() );
9630         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9631         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9632       }
9633     }
9634     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9635     dumpMove( n );
9636
9637     if ( restoreLength )
9638     {
9639       if ( NbSteps() == 0 )
9640         _len = 0.;
9641       else if ( IsOnFace() && Is( MOVED ))
9642         _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
9643       else
9644         _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9645     }
9646   }
9647   return;
9648 }
9649
9650 //================================================================================
9651 /*!
9652  * \brief Return index of a _pos distant from _normal
9653  */
9654 //================================================================================
9655
9656 int _LayerEdge::GetSmoothedPos( const double tol )
9657 {
9658   int iSmoothed = 0;
9659   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9660   {
9661     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9662     if ( normDist > tol * tol )
9663       iSmoothed = i;
9664   }
9665   return iSmoothed;
9666 }
9667
9668 //================================================================================
9669 /*!
9670  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9671  */
9672 //================================================================================
9673
9674 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9675 {
9676   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9677     return;
9678
9679   // find the 1st smoothed _pos
9680   int iSmoothed = GetSmoothedPos( tol );
9681   if ( !iSmoothed ) return;
9682
9683   gp_XYZ normal = _normal;
9684   if ( Is( NORMAL_UPDATED ))
9685   {
9686     double minDot = 1;
9687     for ( size_t i = 0; i < _neibors.size(); ++i )
9688     {
9689       if ( _neibors[i]->IsOnFace() )
9690       {
9691         double dot = _normal * _neibors[i]->_normal;
9692         if ( dot < minDot )
9693         {
9694           normal = _neibors[i]->_normal;
9695           minDot = dot;
9696         }
9697       }
9698     }
9699     if ( minDot == 1. )
9700       for ( size_t i = 1; i < _pos.size(); ++i )
9701       {
9702         normal = _pos[i] - _pos[0];
9703         double size = normal.Modulus();
9704         if ( size > RealSmall() )
9705         {
9706           normal /= size;
9707           break;
9708         }
9709       }
9710   }
9711   const double r = 0.2;
9712   for ( int iter = 0; iter < 50; ++iter )
9713   {
9714     double minDot = 1;
9715     for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9716     {
9717       gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9718       gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9719       _pos[i] = newPos;
9720       double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9721       double newLen = ( 1-r ) * midLen + r * segLen[i];
9722       const_cast< double& >( segLen[i] ) = newLen;
9723       // check angle between normal and (_pos[i+1], _pos[i] )
9724       gp_XYZ posDir = _pos[i+1] - _pos[i];
9725       double size   = posDir.SquareModulus();
9726       if ( size > RealSmall() )
9727         minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9728     }
9729     if ( minDot > 0.5 * 0.5 )
9730       break;
9731   }
9732   return;
9733 }
9734
9735 //================================================================================
9736 /*!
9737  * \brief Print flags
9738  */
9739 //================================================================================
9740
9741 std::string _LayerEdge::DumpFlags() const
9742 {
9743   SMESH_Comment dump;
9744   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9745     if ( _flags & flag )
9746     {
9747       EFlags f = (EFlags) flag;
9748       switch ( f ) {
9749       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
9750       case MOVED:           dump << "MOVED";           break;
9751       case SMOOTHED:        dump << "SMOOTHED";        break;
9752       case DIFFICULT:       dump << "DIFFICULT";       break;
9753       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9754       case BLOCKED:         dump << "BLOCKED";         break;
9755       case INTERSECTED:     dump << "INTERSECTED";     break;
9756       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
9757       case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9758       case MARKED:          dump << "MARKED";          break;
9759       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
9760       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
9761       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
9762       case DISTORTED:       dump << "DISTORTED";       break;
9763       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
9764       case SHRUNK:          dump << "SHRUNK";          break;
9765       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
9766       }
9767       dump << " ";
9768     }
9769   cout << dump << endl;
9770   return dump;
9771 }
9772
9773
9774 //================================================================================
9775 /*!
9776  * \brief Create layers of prisms
9777  */
9778 //================================================================================
9779
9780 bool _ViscousBuilder::refine(_SolidData& data)
9781 {
9782   SMESH_MesherHelper& helper = data.GetHelper();
9783   helper.SetElementsOnShape(false);
9784
9785   Handle(Geom_Curve) curve;
9786   Handle(ShapeAnalysis_Surface) surface;
9787   TopoDS_Edge geomEdge;
9788   TopoDS_Face geomFace;
9789   TopLoc_Location loc;
9790   double f,l, u = 0;
9791   gp_XY uv;
9792   vector< gp_XYZ > pos3D;
9793   bool isOnEdge, isTooConvexFace = false;
9794   TGeomID prevBaseId = -1;
9795   TNode2Edge* n2eMap = 0;
9796   TNode2Edge::iterator n2e;
9797
9798   // Create intermediate nodes on each _LayerEdge
9799
9800   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9801   {
9802     _EdgesOnShape& eos = data._edgesOnShape[iS];
9803     if ( eos._edges.empty() ) continue;
9804
9805     if ( eos._edges[0]->_nodes.size() < 2 )
9806       continue; // on _noShrinkShapes
9807
9808     // get data of a shrink shape
9809     isOnEdge = false;
9810     geomEdge.Nullify(); geomFace.Nullify();
9811     curve.Nullify(); surface.Nullify();
9812     if ( !eos._sWOL.IsNull() )
9813     {
9814       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9815       if ( isOnEdge )
9816       {
9817         geomEdge = TopoDS::Edge( eos._sWOL );
9818         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9819       }
9820       else
9821       {
9822         geomFace = TopoDS::Face( eos._sWOL );
9823         surface  = helper.GetSurface( geomFace );
9824       }
9825     }
9826     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9827     {
9828       geomFace = TopoDS::Face( eos._shape );
9829       surface  = helper.GetSurface( geomFace );
9830       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9831       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9832         eos._eosC1[ i ]->_toSmooth = true;
9833
9834       isTooConvexFace = false;
9835       if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
9836         isTooConvexFace = cf->_isTooCurved;
9837     }
9838
9839     vector< double > segLen;
9840     for ( size_t i = 0; i < eos._edges.size(); ++i )
9841     {
9842       _LayerEdge& edge = *eos._edges[i];
9843       if ( edge._pos.size() < 2 )
9844         continue;
9845
9846       // get accumulated length of segments
9847       segLen.resize( edge._pos.size() );
9848       segLen[0] = 0.0;
9849       if ( eos._sWOL.IsNull() )
9850       {
9851         bool useNormal = true;
9852         bool    usePos = false;
9853         bool  smoothed = false;
9854         double   preci = 0.1 * edge._len;
9855         if ( eos._toSmooth && edge._pos.size() > 2 )
9856         {
9857           smoothed = edge.GetSmoothedPos( preci );
9858         }
9859         if ( smoothed )
9860         {
9861           if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
9862           {
9863             useNormal = usePos = false;
9864             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9865             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9866             {
9867               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9868               if ( surface->Gap() < 2. * edge._len )
9869                 segLen[j] = surface->Gap();
9870               else
9871                 useNormal = true;
9872             }
9873           }
9874         }
9875         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9876         {
9877 #ifndef __NODES_AT_POS
9878           useNormal = usePos = false;
9879           edge._pos[1] = edge._pos.back();
9880           edge._pos.resize( 2 );
9881           segLen.resize( 2 );
9882           segLen[ 1 ] = edge._len;
9883 #endif
9884         }
9885         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9886         {
9887           useNormal = usePos = false;
9888           _LayerEdge tmpEdge; // get original _normal
9889           tmpEdge._nodes.push_back( edge._nodes[0] );
9890           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9891             usePos = true;
9892           else
9893             for ( size_t j = 1; j < edge._pos.size(); ++j )
9894               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9895         }
9896         if ( useNormal )
9897         {
9898           for ( size_t j = 1; j < edge._pos.size(); ++j )
9899             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9900         }
9901         if ( usePos )
9902         {
9903           for ( size_t j = 1; j < edge._pos.size(); ++j )
9904             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9905         }
9906         else
9907         {
9908           bool swapped = ( edge._pos.size() > 2 );
9909           while ( swapped )
9910           {
9911             swapped = false;
9912             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9913               if ( segLen[j] > segLen.back() )
9914               {
9915                 segLen.erase( segLen.begin() + j );
9916                 edge._pos.erase( edge._pos.begin() + j );
9917                 --j;
9918               }
9919               else if ( segLen[j] < segLen[j-1] )
9920               {
9921                 std::swap( segLen[j], segLen[j-1] );
9922                 std::swap( edge._pos[j], edge._pos[j-1] );
9923                 swapped = true;
9924               }
9925           }
9926         }
9927         // smooth a path formed by edge._pos
9928 #ifndef __NODES_AT_POS
9929         if (( smoothed ) /*&&
9930             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9931           edge.SmoothPos( segLen, preci );
9932 #endif
9933       }
9934       else if ( eos._isRegularSWOL ) // usual SWOL
9935       {
9936         if ( edge.Is( _LayerEdge::SMOOTHED ))
9937         {
9938           SMESH_NodeXYZ p0( edge._nodes[0] );
9939           for ( size_t j = 1; j < edge._pos.size(); ++j )
9940           {
9941             gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9942             segLen[j] = ( pj - p0 ) * edge._normal;
9943           }
9944         }
9945         else
9946         {
9947           for ( size_t j = 1; j < edge._pos.size(); ++j )
9948             segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9949         }
9950       }
9951       else if ( !surface.IsNull() ) // SWOL surface with singularities
9952       {
9953         pos3D.resize( edge._pos.size() );
9954         for ( size_t j = 0; j < edge._pos.size(); ++j )
9955           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9956
9957         for ( size_t j = 1; j < edge._pos.size(); ++j )
9958           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9959       }
9960
9961       // allocate memory for new nodes if it is not yet refined
9962       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9963       if ( edge._nodes.size() == 2 )
9964       {
9965 #ifdef __NODES_AT_POS
9966         int nbNodes = edge._pos.size();
9967 #else
9968         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9969 #endif
9970         edge._nodes.resize( nbNodes, 0 );
9971         edge._nodes[1] = 0;
9972         edge._nodes.back() = tgtNode;
9973       }
9974       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9975       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9976       if ( baseShapeId != prevBaseId )
9977       {
9978         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9979         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9980         prevBaseId = baseShapeId;
9981       }
9982       _LayerEdge* edgeOnSameNode = 0;
9983       bool        useExistingPos = false;
9984       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9985       {
9986         edgeOnSameNode = n2e->second;
9987         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9988         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9989         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9990         if ( isOnEdge )
9991         {
9992           SMDS_EdgePositionPtr epos = lastPos;
9993           epos->SetUParameter( otherTgtPos.X() );
9994         }
9995         else
9996         {
9997           SMDS_FacePositionPtr fpos = lastPos;
9998           fpos->SetUParameter( otherTgtPos.X() );
9999           fpos->SetVParameter( otherTgtPos.Y() );
10000         }
10001       }
10002       // calculate height of the first layer
10003       double h0;
10004       const double T = segLen.back(); //data._hyp.GetTotalThickness();
10005       const double f = eos._hyp.GetStretchFactor();
10006       const int    N = eos._hyp.GetNumberLayers();
10007       const double fPowN = pow( f, N );
10008       if ( fPowN - 1 <= numeric_limits<double>::min() )
10009         h0 = T / N;
10010       else
10011         h0 = T * ( f - 1 )/( fPowN - 1 );
10012
10013       const double zeroLen = std::numeric_limits<double>::min();
10014
10015       // create intermediate nodes
10016       double hSum = 0, hi = h0/f;
10017       size_t iSeg = 1;
10018       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10019       {
10020         // compute an intermediate position
10021         hi *= f;
10022         hSum += hi;
10023         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10024           ++iSeg;
10025         int iPrevSeg = iSeg-1;
10026         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10027           --iPrevSeg;
10028         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10029         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10030 #ifdef __NODES_AT_POS
10031         pos = edge._pos[ iStep ];
10032 #endif
10033         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10034         if ( !eos._sWOL.IsNull() )
10035         {
10036           // compute XYZ by parameters <pos>
10037           if ( isOnEdge )
10038           {
10039             u = pos.X();
10040             if ( !node )
10041               pos = curve->Value( u ).Transformed(loc);
10042           }
10043           else if ( eos._isRegularSWOL )
10044           {
10045             uv.SetCoord( pos.X(), pos.Y() );
10046             if ( !node )
10047               pos = surface->Value( pos.X(), pos.Y() );
10048           }
10049           else
10050           {
10051             uv.SetCoord( pos.X(), pos.Y() );
10052             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10053             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10054             if ( !node )
10055               pos = surface->Value( uv );
10056           }
10057         }
10058         // create or update the node
10059         if ( !node )
10060         {
10061           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10062           if ( !eos._sWOL.IsNull() )
10063           {
10064             if ( isOnEdge )
10065               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10066             else
10067               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10068           }
10069           else
10070           {
10071             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10072           }
10073         }
10074         else
10075         {
10076           if ( !eos._sWOL.IsNull() )
10077           {
10078             // make average pos from new and current parameters
10079             if ( isOnEdge )
10080             {
10081               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10082               if ( useExistingPos )
10083                 u = helper.GetNodeU( geomEdge, node );
10084               pos = curve->Value( u ).Transformed(loc);
10085
10086               SMDS_EdgePositionPtr epos = node->GetPosition();
10087               epos->SetUParameter( u );
10088             }
10089             else
10090             {
10091               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10092               if ( useExistingPos )
10093                 uv = helper.GetNodeUV( geomFace, node );
10094               pos = surface->Value( uv );
10095
10096               SMDS_FacePositionPtr fpos = node->GetPosition();
10097               fpos->SetUParameter( uv.X() );
10098               fpos->SetVParameter( uv.Y() );
10099             }
10100           }
10101           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10102         }
10103       } // loop on edge._nodes
10104
10105       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10106       {
10107         if ( isOnEdge )
10108           edge._pos.back().SetCoord( u, 0,0);
10109         else
10110           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10111
10112         if ( edgeOnSameNode )
10113           edgeOnSameNode->_pos.back() = edge._pos.back();
10114       }
10115
10116     } // loop on eos._edges to create nodes
10117
10118
10119     if ( !getMeshDS()->IsEmbeddedMode() )
10120       // Log node movement
10121       for ( size_t i = 0; i < eos._edges.size(); ++i )
10122       {
10123         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10124         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10125       }
10126   }
10127
10128
10129   // Create volumes
10130
10131   helper.SetElementsOnShape(true);
10132
10133   vector< vector<const SMDS_MeshNode*>* > nnVec;
10134   set< vector<const SMDS_MeshNode*>* >    nnSet;
10135   set< int >                       degenEdgeInd;
10136   vector<const SMDS_MeshElement*>     degenVols;
10137
10138   TopExp_Explorer exp( data._solid, TopAbs_FACE );
10139   for ( ; exp.More(); exp.Next() )
10140   {
10141     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10142     if ( data._ignoreFaceIds.count( faceID ))
10143       continue;
10144     const bool isReversedFace = data._reversedFaceIds.count( faceID );
10145     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
10146     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
10147     while ( fIt->more() )
10148     {
10149       const SMDS_MeshElement* face = fIt->next();
10150       const int            nbNodes = face->NbCornerNodes();
10151       nnVec.resize( nbNodes );
10152       nnSet.clear();
10153       degenEdgeInd.clear();
10154       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10155       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10156       for ( int iN = 0; iN < nbNodes; ++iN )
10157       {
10158         const SMDS_MeshNode* n = nIt->next();
10159         _LayerEdge*       edge = data._n2eMap[ n ];
10160         const int i = isReversedFace ? nbNodes-1-iN : iN;
10161         nnVec[ i ] = & edge->_nodes;
10162         maxZ = std::max( maxZ, nnVec[ i ]->size() );
10163         minZ = std::min( minZ, nnVec[ i ]->size() );
10164
10165         if ( helper.HasDegeneratedEdges() )
10166           nnSet.insert( nnVec[ i ]);
10167       }
10168
10169       if ( maxZ == 0 )
10170         continue;
10171       if ( 0 < nnSet.size() && nnSet.size() < 3 )
10172         continue;
10173
10174       switch ( nbNodes )
10175       {
10176       case 3: // TRIA
10177       {
10178         // PENTA
10179         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10180           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10181                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
10182
10183         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10184         {
10185           for ( int iN = 0; iN < nbNodes; ++iN )
10186             if ( nnVec[ iN ]->size() < iZ+1 )
10187               degenEdgeInd.insert( iN );
10188
10189           if ( degenEdgeInd.size() == 1 )  // PYRAM
10190           {
10191             int i2 = *degenEdgeInd.begin();
10192             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10193             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10194             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10195                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
10196           }
10197           else  // TETRA
10198           {
10199             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10200             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10201                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10202                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10203                               (*nnVec[ i3 ])[ iZ ]);
10204           }
10205         }
10206         break; // TRIA
10207       }
10208       case 4: // QUAD
10209       {
10210         // HEX
10211         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10212           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10213                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10214                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
10215                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
10216
10217         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10218         {
10219           for ( int iN = 0; iN < nbNodes; ++iN )
10220             if ( nnVec[ iN ]->size() < iZ+1 )
10221               degenEdgeInd.insert( iN );
10222
10223           switch ( degenEdgeInd.size() )
10224           {
10225           case 2: // PENTA
10226           {
10227             int i2 = *degenEdgeInd.begin();
10228             int i3 = *degenEdgeInd.rbegin();
10229             bool ok = ( i3 - i2 == 1 );
10230             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10231             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10232             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10233
10234             const SMDS_MeshElement* vol =
10235               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10236                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10237             if ( !ok && vol )
10238               degenVols.push_back( vol );
10239           }
10240           break;
10241
10242           default: // degen HEX
10243           {
10244             const SMDS_MeshElement* vol =
10245               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10246                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10247                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10248                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10249                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
10250                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
10251                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
10252                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
10253             degenVols.push_back( vol );
10254           }
10255           }
10256         }
10257         break; // HEX
10258       }
10259       default:
10260         return error("Not supported type of element", data._index);
10261
10262       } // switch ( nbNodes )
10263     } // while ( fIt->more() )
10264   } // loop on FACEs
10265
10266   if ( !degenVols.empty() )
10267   {
10268     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10269     if ( !err || err->IsOK() )
10270     {
10271       SMESH_BadInputElements* badElems =
10272         new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10273       badElems->myBadElements.insert( badElems->myBadElements.end(),
10274                                       degenVols.begin(),degenVols.end() );
10275       err.reset( badElems );
10276     }
10277   }
10278
10279   return true;
10280 }
10281
10282 //================================================================================
10283 /*!
10284  * \brief Shrink 2D mesh on faces to let space for inflated layers
10285  */
10286 //================================================================================
10287
10288 bool _ViscousBuilder::shrink(_SolidData& theData)
10289 {
10290   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10291   // _LayerEdge's inflated along FACE or EDGE)
10292   map< TGeomID, list< _SolidData* > > f2sdMap;
10293   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10294   {
10295     _SolidData& data = _sdVec[i];
10296     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10297     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10298       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
10299       {
10300         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10301
10302         // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
10303         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10304         // by StdMeshers_QuadToTriaAdaptor
10305         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10306         {
10307           SMESH_ProxyMesh::SubMesh* proxySub =
10308             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10309           if ( proxySub->NbElements() == 0 )
10310           {
10311             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10312             while ( fIt->more() )
10313             {
10314               const SMDS_MeshElement* f = fIt->next();
10315               // as a result 3D algo will use elements from proxySub and not from smDS
10316               proxySub->AddElement( f );
10317               f->setIsMarked( true );
10318
10319               // Mark nodes on the FACE to discriminate them from nodes
10320               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10321               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10322               {
10323                 const SMDS_MeshNode* n = f->GetNode( iN );
10324                 if ( n->GetPosition()->GetDim() == 2 )
10325                   n->setIsMarked( true );
10326               }
10327             }
10328           }
10329         }
10330       }
10331   }
10332
10333   SMESH_MesherHelper helper( *_mesh );
10334   helper.ToFixNodeParameters( true );
10335
10336   // EDGEs to shrink
10337   map< TGeomID, _Shrinker1D > e2shrMap;
10338   vector< _EdgesOnShape* > subEOS;
10339   vector< _LayerEdge* > lEdges;
10340
10341   // loop on FACEs to shrink mesh on
10342   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10343   for ( ; f2sd != f2sdMap.end(); ++f2sd )
10344   {
10345     list< _SolidData* > & dataList = f2sd->second;
10346     if ( dataList.front()->_n2eMap.empty() ||
10347          dataList.back() ->_n2eMap.empty() )
10348       continue; // not yet computed
10349     if ( dataList.front() != &theData &&
10350          dataList.back()  != &theData )
10351       continue;
10352
10353     _SolidData&      data = *dataList.front();
10354     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
10355     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10356     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
10357     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10358
10359     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10360
10361     _shrinkedFaces.Add( F );
10362     helper.SetSubShape( F );
10363
10364     // ===========================
10365     // Prepare data for shrinking
10366     // ===========================
10367
10368     // Collect nodes to smooth (they are marked at the beginning of this method)
10369     vector < const SMDS_MeshNode* > smoothNodes;
10370     {
10371       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
10372       while ( nIt->more() )
10373       {
10374         const SMDS_MeshNode* n = nIt->next();
10375         if ( n->isMarked() )
10376           smoothNodes.push_back( n );
10377       }
10378     }
10379     // Find out face orientation
10380     double refSign = 1;
10381     const set<TGeomID> ignoreShapes;
10382     bool isOkUV;
10383     if ( !smoothNodes.empty() )
10384     {
10385       vector<_Simplex> simplices;
10386       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
10387       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
10388       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
10389       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
10390       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
10391         refSign = -1;
10392     }
10393
10394     // Find _LayerEdge's inflated along F
10395     subEOS.clear();
10396     lEdges.clear();
10397     {
10398       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
10399                                                                 /*complexFirst=*/true); //!!!
10400       while ( subIt->more() )
10401       {
10402         const TGeomID subID = subIt->next()->GetId();
10403         if ( data._noShrinkShapes.count( subID ))
10404           continue;
10405         _EdgesOnShape* eos = data.GetShapeEdges( subID );
10406         if ( !eos || eos->_sWOL.IsNull() )
10407           if ( data2 ) // check in adjacent SOLID
10408           {
10409             eos = data2->GetShapeEdges( subID );
10410             if ( !eos || eos->_sWOL.IsNull() )
10411               continue;
10412           }
10413         subEOS.push_back( eos );
10414
10415         for ( size_t i = 0; i < eos->_edges.size(); ++i )
10416         {
10417           lEdges.push_back( eos->_edges[ i ] );
10418           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
10419         }
10420       }
10421     }
10422
10423     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
10424     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10425     while ( fIt->more() )
10426       if ( const SMDS_MeshElement* f = fIt->next() )
10427         dumpChangeNodes( f );
10428     dumpFunctionEnd();
10429
10430     // Replace source nodes by target nodes in mesh faces to shrink
10431     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
10432     const SMDS_MeshNode* nodes[20];
10433     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10434     {
10435       _EdgesOnShape& eos = * subEOS[ iS ];
10436       for ( size_t i = 0; i < eos._edges.size(); ++i )
10437       {
10438         _LayerEdge& edge = *eos._edges[i];
10439         const SMDS_MeshNode* srcNode = edge._nodes[0];
10440         const SMDS_MeshNode* tgtNode = edge._nodes.back();
10441         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
10442         while ( fIt->more() )
10443         {
10444           const SMDS_MeshElement* f = fIt->next();
10445           if ( !smDS->Contains( f ) || !f->isMarked() )
10446             continue;
10447           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
10448           for ( int iN = 0; nIt->more(); ++iN )
10449           {
10450             const SMDS_MeshNode* n = nIt->next();
10451             nodes[iN] = ( n == srcNode ? tgtNode : n );
10452           }
10453           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
10454           dumpChangeNodes( f );
10455         }
10456       }
10457     }
10458     dumpFunctionEnd();
10459
10460     // find out if a FACE is concave
10461     const bool isConcaveFace = isConcave( F, helper );
10462
10463     // Create _SmoothNode's on face F
10464     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
10465     {
10466       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
10467       const bool sortSimplices = isConcaveFace;
10468       for ( size_t i = 0; i < smoothNodes.size(); ++i )
10469       {
10470         const SMDS_MeshNode* n = smoothNodes[i];
10471         nodesToSmooth[ i ]._node = n;
10472         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
10473         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
10474         // fix up incorrect uv of nodes on the FACE
10475         helper.GetNodeUV( F, n, 0, &isOkUV);
10476         dumpMove( n );
10477       }
10478       dumpFunctionEnd();
10479     }
10480     //if ( nodesToSmooth.empty() ) continue;
10481
10482     // Find EDGE's to shrink and set simpices to LayerEdge's
10483     set< _Shrinker1D* > eShri1D;
10484     {
10485       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10486       {
10487         _EdgesOnShape& eos = * subEOS[ iS ];
10488         if ( eos.SWOLType() == TopAbs_EDGE )
10489         {
10490           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
10491           _Shrinker1D& shrinker  = e2shrMap[ edgeSM->GetId() ];
10492           eShri1D.insert( & shrinker );
10493           shrinker.AddEdge( eos._edges[0], eos, helper );
10494           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
10495           // restore params of nodes on EDGE if the EDGE has been already
10496           // shrinked while shrinking other FACE
10497           shrinker.RestoreParams();
10498         }
10499         for ( size_t i = 0; i < eos._edges.size(); ++i )
10500         {
10501           _LayerEdge& edge = * eos._edges[i];
10502           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
10503
10504           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
10505           // not-marked nodes are those added by refine()
10506           edge._nodes.back()->setIsMarked( true );
10507         }
10508       }
10509     }
10510
10511     bool toFixTria = false; // to improve quality of trias by diagonal swap
10512     if ( isConcaveFace )
10513     {
10514       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
10515       if ( hasTria != hasQuad ) {
10516         toFixTria = hasTria;
10517       }
10518       else {
10519         set<int> nbNodesSet;
10520         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10521         while ( fIt->more() && nbNodesSet.size() < 2 )
10522           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
10523         toFixTria = ( *nbNodesSet.begin() == 3 );
10524       }
10525     }
10526
10527     // ==================
10528     // Perform shrinking
10529     // ==================
10530
10531     bool shrinked = true;
10532     int nbBad, shriStep=0, smooStep=0;
10533     _SmoothNode::SmoothType smoothType
10534       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
10535     SMESH_Comment errMsg;
10536     while ( shrinked )
10537     {
10538       shriStep++;
10539       // Move boundary nodes (actually just set new UV)
10540       // -----------------------------------------------
10541       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
10542       shrinked = false;
10543       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10544       {
10545         _EdgesOnShape& eos = * subEOS[ iS ];
10546         for ( size_t i = 0; i < eos._edges.size(); ++i )
10547         {
10548           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10549         }
10550       }
10551       dumpFunctionEnd();
10552
10553       // Move nodes on EDGE's
10554       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10555       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10556       for ( ; shr != eShri1D.end(); ++shr )
10557         (*shr)->Compute( /*set3D=*/false, helper );
10558
10559       // Smoothing in 2D
10560       // -----------------
10561       int nbNoImpSteps = 0;
10562       bool       moved = true;
10563       nbBad = 1;
10564       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10565       {
10566         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10567
10568         int oldBadNb = nbBad;
10569         nbBad = 0;
10570         moved = false;
10571         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10572         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10573         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10574         {
10575           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10576                                             smooTy, /*set3D=*/isConcaveFace);
10577         }
10578         if ( nbBad < oldBadNb )
10579           nbNoImpSteps = 0;
10580         else
10581           nbNoImpSteps++;
10582
10583         dumpFunctionEnd();
10584       }
10585
10586       errMsg.clear();
10587       if ( nbBad > 0 )
10588         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10589       if ( shriStep > 200 )
10590         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10591       if ( !errMsg.empty() )
10592         break;
10593
10594       // Fix narrow triangles by swapping diagonals
10595       // ---------------------------------------
10596       if ( toFixTria )
10597       {
10598         set<const SMDS_MeshNode*> usedNodes;
10599         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10600
10601         // update working data
10602         set<const SMDS_MeshNode*>::iterator n;
10603         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10604         {
10605           n = usedNodes.find( nodesToSmooth[ i ]._node );
10606           if ( n != usedNodes.end())
10607           {
10608             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10609                                     nodesToSmooth[ i ]._simplices,
10610                                     ignoreShapes, NULL,
10611                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10612             usedNodes.erase( n );
10613           }
10614         }
10615         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10616         {
10617           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10618           if ( n != usedNodes.end())
10619           {
10620             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10621                                     lEdges[i]->_simplices,
10622                                     ignoreShapes );
10623             usedNodes.erase( n );
10624           }
10625         }
10626       }
10627       // TODO: check effect of this additional smooth
10628       // additional laplacian smooth to increase allowed shrink step
10629       // for ( int st = 1; st; --st )
10630       // {
10631       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10632       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10633       //   {
10634       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10635       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
10636       //   }
10637       // }
10638
10639     } // while ( shrinked )
10640
10641     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10642     {
10643       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10644
10645       // remove faces
10646       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10647       {
10648         vector< const SMDS_MeshElement* > facesToRm;
10649         if ( psm )
10650         {
10651           facesToRm.reserve( psm->NbElements() );
10652           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10653             facesToRm.push_back( ite->next() );
10654
10655           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10656             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10657               psm->Clear();
10658         }
10659         for ( size_t i = 0; i < facesToRm.size(); ++i )
10660           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10661       }
10662       // remove nodes
10663       {
10664         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10665         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10666           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10667             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10668                                 subEOS[iS]->_edges[i]->_nodes.end() );
10669         }
10670         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10671         while ( itn->more() ) {
10672           const SMDS_MeshNode* n = itn->next();
10673           if ( !nodesToKeep.count( n ))
10674             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10675         }
10676       }
10677       // restore position and UV of target nodes
10678       gp_Pnt p;
10679       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10680         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10681         {
10682           _LayerEdge*       edge = subEOS[iS]->_edges[i];
10683           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10684           if ( edge->_pos.empty() ||
10685                edge->Is( _LayerEdge::SHRUNK )) continue;
10686           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10687           {
10688             SMDS_FacePositionPtr pos = tgtNode->GetPosition();
10689             pos->SetUParameter( edge->_pos[0].X() );
10690             pos->SetVParameter( edge->_pos[0].Y() );
10691             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10692           }
10693           else
10694           {
10695             SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
10696             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10697             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10698           }
10699           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10700           dumpMove( tgtNode );
10701         }
10702       // shrink EDGE sub-meshes and set proxy sub-meshes
10703       UVPtStructVec uvPtVec;
10704       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10705       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10706       {
10707         _Shrinker1D* shr = (*shrIt);
10708         shr->Compute( /*set3D=*/true, helper );
10709
10710         // set proxy mesh of EDGEs w/o layers
10711         map< double, const SMDS_MeshNode* > nodes;
10712         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10713         // remove refinement nodes
10714         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10715         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10716         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10717         if ( u2n->second == sn0 || u2n->second == sn1 )
10718         {
10719           while ( u2n->second != tn0 && u2n->second != tn1 )
10720             ++u2n;
10721           nodes.erase( nodes.begin(), u2n );
10722         }
10723         u2n = --nodes.end();
10724         if ( u2n->second == sn0 || u2n->second == sn1 )
10725         {
10726           while ( u2n->second != tn0 && u2n->second != tn1 )
10727             --u2n;
10728           nodes.erase( ++u2n, nodes.end() );
10729         }
10730         // set proxy sub-mesh
10731         uvPtVec.resize( nodes.size() );
10732         u2n = nodes.begin();
10733         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10734         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10735         {
10736           uvPtVec[ i ].node = u2n->second;
10737           uvPtVec[ i ].param = u2n->first;
10738           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10739         }
10740         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10741         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10742       }
10743
10744       // set proxy mesh of EDGEs with layers
10745       vector< _LayerEdge* > edges;
10746       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10747       {
10748         _EdgesOnShape& eos = * subEOS[ iS ];
10749         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10750
10751         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10752         data.SortOnEdge( E, eos._edges );
10753
10754         edges.clear();
10755         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10756           if ( !eov->_edges.empty() )
10757             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10758
10759         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10760
10761         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10762           if ( !eov->_edges.empty() )
10763             edges.push_back( eov->_edges[0] ); // on last VERTEX
10764
10765         uvPtVec.resize( edges.size() );
10766         for ( size_t i = 0; i < edges.size(); ++i )
10767         {
10768           uvPtVec[ i ].node = edges[i]->_nodes.back();
10769           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10770           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10771         }
10772         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10773         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10774         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10775       }
10776       // temporary clear the FACE sub-mesh from faces made by refine()
10777       vector< const SMDS_MeshElement* > elems;
10778       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10779       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10780         elems.push_back( ite->next() );
10781       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10782         elems.push_back( ite->next() );
10783       smDS->Clear();
10784
10785       // compute the mesh on the FACE
10786       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10787       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10788
10789       // re-fill proxy sub-meshes of the FACE
10790       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10791         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10792           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10793             psm->AddElement( ite->next() );
10794
10795       // re-fill smDS
10796       for ( size_t i = 0; i < elems.size(); ++i )
10797         smDS->AddElement( elems[i] );
10798
10799       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10800         return error( errMsg );
10801
10802     } // end of re-meshing in case of failed smoothing
10803     else
10804     {
10805       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10806       bool isStructuredFixed = false;
10807       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10808         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10809       if ( !isStructuredFixed )
10810       {
10811         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10812           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10813
10814         for ( int st = 3; st; --st )
10815         {
10816           switch( st ) {
10817           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10818           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10819           case 3: smoothType = _SmoothNode::ANGULAR; break;
10820           }
10821           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10822           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10823           {
10824             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10825                                      smoothType,/*set3D=*/st==1 );
10826           }
10827           dumpFunctionEnd();
10828         }
10829       }
10830       if ( !getMeshDS()->IsEmbeddedMode() )
10831         // Log node movement
10832         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10833         {
10834           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10835           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10836         }
10837     }
10838
10839     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10840     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10841     if ( data2 )
10842       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
10843
10844   } // loop on FACES to shrink mesh on
10845
10846
10847   // Replace source nodes by target nodes in shrinked mesh edges
10848
10849   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10850   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10851     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10852
10853   return true;
10854 }
10855
10856 //================================================================================
10857 /*!
10858  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10859  */
10860 //================================================================================
10861
10862 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10863                                            _EdgesOnShape&         eos,
10864                                            SMESH_MesherHelper&    helper,
10865                                            const SMESHDS_SubMesh* faceSubMesh)
10866 {
10867   const SMDS_MeshNode* srcNode = edge._nodes[0];
10868   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10869
10870   if ( eos.SWOLType() == TopAbs_FACE )
10871   {
10872     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10873     {
10874       edge._pos.clear();
10875       edge.Set( _LayerEdge::SHRUNK );
10876       return srcNode == tgtNode;
10877     }
10878     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10879     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10880     gp_Vec2d uvDir( srcUV, tgtUV );
10881     double uvLen = uvDir.Magnitude();
10882     uvDir /= uvLen;
10883     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10884     edge._len = uvLen;
10885
10886     //edge._pos.resize(1);
10887     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10888
10889     // set UV of source node to target node
10890     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
10891     pos->SetUParameter( srcUV.X() );
10892     pos->SetVParameter( srcUV.Y() );
10893   }
10894   else // _sWOL is TopAbs_EDGE
10895   {
10896     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10897     {
10898       edge._pos.clear();
10899       edge.Set( _LayerEdge::SHRUNK );
10900       return srcNode == tgtNode;
10901     }
10902     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10903     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10904     if ( !edgeSM || edgeSM->NbElements() == 0 )
10905       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10906
10907     const SMDS_MeshNode* n2 = 0;
10908     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10909     while ( eIt->more() && !n2 )
10910     {
10911       const SMDS_MeshElement* e = eIt->next();
10912       if ( !edgeSM->Contains(e)) continue;
10913       n2 = e->GetNode( 0 );
10914       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10915     }
10916     if ( !n2 )
10917       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10918
10919     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10920     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10921     double u2   = helper.GetNodeU( E, n2,      srcNode );
10922
10923     //edge._pos.clear();
10924
10925     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10926     {
10927       // tgtNode is located so that it does not make faces with wrong orientation
10928       edge.Set( _LayerEdge::SHRUNK );
10929       return true;
10930     }
10931     //edge._pos.resize(1);
10932     edge._pos[0].SetCoord( U_TGT, uTgt );
10933     edge._pos[0].SetCoord( U_SRC, uSrc );
10934     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10935
10936     edge._simplices.resize( 1 );
10937     edge._simplices[0]._nPrev = n2;
10938
10939     // set U of source node to the target node
10940     SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
10941     pos->SetUParameter( uSrc );
10942   }
10943   return true;
10944 }
10945
10946 //================================================================================
10947 /*!
10948  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10949  */
10950 //================================================================================
10951
10952 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10953 {
10954   if ( edge._nodes.size() == 1 )
10955   {
10956     edge._pos.clear();
10957     edge._len = 0;
10958
10959     const SMDS_MeshNode* srcNode = edge._nodes[0];
10960     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10961     if ( S.IsNull() ) return;
10962
10963     gp_Pnt p;
10964
10965     switch ( S.ShapeType() )
10966     {
10967     case TopAbs_EDGE:
10968     {
10969       double f,l;
10970       TopLoc_Location loc;
10971       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10972       if ( curve.IsNull() ) return;
10973       SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
10974       p = curve->Value( ePos->GetUParameter() );
10975       break;
10976     }
10977     case TopAbs_VERTEX:
10978     {
10979       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10980       break;
10981     }
10982     default: return;
10983     }
10984     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10985     dumpMove( srcNode );
10986   }
10987 }
10988
10989 //================================================================================
10990 /*!
10991  * \brief Try to fix triangles with high aspect ratio by swapping diagonals
10992  */
10993 //================================================================================
10994
10995 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10996                                   SMESH_MesherHelper&         helper,
10997                                   const bool                  is2D,
10998                                   const int                   step,
10999                                   set<const SMDS_MeshNode*> * involvedNodes)
11000 {
11001   SMESH::Controls::AspectRatio qualifier;
11002   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
11003   const double maxAspectRatio = is2D ? 4. : 2;
11004   _NodeCoordHelper xyz( F, helper, is2D );
11005
11006   // find bad triangles
11007
11008   vector< const SMDS_MeshElement* > badTrias;
11009   vector< double >                  badAspects;
11010   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
11011   SMDS_ElemIteratorPtr fIt = sm->GetElements();
11012   while ( fIt->more() )
11013   {
11014     const SMDS_MeshElement * f = fIt->next();
11015     if ( f->NbCornerNodes() != 3 ) continue;
11016     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
11017     double aspect = qualifier.GetValue( points );
11018     if ( aspect > maxAspectRatio )
11019     {
11020       badTrias.push_back( f );
11021       badAspects.push_back( aspect );
11022     }
11023   }
11024   if ( step == 1 )
11025   {
11026     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
11027     SMDS_ElemIteratorPtr fIt = sm->GetElements();
11028     while ( fIt->more() )
11029     {
11030       const SMDS_MeshElement * f = fIt->next();
11031       if ( f->NbCornerNodes() == 3 )
11032         dumpChangeNodes( f );
11033     }
11034     dumpFunctionEnd();
11035   }
11036   if ( badTrias.empty() )
11037     return;
11038
11039   // find couples of faces to swap diagonal
11040
11041   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
11042   vector< T2Trias > triaCouples; 
11043
11044   TIDSortedElemSet involvedFaces, emptySet;
11045   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
11046   {
11047     T2Trias trias    [3];
11048     double  aspRatio [3];
11049     int i1, i2, i3;
11050
11051     if ( !involvedFaces.insert( badTrias[iTia] ).second )
11052       continue;
11053     for ( int iP = 0; iP < 3; ++iP )
11054       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
11055
11056     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
11057     int bestCouple = -1;
11058     for ( int iSide = 0; iSide < 3; ++iSide )
11059     {
11060       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
11061       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
11062       trias [iSide].first  = badTrias[iTia];
11063       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
11064                                                              & i1, & i2 );
11065       if (( ! trias[iSide].second ) ||
11066           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
11067           ( ! sm->Contains( trias[iSide].second )))
11068         continue;
11069
11070       // aspect ratio of an adjacent tria
11071       for ( int iP = 0; iP < 3; ++iP )
11072         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
11073       double aspectInit = qualifier.GetValue( points2 );
11074
11075       // arrange nodes as after diag-swaping
11076       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
11077         i3 = helper.WrapIndex( i1-1, 3 );
11078       else
11079         i3 = helper.WrapIndex( i1+1, 3 );
11080       points1 = points;
11081       points1( 1+ iSide ) = points2( 1+ i3 );
11082       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
11083
11084       // aspect ratio after diag-swaping
11085       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
11086       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
11087         continue;
11088
11089       // prevent inversion of a triangle
11090       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
11091       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
11092       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
11093         continue;
11094
11095       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
11096         bestCouple = iSide;
11097     }
11098
11099     if ( bestCouple >= 0 )
11100     {
11101       triaCouples.push_back( trias[bestCouple] );
11102       involvedFaces.insert ( trias[bestCouple].second );
11103     }
11104     else
11105     {
11106       involvedFaces.erase( badTrias[iTia] );
11107     }
11108   }
11109   if ( triaCouples.empty() )
11110     return;
11111
11112   // swap diagonals
11113
11114   SMESH_MeshEditor editor( helper.GetMesh() );
11115   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11116   for ( size_t i = 0; i < triaCouples.size(); ++i )
11117   {
11118     dumpChangeNodes( triaCouples[i].first );
11119     dumpChangeNodes( triaCouples[i].second );
11120     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11121   }
11122
11123   if ( involvedNodes )
11124     for ( size_t i = 0; i < triaCouples.size(); ++i )
11125     {
11126       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11127                              triaCouples[i].first->end_nodes() );
11128       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11129                              triaCouples[i].second->end_nodes() );
11130     }
11131
11132   // just for debug dump resulting triangles
11133   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11134   for ( size_t i = 0; i < triaCouples.size(); ++i )
11135   {
11136     dumpChangeNodes( triaCouples[i].first );
11137     dumpChangeNodes( triaCouples[i].second );
11138   }
11139 }
11140
11141 //================================================================================
11142 /*!
11143  * \brief Move target node to it's final position on the FACE during shrinking
11144  */
11145 //================================================================================
11146
11147 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
11148                                  const TopoDS_Face&    F,
11149                                  _EdgesOnShape&        eos,
11150                                  SMESH_MesherHelper&   helper )
11151 {
11152   if ( Is( SHRUNK ))
11153     return false; // already at the target position
11154
11155   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11156
11157   if ( eos.SWOLType() == TopAbs_FACE )
11158   {
11159     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
11160     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11161     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11162     const double uvLen = tgtUV.Distance( curUV );
11163     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11164
11165     // Select shrinking step such that not to make faces with wrong orientation.
11166     double stepSize = 1e100;
11167     for ( size_t i = 0; i < _simplices.size(); ++i )
11168     {
11169       if ( !_simplices[i]._nPrev->isMarked() ||
11170            !_simplices[i]._nNext->isMarked() )
11171         continue; // simplex of quadrangle created by addBoundaryElements()
11172
11173       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11174       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11175       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11176       gp_XY dirN = uvN2 - uvN1;
11177       double det = uvDir.Crossed( dirN );
11178       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
11179       gp_XY dirN2Cur = curUV - uvN1;
11180       double step = dirN.Crossed( dirN2Cur ) / det;
11181       if ( step > 0 )
11182         stepSize = Min( step, stepSize );
11183     }
11184     gp_Pnt2d newUV;
11185     if ( uvLen <= stepSize )
11186     {
11187       newUV = tgtUV;
11188       Set( SHRUNK );
11189       //_pos.clear();
11190     }
11191     else if ( stepSize > 0 )
11192     {
11193       newUV = curUV + uvDir.XY() * stepSize * kSafe;
11194     }
11195     else
11196     {
11197       return true;
11198     }
11199     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11200     pos->SetUParameter( newUV.X() );
11201     pos->SetVParameter( newUV.Y() );
11202
11203 #ifdef __myDEBUG
11204     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11205     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11206     dumpMove( tgtNode );
11207 #endif
11208   }
11209   else // _sWOL is TopAbs_EDGE
11210   {
11211     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
11212     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
11213     SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
11214
11215     const double u2     = helper.GetNodeU( E, n2, tgtNode );
11216     const double uSrc   = _pos[0].Coord( U_SRC );
11217     const double lenTgt = _pos[0].Coord( LEN_TGT );
11218
11219     double newU = _pos[0].Coord( U_TGT );
11220     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11221     {
11222       Set( _LayerEdge::SHRUNK );
11223       //_pos.clear();
11224     }
11225     else
11226     {
11227       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11228     }
11229     tgtPos->SetUParameter( newU );
11230 #ifdef __myDEBUG
11231     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11232     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11233     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11234     dumpMove( tgtNode );
11235 #endif
11236   }
11237
11238   return true;
11239 }
11240
11241 //================================================================================
11242 /*!
11243  * \brief Perform smooth on the FACE
11244  *  \retval bool - true if the node has been moved
11245  */
11246 //================================================================================
11247
11248 bool _SmoothNode::Smooth(int&                  nbBad,
11249                          Handle(Geom_Surface)& surface,
11250                          SMESH_MesherHelper&   helper,
11251                          const double          refSign,
11252                          SmoothType            how,
11253                          bool                  set3D)
11254 {
11255   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11256
11257   // get uv of surrounding nodes
11258   vector<gp_XY> uv( _simplices.size() );
11259   for ( size_t i = 0; i < _simplices.size(); ++i )
11260     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11261
11262   // compute new UV for the node
11263   gp_XY newPos (0,0);
11264   if ( how == TFI && _simplices.size() == 4 )
11265   {
11266     gp_XY corners[4];
11267     for ( size_t i = 0; i < _simplices.size(); ++i )
11268       if ( _simplices[i]._nOpp )
11269         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11270       else
11271         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11272
11273     newPos = helper.calcTFI ( 0.5, 0.5,
11274                               corners[0], corners[1], corners[2], corners[3],
11275                               uv[1], uv[2], uv[3], uv[0] );
11276   }
11277   else if ( how == ANGULAR )
11278   {
11279     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11280   }
11281   else if ( how == CENTROIDAL && _simplices.size() > 3 )
11282   {
11283     // average centers of diagonals wieghted with their reciprocal lengths
11284     if ( _simplices.size() == 4 )
11285     {
11286       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11287       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11288       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11289     }
11290     else
11291     {
11292       double sumWeight = 0;
11293       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11294       for ( int i = 0; i < nb; ++i )
11295       {
11296         int iFrom = i + 2;
11297         int iTo   = i + _simplices.size() - 1;
11298         for ( int j = iFrom; j < iTo; ++j )
11299         {
11300           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11301           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11302           sumWeight += w;
11303           newPos += w * ( uv[i]+uv[i2] );
11304         }
11305       }
11306       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11307     }
11308   }
11309   else
11310   {
11311     // Laplacian smooth
11312     for ( size_t i = 0; i < _simplices.size(); ++i )
11313       newPos += uv[i];
11314     newPos /= _simplices.size();
11315   }
11316
11317   // count quality metrics (orientation) of triangles around the node
11318   int nbOkBefore = 0;
11319   gp_XY tgtUV = helper.GetNodeUV( face, _node );
11320   for ( size_t i = 0; i < _simplices.size(); ++i )
11321     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11322
11323   int nbOkAfter = 0;
11324   for ( size_t i = 0; i < _simplices.size(); ++i )
11325     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11326
11327   if ( nbOkAfter < nbOkBefore )
11328   {
11329     nbBad += _simplices.size() - nbOkBefore;
11330     return false;
11331   }
11332
11333   SMDS_FacePositionPtr pos = _node->GetPosition();
11334   pos->SetUParameter( newPos.X() );
11335   pos->SetVParameter( newPos.Y() );
11336
11337 #ifdef __myDEBUG
11338   set3D = true;
11339 #endif
11340   if ( set3D )
11341   {
11342     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
11343     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
11344     dumpMove( _node );
11345   }
11346
11347   nbBad += _simplices.size() - nbOkAfter;
11348   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
11349 }
11350
11351 //================================================================================
11352 /*!
11353  * \brief Computes new UV using angle based smoothing technique
11354  */
11355 //================================================================================
11356
11357 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
11358                                      const gp_XY&   uvToFix,
11359                                      const double   refSign)
11360 {
11361   uv.push_back( uv.front() );
11362
11363   vector< gp_XY >  edgeDir ( uv.size() );
11364   vector< double > edgeSize( uv.size() );
11365   for ( size_t i = 1; i < edgeDir.size(); ++i )
11366   {
11367     edgeDir [i-1] = uv[i] - uv[i-1];
11368     edgeSize[i-1] = edgeDir[i-1].Modulus();
11369     if ( edgeSize[i-1] < numeric_limits<double>::min() )
11370       edgeDir[i-1].SetX( 100 );
11371     else
11372       edgeDir[i-1] /= edgeSize[i-1] * refSign;
11373   }
11374   edgeDir.back()  = edgeDir.front();
11375   edgeSize.back() = edgeSize.front();
11376
11377   gp_XY  newPos(0,0);
11378   //int    nbEdges = 0;
11379   double sumSize = 0;
11380   for ( size_t i = 1; i < edgeDir.size(); ++i )
11381   {
11382     if ( edgeDir[i-1].X() > 1. ) continue;
11383     int i1 = i-1;
11384     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
11385     if ( i == edgeDir.size() ) break;
11386     gp_XY p = uv[i];
11387     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
11388     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
11389     gp_XY bisec = norm1 + norm2;
11390     double bisecSize = bisec.Modulus();
11391     if ( bisecSize < numeric_limits<double>::min() )
11392     {
11393       bisec = -edgeDir[i1] + edgeDir[i];
11394       bisecSize = bisec.Modulus();
11395     }
11396     bisec /= bisecSize;
11397
11398     gp_XY  dirToN  = uvToFix - p;
11399     double distToN = dirToN.Modulus();
11400     if ( bisec * dirToN < 0 )
11401       distToN = -distToN;
11402
11403     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
11404     //++nbEdges;
11405     sumSize += edgeSize[i1] + edgeSize[i];
11406   }
11407   newPos /= /*nbEdges * */sumSize;
11408   return newPos;
11409 }
11410
11411 //================================================================================
11412 /*!
11413  * \brief Delete _SolidData
11414  */
11415 //================================================================================
11416
11417 _SolidData::~_SolidData()
11418 {
11419   TNode2Edge::iterator n2e = _n2eMap.begin();
11420   for ( ; n2e != _n2eMap.end(); ++n2e )
11421   {
11422     _LayerEdge* & e = n2e->second;
11423     if ( e )
11424     {
11425       delete e->_curvature;
11426       if ( e->_2neibors )
11427         delete e->_2neibors->_plnNorm;
11428       delete e->_2neibors;
11429     }
11430     delete e;
11431     e = 0;
11432   }
11433   _n2eMap.clear();
11434
11435   delete _helper;
11436   _helper = 0;
11437 }
11438
11439 //================================================================================
11440 /*!
11441  * \brief Keep a _LayerEdge inflated along the EDGE
11442  */
11443 //================================================================================
11444
11445 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
11446                            _EdgesOnShape&      eos,
11447                            SMESH_MesherHelper& helper )
11448 {
11449   // init
11450   if ( _nodes.empty() )
11451   {
11452     _edges[0] = _edges[1] = 0;
11453     _done = false;
11454   }
11455   // check _LayerEdge
11456   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
11457     return;
11458   if ( eos.SWOLType() != TopAbs_EDGE )
11459     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11460   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
11461     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11462
11463   // store _LayerEdge
11464   _geomEdge = TopoDS::Edge( eos._sWOL );
11465   double f,l;
11466   BRep_Tool::Range( _geomEdge, f,l );
11467   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
11468   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
11469
11470   // Update _nodes
11471
11472   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
11473   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
11474
11475   if ( _nodes.empty() )
11476   {
11477     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
11478     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
11479       return;
11480     TopLoc_Location loc;
11481     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
11482     GeomAdaptor_Curve aCurve(C, f,l);
11483     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
11484
11485     int nbExpectNodes = eSubMesh->NbNodes();
11486     _initU  .reserve( nbExpectNodes );
11487     _normPar.reserve( nbExpectNodes );
11488     _nodes  .reserve( nbExpectNodes );
11489     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
11490     while ( nIt->more() )
11491     {
11492       const SMDS_MeshNode* node = nIt->next();
11493
11494       // skip refinement nodes
11495       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
11496            node == tgtNode0 || node == tgtNode1 )
11497         continue;
11498       bool hasMarkedFace = false;
11499       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
11500       while ( fIt->more() && !hasMarkedFace )
11501         hasMarkedFace = fIt->next()->isMarked();
11502       if ( !hasMarkedFace )
11503         continue;
11504
11505       _nodes.push_back( node );
11506       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
11507       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
11508       _normPar.push_back(  len / totLen );
11509     }
11510   }
11511   else
11512   {
11513     // remove target node of the _LayerEdge from _nodes
11514     size_t nbFound = 0;
11515     for ( size_t i = 0; i < _nodes.size(); ++i )
11516       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
11517         _nodes[i] = 0, nbFound++;
11518     if ( nbFound == _nodes.size() )
11519       _nodes.clear();
11520   }
11521 }
11522
11523 //================================================================================
11524 /*!
11525  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
11526  */
11527 //================================================================================
11528
11529 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
11530 {
11531   if ( _done || _nodes.empty())
11532     return;
11533   const _LayerEdge* e = _edges[0];
11534   if ( !e ) e = _edges[1];
11535   if ( !e ) return;
11536
11537   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
11538             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
11539
11540   double f,l;
11541   if ( set3D || _done )
11542   {
11543     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
11544     GeomAdaptor_Curve aCurve(C, f,l);
11545
11546     if ( _edges[0] )
11547       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11548     if ( _edges[1] )
11549       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11550     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
11551
11552     for ( size_t i = 0; i < _nodes.size(); ++i )
11553     {
11554       if ( !_nodes[i] ) continue;
11555       double len = totLen * _normPar[i];
11556       GCPnts_AbscissaPoint discret( aCurve, len, f );
11557       if ( !discret.IsDone() )
11558         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11559       double u = discret.Parameter();
11560       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
11561       pos->SetUParameter( u );
11562       gp_Pnt p = C->Value( u );
11563       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11564     }
11565   }
11566   else
11567   {
11568     BRep_Tool::Range( _geomEdge, f,l );
11569     if ( _edges[0] )
11570       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11571     if ( _edges[1] )
11572       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11573     
11574     for ( size_t i = 0; i < _nodes.size(); ++i )
11575     {
11576       if ( !_nodes[i] ) continue;
11577       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11578       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
11579       pos->SetUParameter( u );
11580     }
11581   }
11582 }
11583
11584 //================================================================================
11585 /*!
11586  * \brief Restore initial parameters of nodes on EDGE
11587  */
11588 //================================================================================
11589
11590 void _Shrinker1D::RestoreParams()
11591 {
11592   if ( _done )
11593     for ( size_t i = 0; i < _nodes.size(); ++i )
11594     {
11595       if ( !_nodes[i] ) continue;
11596       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
11597       pos->SetUParameter( _initU[i] );
11598     }
11599   _done = false;
11600 }
11601
11602 //================================================================================
11603 /*!
11604  * \brief Replace source nodes by target nodes in shrinked mesh edges
11605  */
11606 //================================================================================
11607
11608 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11609 {
11610   const SMDS_MeshNode* nodes[3];
11611   for ( int i = 0; i < 2; ++i )
11612   {
11613     if ( !_edges[i] ) continue;
11614
11615     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11616     if ( !eSubMesh ) return;
11617     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11618     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11619     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11620     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11621     while ( eIt->more() )
11622     {
11623       const SMDS_MeshElement* e = eIt->next();
11624       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11625           continue;
11626       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11627       for ( int iN = 0; iN < e->NbNodes(); ++iN )
11628       {
11629         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11630         nodes[iN] = ( n == srcNode ? tgtNode : n );
11631       }
11632       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11633     }
11634   }
11635 }
11636
11637 //================================================================================
11638 /*!
11639  * \brief Creates 2D and 1D elements on boundaries of new prisms
11640  */
11641 //================================================================================
11642
11643 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11644 {
11645   SMESH_MesherHelper helper( *_mesh );
11646
11647   vector< const SMDS_MeshNode* > faceNodes;
11648
11649   //for ( size_t i = 0; i < _sdVec.size(); ++i )
11650   {
11651     //_SolidData& data = _sdVec[i];
11652     TopTools_IndexedMapOfShape geomEdges;
11653     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11654     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11655     {
11656       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11657       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
11658       if ( data._noShrinkShapes.count( edgeID ))
11659         continue;
11660
11661       // Get _LayerEdge's based on E
11662
11663       map< double, const SMDS_MeshNode* > u2nodes;
11664       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11665         continue;
11666
11667       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11668       TNode2Edge & n2eMap = data._n2eMap;
11669       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11670       {
11671         //check if 2D elements are needed on E
11672         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11673         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11674         ledges.push_back( n2e->second );
11675         u2n++;
11676         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11677           continue; // no layers on E
11678         ledges.push_back( n2eMap[ u2n->second ]);
11679
11680         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11681         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11682         int nbSharedPyram = 0;
11683         SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
11684         while ( vIt->more() )
11685         {
11686           const SMDS_MeshElement* v = vIt->next();
11687           nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
11688         }
11689         if ( nbSharedPyram > 1 )
11690           continue; // not free border of the pyramid
11691
11692         faceNodes.clear();
11693         faceNodes.push_back( ledges[0]->_nodes[0] );
11694         faceNodes.push_back( ledges[1]->_nodes[0] );
11695         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11696         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11697
11698         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11699           continue; // faces already created
11700       }
11701       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11702         ledges.push_back( n2eMap[ u2n->second ]);
11703
11704       // Find out orientation and type of face to create
11705
11706       bool reverse = false, isOnFace;
11707       TopoDS_Shape F;
11708
11709       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
11710       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11711       {
11712         F = e2f->second.Oriented( TopAbs_FORWARD );
11713         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11714         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11715           reverse = !reverse, F.Reverse();
11716         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11717           reverse = !reverse;
11718       }
11719       else if ( !data._ignoreFaceIds.count( e2f->first ))
11720       {
11721         // find FACE with layers sharing E
11722         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11723         if ( fIt->more() )
11724           F = *( fIt->next() );
11725       }
11726       // Find the sub-mesh to add new faces
11727       SMESHDS_SubMesh* sm = 0;
11728       if ( isOnFace )
11729         sm = getMeshDS()->MeshElements( F );
11730       else
11731         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11732       if ( !sm )
11733         return error("error in addBoundaryElements()", data._index);
11734
11735       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
11736       // faces for 3D meshing (PAL23414)
11737       SMESHDS_SubMesh* adjSM = 0;
11738       if ( isOnFace )
11739       {
11740         const TGeomID   faceID = sm->GetID();
11741         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
11742         while ( const TopoDS_Shape* solid = soIt->next() )
11743           if ( !solid->IsSame( data._solid ))
11744           {
11745             size_t iData = _solids.FindIndex( *solid ) - 1;
11746             if ( iData < _sdVec.size() &&
11747                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
11748                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
11749             {
11750               SMESH_ProxyMesh::SubMesh* proxySub =
11751                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
11752               if ( proxySub && proxySub->NbElements() > 0 )
11753                 adjSM = proxySub;
11754             }
11755           }
11756       }
11757
11758       // Make faces
11759       const int dj1 = reverse ? 0 : 1;
11760       const int dj2 = reverse ? 1 : 0;
11761       vector< const SMDS_MeshElement*> ff; // new faces row
11762       SMESHDS_Mesh* m = getMeshDS();
11763       for ( size_t j = 1; j < ledges.size(); ++j )
11764       {
11765         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11766         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11767         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
11768         if ( nn1.size() == nn2.size() )
11769         {
11770           if ( isOnFace )
11771             for ( size_t z = 1; z < nn1.size(); ++z )
11772               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11773           else
11774             for ( size_t z = 1; z < nn1.size(); ++z )
11775               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11776         }
11777         else if ( nn1.size() == 1 )
11778         {
11779           if ( isOnFace )
11780             for ( size_t z = 1; z < nn2.size(); ++z )
11781               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11782           else
11783             for ( size_t z = 1; z < nn2.size(); ++z )
11784               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11785         }
11786         else
11787         {
11788           if ( isOnFace )
11789             for ( size_t z = 1; z < nn1.size(); ++z )
11790               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11791           else
11792             for ( size_t z = 1; z < nn1.size(); ++z )
11793               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11794         }
11795
11796         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
11797         {
11798           for ( size_t z = 0; z < ff.size(); ++z )
11799             if ( ff[ z ])
11800               adjSM->AddElement( ff[ z ]);
11801           ff.clear();
11802         }
11803       }
11804
11805       // Make edges
11806       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11807       {
11808         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11809         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11810         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11811         {
11812           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11813           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
11814             continue;
11815           helper.SetSubShape( eos->_sWOL );
11816           helper.SetElementsOnShape( true );
11817           for ( size_t z = 1; z < nn.size(); ++z )
11818             helper.AddEdge( nn[z-1], nn[z] );
11819         }
11820       }
11821
11822     } // loop on EDGE's
11823   } // loop on _SolidData's
11824
11825   return true;
11826 }