Salome HOME
#16479 [CEA 12950] ViscousLayers hypothesis and periodic condition
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2019  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "ObjectPool.hxx"
27 #include "SMDS_EdgePosition.hxx"
28 #include "SMDS_FaceOfNodes.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_MeshNode.hxx"
31 #include "SMDS_PolygonalFaceOfNodes.hxx"
32 #include "SMDS_SetIterator.hxx"
33 #include "SMESHDS_Group.hxx"
34 #include "SMESHDS_Hypothesis.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESH_Algo.hxx"
37 #include "SMESH_Block.hxx"
38 #include "SMESH_ComputeError.hxx"
39 #include "SMESH_ControlsDef.hxx"
40 #include "SMESH_Gen.hxx"
41 #include "SMESH_Group.hxx"
42 #include "SMESH_HypoFilter.hxx"
43 #include "SMESH_Mesh.hxx"
44 #include "SMESH_MeshAlgos.hxx"
45 #include "SMESH_MeshEditor.hxx"
46 #include "SMESH_MesherHelper.hxx"
47 #include "SMESH_ProxyMesh.hxx"
48 #include "SMESH_subMesh.hxx"
49 #include "SMESH_subMeshEventListener.hxx"
50 #include "StdMeshers_FaceSide.hxx"
51 #include "StdMeshers_ProjectionUtils.hxx"
52 #include "StdMeshers_ViscousLayers2D.hxx"
53
54 #include <Adaptor3d_HSurface.hxx>
55 #include <BRepAdaptor_Curve.hxx>
56 #include <BRepAdaptor_Curve2d.hxx>
57 #include <BRepAdaptor_Surface.hxx>
58 //#include <BRepLProp_CLProps.hxx>
59 #include <BRepLProp_SLProps.hxx>
60 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
61 #include <BRep_Tool.hxx>
62 #include <Bnd_B2d.hxx>
63 #include <Bnd_B3d.hxx>
64 #include <ElCLib.hxx>
65 #include <GCPnts_AbscissaPoint.hxx>
66 #include <GCPnts_TangentialDeflection.hxx>
67 #include <Geom2d_Circle.hxx>
68 #include <Geom2d_Line.hxx>
69 #include <Geom2d_TrimmedCurve.hxx>
70 #include <GeomAdaptor_Curve.hxx>
71 #include <GeomLib.hxx>
72 #include <Geom_Circle.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Line.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <Precision.hxx>
77 #include <Standard_ErrorHandler.hxx>
78 #include <Standard_Failure.hxx>
79 #include <TColStd_Array1OfReal.hxx>
80 #include <TopExp.hxx>
81 #include <TopExp_Explorer.hxx>
82 #include <TopTools_IndexedMapOfShape.hxx>
83 #include <TopTools_ListOfShape.hxx>
84 #include <TopTools_MapIteratorOfMapOfShape.hxx>
85 #include <TopTools_MapOfShape.hxx>
86 #include <TopoDS.hxx>
87 #include <TopoDS_Edge.hxx>
88 #include <TopoDS_Face.hxx>
89 #include <TopoDS_Vertex.hxx>
90 #include <gp_Ax1.hxx>
91 #include <gp_Cone.hxx>
92 #include <gp_Sphere.hxx>
93 #include <gp_Vec.hxx>
94 #include <gp_XY.hxx>
95
96 #include <cmath>
97 #include <limits>
98 #include <list>
99 #include <queue>
100 #include <string>
101 #include <unordered_map>
102
103 #ifdef _DEBUG_
104 //#define __myDEBUG
105 //#define __NOT_INVALIDATE_BAD_SMOOTH
106 //#define __NODES_AT_POS
107 #endif
108
109 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
110 #define BLOCK_INFLATION // of individual _LayerEdge's
111 #define OLD_NEF_POLYGON
112
113 using namespace std;
114
115 //================================================================================
116 namespace VISCOUS_3D
117 {
118   typedef int TGeomID;
119
120   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
121
122   const double theMinSmoothCosin = 0.1;
123   const double theSmoothThickToElemSizeRatio = 0.6;
124   const double theMinSmoothTriaAngle = 30;
125   const double theMinSmoothQuadAngle = 45;
126
127   // what part of thickness is allowed till intersection
128   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
129   const double theThickToIntersection = 1.5;
130
131   bool needSmoothing( double cosin, double tgtThick, double elemSize )
132   {
133     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
134   }
135   double getSmoothingThickness( double cosin, double elemSize )
136   {
137     return theSmoothThickToElemSizeRatio * elemSize / cosin;
138   }
139
140   /*!
141    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
142    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
143    */
144   struct _MeshOfSolid : public SMESH_ProxyMesh,
145                         public SMESH_subMeshEventListenerData
146   {
147     bool                  _n2nMapComputed;
148     SMESH_ComputeErrorPtr _warning;
149
150     _MeshOfSolid( SMESH_Mesh* mesh)
151       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
152     {
153       SMESH_ProxyMesh::setMesh( *mesh );
154     }
155
156     // returns submesh for a geom face
157     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
158     {
159       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
160       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
161     }
162     void setNode2Node(const SMDS_MeshNode*                 srcNode,
163                       const SMDS_MeshNode*                 proxyNode,
164                       const SMESH_ProxyMesh::SubMesh* subMesh)
165     {
166       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
167     }
168   };
169   //--------------------------------------------------------------------------------
170   /*!
171    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
172    * It is used to clear an inferior dim sub-meshes modified by viscous layers
173    */
174   class _ShrinkShapeListener : SMESH_subMeshEventListener
175   {
176     _ShrinkShapeListener()
177       : SMESH_subMeshEventListener(/*isDeletable=*/false,
178                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
179   public:
180     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
181     virtual void ProcessEvent(const int                       event,
182                               const int                       eventType,
183                               SMESH_subMesh*                  solidSM,
184                               SMESH_subMeshEventListenerData* data,
185                               const SMESH_Hypothesis*         hyp)
186     {
187       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
188       {
189         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
190       }
191     }
192   };
193   //--------------------------------------------------------------------------------
194   /*!
195    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
196    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
197    * delete the data as soon as it has been used
198    */
199   class _ViscousListener : SMESH_subMeshEventListener
200   {
201     _ViscousListener():
202       SMESH_subMeshEventListener(/*isDeletable=*/false,
203                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
204     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
205   public:
206     virtual void ProcessEvent(const int                       event,
207                               const int                       eventType,
208                               SMESH_subMesh*                  subMesh,
209                               SMESH_subMeshEventListenerData* data,
210                               const SMESH_Hypothesis*         hyp)
211     {
212       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
213           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
214             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
215       {
216         // delete SMESH_ProxyMesh containing temporary faces
217         subMesh->DeleteEventListener( this );
218       }
219     }
220     // Finds or creates proxy mesh of the solid
221     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
222                                       const TopoDS_Shape& solid,
223                                       bool                toCreate=false)
224     {
225       if ( !mesh ) return 0;
226       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
227       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
228       if ( !data && toCreate )
229       {
230         data = new _MeshOfSolid(mesh);
231         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
232         sm->SetEventListener( Get(), data, sm );
233       }
234       return data;
235     }
236     // Removes proxy mesh of the solid
237     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
238     {
239       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
240     }
241   };
242   
243   //================================================================================
244   /*!
245    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
246    * the main shape when sub-mesh of the main shape is cleared,
247    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
248    * is cleared
249    */
250   //================================================================================
251
252   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
253   {
254     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
255     SMESH_subMeshEventListenerData* data =
256       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
257     if ( data )
258     {
259       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
260            data->mySubMeshes.end())
261         data->mySubMeshes.push_back( sub );
262     }
263     else
264     {
265       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
266       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
267     }
268   }
269   struct _SolidData;
270   //--------------------------------------------------------------------------------
271   /*!
272    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
273    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
274    * The class is used to check validity of face or volumes around a smoothed node;
275    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
276    */
277   struct _Simplex
278   {
279     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
280     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
281     _Simplex(const SMDS_MeshNode* nPrev=0,
282              const SMDS_MeshNode* nNext=0,
283              const SMDS_MeshNode* nOpp=0)
284       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
285     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
286     {
287       const double M[3][3] =
288         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
289          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
290          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
291       vol = ( + M[0][0] * M[1][1] * M[2][2]
292               + M[0][1] * M[1][2] * M[2][0]
293               + M[0][2] * M[1][0] * M[2][1]
294               - M[0][0] * M[1][2] * M[2][1]
295               - M[0][1] * M[1][0] * M[2][2]
296               - M[0][2] * M[1][1] * M[2][0]);
297       return vol > 1e-100;
298     }
299     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
300     {
301       SMESH_TNodeXYZ pSrc( nSrc );
302       return IsForward( &pSrc, &pTgt, vol );
303     }
304     bool IsForward(const gp_XY&         tgtUV,
305                    const SMDS_MeshNode* smoothedNode,
306                    const TopoDS_Face&   face,
307                    SMESH_MesherHelper&  helper,
308                    const double         refSign) const
309     {
310       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
311       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
312       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
313       double d = v1 ^ v2;
314       return d*refSign > 1e-100;
315     }
316     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
317     {
318       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
319       if ( !_nOpp ) // triangle
320       {
321         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
322         double tp2 = tp.SquareMagnitude();
323         double pn2 = pn.SquareMagnitude();
324         double nt2 = nt.SquareMagnitude();
325
326         if ( tp2 < pn2 && tp2 < nt2 )
327           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
328         else if ( pn2 < nt2 )
329           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
330         else
331           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
332
333         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
334                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
335         return minAngle < theMaxCos2;
336       }
337       else // quadrangle
338       {
339         SMESH_TNodeXYZ pOpp( _nOpp );
340         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
341         double tp2 = tp.SquareMagnitude();
342         double po2 = po.SquareMagnitude();
343         double on2 = on.SquareMagnitude();
344         double nt2 = nt.SquareMagnitude();
345         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
346                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
347                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
348                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
349
350         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
351                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
352         return minAngle < theMaxCos2;
353       }
354     }
355     bool IsNeighbour(const _Simplex& other) const
356     {
357       return _nPrev == other._nNext || _nNext == other._nPrev;
358     }
359     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
360     static void GetSimplices( const SMDS_MeshNode* node,
361                               vector<_Simplex>&   simplices,
362                               const set<TGeomID>& ingnoreShapes,
363                               const _SolidData*   dataToCheckOri = 0,
364                               const bool          toSort = false);
365     static void SortSimplices(vector<_Simplex>& simplices);
366   };
367   //--------------------------------------------------------------------------------
368   /*!
369    * Structure used to take into account surface curvature while smoothing
370    */
371   struct _Curvature
372   {
373     double   _r; // radius
374     double   _k; // factor to correct node smoothed position
375     double   _h2lenRatio; // avgNormProj / (2*avgDist)
376     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
377   public:
378     static _Curvature* New( double avgNormProj, double avgDist );
379     double lenDelta(double len) const { return _k * ( _r + len ); }
380     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
381   };
382   //--------------------------------------------------------------------------------
383
384   struct _2NearEdges;
385   struct _LayerEdge;
386   struct _EdgesOnShape;
387   struct _Smoother1D;
388   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
389
390   //--------------------------------------------------------------------------------
391   /*!
392    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
393    * and a node of the most internal layer (_nodes.back())
394    */
395   struct _LayerEdge
396   {
397     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
398
399     vector< const SMDS_MeshNode*> _nodes;
400
401     gp_XYZ              _normal;    // to boundary of solid
402     vector<gp_XYZ>      _pos;       // points computed during inflation
403     double              _len;       // length achieved with the last inflation step
404     double              _maxLen;    // maximal possible length
405     double              _cosin;     // of angle (_normal ^ surface)
406     double              _minAngle;  // of _simplices
407     double              _lenFactor; // to compute _len taking _cosin into account
408     int                 _flags;
409
410     // simplices connected to the source node (_nodes[0]);
411     // used for smoothing and quality check of _LayerEdge's based on the FACE
412     vector<_Simplex>    _simplices;
413     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
414     PSmooFun            _smooFunction; // smoothing function
415     _Curvature*         _curvature;
416     // data for smoothing of _LayerEdge's based on the EDGE
417     _2NearEdges*        _2neibors;
418
419     enum EFlags { TO_SMOOTH       = 0x0000001,
420                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
421                   SMOOTHED        = 0x0000004, // set by _LayerEdge::Smooth()
422                   DIFFICULT       = 0x0000008, // near concave VERTEX
423                   ON_CONCAVE_FACE = 0x0000010,
424                   BLOCKED         = 0x0000020, // not to inflate any more
425                   INTERSECTED     = 0x0000040, // close intersection with a face found
426                   NORMAL_UPDATED  = 0x0000080,
427                   UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
428                   MARKED          = 0x0000200, // local usage
429                   MULTI_NORMAL    = 0x0000400, // a normal is invisible by some of surrounding faces
430                   NEAR_BOUNDARY   = 0x0000800, // is near FACE boundary forcing smooth
431                   SMOOTHED_C1     = 0x0001000, // is on _eosC1
432                   DISTORTED       = 0x0002000, // was bad before smoothing
433                   RISKY_SWOL      = 0x0004000, // SWOL is parallel to a source FACE
434                   SHRUNK          = 0x0008000, // target node reached a tgt position while shrink()
435                   UNUSED_FLAG     = 0x0100000  // to add user flags after
436     };
437     bool Is   ( int flag ) const { return _flags & flag; }
438     void Set  ( int flag ) { _flags |= flag; }
439     void Unset( int flag ) { _flags &= ~flag; }
440     std::string DumpFlags() const; // debug
441
442     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
443     bool SetNewLength2d( Handle(Geom_Surface)& surface,
444                          const TopoDS_Face&    F,
445                          _EdgesOnShape&        eos,
446                          SMESH_MesherHelper&   helper );
447     void SetDataByNeighbors( const SMDS_MeshNode* n1,
448                              const SMDS_MeshNode* n2,
449                              const _EdgesOnShape& eos,
450                              SMESH_MesherHelper&  helper);
451     void Block( _SolidData& data );
452     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
453     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
454                             const TNode2Edge&     n2eMap);
455     void SmoothPos( const vector< double >& segLen, const double tol );
456     int  GetSmoothedPos( const double tol );
457     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
458     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
459     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
460     void SmoothWoCheck();
461     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
462                       const TopoDS_Face&             F,
463                       SMESH_MesherHelper&            helper);
464     void MoveNearConcaVer( const _EdgesOnShape*    eov,
465                            const _EdgesOnShape*    eos,
466                            const int               step,
467                            vector< _LayerEdge* > & badSmooEdges);
468     bool FindIntersection( SMESH_ElementSearcher&   searcher,
469                            double &                 distance,
470                            const double&            epsilon,
471                            _EdgesOnShape&           eos,
472                            const SMDS_MeshElement** face = 0);
473     bool SegTriaInter( const gp_Ax1&        lastSegment,
474                        const gp_XYZ&        p0,
475                        const gp_XYZ&        p1,
476                        const gp_XYZ&        p2,
477                        double&              dist,
478                        const double&        epsilon) const;
479     bool SegTriaInter( const gp_Ax1&        lastSegment,
480                        const SMDS_MeshNode* n0,
481                        const SMDS_MeshNode* n1,
482                        const SMDS_MeshNode* n2,
483                        double&              dist,
484                        const double&        epsilon) const
485     { return SegTriaInter( lastSegment,
486                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
487                            dist, epsilon );
488     }
489     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
490     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
491     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
492     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
493     bool   IsOnEdge() const { return _2neibors; }
494     bool   IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
495     int    BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
496     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
497     void   SetCosin( double cosin );
498     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
499     void   SetMaxLen( double l ) { _maxLen = l; }
500     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
501     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
502     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
503       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
504     }
505     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
506
507     gp_XYZ smoothLaplacian();
508     gp_XYZ smoothAngular();
509     gp_XYZ smoothLengthWeighted();
510     gp_XYZ smoothCentroidal();
511     gp_XYZ smoothNefPolygon();
512
513     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
514     static const int theNbSmooFuns = FUN_NB;
515     static PSmooFun _funs[theNbSmooFuns];
516     static const char* _funNames[theNbSmooFuns+1];
517     int smooFunID( PSmooFun fun=0) const;
518   };
519   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
520                                                             &_LayerEdge::smoothLengthWeighted,
521                                                             &_LayerEdge::smoothCentroidal,
522                                                             &_LayerEdge::smoothNefPolygon,
523                                                             &_LayerEdge::smoothAngular };
524   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
525                                                          "LengthWeighted",
526                                                          "Centroidal",
527                                                          "NefPolygon",
528                                                          "Angular",
529                                                          "None"};
530   struct _LayerEdgeCmp
531   {
532     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
533     {
534       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
535       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
536     }
537   };
538   //--------------------------------------------------------------------------------
539   /*!
540    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
541    */
542   struct _halfPlane
543   {
544     gp_XY _pos, _dir, _inNorm;
545     bool IsOut( const gp_XY p, const double tol ) const
546     {
547       return _inNorm * ( p - _pos ) < -tol;
548     }
549     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
550     {
551       //const double eps = 1e-10;
552       double D = _dir.Crossed( hp._dir );
553       if ( fabs(D) < std::numeric_limits<double>::min())
554         return false;
555       gp_XY vec21 = _pos - hp._pos; 
556       double u = hp._dir.Crossed( vec21 ) / D; 
557       intPnt = _pos + _dir * u;
558       return true;
559     }
560   };
561   //--------------------------------------------------------------------------------
562   /*!
563    * Structure used to smooth a _LayerEdge based on an EDGE.
564    */
565   struct _2NearEdges
566   {
567     double               _wgt  [2]; // weights of _nodes
568     _LayerEdge*          _edges[2];
569
570      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
571     gp_XYZ*              _plnNorm;
572
573     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
574     ~_2NearEdges(){ delete _plnNorm; }
575     const SMDS_MeshNode* tgtNode(bool is2nd) {
576       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
577     }
578     const SMDS_MeshNode* srcNode(bool is2nd) {
579       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
580     }
581     void reverse() {
582       std::swap( _wgt  [0], _wgt  [1] );
583       std::swap( _edges[0], _edges[1] );
584     }
585     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
586       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
587     }
588     bool include( const _LayerEdge* e ) {
589       return ( _edges[0] == e || _edges[1] == e );
590     }
591   };
592
593
594   //--------------------------------------------------------------------------------
595   /*!
596    * \brief Layers parameters got by averaging several hypotheses
597    */
598   struct AverageHyp
599   {
600     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
601       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
602     {
603       Add( hyp );
604     }
605     void Add( const StdMeshers_ViscousLayers* hyp )
606     {
607       if ( hyp )
608       {
609         _nbHyps++;
610         _nbLayers       = hyp->GetNumberLayers();
611         //_thickness     += hyp->GetTotalThickness();
612         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
613         _stretchFactor += hyp->GetStretchFactor();
614         _method         = hyp->GetMethod();
615       }
616     }
617     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
618     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
619     int    GetNumberLayers()   const { return _nbLayers; }
620     int    GetMethod()         const { return _method; }
621
622     bool   UseSurfaceNormal()  const
623     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
624     bool   ToSmooth()          const
625     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
626     bool   IsOffsetMethod()    const
627     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
628
629     bool operator==( const AverageHyp& other ) const
630     {
631       return ( _nbLayers == other._nbLayers &&
632                _method   == other._method   &&
633                Equals( GetTotalThickness(), other.GetTotalThickness() ) &&
634                Equals( GetStretchFactor(), other.GetStretchFactor() ));
635     }
636     static bool Equals( double v1, double v2 ) { return Abs( v1 - v2 ) < 0.01 * ( v1 + v2 ); }
637
638   private:
639     int     _nbLayers, _nbHyps, _method;
640     double  _thickness, _stretchFactor;
641   };
642
643   //--------------------------------------------------------------------------------
644   /*!
645    * \brief _LayerEdge's on a shape and other shape data
646    */
647   struct _EdgesOnShape
648   {
649     vector< _LayerEdge* > _edges;
650
651     TopoDS_Shape          _shape;
652     TGeomID               _shapeID;
653     SMESH_subMesh *       _subMesh;
654     // face or edge w/o layer along or near which _edges are inflated
655     TopoDS_Shape          _sWOL;
656     bool                  _isRegularSWOL; // w/o singularities
657     // averaged StdMeshers_ViscousLayers parameters
658     AverageHyp            _hyp;
659     bool                  _toSmooth;
660     _Smoother1D*          _edgeSmoother;
661     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
662     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
663
664     typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
665     TFace2NormMap            _faceNormals; // if _shape is FACE
666     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
667
668     Handle(ShapeAnalysis_Surface) _offsetSurf;
669     _LayerEdge*                   _edgeForOffset;
670
671     _SolidData*            _data; // parent SOLID
672
673     _LayerEdge*      operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
674     size_t           size() const { return _edges.size(); }
675     TopAbs_ShapeEnum ShapeType() const
676     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
677     TopAbs_ShapeEnum SWOLType() const
678     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
679     bool             HasC1( const _EdgesOnShape* other ) const
680     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
681     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
682     _SolidData&      GetData() const { return *_data; }
683
684     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
685     ~_EdgesOnShape();
686   };
687
688   //--------------------------------------------------------------------------------
689   /*!
690    * \brief Convex FACE whose radius of curvature is less than the thickness of
691    *        layers. It is used to detect distortion of prisms based on a convex
692    *        FACE and to update normals to enable further increasing the thickness
693    */
694   struct _ConvexFace
695   {
696     TopoDS_Face                     _face;
697
698     // edges whose _simplices are used to detect prism distortion
699     vector< _LayerEdge* >           _simplexTestEdges;
700
701     // map a sub-shape to _SolidData::_edgesOnShape
702     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
703
704     bool                            _isTooCurved;
705     bool                            _normalsFixed;
706     bool                            _normalsFixedOnBorders; // used in putOnOffsetSurface()
707
708     double GetMaxCurvature( _SolidData&         data,
709                             _EdgesOnShape&      eof,
710                             BRepLProp_SLProps&  surfProp,
711                             SMESH_MesherHelper& helper);
712
713     bool GetCenterOfCurvature( _LayerEdge*         ledge,
714                                BRepLProp_SLProps&  surfProp,
715                                SMESH_MesherHelper& helper,
716                                gp_Pnt &            center ) const;
717     bool CheckPrisms() const;
718   };
719
720   //--------------------------------------------------------------------------------
721   /*!
722    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
723    *        at inflation up to the full thickness. A detected collision
724    *        is fixed in updateNormals()
725    */
726   struct _CollisionEdges
727   {
728     _LayerEdge*           _edge;
729     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
730     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
731     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
732   };
733
734   //--------------------------------------------------------------------------------
735   /*!
736    * \brief Data of a SOLID
737    */
738   struct _SolidData
739   {
740     typedef const StdMeshers_ViscousLayers* THyp;
741     TopoDS_Shape                    _solid;
742     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
743     TGeomID                         _index; // SOLID id
744     _MeshOfSolid*                   _proxyMesh;
745     bool                            _done;
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), _done(false),_helper(0) {}
790     ~_SolidData() { delete _helper; _helper = 0; }
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   struct Periodicity;
892   //--------------------------------------------------------------------------------
893   /*!
894    * \brief Builder of viscous layers
895    */
896   class _ViscousBuilder
897   {
898   public:
899     _ViscousBuilder();
900     // does it's job
901     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
902                                   const TopoDS_Shape& shape);
903     // check validity of hypotheses
904     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
905                                            const TopoDS_Shape& shape );
906
907     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
908     void RestoreListeners();
909
910     // computes SMESH_ProxyMesh::SubMesh::_n2n;
911     bool MakeN2NMap( _MeshOfSolid* pm );
912
913   private:
914
915     bool findSolidsWithLayers();
916     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
917     bool findFacesWithLayers(const bool onlyWith=false);
918     void findPeriodicFaces();
919     void getIgnoreFaces(const TopoDS_Shape&             solid,
920                         const StdMeshers_ViscousLayers* hyp,
921                         const TopoDS_Shape&             hypShape,
922                         set<TGeomID>&                   ignoreFaces);
923     void makeEdgesOnShape();
924     bool makeLayer(_SolidData& data);
925     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
926     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
927                       SMESH_MesherHelper& helper, _SolidData& data);
928     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
929                          const TopoDS_Face&   face,
930                          SMESH_MesherHelper&  helper,
931                          bool&                isOK,
932                          bool                 shiftInside=false);
933     bool getFaceNormalAtSingularity(const gp_XY&        uv,
934                                     const TopoDS_Face&  face,
935                                     SMESH_MesherHelper& helper,
936                                     gp_Dir&             normal );
937     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
938     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
939                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
940                               int                              nbFaces,
941                               bool                             lastNoOffset = false);
942     bool findNeiborsOnEdge(const _LayerEdge*     edge,
943                            const SMDS_MeshNode*& n1,
944                            const SMDS_MeshNode*& n2,
945                            _EdgesOnShape&        eos,
946                            _SolidData&           data);
947     void findSimplexTestEdges( _SolidData&                    data,
948                                vector< vector<_LayerEdge*> >& edgesByGeom);
949     void computeGeomSize( _SolidData& data );
950     bool findShapesToSmooth( _SolidData& data);
951     void limitStepSizeByCurvature( _SolidData&  data );
952     void limitStepSize( _SolidData&             data,
953                         const SMDS_MeshElement* face,
954                         const _LayerEdge*       maxCosinEdge );
955     void limitStepSize( _SolidData& data, const double minSize);
956     bool inflate(_SolidData& data);
957     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
958     int  invalidateBadSmooth( _SolidData&               data,
959                               SMESH_MesherHelper&       helper,
960                               vector< _LayerEdge* >&    badSmooEdges,
961                               vector< _EdgesOnShape* >& eosC1,
962                               const int                 infStep );
963     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
964     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
965                              vector< _EdgesOnShape* >& eosC1,
966                              int smooStep=0, int moveAll=false );
967     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
968     void findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
969                                                 _SolidData&         data,
970                                                 SMESH_MesherHelper& helper );
971     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
972     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
973                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
974                                  const bool isSmoothable );
975     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
976     bool updateNormalsOfConvexFaces( _SolidData&         data,
977                                      SMESH_MesherHelper& helper,
978                                      int                 stepNb );
979     void updateNormalsOfC1Vertices( _SolidData& data );
980     bool updateNormalsOfSmoothed( _SolidData&         data,
981                                   SMESH_MesherHelper& helper,
982                                   const int           nbSteps,
983                                   const double        stepSize );
984     bool isNewNormalOk( _SolidData&   data,
985                         _LayerEdge&   edge,
986                         const gp_XYZ& newNormal);
987     bool refine(_SolidData& data);
988     bool shrink(_SolidData& data);
989     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
990                               SMESH_MesherHelper& helper,
991                               const SMESHDS_SubMesh* faceSubMesh );
992     void restoreNoShrink( _LayerEdge& edge ) const;
993     void fixBadFaces(const TopoDS_Face&          F,
994                      SMESH_MesherHelper&         helper,
995                      const bool                  is2D,
996                      const int                   step,
997                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
998     bool addBoundaryElements(_SolidData& data);
999
1000     bool error( const string& text, int solidID=-1 );
1001     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1002
1003     // debug
1004     void makeGroupOfLE();
1005
1006     SMESH_Mesh*                  _mesh;
1007     SMESH_ComputeErrorPtr        _error;
1008
1009     vector<                      _SolidData >  _sdVec;
1010     TopTools_IndexedMapOfShape   _solids; // to find _SolidData by a solid
1011     TopTools_MapOfShape          _shrunkFaces;
1012     std::unique_ptr<Periodicity> _periodicity;
1013
1014     int                          _tmpFaceID;
1015     PyDump*                      _pyDump;
1016   };
1017   //--------------------------------------------------------------------------------
1018   /*!
1019    * \brief Shrinker of nodes on the EDGE
1020    */
1021   class _Shrinker1D
1022   {
1023     TopoDS_Edge                   _geomEdge;
1024     vector<double>                _initU;
1025     vector<double>                _normPar;
1026     vector<const SMDS_MeshNode*>  _nodes;
1027     const _LayerEdge*             _edges[2];
1028     bool                          _done;
1029   public:
1030     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1031     void Compute(bool set3D, SMESH_MesherHelper& helper);
1032     void RestoreParams();
1033     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1034     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1035     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1036     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1037     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1038     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1039   };
1040   //--------------------------------------------------------------------------------
1041   /*!
1042    * \brief Smoother of _LayerEdge's on EDGE.
1043    */
1044   struct _Smoother1D
1045   {
1046     struct OffPnt // point of the offsetted EDGE
1047     {
1048       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1049       double      _len;    // length reached at previous inflation step
1050       double      _param;  // on EDGE
1051       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1052       gp_XYZ      _edgeDir;// EDGE tangent at _param
1053       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1054     };
1055     vector< OffPnt >   _offPoints;
1056     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1057     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1058     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1059     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1060     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1061     _EdgesOnShape&     _eos;
1062     double             _curveLen; // length of the EDGE
1063     std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1064
1065     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1066                                               _EdgesOnShape&      eos,
1067                                               SMESH_MesherHelper& helper);
1068
1069     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1070                  _EdgesOnShape&     eos )
1071       : _anaCurve( curveForSmooth ), _eos( eos )
1072     {
1073     }
1074     bool Perform(_SolidData&                    data,
1075                  Handle(ShapeAnalysis_Surface)& surface,
1076                  const TopoDS_Face&             F,
1077                  SMESH_MesherHelper&            helper );
1078
1079     void prepare(_SolidData& data );
1080
1081     void findEdgesToSmooth();
1082
1083     bool isToSmooth( int iE );
1084
1085     bool smoothAnalyticEdge( _SolidData&                    data,
1086                              Handle(ShapeAnalysis_Surface)& surface,
1087                              const TopoDS_Face&             F,
1088                              SMESH_MesherHelper&            helper);
1089     bool smoothComplexEdge( _SolidData&                    data,
1090                             Handle(ShapeAnalysis_Surface)& surface,
1091                             const TopoDS_Face&             F,
1092                             SMESH_MesherHelper&            helper);
1093     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1094                             const gp_XYZ&  edgeDir);
1095     _LayerEdge* getLEdgeOnV( bool is2nd )
1096     {
1097       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1098     }
1099     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1100
1101     void offPointsToPython() const; // debug
1102   };
1103   //--------------------------------------------------------------------------------
1104   /*!
1105    * \brief Class of temporary mesh face.
1106    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1107    * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1108    */
1109   struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1110   {
1111     const SMDS_MeshElement* _srcFace;
1112
1113     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1114                   int                                 ID,
1115                   int                                 faceID=-1,
1116                   const SMDS_MeshElement*             srcFace=0 ):
1117       SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1118     virtual SMDSAbs_EntityType  GetEntityType() const
1119     { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1120     virtual SMDSAbs_GeometryType GetGeomType()  const
1121     { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1122   };
1123   //--------------------------------------------------------------------------------
1124   /*!
1125    * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1126    */
1127   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1128   {
1129     _LayerEdge *_le1, *_le2;
1130     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1131       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1132     {
1133       myNodes[0]=_le1->_nodes[0];
1134       myNodes[1]=_le1->_nodes.back();
1135       myNodes[2]=_le2->_nodes.back();
1136       myNodes[3]=_le2->_nodes[0];
1137     }
1138     const SMDS_MeshNode* n( size_t i ) const
1139     {
1140       return myNodes[ i ];
1141     }
1142     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1143     {
1144       SMESH_TNodeXYZ p0s( myNodes[0] );
1145       SMESH_TNodeXYZ p0t( myNodes[1] );
1146       SMESH_TNodeXYZ p1t( myNodes[2] );
1147       SMESH_TNodeXYZ p1s( myNodes[3] );
1148       gp_XYZ  v0 = p0t - p0s;
1149       gp_XYZ  v1 = p1t - p1s;
1150       gp_XYZ v01 = p1s - p0s;
1151       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1152       gp_XYZ   d = v01 ^ n;
1153       d.Normalize();
1154       return d;
1155     }
1156     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1157     {
1158       myNodes[0]=le1->_nodes[0];
1159       myNodes[1]=le1->_nodes.back();
1160       myNodes[2]=le2->_nodes.back();
1161       myNodes[3]=le2->_nodes[0];
1162       return GetDir();
1163     }
1164   };
1165   //--------------------------------------------------------------------------------
1166   /*!
1167    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1168    * \warning Location of a surface is ignored
1169    */
1170   struct _NodeCoordHelper
1171   {
1172     SMESH_MesherHelper&        _helper;
1173     const TopoDS_Face&         _face;
1174     Handle(Geom_Surface)       _surface;
1175     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1176
1177     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1178       : _helper( helper ), _face( F )
1179     {
1180       if ( is2D )
1181       {
1182         TopLoc_Location loc;
1183         _surface = BRep_Tool::Surface( _face, loc );
1184       }
1185       if ( _surface.IsNull() )
1186         _fun = & _NodeCoordHelper::direct;
1187       else
1188         _fun = & _NodeCoordHelper::byUV;
1189     }
1190     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1191
1192   private:
1193     gp_XYZ direct(const SMDS_MeshNode* n) const
1194     {
1195       return SMESH_TNodeXYZ( n );
1196     }
1197     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1198     {
1199       gp_XY uv = _helper.GetNodeUV( _face, n );
1200       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1201     }
1202   };
1203
1204   //================================================================================
1205   /*!
1206    * \brief Check angle between vectors 
1207    */
1208   //================================================================================
1209
1210   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1211   {
1212     double dot = v1 * v2; // cos * |v1| * |v2|
1213     double l1  = v1.SquareMagnitude();
1214     double l2  = v2.SquareMagnitude();
1215     return (( dot * cos >= 0 ) && 
1216             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1217   }
1218
1219   class _Factory
1220   {
1221     ObjectPool< _LayerEdge >  _edgePool;
1222     ObjectPool< _Curvature >  _curvaturePool;
1223     ObjectPool< _2NearEdges > _nearEdgesPool;
1224
1225     static _Factory* & me()
1226     {
1227       static _Factory* theFactory = 0;
1228       return theFactory;
1229     }
1230   public:
1231
1232     _Factory()  { me() = this; }
1233     ~_Factory() { me() = 0; }
1234
1235     static _LayerEdge*  NewLayerEdge() { return me()->_edgePool.getNew(); }
1236     static _Curvature * NewCurvature() { return me()->_curvaturePool.getNew(); }
1237     static _2NearEdges* NewNearEdges() { return me()->_nearEdgesPool.getNew(); }
1238   };
1239
1240 } // namespace VISCOUS_3D
1241
1242
1243
1244 //================================================================================
1245 // StdMeshers_ViscousLayers hypothesis
1246 //
1247 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1248   :SMESH_Hypothesis(hypId, gen),
1249    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1250    _method( SURF_OFFSET_SMOOTH )
1251 {
1252   _name = StdMeshers_ViscousLayers::GetHypType();
1253   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1254 } // --------------------------------------------------------------------------------
1255 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1256 {
1257   if ( faceIds != _shapeIds )
1258     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1259   if ( _isToIgnoreShapes != toIgnore )
1260     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1261 } // --------------------------------------------------------------------------------
1262 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1263 {
1264   if ( thickness != _thickness )
1265     _thickness = thickness, NotifySubMeshesHypothesisModification();
1266 } // --------------------------------------------------------------------------------
1267 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1268 {
1269   if ( _nbLayers != nb )
1270     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1271 } // --------------------------------------------------------------------------------
1272 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1273 {
1274   if ( _stretchFactor != factor )
1275     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1276 } // --------------------------------------------------------------------------------
1277 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1278 {
1279   if ( _method != method )
1280     _method = method, NotifySubMeshesHypothesisModification();
1281 } // --------------------------------------------------------------------------------
1282 SMESH_ProxyMesh::Ptr
1283 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1284                                   const TopoDS_Shape& theShape,
1285                                   const bool          toMakeN2NMap) const
1286 {
1287   using namespace VISCOUS_3D;
1288   _ViscousBuilder builder;
1289   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1290   if ( err && !err->IsOK() )
1291     return SMESH_ProxyMesh::Ptr();
1292
1293   vector<SMESH_ProxyMesh::Ptr> components;
1294   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1295   for ( ; exp.More(); exp.Next() )
1296   {
1297     if ( _MeshOfSolid* pm =
1298          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1299     {
1300       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1301         if ( !builder.MakeN2NMap( pm ))
1302           return SMESH_ProxyMesh::Ptr();
1303       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1304       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1305
1306       if ( pm->_warning && !pm->_warning->IsOK() )
1307       {
1308         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1309         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1310         if ( !smError || smError->IsOK() )
1311           smError = pm->_warning;
1312       }
1313     }
1314     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1315   }
1316   switch ( components.size() )
1317   {
1318   case 0: break;
1319
1320   case 1: return components[0];
1321
1322   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1323   }
1324   return SMESH_ProxyMesh::Ptr();
1325 } // --------------------------------------------------------------------------------
1326 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1327 {
1328   save << " " << _nbLayers
1329        << " " << _thickness
1330        << " " << _stretchFactor
1331        << " " << _shapeIds.size();
1332   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1333     save << " " << _shapeIds[i];
1334   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1335   save << " " << _method;
1336   return save;
1337 } // --------------------------------------------------------------------------------
1338 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1339 {
1340   int nbFaces, faceID, shapeToTreat, method;
1341   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1342   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1343     _shapeIds.push_back( faceID );
1344   if ( load >> shapeToTreat ) {
1345     _isToIgnoreShapes = !shapeToTreat;
1346     if ( load >> method )
1347       _method = (ExtrusionMethod) method;
1348   }
1349   else {
1350     _isToIgnoreShapes = true; // old behavior
1351   }
1352   return load;
1353 } // --------------------------------------------------------------------------------
1354 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1355                                                    const TopoDS_Shape& theShape)
1356 {
1357   // TODO
1358   return false;
1359 } // --------------------------------------------------------------------------------
1360 SMESH_ComputeErrorPtr
1361 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1362                                           const TopoDS_Shape&                  theShape,
1363                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1364 {
1365   VISCOUS_3D::_ViscousBuilder builder;
1366   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1367   if ( err && !err->IsOK() )
1368     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1369   else
1370     theStatus = SMESH_Hypothesis::HYP_OK;
1371
1372   return err;
1373 }
1374 // --------------------------------------------------------------------------------
1375 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1376 {
1377   bool isIn =
1378     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1379   return IsToIgnoreShapes() ? !isIn : isIn;
1380 }
1381 // END StdMeshers_ViscousLayers hypothesis
1382 //================================================================================
1383
1384 namespace VISCOUS_3D
1385 {
1386   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1387   {
1388     gp_Vec dir;
1389     double f,l;
1390     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1391     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1392     gp_Pnt p = BRep_Tool::Pnt( fromV );
1393     double distF = p.SquareDistance( c->Value( f ));
1394     double distL = p.SquareDistance( c->Value( l ));
1395     c->D1(( distF < distL ? f : l), p, dir );
1396     if ( distL < distF ) dir.Reverse();
1397     return dir.XYZ();
1398   }
1399   //--------------------------------------------------------------------------------
1400   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1401                      SMESH_MesherHelper& helper)
1402   {
1403     gp_Vec dir;
1404     double f,l; gp_Pnt p;
1405     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1406     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1407     double u = helper.GetNodeU( E, atNode );
1408     c->D1( u, p, dir );
1409     return dir.XYZ();
1410   }
1411   //--------------------------------------------------------------------------------
1412   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1413                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1414                      double* cosin=0);
1415   //--------------------------------------------------------------------------------
1416   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1417                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1418   {
1419     double f,l;
1420     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1421     if ( c.IsNull() )
1422     {
1423       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1424       return getFaceDir( F, v, node, helper, ok );
1425     }
1426     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1427     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1428     gp_Pnt p; gp_Vec du, dv, norm;
1429     surface->D1( uv.X(),uv.Y(), p, du,dv );
1430     norm = du ^ dv;
1431
1432     double u = helper.GetNodeU( fromE, node, 0, &ok );
1433     c->D1( u, p, du );
1434     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1435     if ( o == TopAbs_REVERSED )
1436       du.Reverse();
1437
1438     gp_Vec dir = norm ^ du;
1439
1440     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1441          helper.IsClosedEdge( fromE ))
1442     {
1443       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1444       else                        c->D1( f, p, dv );
1445       if ( o == TopAbs_REVERSED )
1446         dv.Reverse();
1447       gp_Vec dir2 = norm ^ dv;
1448       dir = dir.Normalized() + dir2.Normalized();
1449     }
1450     return dir.XYZ();
1451   }
1452   //--------------------------------------------------------------------------------
1453   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1454                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1455                      bool& ok, double* cosin)
1456   {
1457     TopoDS_Face faceFrw = F;
1458     faceFrw.Orientation( TopAbs_FORWARD );
1459     //double f,l; TopLoc_Location loc;
1460     TopoDS_Edge edges[2]; // sharing a vertex
1461     size_t nbEdges = 0;
1462     {
1463       TopoDS_Vertex VV[2];
1464       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1465       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1466       {
1467         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1468         if ( SMESH_Algo::isDegenerated( e )) continue;
1469         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1470         if ( VV[1].IsSame( fromV )) {
1471           nbEdges += edges[ 0 ].IsNull();
1472           edges[ 0 ] = e;
1473         }
1474         else if ( VV[0].IsSame( fromV )) {
1475           nbEdges += edges[ 1 ].IsNull();
1476           edges[ 1 ] = e;
1477         }
1478       }
1479     }
1480     gp_XYZ dir(0,0,0), edgeDir[2];
1481     if ( nbEdges == 2 )
1482     {
1483       // get dirs of edges going fromV
1484       ok = true;
1485       for ( size_t i = 0; i < nbEdges && ok; ++i )
1486       {
1487         edgeDir[i] = getEdgeDir( edges[i], fromV );
1488         double size2 = edgeDir[i].SquareModulus();
1489         if (( ok = size2 > numeric_limits<double>::min() ))
1490           edgeDir[i] /= sqrt( size2 );
1491       }
1492       if ( !ok ) return dir;
1493
1494       // get angle between the 2 edges
1495       gp_Vec faceNormal;
1496       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1497       if ( Abs( angle ) < 5 * M_PI/180 )
1498       {
1499         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1500       }
1501       else
1502       {
1503         dir = edgeDir[0] + edgeDir[1];
1504         if ( angle < 0 )
1505           dir.Reverse();
1506       }
1507       if ( cosin ) {
1508         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1509         *cosin = Cos( angle );
1510       }
1511     }
1512     else if ( nbEdges == 1 )
1513     {
1514       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1515       if ( cosin ) *cosin = 1.;
1516     }
1517     else
1518     {
1519       ok = false;
1520     }
1521
1522     return dir;
1523   }
1524
1525   //================================================================================
1526   /*!
1527    * \brief Finds concave VERTEXes of a FACE
1528    */
1529   //================================================================================
1530
1531   bool getConcaveVertices( const TopoDS_Face&  F,
1532                            SMESH_MesherHelper& helper,
1533                            set< TGeomID >*     vertices = 0)
1534   {
1535     // check angles at VERTEXes
1536     TError error;
1537     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1538     for ( size_t iW = 0; iW < wires.size(); ++iW )
1539     {
1540       const int nbEdges = wires[iW]->NbEdges();
1541       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1542         continue;
1543       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1544       {
1545         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1546         int iE2 = ( iE1 + 1 ) % nbEdges;
1547         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1548           iE2 = ( iE2 + 1 ) % nbEdges;
1549         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1550         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1551                                         wires[iW]->Edge( iE2 ), F, V );
1552         if ( angle < -5. * M_PI / 180. )
1553         {
1554           if ( !vertices )
1555             return true;
1556           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1557         }
1558       }
1559     }
1560     return vertices ? !vertices->empty() : false;
1561   }
1562
1563   //================================================================================
1564   /*!
1565    * \brief Returns true if a FACE is bound by a concave EDGE
1566    */
1567   //================================================================================
1568
1569   bool isConcave( const TopoDS_Face&  F,
1570                   SMESH_MesherHelper& helper,
1571                   set< TGeomID >*     vertices = 0 )
1572   {
1573     bool isConcv = false;
1574     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1575     //   return true;
1576     gp_Vec2d drv1, drv2;
1577     gp_Pnt2d p;
1578     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1579     for ( ; eExp.More(); eExp.Next() )
1580     {
1581       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1582       if ( SMESH_Algo::isDegenerated( E )) continue;
1583       // check if 2D curve is concave
1584       BRepAdaptor_Curve2d curve( E, F );
1585       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1586       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1587       curve.Intervals( intervals, GeomAbs_C2 );
1588       bool isConvex = true;
1589       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1590       {
1591         double u1 = intervals( i );
1592         double u2 = intervals( i+1 );
1593         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1594         double cross = drv1 ^ drv2;
1595         if ( E.Orientation() == TopAbs_REVERSED )
1596           cross = -cross;
1597         isConvex = ( cross > -1e-9 ); // 0.1 );
1598       }
1599       if ( !isConvex )
1600       {
1601         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1602         isConcv = true;
1603         if ( vertices )
1604           break;
1605         else
1606           return true;
1607       }
1608     }
1609
1610     // check angles at VERTEXes
1611     if ( getConcaveVertices( F, helper, vertices ))
1612       isConcv = true;
1613
1614     return isConcv;
1615   }
1616
1617   //================================================================================
1618   /*!
1619    * \brief Computes minimal distance of face in-FACE nodes from an EDGE
1620    *  \param [in] face - the mesh face to treat
1621    *  \param [in] nodeOnEdge - a node on the EDGE
1622    *  \param [out] faceSize - the computed distance
1623    *  \return bool - true if faceSize computed
1624    */
1625   //================================================================================
1626
1627   bool getDistFromEdge( const SMDS_MeshElement* face,
1628                         const SMDS_MeshNode*    nodeOnEdge,
1629                         double &                faceSize )
1630   {
1631     faceSize = Precision::Infinite();
1632     bool done = false;
1633
1634     int nbN  = face->NbCornerNodes();
1635     int iOnE = face->GetNodeIndex( nodeOnEdge );
1636     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1637                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1638     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1639                                       face->GetNode( iNext[1] ) };
1640     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1641     double segLen = -1.;
1642     // look for two neighbor not in-FACE nodes of face
1643     for ( int i = 0; i < 2; ++i )
1644     {
1645       if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1646           ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1647       {
1648         // look for an in-FACE node
1649         for ( int iN = 0; iN < nbN; ++iN )
1650         {
1651           if ( iN == iOnE || iN == iNext[i] )
1652             continue;
1653           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1654           gp_XYZ v = pInFace - segEnd;
1655           if ( segLen < 0 )
1656           {
1657             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1658             segLen = segVec.Modulus();
1659           }
1660           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1661           faceSize = Min( faceSize, distToSeg );
1662           done = true;
1663         }
1664         segLen = -1;
1665       }
1666     }
1667     return done;
1668   }
1669   //================================================================================
1670   /*!
1671    * \brief Return direction of axis or revolution of a surface
1672    */
1673   //================================================================================
1674
1675   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1676                           gp_Dir &                 axis )
1677   {
1678     switch ( surface.GetType() ) {
1679     case GeomAbs_Cone:
1680     {
1681       gp_Cone cone = surface.Cone();
1682       axis = cone.Axis().Direction();
1683       break;
1684     }
1685     case GeomAbs_Sphere:
1686     {
1687       gp_Sphere sphere = surface.Sphere();
1688       axis = sphere.Position().Direction();
1689       break;
1690     }
1691     case GeomAbs_SurfaceOfRevolution:
1692     {
1693       axis = surface.AxeOfRevolution().Direction();
1694       break;
1695     }
1696     //case GeomAbs_SurfaceOfExtrusion:
1697     case GeomAbs_OffsetSurface:
1698     {
1699       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1700       return getRovolutionAxis( base->Surface(), axis );
1701     }
1702     default: return false;
1703     }
1704     return true;
1705   }
1706
1707   //--------------------------------------------------------------------------------
1708   // DEBUG. Dump intermediate node positions into a python script
1709   // HOWTO use: run python commands written in a console to see
1710   //  construction steps of viscous layers
1711 #ifdef __myDEBUG
1712   ostream* py;
1713   int      theNbPyFunc;
1714   struct PyDump
1715   {
1716     PyDump(SMESH_Mesh& m) {
1717       int tag = 3 + m.GetId();
1718       const char* fname = "/tmp/viscous.py";
1719       cout << "execfile('"<<fname<<"')"<<endl;
1720       py = _pyStream = new ofstream(fname);
1721       *py << "import SMESH" << endl
1722           << "from salome.smesh import smeshBuilder" << endl
1723           << "smesh  = smeshBuilder.New()" << endl
1724           << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1725           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1726       theNbPyFunc = 0;
1727     }
1728     void Finish() {
1729       if (py) {
1730         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1731           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1732         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1733           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1734       }
1735       delete py; py=0;
1736     }
1737     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1738     struct MyStream : public ostream
1739     {
1740       template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1741     };
1742     void Pause() { py = &_mystream; }
1743     void Resume() { py = _pyStream; }
1744     MyStream _mystream;
1745     ostream* _pyStream;
1746   };
1747 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1748 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1749 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1750 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1751   void _dumpFunction(const string& fun, int ln)
1752   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1753   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1754   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1755                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1756   void _dumpCmd(const string& txt, int ln)
1757   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1758   void dumpFunctionEnd()
1759   { if (py) *py<< "  return"<< endl; }
1760   void dumpChangeNodes( const SMDS_MeshElement* f )
1761   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1762       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1763       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1764 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1765
1766 #else
1767
1768   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1769 #define dumpFunction(f) f
1770 #define dumpMove(n)
1771 #define dumpMoveComm(n,txt)
1772 #define dumpCmd(txt)
1773 #define dumpFunctionEnd()
1774 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1775 #define debugMsg( txt ) {}
1776
1777 #endif
1778 }
1779
1780 using namespace VISCOUS_3D;
1781
1782 //================================================================================
1783 /*!
1784  * \brief Constructor of _ViscousBuilder
1785  */
1786 //================================================================================
1787
1788 _ViscousBuilder::_ViscousBuilder()
1789 {
1790   _error = SMESH_ComputeError::New(COMPERR_OK);
1791   _tmpFaceID = 0;
1792 }
1793
1794 //================================================================================
1795 /*!
1796  * \brief Stores error description and returns false
1797  */
1798 //================================================================================
1799
1800 bool _ViscousBuilder::error(const string& text, int solidId )
1801 {
1802   const string prefix = string("Viscous layers builder: ");
1803   _error->myName    = COMPERR_ALGO_FAILED;
1804   _error->myComment = prefix + text;
1805   if ( _mesh )
1806   {
1807     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1808     if ( !sm && !_sdVec.empty() )
1809       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1810     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1811     {
1812       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1813       if ( smError && smError->myAlgo )
1814         _error->myAlgo = smError->myAlgo;
1815       smError = _error;
1816       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1817     }
1818     // set KO to all solids
1819     for ( size_t i = 0; i < _sdVec.size(); ++i )
1820     {
1821       if ( _sdVec[i]._index == solidId )
1822         continue;
1823       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1824       if ( !sm->IsEmpty() )
1825         continue;
1826       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1827       if ( !smError || smError->IsOK() )
1828       {
1829         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1830         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1831       }
1832     }
1833   }
1834   makeGroupOfLE(); // debug
1835
1836   return false;
1837 }
1838
1839 //================================================================================
1840 /*!
1841  * \brief At study restoration, restore event listeners used to clear an inferior
1842  *  dim sub-mesh modified by viscous layers
1843  */
1844 //================================================================================
1845
1846 void _ViscousBuilder::RestoreListeners()
1847 {
1848   // TODO
1849 }
1850
1851 //================================================================================
1852 /*!
1853  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1854  */
1855 //================================================================================
1856
1857 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1858 {
1859   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1860   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1861   for ( ; fExp.More(); fExp.Next() )
1862   {
1863     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1864     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1865
1866     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1867       continue;
1868     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1869       continue;
1870
1871     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1872       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1873
1874     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1875     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1876     while( prxIt->more() )
1877     {
1878       const SMDS_MeshElement* fSrc = srcIt->next();
1879       const SMDS_MeshElement* fPrx = prxIt->next();
1880       if ( fSrc->NbNodes() != fPrx->NbNodes())
1881         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1882       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1883         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1884     }
1885   }
1886   pm->_n2nMapComputed = true;
1887   return true;
1888 }
1889
1890 //================================================================================
1891 /*!
1892  * \brief Does its job
1893  */
1894 //================================================================================
1895
1896 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1897                                                const TopoDS_Shape& theShape)
1898 {
1899   _mesh = & theMesh;
1900
1901   _Factory factory;
1902
1903   // check if proxy mesh already computed
1904   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1905   if ( !exp.More() )
1906     return error("No SOLID's in theShape"), _error;
1907
1908   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1909     return SMESH_ComputeErrorPtr(); // everything already computed
1910
1911   PyDump debugDump( theMesh );
1912   _pyDump = &debugDump;
1913
1914   // TODO: ignore already computed SOLIDs
1915   if ( !findSolidsWithLayers())
1916     return _error;
1917
1918   if ( !findFacesWithLayers() )
1919     return _error;
1920
1921   // for ( size_t i = 0; i < _sdVec.size(); ++i )
1922   // {
1923   //   if ( ! makeLayer( _sdVec[ i ]))   // create _LayerEdge's
1924   //     return _error;
1925   // }
1926
1927   makeEdgesOnShape();
1928
1929   findPeriodicFaces();
1930
1931   for ( size_t i = 0; i < _sdVec.size(); ++i )
1932   {
1933     size_t iSD = 0;
1934     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1935       if ( _sdVec[iSD]._before.IsEmpty() &&
1936            !_sdVec[iSD]._solid.IsNull() &&
1937            !_sdVec[iSD]._done )
1938         break;
1939
1940     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1941       return _error;
1942
1943     if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1944     {
1945       _sdVec[iSD]._solid.Nullify();
1946       continue;
1947     }
1948
1949     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
1950       return _error;
1951
1952     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
1953       return _error;
1954
1955     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
1956       return _error;
1957
1958     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1959
1960     _sdVec[iSD]._done = true;
1961
1962     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1963     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1964       _sdVec[iSD]._before.Remove( solid );
1965   }
1966
1967   makeGroupOfLE(); // debug
1968   debugDump.Finish();
1969
1970   return _error;
1971 }
1972
1973 //================================================================================
1974 /*!
1975  * \brief Check validity of hypotheses
1976  */
1977 //================================================================================
1978
1979 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1980                                                         const TopoDS_Shape& shape )
1981 {
1982   _mesh = & mesh;
1983
1984   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1985     return SMESH_ComputeErrorPtr(); // everything already computed
1986
1987
1988   findSolidsWithLayers();
1989   bool ok = findFacesWithLayers( true );
1990
1991   // remove _MeshOfSolid's of _SolidData's
1992   for ( size_t i = 0; i < _sdVec.size(); ++i )
1993     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1994
1995   if ( !ok )
1996     return _error;
1997
1998   return SMESH_ComputeErrorPtr();
1999 }
2000
2001 //================================================================================
2002 /*!
2003  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
2004  */
2005 //================================================================================
2006
2007 bool _ViscousBuilder::findSolidsWithLayers()
2008 {
2009   // get all solids
2010   TopTools_IndexedMapOfShape allSolids;
2011   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
2012   _sdVec.reserve( allSolids.Extent());
2013
2014   SMESH_HypoFilter filter;
2015   for ( int i = 1; i <= allSolids.Extent(); ++i )
2016   {
2017     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
2018     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
2019     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
2020       continue; // solid is already meshed
2021     SMESH_Algo* algo = sm->GetAlgo();
2022     if ( !algo ) continue;
2023     // TODO: check if algo is hidden
2024     const list <const SMESHDS_Hypothesis *> & allHyps =
2025       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
2026     _SolidData* soData = 0;
2027     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
2028     const StdMeshers_ViscousLayers* viscHyp = 0;
2029     for ( ; hyp != allHyps.end(); ++hyp )
2030       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
2031       {
2032         TopoDS_Shape hypShape;
2033         filter.Init( filter.Is( viscHyp ));
2034         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
2035
2036         if ( !soData )
2037         {
2038           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2039                                                                     allSolids(i),
2040                                                                     /*toCreate=*/true);
2041           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2042           soData = & _sdVec.back();
2043           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2044           soData->_helper = new SMESH_MesherHelper( *_mesh );
2045           soData->_helper->SetSubShape( allSolids(i) );
2046           _solids.Add( allSolids(i) );
2047         }
2048         soData->_hyps.push_back( viscHyp );
2049         soData->_hypShapes.push_back( hypShape );
2050       }
2051   }
2052   if ( _sdVec.empty() )
2053     return error
2054       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2055
2056   return true;
2057 }
2058
2059 //================================================================================
2060 /*!
2061  * \brief Set a _SolidData to be computed before another
2062  */
2063 //================================================================================
2064
2065 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2066 {
2067   // check possibility to set this order; get all solids before solidBefore
2068   TopTools_IndexedMapOfShape allSolidsBefore;
2069   allSolidsBefore.Add( solidBefore._solid );
2070   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2071   {
2072     int iSD = _solids.FindIndex( allSolidsBefore(i) );
2073     if ( iSD )
2074     {
2075       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2076       for ( ; soIt.More(); soIt.Next() )
2077         allSolidsBefore.Add( soIt.Value() );
2078     }
2079   }
2080   if ( allSolidsBefore.Contains( solidAfter._solid ))
2081     return false;
2082
2083   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2084     solidAfter._before.Add( allSolidsBefore(i) );
2085
2086   return true;
2087 }
2088
2089 //================================================================================
2090 /*!
2091  * \brief
2092  */
2093 //================================================================================
2094
2095 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2096 {
2097   SMESH_MesherHelper helper( *_mesh );
2098   TopExp_Explorer exp;
2099
2100   // collect all faces-to-ignore defined by hyp
2101   for ( size_t i = 0; i < _sdVec.size(); ++i )
2102   {
2103     // get faces-to-ignore defined by each hyp
2104     typedef const StdMeshers_ViscousLayers* THyp;
2105     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2106     list< TFacesOfHyp > ignoreFacesOfHyps;
2107     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2108     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2109     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2110     {
2111       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2112       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2113     }
2114
2115     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2116     const int nbHyps = _sdVec[i]._hyps.size();
2117     if ( nbHyps > 1 )
2118     {
2119       // check if two hypotheses define different parameters for the same FACE
2120       list< TFacesOfHyp >::iterator igFacesOfHyp;
2121       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2122       {
2123         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2124         THyp hyp = 0;
2125         igFacesOfHyp = ignoreFacesOfHyps.begin();
2126         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2127           if ( ! igFacesOfHyp->first.count( faceID ))
2128           {
2129             if ( hyp )
2130               return error(SMESH_Comment("Several hypotheses define "
2131                                          "Viscous Layers on the face #") << faceID );
2132             hyp = igFacesOfHyp->second;
2133           }
2134         if ( hyp )
2135           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2136         else
2137           _sdVec[i]._ignoreFaceIds.insert( faceID );
2138       }
2139
2140       // check if two hypotheses define different number of viscous layers for
2141       // adjacent faces of a solid
2142       set< int > nbLayersSet;
2143       igFacesOfHyp = ignoreFacesOfHyps.begin();
2144       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2145       {
2146         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2147       }
2148       if ( nbLayersSet.size() > 1 )
2149       {
2150         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2151         {
2152           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2153           THyp hyp1 = 0, hyp2 = 0;
2154           while( const TopoDS_Shape* face = fIt->next() )
2155           {
2156             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2157             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2158             if ( f2h != _sdVec[i]._face2hyp.end() )
2159             {
2160               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2161             }
2162           }
2163           if ( hyp1 && hyp2 &&
2164                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2165           {
2166             return error("Two hypotheses define different number of "
2167                          "viscous layers on adjacent faces");
2168           }
2169         }
2170       }
2171     } // if ( nbHyps > 1 )
2172     else
2173     {
2174       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2175     }
2176   } // loop on _sdVec
2177
2178   if ( onlyWith ) // is called to check hypotheses compatibility only
2179     return true;
2180
2181   // fill _SolidData::_reversedFaceIds
2182   for ( size_t i = 0; i < _sdVec.size(); ++i )
2183   {
2184     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2185     for ( ; exp.More(); exp.Next() )
2186     {
2187       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2188       const TGeomID    faceID = getMeshDS()->ShapeToIndex( face );
2189       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2190           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2191           helper.IsReversedSubMesh( face ))
2192       {
2193         _sdVec[i]._reversedFaceIds.insert( faceID );
2194       }
2195     }
2196   }
2197
2198   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2199   TopTools_IndexedMapOfShape shapes;
2200   std::string structAlgoName = "Hexa_3D";
2201   for ( size_t i = 0; i < _sdVec.size(); ++i )
2202   {
2203     shapes.Clear();
2204     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2205     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2206     {
2207       const TopoDS_Shape& edge = shapes(iE);
2208       // find 2 FACEs sharing an EDGE
2209       TopoDS_Shape FF[2];
2210       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2211       while ( fIt->more())
2212       {
2213         const TopoDS_Shape* f = fIt->next();
2214         FF[ int( !FF[0].IsNull()) ] = *f;
2215       }
2216       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2217
2218       // check presence of layers on them
2219       int ignore[2];
2220       for ( int j = 0; j < 2; ++j )
2221         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2222       if ( ignore[0] == ignore[1] )
2223         continue; // nothing interesting
2224       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ]; // FACE w/o layers
2225
2226       // add EDGE to maps
2227       if ( !fWOL.IsNull())
2228       {
2229         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2230         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2231       }
2232     }
2233   }
2234
2235   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2236
2237   for ( size_t i = 0; i < _sdVec.size(); ++i )
2238   {
2239     shapes.Clear();
2240     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2241     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2242     {
2243       const TopoDS_Shape& vertex = shapes(iV);
2244       // find faces WOL sharing the vertex
2245       vector< TopoDS_Shape > facesWOL;
2246       size_t totalNbFaces = 0;
2247       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2248       while ( fIt->more())
2249       {
2250         const TopoDS_Shape* f = fIt->next();
2251         totalNbFaces++;
2252         const int fID = getMeshDS()->ShapeToIndex( *f );
2253         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2254           facesWOL.push_back( *f );
2255       }
2256       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2257         continue; // no layers at this vertex or no WOL
2258       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2259       switch ( facesWOL.size() )
2260       {
2261       case 1:
2262       {
2263         helper.SetSubShape( facesWOL[0] );
2264         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2265         {
2266           TopoDS_Shape seamEdge;
2267           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2268           while ( eIt->more() && seamEdge.IsNull() )
2269           {
2270             const TopoDS_Shape* e = eIt->next();
2271             if ( helper.IsRealSeam( *e ) )
2272               seamEdge = *e;
2273           }
2274           if ( !seamEdge.IsNull() )
2275           {
2276             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2277             break;
2278           }
2279         }
2280         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2281         break;
2282       }
2283       case 2:
2284       {
2285         // find an edge shared by 2 faces
2286         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2287         while ( eIt->more())
2288         {
2289           const TopoDS_Shape* e = eIt->next();
2290           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2291                helper.IsSubShape( *e, facesWOL[1]))
2292           {
2293             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2294           }
2295         }
2296         break;
2297       }
2298       default:
2299         return error("Not yet supported case", _sdVec[i]._index);
2300       }
2301     }
2302   }
2303
2304   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrunk since
2305   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2306   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2307   for ( size_t i = 0; i < _sdVec.size(); ++i )
2308   {
2309     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2310     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2311     {
2312       const TopoDS_Shape& fWOL = e2f->second;
2313       const TGeomID     edgeID = e2f->first;
2314       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2315       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2316       if ( edge.ShapeType() != TopAbs_EDGE )
2317         continue; // shrink shape is VERTEX
2318
2319       TopoDS_Shape solid;
2320       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2321       while ( soIt->more() && solid.IsNull() )
2322       {
2323         const TopoDS_Shape* so = soIt->next();
2324         if ( !so->IsSame( _sdVec[i]._solid ))
2325           solid = *so;
2326       }
2327       if ( solid.IsNull() )
2328         continue;
2329
2330       bool noShrinkE = false;
2331       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2332       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2333       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2334       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2335       {
2336         // the adjacent SOLID has NO layers on fWOL;
2337         // shrink allowed if
2338         // - there are layers on the EDGE in the adjacent SOLID
2339         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2340         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2341         bool shrinkAllowed = (( hasWLAdj ) ||
2342                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2343         noShrinkE = !shrinkAllowed;
2344       }
2345       else if ( iSolid < _sdVec.size() )
2346       {
2347         // the adjacent SOLID has layers on fWOL;
2348         // check if SOLID's mesh is unstructured and then try to set it
2349         // to be computed after the i-th solid
2350         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2351           noShrinkE = true; // don't shrink fWOL
2352       }
2353       else
2354       {
2355         // the adjacent SOLID has NO layers at all
2356         noShrinkE = isStructured;
2357       }
2358
2359       if ( noShrinkE )
2360       {
2361         _sdVec[i]._noShrinkShapes.insert( edgeID );
2362
2363         // check if there is a collision with to-shrink-from EDGEs in iSolid
2364         // if ( iSolid < _sdVec.size() )
2365         // {
2366         //   shapes.Clear();
2367         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2368         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2369         //   {
2370         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2371         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2372         //     if ( eID == edgeID ||
2373         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2374         //          _sdVec[i]._noShrinkShapes.count( eID ))
2375         //       continue;
2376         //     for ( int is1st = 0; is1st < 2; ++is1st )
2377         //     {
2378         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2379         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2380         //       {
2381         //         return error("No way to make a conformal mesh with "
2382         //                      "the given set of faces with layers", _sdVec[i]._index);
2383         //       }
2384         //     }
2385         //   }
2386         // }
2387       }
2388
2389       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2390       // _shrinkShape2Shape is different in the adjacent SOLID
2391       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2392       {
2393         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2394         bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2395
2396         if ( iSolid < _sdVec.size() )
2397         {
2398           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2399           {
2400             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2401             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2402             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2403             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2404               noShrinkV = (( isStructured ) ||
2405                            ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2406             else
2407               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2408           }
2409           else
2410           {
2411             noShrinkV = noShrinkE;
2412           }
2413         }
2414         else
2415         {
2416           // the adjacent SOLID has NO layers at all
2417           if ( isStructured )
2418           {
2419             noShrinkV = true;
2420           }
2421           else
2422           {
2423             noShrinkV = noShrinkIfAdjMeshed =
2424               ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2425           }
2426         }
2427
2428         if ( noShrinkV && noShrinkIfAdjMeshed )
2429         {
2430           // noShrinkV if FACEs in the adjacent SOLID are meshed
2431           PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2432                                                        *_mesh, TopAbs_FACE, &solid );
2433           while ( fIt->more() )
2434           {
2435             const TopoDS_Shape* f = fIt->next();
2436             if ( !f->IsSame( fWOL ))
2437             {
2438               noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2439               break;
2440             }
2441           }
2442         }
2443         if ( noShrinkV )
2444           _sdVec[i]._noShrinkShapes.insert( vID );
2445       }
2446
2447     } // loop on _sdVec[i]._shrinkShape2Shape
2448   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2449
2450
2451     // add FACEs of other SOLIDs to _ignoreFaceIds
2452   for ( size_t i = 0; i < _sdVec.size(); ++i )
2453   {
2454     shapes.Clear();
2455     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2456
2457     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2458     {
2459       if ( !shapes.Contains( exp.Current() ))
2460         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2461     }
2462   }
2463
2464   return true;
2465 }
2466
2467 //================================================================================
2468 /*!
2469  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2470  */
2471 //================================================================================
2472
2473 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2474                                      const StdMeshers_ViscousLayers* hyp,
2475                                      const TopoDS_Shape&             hypShape,
2476                                      set<TGeomID>&                   ignoreFaceIds)
2477 {
2478   TopExp_Explorer exp;
2479
2480   vector<TGeomID> ids = hyp->GetBndShapes();
2481   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2482   {
2483     for ( size_t ii = 0; ii < ids.size(); ++ii )
2484     {
2485       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2486       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2487         ignoreFaceIds.insert( ids[ii] );
2488     }
2489   }
2490   else // FACEs with layers are given
2491   {
2492     exp.Init( solid, TopAbs_FACE );
2493     for ( ; exp.More(); exp.Next() )
2494     {
2495       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2496       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2497         ignoreFaceIds.insert( faceInd );
2498     }
2499   }
2500
2501   // ignore internal FACEs if inlets and outlets are specified
2502   if ( hyp->IsToIgnoreShapes() )
2503   {
2504     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2505     TopExp::MapShapesAndAncestors( hypShape,
2506                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2507
2508     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2509     {
2510       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2511       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2512         continue;
2513
2514       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2515       if ( nbSolids > 1 )
2516         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2517     }
2518   }
2519 }
2520
2521 //================================================================================
2522 /*!
2523  * \brief Create the inner surface of the viscous layer and prepare data for infation
2524  */
2525 //================================================================================
2526
2527 bool _ViscousBuilder::makeLayer(_SolidData& data)
2528 {
2529   // make a map to find new nodes on sub-shapes shared with other SOLID
2530   map< TGeomID, TNode2Edge* >::iterator s2ne;
2531   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2532   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2533   {
2534     TGeomID shapeInd = s2s->first;
2535     for ( size_t i = 0; i < _sdVec.size(); ++i )
2536     {
2537       if ( _sdVec[i]._index == data._index ) continue;
2538       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2539       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2540            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2541       {
2542         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2543         break;
2544       }
2545     }
2546   }
2547
2548   // Create temporary faces and _LayerEdge's
2549
2550   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2551
2552   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2553
2554   data._stepSize = Precision::Infinite();
2555   data._stepSizeNodes[0] = 0;
2556
2557   SMESH_MesherHelper helper( *_mesh );
2558   helper.SetSubShape( data._solid );
2559   helper.SetElementsOnShape( true );
2560
2561   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2562   TNode2Edge::iterator n2e2;
2563
2564   // make _LayerEdge's
2565   for ( TopExp_Explorer exp( data._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2566   {
2567     const TopoDS_Face& F = TopoDS::Face( exp.Current() );
2568     SMESH_subMesh*    sm = _mesh->GetSubMesh( F );
2569     const TGeomID     id = sm->GetId();
2570     if ( edgesByGeom[ id ]._shape.IsNull() )
2571       continue; // no layers
2572     SMESH_ProxyMesh::SubMesh* proxySub =
2573       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2574
2575     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2576     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << id, data._index );
2577
2578     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2579     while ( eIt->more() )
2580     {
2581       const SMDS_MeshElement* face = eIt->next();
2582       double          faceMaxCosin = -1;
2583       _LayerEdge*     maxCosinEdge = 0;
2584       int             nbDegenNodes = 0;
2585
2586       newNodes.resize( face->NbCornerNodes() );
2587       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2588       {
2589         const SMDS_MeshNode* n = face->GetNode( i );
2590         const int      shapeID = n->getshapeId();
2591         const bool onDegenShap = helper.IsDegenShape( shapeID );
2592         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2593         if ( onDegenShap )
2594         {
2595           if ( onDegenEdge )
2596           {
2597             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2598             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2599             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2600             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2601               n = vN;
2602               nbDegenNodes++;
2603             }
2604           }
2605           else
2606           {
2607             nbDegenNodes++;
2608           }
2609         }
2610         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2611         if ( !(*n2e).second )
2612         {
2613           // add a _LayerEdge
2614           _LayerEdge* edge = _Factory::NewLayerEdge();
2615           edge->_nodes.push_back( n );
2616           n2e->second = edge;
2617           edgesByGeom[ shapeID ]._edges.push_back( edge );
2618           const bool noShrink = data._noShrinkShapes.count( shapeID );
2619
2620           SMESH_TNodeXYZ xyz( n );
2621
2622           // set edge data or find already refined _LayerEdge and get data from it
2623           if (( !noShrink                                                     ) &&
2624               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2625               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2626               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2627           {
2628             _LayerEdge* foundEdge = (*n2e2).second;
2629             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2630             foundEdge->_pos.push_back( lastPos );
2631             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2632             const_cast< SMDS_MeshNode* >
2633               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2634           }
2635           else
2636           {
2637             if ( !noShrink )
2638             {
2639               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2640             }
2641             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2642               return false;
2643
2644             if ( edge->_nodes.size() < 2 )
2645               edge->Block( data );
2646               //data._noShrinkShapes.insert( shapeID );
2647           }
2648           dumpMove(edge->_nodes.back());
2649
2650           if ( edge->_cosin > faceMaxCosin )
2651           {
2652             faceMaxCosin = edge->_cosin;
2653             maxCosinEdge = edge;
2654           }
2655         }
2656         newNodes[ i ] = n2e->second->_nodes.back();
2657
2658         if ( onDegenEdge )
2659           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2660       }
2661       if ( newNodes.size() - nbDegenNodes < 2 )
2662         continue;
2663
2664       // create a temporary face
2665       const SMDS_MeshElement* newFace =
2666         new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2667       proxySub->AddElement( newFace );
2668
2669       // compute inflation step size by min size of element on a convex surface
2670       if ( faceMaxCosin > theMinSmoothCosin )
2671         limitStepSize( data, face, maxCosinEdge );
2672
2673     } // loop on 2D elements on a FACE
2674   } // loop on FACEs of a SOLID to create _LayerEdge's
2675
2676
2677   // Set _LayerEdge::_neibors
2678   TNode2Edge::iterator n2e;
2679   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2680   {
2681     _EdgesOnShape& eos = data._edgesOnShape[iS];
2682     for ( size_t i = 0; i < eos._edges.size(); ++i )
2683     {
2684       _LayerEdge* edge = eos._edges[i];
2685       TIDSortedNodeSet nearNodes;
2686       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2687       while ( fIt->more() )
2688       {
2689         const SMDS_MeshElement* f = fIt->next();
2690         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2691           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2692       }
2693       nearNodes.erase( edge->_nodes[0] );
2694       edge->_neibors.reserve( nearNodes.size() );
2695       TIDSortedNodeSet::iterator node = nearNodes.begin();
2696       for ( ; node != nearNodes.end(); ++node )
2697         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2698           edge->_neibors.push_back( n2e->second );
2699     }
2700   }
2701
2702   data._epsilon = 1e-7;
2703   if ( data._stepSize < 1. )
2704     data._epsilon *= data._stepSize;
2705
2706   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2707     return false;
2708
2709   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2710   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2711
2712   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2713   const SMDS_MeshNode* nn[2];
2714   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2715   {
2716     _EdgesOnShape& eos = data._edgesOnShape[iS];
2717     for ( size_t i = 0; i < eos._edges.size(); ++i )
2718     {
2719       _LayerEdge* edge = eos._edges[i];
2720       if ( edge->IsOnEdge() )
2721       {
2722         // get neighbor nodes
2723         bool hasData = ( edge->_2neibors->_edges[0] );
2724         if ( hasData ) // _LayerEdge is a copy of another one
2725         {
2726           nn[0] = edge->_2neibors->srcNode(0);
2727           nn[1] = edge->_2neibors->srcNode(1);
2728         }
2729         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2730         {
2731           return false;
2732         }
2733         // set neighbor _LayerEdge's
2734         for ( int j = 0; j < 2; ++j )
2735         {
2736           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2737             return error("_LayerEdge not found by src node", data._index);
2738           edge->_2neibors->_edges[j] = n2e->second;
2739         }
2740         if ( !hasData )
2741           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2742       }
2743
2744       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2745       {
2746         _Simplex& s = edge->_simplices[j];
2747         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2748         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2749       }
2750
2751       // For an _LayerEdge on a degenerated EDGE, copy some data from
2752       // a corresponding _LayerEdge on a VERTEX
2753       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2754       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2755       {
2756         // Generally we should not get here
2757         if ( eos.ShapeType() != TopAbs_EDGE )
2758           continue;
2759         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2760         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2761         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2762           continue;
2763         const _LayerEdge* vEdge = n2e->second;
2764         edge->_normal    = vEdge->_normal;
2765         edge->_lenFactor = vEdge->_lenFactor;
2766         edge->_cosin     = vEdge->_cosin;
2767       }
2768
2769     } // loop on data._edgesOnShape._edges
2770   } // loop on data._edgesOnShape
2771
2772   // fix _LayerEdge::_2neibors on EDGEs to smooth
2773   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2774   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2775   //   if ( !e2c->second.IsNull() )
2776   //   {
2777   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2778   //       data.Sort2NeiborsOnEdge( eos->_edges );
2779   //   }
2780
2781   dumpFunctionEnd();
2782   return true;
2783 }
2784
2785 //================================================================================
2786 /*!
2787  * \brief Compute inflation step size by min size of element on a convex surface
2788  */
2789 //================================================================================
2790
2791 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2792                                      const SMDS_MeshElement* face,
2793                                      const _LayerEdge*       maxCosinEdge )
2794 {
2795   int iN = 0;
2796   double minSize = 10 * data._stepSize;
2797   const int nbNodes = face->NbCornerNodes();
2798   for ( int i = 0; i < nbNodes; ++i )
2799   {
2800     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2801     const SMDS_MeshNode*  curN = face->GetNode( i );
2802     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2803          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2804     {
2805       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2806       if ( dist < minSize )
2807         minSize = dist, iN = i;
2808     }
2809   }
2810   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2811   if ( newStep < data._stepSize )
2812   {
2813     data._stepSize = newStep;
2814     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2815     data._stepSizeNodes[0] = face->GetNode( iN );
2816     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2817   }
2818 }
2819
2820 //================================================================================
2821 /*!
2822  * \brief Compute inflation step size by min size of element on a convex surface
2823  */
2824 //================================================================================
2825
2826 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2827 {
2828   if ( minSize < data._stepSize )
2829   {
2830     data._stepSize = minSize;
2831     if ( data._stepSizeNodes[0] )
2832     {
2833       double dist =
2834         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2835       data._stepSizeCoeff = data._stepSize / dist;
2836     }
2837   }
2838 }
2839
2840 //================================================================================
2841 /*!
2842  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2843  */
2844 //================================================================================
2845
2846 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2847 {
2848   SMESH_MesherHelper helper( *_mesh );
2849
2850   BRepLProp_SLProps surfProp( 2, 1e-6 );
2851   data._convexFaces.clear();
2852
2853   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2854   {
2855     _EdgesOnShape& eof = data._edgesOnShape[iS];
2856     if ( eof.ShapeType() != TopAbs_FACE ||
2857          data._ignoreFaceIds.count( eof._shapeID ))
2858       continue;
2859
2860     TopoDS_Face        F = TopoDS::Face( eof._shape );
2861     const TGeomID faceID = eof._shapeID;
2862
2863     BRepAdaptor_Surface surface( F, false );
2864     surfProp.SetSurface( surface );
2865
2866     _ConvexFace cnvFace;
2867     cnvFace._face = F;
2868     cnvFace._normalsFixed = false;
2869     cnvFace._isTooCurved = false;
2870
2871     double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2872     if ( maxCurvature > 0 )
2873     {
2874       limitStepSize( data, 0.9 / maxCurvature );
2875       findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2876     }
2877     if ( !cnvFace._isTooCurved ) continue;
2878
2879     _ConvexFace & convFace =
2880       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2881
2882     // skip a closed surface (data._convexFaces is useful anyway)
2883     bool isClosedF = false;
2884     helper.SetSubShape( F );
2885     if ( helper.HasRealSeam() )
2886     {
2887       // in the closed surface there must be a closed EDGE
2888       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2889         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2890     }
2891     if ( isClosedF )
2892     {
2893       // limit _LayerEdge::_maxLen on the FACE
2894       const double oriFactor    = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2895       const double minCurvature =
2896         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2897       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2898       if ( id2eos != cnvFace._subIdToEOS.end() )
2899       {
2900         _EdgesOnShape& eos = * id2eos->second;
2901         for ( size_t i = 0; i < eos._edges.size(); ++i )
2902         {
2903           _LayerEdge* ledge = eos._edges[ i ];
2904           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2905           surfProp.SetParameters( uv.X(), uv.Y() );
2906           if ( surfProp.IsCurvatureDefined() )
2907           {
2908             double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2909                                     surfProp.MinCurvature() * oriFactor );
2910             if ( curvature > minCurvature )
2911               ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
2912           }
2913         }
2914       }
2915       continue;
2916     }
2917
2918     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2919     // prism distortion.
2920     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2921     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2922     {
2923       // there are _LayerEdge's on the FACE it-self;
2924       // select _LayerEdge's near EDGEs
2925       _EdgesOnShape& eos = * id2eos->second;
2926       for ( size_t i = 0; i < eos._edges.size(); ++i )
2927       {
2928         _LayerEdge* ledge = eos._edges[ i ];
2929         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2930           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2931           {
2932             // do not select _LayerEdge's neighboring sharp EDGEs
2933             bool sharpNbr = false;
2934             for ( size_t iN = 0; iN < ledge->_neibors.size()  && !sharpNbr; ++iN )
2935               sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
2936             if ( !sharpNbr )
2937               convFace._simplexTestEdges.push_back( ledge );
2938             break;
2939           }
2940       }
2941     }
2942     else
2943     {
2944       // where there are no _LayerEdge's on a _ConvexFace,
2945       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2946       // so that collision of viscous internal faces is not detected by check of
2947       // intersection of _LayerEdge's with the viscous internal faces.
2948
2949       set< const SMDS_MeshNode* > usedNodes;
2950
2951       // look for _LayerEdge's with null _sWOL
2952       id2eos = convFace._subIdToEOS.begin();
2953       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2954       {
2955         _EdgesOnShape& eos = * id2eos->second;
2956         if ( !eos._sWOL.IsNull() )
2957           continue;
2958         for ( size_t i = 0; i < eos._edges.size(); ++i )
2959         {
2960           _LayerEdge* ledge = eos._edges[ i ];
2961           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2962           if ( !usedNodes.insert( srcNode ).second ) continue;
2963
2964           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2965           {
2966             usedNodes.insert( ledge->_simplices[i]._nPrev );
2967             usedNodes.insert( ledge->_simplices[i]._nNext );
2968           }
2969           convFace._simplexTestEdges.push_back( ledge );
2970         }
2971       }
2972     }
2973   } // loop on FACEs of data._solid
2974 }
2975
2976 //================================================================================
2977 /*!
2978  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2979  */
2980 //================================================================================
2981
2982 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2983 {
2984   // define allowed thickness
2985   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2986
2987
2988   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2989   // boundary inclined to the shape at a sharp angle
2990
2991   TopTools_MapOfShape edgesOfSmooFaces;
2992   SMESH_MesherHelper helper( *_mesh );
2993   bool ok = true;
2994
2995   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2996   data._nbShapesToSmooth = 0;
2997
2998   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2999   {
3000     _EdgesOnShape& eos = edgesByGeom[iS];
3001     eos._toSmooth = false;
3002     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
3003       continue;
3004
3005     double tgtThick = eos._hyp.GetTotalThickness();
3006     SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
3007     while ( subIt->more() && !eos._toSmooth )
3008     {
3009       TGeomID iSub = subIt->next()->GetId();
3010       const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
3011       if ( eSub.empty() ) continue;
3012
3013       double faceSize;
3014       for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3015         if ( eSub[i]->_cosin > theMinSmoothCosin )
3016         {
3017           SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3018           while ( fIt->more() && !eos._toSmooth )
3019           {
3020             const SMDS_MeshElement* face = fIt->next();
3021             if ( face->getshapeId() == eos._shapeID &&
3022                  getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3023             {
3024               eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3025                                              tgtThick * eSub[i]->_lenFactor,
3026                                              faceSize);
3027             }
3028           }
3029         }
3030     }
3031     if ( eos._toSmooth )
3032     {
3033       for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3034         edgesOfSmooFaces.Add( eExp.Current() );
3035
3036       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3037     }
3038     data._nbShapesToSmooth += eos._toSmooth;
3039
3040   }  // check FACEs
3041
3042   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3043   {
3044     _EdgesOnShape& eos = edgesByGeom[iS];
3045     eos._edgeSmoother = NULL;
3046     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3047     if ( !eos._hyp.ToSmooth() ) continue;
3048
3049     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3050     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3051       continue;
3052
3053     double tgtThick = eos._hyp.GetTotalThickness();
3054     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3055     {
3056       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3057       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3058       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3059       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3060       double angle    = eDir.Angle( eV[0]->_normal );
3061       double cosin    = Cos( angle );
3062       double cosinAbs = Abs( cosin );
3063       if ( cosinAbs > theMinSmoothCosin )
3064       {
3065         // always smooth analytic EDGEs
3066         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3067         eos._toSmooth = ! curve.IsNull();
3068
3069         // compare tgtThick with the length of an end segment
3070         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3071         while ( eIt->more() && !eos._toSmooth )
3072         {
3073           const SMDS_MeshElement* endSeg = eIt->next();
3074           if ( endSeg->getshapeId() == (int) iS )
3075           {
3076             double segLen =
3077               SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3078             eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3079           }
3080         }
3081         if ( eos._toSmooth )
3082         {
3083           eos._edgeSmoother = new _Smoother1D( curve, eos );
3084
3085           // for ( size_t i = 0; i < eos._edges.size(); ++i )
3086           //   eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3087         }
3088       }
3089     }
3090     data._nbShapesToSmooth += eos._toSmooth;
3091
3092   } // check EDGEs
3093
3094   // Reset _cosin if no smooth is allowed by the user
3095   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3096   {
3097     _EdgesOnShape& eos = edgesByGeom[iS];
3098     if ( eos._edges.empty() ) continue;
3099
3100     if ( !eos._hyp.ToSmooth() )
3101       for ( size_t i = 0; i < eos._edges.size(); ++i )
3102         //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3103         eos._edges[i]->_lenFactor = 1;
3104   }
3105
3106
3107   // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3108
3109   TopTools_MapOfShape c1VV;
3110
3111   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3112   {
3113     _EdgesOnShape& eos = edgesByGeom[iS];
3114     if ( eos._edges.empty() ||
3115          eos.ShapeType() != TopAbs_FACE ||
3116          !eos._toSmooth )
3117       continue;
3118
3119     // check EDGEs of a FACE
3120     TopTools_MapOfShape checkedEE, allVV;
3121     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3122     while ( !smQueue.empty() )
3123     {
3124       SMESH_subMesh* sm = smQueue.front();
3125       smQueue.pop_front();
3126       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3127       while ( smIt->more() )
3128       {
3129         sm = smIt->next();
3130         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3131           allVV.Add( sm->GetSubShape() );
3132         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3133              !checkedEE.Add( sm->GetSubShape() ))
3134           continue;
3135
3136         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3137         vector<_LayerEdge*>& eE = eoe->_edges;
3138         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3139           continue;
3140
3141         bool isC1 = true; // check continuity along an EDGE
3142         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3143           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3144         if ( !isC1 )
3145           continue;
3146
3147         // check that mesh faces are C1 as well
3148         {
3149           gp_XYZ norm1, norm2;
3150           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3151           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3152           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3153             continue;
3154           while ( fIt->more() && isC1 )
3155             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3156                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3157           if ( !isC1 )
3158             continue;
3159         }
3160
3161         // add the EDGE and an adjacent FACE to _eosC1
3162         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3163         while ( const TopoDS_Shape* face = fIt->next() )
3164         {
3165           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3166           if ( !eof ) continue; // other solid
3167           if ( eos._shapeID == eof->_shapeID ) continue;
3168           if ( !eos.HasC1( eof ))
3169           {
3170             // check the FACEs
3171             eos._eosC1.push_back( eof );
3172             eof->_toSmooth = false;
3173             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3174             smQueue.push_back( eof->_subMesh );
3175           }
3176           if ( !eos.HasC1( eoe ))
3177           {
3178             eos._eosC1.push_back( eoe );
3179             eoe->_toSmooth = false;
3180             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3181           }
3182         }
3183       }
3184     }
3185     if ( eos._eosC1.empty() )
3186       continue;
3187
3188     // check VERTEXes of C1 FACEs
3189     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3190     for ( ; vIt.More(); vIt.Next() )
3191     {
3192       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3193       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3194         continue;
3195
3196       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3197       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3198       while ( const TopoDS_Shape* face = fIt->next() )
3199       {
3200         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3201         if ( !eof ) continue; // other solid
3202         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3203         if ( !isC1 )
3204           break;
3205       }
3206       if ( isC1 )
3207       {
3208         eos._eosC1.push_back( eov );
3209         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3210         c1VV.Add( eov->_shape );
3211       }
3212     }
3213
3214   } // fill _eosC1 of FACEs
3215
3216
3217   // Find C1 EDGEs
3218
3219   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3220
3221   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3222   {
3223     _EdgesOnShape& eov = edgesByGeom[iS];
3224     if ( eov._edges.empty() ||
3225          eov.ShapeType() != TopAbs_VERTEX ||
3226          c1VV.Contains( eov._shape ))
3227       continue;
3228     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3229
3230     // get directions of surrounding EDGEs
3231     dirOfEdges.clear();
3232     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3233     while ( const TopoDS_Shape* e = fIt->next() )
3234     {
3235       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3236       if ( !eoe ) continue; // other solid
3237       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3238       if ( !Precision::IsInfinite( eDir.X() ))
3239         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3240     }
3241
3242     // find EDGEs with C1 directions
3243     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3244       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3245         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3246         {
3247           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3248           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3249           if ( isC1 )
3250           {
3251             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3252             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3253             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3254             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3255             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3256             dirOfEdges[i].first = 0;
3257             dirOfEdges[j].first = 0;
3258           }
3259         }
3260   } // fill _eosC1 of VERTEXes
3261
3262
3263
3264   return ok;
3265 }
3266
3267 //================================================================================
3268 /*!
3269  * \brief Set up _SolidData::_edgesOnShape
3270  */
3271 //================================================================================
3272
3273 void _ViscousBuilder::makeEdgesOnShape()
3274 {
3275   const int nbShapes = getMeshDS()->MaxShapeIndex();
3276
3277   for ( size_t i = 0; i < _sdVec.size(); ++i )
3278   {
3279     _SolidData& data = _sdVec[ i ];
3280     vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3281     edgesByGeom.resize( nbShapes+1 );
3282
3283     // set data of _EdgesOnShape's
3284     if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
3285     {
3286       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3287       while ( smIt->more() )
3288       {
3289         sm = smIt->next();
3290         if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
3291              data._ignoreFaceIds.count( sm->GetId() ))
3292           continue;
3293
3294         setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
3295       }
3296     }
3297   }
3298 }
3299
3300 //================================================================================
3301 /*!
3302  * \brief initialize data of _EdgesOnShape
3303  */
3304 //================================================================================
3305
3306 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3307                                     SMESH_subMesh* sm,
3308                                     _SolidData&    data )
3309 {
3310   if ( !eos._shape.IsNull() ||
3311        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3312     return;
3313
3314   SMESH_MesherHelper helper( *_mesh );
3315
3316   eos._subMesh = sm;
3317   eos._shapeID = sm->GetId();
3318   eos._shape   = sm->GetSubShape();
3319   if ( eos.ShapeType() == TopAbs_FACE )
3320     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3321   eos._toSmooth = false;
3322   eos._data = &data;
3323
3324   // set _SWOL
3325   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3326     data._shrinkShape2Shape.find( eos._shapeID );
3327   if ( s2s != data._shrinkShape2Shape.end() )
3328     eos._sWOL = s2s->second;
3329
3330   eos._isRegularSWOL = true;
3331   if ( eos.SWOLType() == TopAbs_FACE )
3332   {
3333     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3334     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3335     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3336   }
3337
3338   // set _hyp
3339   if ( data._hyps.size() == 1 )
3340   {
3341     eos._hyp = data._hyps.back();
3342   }
3343   else
3344   {
3345     // compute average StdMeshers_ViscousLayers parameters
3346     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3347     if ( eos.ShapeType() == TopAbs_FACE )
3348     {
3349       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3350         eos._hyp = f2hyp->second;
3351     }
3352     else
3353     {
3354       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3355       while ( const TopoDS_Shape* face = fIt->next() )
3356       {
3357         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3358         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3359           eos._hyp.Add( f2hyp->second );
3360       }
3361     }
3362   }
3363
3364   // set _faceNormals
3365   if ( ! eos._hyp.UseSurfaceNormal() )
3366   {
3367     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3368     {
3369       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3370       if ( !smDS ) return;
3371       eos._faceNormals.reserve( smDS->NbElements() );
3372
3373       double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3374       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3375       for ( ; eIt->more(); )
3376       {
3377         const SMDS_MeshElement* face = eIt->next();
3378         gp_XYZ&                 norm = eos._faceNormals[face];
3379         if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3380           norm.SetCoord( 0,0,0 );
3381         norm *= oriFactor;
3382       }
3383     }
3384     else // find EOS of adjacent FACEs
3385     {
3386       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3387       while ( const TopoDS_Shape* face = fIt->next() )
3388       {
3389         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3390         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3391         if ( eos._faceEOS.back()->_shape.IsNull() )
3392           // avoid using uninitialised _shapeID in GetNormal()
3393           eos._faceEOS.back()->_shapeID = faceID;
3394       }
3395     }
3396   }
3397 }
3398
3399 //================================================================================
3400 /*!
3401  * \brief Returns normal of a face
3402  */
3403 //================================================================================
3404
3405 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3406 {
3407   bool ok = false;
3408   _EdgesOnShape* eos = 0;
3409
3410   if ( face->getshapeId() == _shapeID )
3411   {
3412     eos = this;
3413   }
3414   else
3415   {
3416     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3417       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3418         eos = _faceEOS[ iF ];
3419   }
3420
3421   if (( eos ) &&
3422       ( ok = ( eos->_faceNormals.count( face ) )))
3423   {
3424     norm = eos->_faceNormals[ face ];
3425   }
3426   else if ( !eos )
3427   {
3428     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3429               << " on _shape #" << _shapeID );
3430   }
3431   return ok;
3432 }
3433
3434 //================================================================================
3435 /*!
3436  * \brief EdgesOnShape destructor
3437  */
3438 //================================================================================
3439
3440 _EdgesOnShape::~_EdgesOnShape()
3441 {
3442   delete _edgeSmoother;
3443 }
3444
3445 //================================================================================
3446 /*!
3447  * \brief Set data of _LayerEdge needed for smoothing
3448  */
3449 //================================================================================
3450
3451 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3452                                   _EdgesOnShape&      eos,
3453                                   SMESH_MesherHelper& helper,
3454                                   _SolidData&         data)
3455 {
3456   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3457
3458   edge._len          = 0;
3459   edge._maxLen       = Precision::Infinite();
3460   edge._minAngle     = 0;
3461   edge._2neibors     = 0;
3462   edge._curvature    = 0;
3463   edge._flags        = 0;
3464   edge._smooFunction = 0;
3465
3466   // --------------------------
3467   // Compute _normal and _cosin
3468   // --------------------------
3469
3470   edge._cosin     = 0;
3471   edge._lenFactor = 1.;
3472   edge._normal.SetCoord(0,0,0);
3473   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3474
3475   int totalNbFaces = 0;
3476   TopoDS_Face F;
3477   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3478   gp_Vec geomNorm;
3479   bool normOK = true;
3480
3481   const bool onShrinkShape = !eos._sWOL.IsNull();
3482   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3483                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3484
3485   // get geom FACEs the node lies on
3486   //if ( useGeometry )
3487   {
3488     set<TGeomID> faceIds;
3489     if  ( eos.ShapeType() == TopAbs_FACE )
3490     {
3491       faceIds.insert( eos._shapeID );
3492     }
3493     else
3494     {
3495       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3496       while ( fIt->more() )
3497         faceIds.insert( fIt->next()->getshapeId() );
3498     }
3499     set<TGeomID>::iterator id = faceIds.begin();
3500     for ( ; id != faceIds.end(); ++id )
3501     {
3502       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3503       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3504         continue;
3505       F = TopoDS::Face( s );
3506       face2Norm[ totalNbFaces ].first = F;
3507       totalNbFaces++;
3508     }
3509   }
3510
3511   // find _normal
3512   bool fromVonF = false;
3513   if ( useGeometry )
3514   {
3515     fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3516                  eos.SWOLType()  == TopAbs_FACE  &&
3517                  totalNbFaces > 1 );
3518
3519     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3520     {
3521       if ( eos.SWOLType() == TopAbs_EDGE )
3522       {
3523         // inflate from VERTEX along EDGE
3524         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3525       }
3526       else if ( eos.ShapeType() == TopAbs_VERTEX )
3527       {
3528         // inflate from VERTEX along FACE
3529         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3530                                    node, helper, normOK, &edge._cosin);
3531       }
3532       else
3533       {
3534         // inflate from EDGE along FACE
3535         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3536                                    node, helper, normOK);
3537       }
3538     }
3539     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3540     {
3541       if ( fromVonF )
3542         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3543
3544       int nbOkNorms = 0;
3545       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3546       {
3547         F = face2Norm[ iF ].first;
3548         geomNorm = getFaceNormal( node, F, helper, normOK );
3549         if ( !normOK ) continue;
3550         nbOkNorms++;
3551
3552         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3553           geomNorm.Reverse();
3554         face2Norm[ iF ].second = geomNorm.XYZ();
3555         edge._normal += geomNorm.XYZ();
3556       }
3557       if ( nbOkNorms == 0 )
3558         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3559
3560       if ( totalNbFaces >= 3 )
3561       {
3562         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3563       }
3564
3565       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3566       {
3567         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3568         edge._normal.SetCoord( 0,0,0 );
3569         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3570         {
3571           const TopoDS_Face& F = face2Norm[iF].first;
3572           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3573           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3574             geomNorm.Reverse();
3575           if ( normOK )
3576             face2Norm[ iF ].second = geomNorm.XYZ();
3577           edge._normal += face2Norm[ iF ].second;
3578         }
3579       }
3580     }
3581   }
3582   else // !useGeometry - get _normal using surrounding mesh faces
3583   {
3584     edge._normal = getWeigthedNormal( &edge );
3585
3586     // set<TGeomID> faceIds;
3587     //
3588     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3589     // while ( fIt->more() )
3590     // {
3591     //   const SMDS_MeshElement* face = fIt->next();
3592     //   if ( eos.GetNormal( face, geomNorm ))
3593     //   {
3594     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3595     //       continue; // use only one mesh face on FACE
3596     //     edge._normal += geomNorm.XYZ();
3597     //     totalNbFaces++;
3598     //   }
3599     // }
3600   }
3601
3602   // compute _cosin
3603   //if ( eos._hyp.UseSurfaceNormal() )
3604   {
3605     switch ( eos.ShapeType() )
3606     {
3607     case TopAbs_FACE: {
3608       edge._cosin = 0;
3609       break;
3610     }
3611     case TopAbs_EDGE: {
3612       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3613       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3614       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3615       edge._cosin      = Cos( angle );
3616       break;
3617     }
3618     case TopAbs_VERTEX: {
3619       if ( fromVonF )
3620       {
3621         getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3622                     node, helper, normOK, &edge._cosin );
3623       }
3624       else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3625       {
3626         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3627         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3628         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3629         edge._cosin      = Cos( angle );
3630         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3631           for ( int iF = 1; iF < totalNbFaces; ++iF )
3632           {
3633             F = face2Norm[ iF ].first;
3634             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3635             if ( normOK ) {
3636               double angle = inFaceDir.Angle( edge._normal );
3637               double cosin = Cos( angle );
3638               if ( Abs( cosin ) > Abs( edge._cosin ))
3639                 edge._cosin = cosin;
3640             }
3641           }
3642       }
3643       break;
3644     }
3645     default:
3646       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3647     }
3648   }
3649
3650   double normSize = edge._normal.SquareModulus();
3651   if ( normSize < numeric_limits<double>::min() )
3652     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3653
3654   edge._normal /= sqrt( normSize );
3655
3656   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3657   {
3658     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3659     edge._nodes.resize( 1 );
3660     edge._normal.SetCoord( 0,0,0 );
3661     edge.SetMaxLen( 0 );
3662   }
3663
3664   // Set the rest data
3665   // --------------------
3666
3667   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3668
3669   if ( onShrinkShape )
3670   {
3671     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3672     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3673       sm->RemoveNode( tgtNode );
3674
3675     // set initial position which is parameters on _sWOL in this case
3676     if ( eos.SWOLType() == TopAbs_EDGE )
3677     {
3678       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3679       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3680       if ( edge._nodes.size() > 1 )
3681         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3682     }
3683     else // eos.SWOLType() == TopAbs_FACE
3684     {
3685       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3686       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3687       if ( edge._nodes.size() > 1 )
3688         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3689     }
3690
3691     if ( edge._nodes.size() > 1 )
3692     {
3693       // check if an angle between a FACE with layers and SWOL is sharp,
3694       // else the edge should not inflate
3695       F.Nullify();
3696       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3697         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3698           F = face2Norm[iF].first;
3699       if ( !F.IsNull())
3700       {
3701         geomNorm = getFaceNormal( node, F, helper, normOK );
3702         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3703           geomNorm.Reverse(); // inside the SOLID
3704         if ( geomNorm * edge._normal < -0.001 )
3705         {
3706           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3707           edge._nodes.resize( 1 );
3708         }
3709         else if ( edge._lenFactor > 3 )
3710         {
3711           edge._lenFactor = 2;
3712           edge.Set( _LayerEdge::RISKY_SWOL );
3713         }
3714       }
3715     }
3716   }
3717   else
3718   {
3719     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3720
3721     if ( eos.ShapeType() == TopAbs_FACE )
3722     {
3723       double angle;
3724       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3725       {
3726         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3727         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3728       }
3729     }
3730   }
3731
3732   // Set neighbor nodes for a _LayerEdge based on EDGE
3733
3734   if ( eos.ShapeType() == TopAbs_EDGE /*||
3735        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3736   {
3737     edge._2neibors = _Factory::NewNearEdges();
3738     // target nodes instead of source ones will be set later
3739   }
3740
3741   return true;
3742 }
3743
3744 //================================================================================
3745 /*!
3746  * \brief Return normal to a FACE at a node
3747  *  \param [in] n - node
3748  *  \param [in] face - FACE
3749  *  \param [in] helper - helper
3750  *  \param [out] isOK - true or false
3751  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3752  *  \return gp_XYZ - normal
3753  */
3754 //================================================================================
3755
3756 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3757                                       const TopoDS_Face&   face,
3758                                       SMESH_MesherHelper&  helper,
3759                                       bool&                isOK,
3760                                       bool                 shiftInside)
3761 {
3762   gp_XY uv;
3763   if ( shiftInside )
3764   {
3765     // get a shifted position
3766     gp_Pnt p = SMESH_TNodeXYZ( node );
3767     gp_XYZ shift( 0,0,0 );
3768     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3769     switch ( S.ShapeType() ) {
3770     case TopAbs_VERTEX:
3771     {
3772       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3773       break;
3774     }
3775     case TopAbs_EDGE:
3776     {
3777       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3778       break;
3779     }
3780     default:
3781       isOK = false;
3782     }
3783     if ( isOK )
3784       shift.Normalize();
3785     p.Translate( shift * 1e-5 );
3786
3787     TopLoc_Location loc;
3788     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3789
3790     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3791     
3792     projector.Perform( p );
3793     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3794     {
3795       isOK = false;
3796       return p.XYZ();
3797     }
3798     Standard_Real U,V;
3799     projector.LowerDistanceParameters(U,V);
3800     uv.SetCoord( U,V );
3801   }
3802   else
3803   {
3804     uv = helper.GetNodeUV( face, node, 0, &isOK );
3805   }
3806
3807   gp_Dir normal;
3808   isOK = false;
3809
3810   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3811
3812   if ( !shiftInside &&
3813        helper.IsDegenShape( node->getshapeId() ) &&
3814        getFaceNormalAtSingularity( uv, face, helper, normal ))
3815   {
3816     isOK = true;
3817     return normal.XYZ();
3818   }
3819
3820   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3821   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3822
3823   if ( pointKind == IMPOSSIBLE &&
3824        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3825   {
3826     // probably NormEstim() failed due to a too high tolerance
3827     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3828     isOK = ( pointKind < IMPOSSIBLE );
3829   }
3830   if ( pointKind < IMPOSSIBLE )
3831   {
3832     if ( pointKind != REGULAR &&
3833          !shiftInside &&
3834          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3835     {
3836       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3837       if ( normShift * normal.XYZ() < 0. )
3838         normal = normShift;
3839     }
3840     isOK = true;
3841   }
3842
3843   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3844   {
3845     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3846
3847     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3848     while ( fIt->more() )
3849     {
3850       const SMDS_MeshElement* f = fIt->next();
3851       if ( f->getshapeId() == faceID )
3852       {
3853         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3854         if ( isOK )
3855         {
3856           TopoDS_Face ff = face;
3857           ff.Orientation( TopAbs_FORWARD );
3858           if ( helper.IsReversedSubMesh( ff ))
3859             normal.Reverse();
3860           break;
3861         }
3862       }
3863     }
3864   }
3865   return normal.XYZ();
3866 }
3867
3868 //================================================================================
3869 /*!
3870  * \brief Try to get normal at a singularity of a surface basing on it's nature
3871  */
3872 //================================================================================
3873
3874 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3875                                                   const TopoDS_Face&  face,
3876                                                   SMESH_MesherHelper& helper,
3877                                                   gp_Dir&             normal )
3878 {
3879   BRepAdaptor_Surface surface( face );
3880   gp_Dir axis;
3881   if ( !getRovolutionAxis( surface, axis ))
3882     return false;
3883
3884   double f,l, d, du, dv;
3885   f = surface.FirstUParameter();
3886   l = surface.LastUParameter();
3887   d = ( uv.X() - f ) / ( l - f );
3888   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3889   f = surface.FirstVParameter();
3890   l = surface.LastVParameter();
3891   d = ( uv.Y() - f ) / ( l - f );
3892   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3893
3894   gp_Dir refDir;
3895   gp_Pnt2d testUV = uv;
3896   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3897   double tol = 1e-5;
3898   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3899   for ( int iLoop = 0; true ; ++iLoop )
3900   {
3901     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3902     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3903       break;
3904     if ( iLoop > 20 )
3905       return false;
3906     tol /= 10.;
3907   }
3908
3909   if ( axis * refDir < 0. )
3910     axis.Reverse();
3911
3912   normal = axis;
3913
3914   return true;
3915 }
3916
3917 //================================================================================
3918 /*!
3919  * \brief Return a normal at a node weighted with angles taken by faces
3920  */
3921 //================================================================================
3922
3923 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3924 {
3925   const SMDS_MeshNode* n = edge->_nodes[0];
3926
3927   gp_XYZ resNorm(0,0,0);
3928   SMESH_TNodeXYZ p0( n ), pP, pN;
3929   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3930   {
3931     pP.Set( edge->_simplices[i]._nPrev );
3932     pN.Set( edge->_simplices[i]._nNext );
3933     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3934     double l0P = v0P.SquareMagnitude();
3935     double l0N = v0N.SquareMagnitude();
3936     double lPN = vPN.SquareMagnitude();
3937     if ( l0P < std::numeric_limits<double>::min() ||
3938          l0N < std::numeric_limits<double>::min() ||
3939          lPN < std::numeric_limits<double>::min() )
3940       continue;
3941     double lNorm = norm.SquareMagnitude();
3942     double  sin2 = lNorm / l0P / l0N;
3943     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3944
3945     double weight = sin2 * angle / lPN;
3946     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3947   }
3948
3949   return resNorm;
3950 }
3951
3952 //================================================================================
3953 /*!
3954  * \brief Return a normal at a node by getting a common point of offset planes
3955  *        defined by the FACE normals
3956  */
3957 //================================================================================
3958
3959 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3960                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3961                                            int                              nbFaces,
3962                                            bool                             lastNoOffset)
3963 {
3964   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3965
3966   gp_XYZ resNorm(0,0,0);
3967   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3968   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3969   {
3970     for ( int i = 0; i < nbFaces; ++i )
3971       resNorm += f2Normal[i].second;
3972     return resNorm;
3973   }
3974
3975   // prepare _OffsetPlane's
3976   vector< _OffsetPlane > pln( nbFaces );
3977   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3978   {
3979     pln[i]._faceIndex = i;
3980     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3981   }
3982   if ( lastNoOffset )
3983   {
3984     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3985     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3986   }
3987
3988   // intersect neighboring OffsetPlane's
3989   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3990   while ( const TopoDS_Shape* edge = edgeIt->next() )
3991   {
3992     int f1 = -1, f2 = -1;
3993     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3994       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3995         (( f1 < 0 ) ? f1 : f2 ) = i;
3996
3997     if ( f2 >= 0 )
3998       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3999   }
4000
4001   // get a common point
4002   gp_XYZ commonPnt( 0, 0, 0 );
4003   int nbPoints = 0;
4004   bool isPointFound;
4005   for ( int i = 0; i < nbFaces; ++i )
4006   {
4007     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
4008     nbPoints  += isPointFound;
4009   }
4010   gp_XYZ wgtNorm = getWeigthedNormal( edge );
4011   if ( nbPoints == 0 )
4012     return wgtNorm;
4013
4014   commonPnt /= nbPoints;
4015   resNorm = commonPnt - p0;
4016   if ( lastNoOffset )
4017     return resNorm;
4018
4019   // choose the best among resNorm and wgtNorm
4020   resNorm.Normalize();
4021   wgtNorm.Normalize();
4022   double resMinDot = std::numeric_limits<double>::max();
4023   double wgtMinDot = std::numeric_limits<double>::max();
4024   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4025   {
4026     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
4027     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
4028   }
4029
4030   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
4031   {
4032     edge->Set( _LayerEdge::MULTI_NORMAL );
4033   }
4034
4035   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
4036 }
4037
4038 //================================================================================
4039 /*!
4040  * \brief Compute line of intersection of 2 planes
4041  */
4042 //================================================================================
4043
4044 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
4045                                             const TopoDS_Edge&   E,
4046                                             const TopoDS_Vertex& V )
4047 {
4048   int iNext = bool( _faceIndexNext[0] >= 0 );
4049   _faceIndexNext[ iNext ] = pln._faceIndex;
4050
4051   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
4052   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
4053
4054   gp_XYZ lineDir = n1 ^ n2;
4055
4056   double x = Abs( lineDir.X() );
4057   double y = Abs( lineDir.Y() );
4058   double z = Abs( lineDir.Z() );
4059
4060   int cooMax; // max coordinate
4061   if (x > y) {
4062     if (x > z) cooMax = 1;
4063     else       cooMax = 3;
4064   }
4065   else {
4066     if (y > z) cooMax = 2;
4067     else       cooMax = 3;
4068   }
4069
4070   gp_Pnt linePos;
4071   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4072   {
4073     // parallel planes - intersection is an offset of the common EDGE
4074     gp_Pnt p = BRep_Tool::Pnt( V );
4075     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4076     lineDir  = getEdgeDir( E, V );
4077   }
4078   else
4079   {
4080     // the constants in the 2 plane equations
4081     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
4082     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4083
4084     switch ( cooMax ) {
4085     case 1:
4086       linePos.SetX(  0 );
4087       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4088       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4089       break;
4090     case 2:
4091       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4092       linePos.SetY(  0 );
4093       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4094       break;
4095     case 3:
4096       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4097       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4098       linePos.SetZ(  0 );
4099     }
4100   }
4101   gp_Lin& line = _lines[ iNext ];
4102   line.SetDirection( lineDir );
4103   line.SetLocation ( linePos );
4104
4105   _isLineOK[ iNext ] = true;
4106
4107
4108   iNext = bool( pln._faceIndexNext[0] >= 0 );
4109   pln._lines        [ iNext ] = line;
4110   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4111   pln._isLineOK     [ iNext ] = true;
4112 }
4113
4114 //================================================================================
4115 /*!
4116  * \brief Computes intersection point of two _lines
4117  */
4118 //================================================================================
4119
4120 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4121                                     const TopoDS_Vertex & V) const
4122 {
4123   gp_XYZ p( 0,0,0 );
4124   isFound = false;
4125
4126   if ( NbLines() == 2 )
4127   {
4128     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4129     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4130     if ( Abs( dot01 ) > 0.05 )
4131     {
4132       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4133       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4134       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4135       isFound = true;
4136     }
4137     else
4138     {
4139       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4140       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4141       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4142       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4143       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4144       isFound = true;
4145     }
4146   }
4147
4148   return p;
4149 }
4150
4151 //================================================================================
4152 /*!
4153  * \brief Find 2 neighbor nodes of a node on EDGE
4154  */
4155 //================================================================================
4156
4157 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4158                                         const SMDS_MeshNode*& n1,
4159                                         const SMDS_MeshNode*& n2,
4160                                         _EdgesOnShape&        eos,
4161                                         _SolidData&           data)
4162 {
4163   const SMDS_MeshNode* node = edge->_nodes[0];
4164   const int        shapeInd = eos._shapeID;
4165   SMESHDS_SubMesh*   edgeSM = 0;
4166   if ( eos.ShapeType() == TopAbs_EDGE )
4167   {
4168     edgeSM = eos._subMesh->GetSubMeshDS();
4169     if ( !edgeSM || edgeSM->NbElements() == 0 )
4170       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4171   }
4172   int iN = 0;
4173   n2 = 0;
4174   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4175   while ( eIt->more() && !n2 )
4176   {
4177     const SMDS_MeshElement* e = eIt->next();
4178     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4179     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4180     if ( edgeSM )
4181     {
4182       if (!edgeSM->Contains(e)) continue;
4183     }
4184     else
4185     {
4186       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4187       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4188     }
4189     ( iN++ ? n2 : n1 ) = nNeibor;
4190   }
4191   if ( !n2 )
4192     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4193   return true;
4194 }
4195
4196 //================================================================================
4197 /*!
4198  * \brief Create _Curvature
4199  */
4200 //================================================================================
4201
4202 _Curvature* _Curvature::New( double avgNormProj, double avgDist )
4203 {
4204   // double   _r; // radius
4205   // double   _k; // factor to correct node smoothed position
4206   // double   _h2lenRatio; // avgNormProj / (2*avgDist)
4207   // gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
4208
4209   _Curvature* c = 0;
4210   if ( fabs( avgNormProj / avgDist ) > 1./200 )
4211   {
4212     c = _Factory::NewCurvature();
4213     c->_r = avgDist * avgDist / avgNormProj;
4214     c->_k = avgDist * avgDist / c->_r / c->_r;
4215     //c->_k = avgNormProj / c->_r;
4216     c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
4217     c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
4218
4219     c->_uv.SetCoord( 0., 0. );
4220   }
4221   return c;
4222 }
4223
4224 //================================================================================
4225 /*!
4226  * \brief Set _curvature and _2neibors->_plnNorm by 2 neighbor nodes residing the same EDGE
4227  */
4228 //================================================================================
4229
4230 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4231                                      const SMDS_MeshNode* n2,
4232                                      const _EdgesOnShape& eos,
4233                                      SMESH_MesherHelper&  helper)
4234 {
4235   if ( eos.ShapeType() != TopAbs_EDGE )
4236     return;
4237   if ( _curvature && Is( SMOOTHED_C1 ))
4238     return;
4239
4240   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4241   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4242   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4243
4244   // Set _curvature
4245
4246   double      sumLen = vec1.Modulus() + vec2.Modulus();
4247   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4248   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4249   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4250   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4251   _curvature = _Curvature::New( avgNormProj, avgLen );
4252   // if ( _curvature )
4253   //   debugMsg( _nodes[0]->GetID()
4254   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4255   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4256   //             << _curvature->lenDelta(0) );
4257
4258   // Set _plnNorm
4259
4260   if ( eos._sWOL.IsNull() )
4261   {
4262     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4263     // if ( SMESH_Algo::isDegenerated( E ))
4264     //   return;
4265     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4266     gp_XYZ plnNorm = dirE ^ _normal;
4267     double proj0   = plnNorm * vec1;
4268     double proj1   = plnNorm * vec2;
4269     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4270     {
4271       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4272       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4273     }
4274   }
4275 }
4276
4277 //================================================================================
4278 /*!
4279  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4280  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4281  */
4282 //================================================================================
4283
4284 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4285                          _EdgesOnShape&      eos,
4286                          SMESH_MesherHelper& helper )
4287 {
4288   _nodes     = other._nodes;
4289   _normal    = other._normal;
4290   _len       = 0;
4291   _lenFactor = other._lenFactor;
4292   _cosin     = other._cosin;
4293   _2neibors  = other._2neibors;
4294   _curvature = other._curvature;
4295   _2neibors  = other._2neibors;
4296   _maxLen    = Precision::Infinite();//other._maxLen;
4297   _flags     = 0;
4298   _smooFunction = 0;
4299
4300   gp_XYZ lastPos( 0,0,0 );
4301   if ( eos.SWOLType() == TopAbs_EDGE )
4302   {
4303     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4304     _pos.push_back( gp_XYZ( u, 0, 0));
4305
4306     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4307     lastPos.SetX( u );
4308   }
4309   else // TopAbs_FACE
4310   {
4311     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4312     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4313
4314     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4315     lastPos.SetX( uv.X() );
4316     lastPos.SetY( uv.Y() );
4317   }
4318   return lastPos;
4319 }
4320
4321 //================================================================================
4322 /*!
4323  * \brief Set _cosin and _lenFactor
4324  */
4325 //================================================================================
4326
4327 void _LayerEdge::SetCosin( double cosin )
4328 {
4329   _cosin = cosin;
4330   cosin = Abs( _cosin );
4331   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4332   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4333 }
4334
4335 //================================================================================
4336 /*!
4337  * \brief Check if another _LayerEdge is a neighbor on EDGE
4338  */
4339 //================================================================================
4340
4341 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4342 {
4343   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4344           ( edge->_2neibors && edge->_2neibors->include( this )));
4345 }
4346
4347 //================================================================================
4348 /*!
4349  * \brief Fills a vector<_Simplex > 
4350  */
4351 //================================================================================
4352
4353 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4354                              vector<_Simplex>&    simplices,
4355                              const set<TGeomID>&  ingnoreShapes,
4356                              const _SolidData*    dataToCheckOri,
4357                              const bool           toSort)
4358 {
4359   simplices.clear();
4360   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4361   while ( fIt->more() )
4362   {
4363     const SMDS_MeshElement* f = fIt->next();
4364     const TGeomID    shapeInd = f->getshapeId();
4365     if ( ingnoreShapes.count( shapeInd )) continue;
4366     const int nbNodes = f->NbCornerNodes();
4367     const int  srcInd = f->GetNodeIndex( node );
4368     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4369     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4370     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4371     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4372       std::swap( nPrev, nNext );
4373     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4374   }
4375
4376   if ( toSort )
4377     SortSimplices( simplices );
4378 }
4379
4380 //================================================================================
4381 /*!
4382  * \brief Set neighbor simplices side by side
4383  */
4384 //================================================================================
4385
4386 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4387 {
4388   vector<_Simplex> sortedSimplices( simplices.size() );
4389   sortedSimplices[0] = simplices[0];
4390   size_t nbFound = 0;
4391   for ( size_t i = 1; i < simplices.size(); ++i )
4392   {
4393     for ( size_t j = 1; j < simplices.size(); ++j )
4394       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4395       {
4396         sortedSimplices[i] = simplices[j];
4397         nbFound++;
4398         break;
4399       }
4400   }
4401   if ( nbFound == simplices.size() - 1 )
4402     simplices.swap( sortedSimplices );
4403 }
4404
4405 //================================================================================
4406 /*!
4407  * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4408  */
4409 //================================================================================
4410
4411 void _ViscousBuilder::makeGroupOfLE()
4412 {
4413 #ifdef _DEBUG_
4414   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4415   {
4416     if ( _sdVec[i]._n2eMap.empty() ) continue;
4417
4418     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4419     TNode2Edge::iterator n2e;
4420     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4421     {
4422       _LayerEdge* le = n2e->second;
4423       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4424       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4425       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4426       if ( le ) {
4427         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4428                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4429       }
4430     }
4431     dumpFunctionEnd();
4432
4433     dumpFunction( SMESH_Comment("makeNormals") << i );
4434     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4435     {
4436       _LayerEdge* edge = n2e->second;
4437       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4438       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4439       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4440               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4441     }
4442     dumpFunctionEnd();
4443
4444     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4445     dumpCmd( "faceId1 = mesh.NbElements()" );
4446     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4447     for ( ; fExp.More(); fExp.Next() )
4448     {
4449       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4450       {
4451         if ( sm->NbElements() == 0 ) continue;
4452         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4453         while ( fIt->more())
4454         {
4455           const SMDS_MeshElement* e = fIt->next();
4456           SMESH_Comment cmd("mesh.AddFace([");
4457           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4458             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4459           dumpCmd( cmd );
4460         }
4461       }
4462     }
4463     dumpCmd( "faceId2 = mesh.NbElements()" );
4464     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4465              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4466              << "'%s-%s' % (faceId1+1, faceId2))");
4467     dumpFunctionEnd();
4468   }
4469 #endif
4470 }
4471
4472 //================================================================================
4473 /*!
4474  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4475  */
4476 //================================================================================
4477
4478 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4479 {
4480   data._geomSize = Precision::Infinite();
4481   double intersecDist;
4482   const SMDS_MeshElement* face;
4483   SMESH_MesherHelper helper( *_mesh );
4484
4485   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4486     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4487                                            data._proxyMesh->GetFaces( data._solid )));
4488
4489   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4490   {
4491     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4492     if ( eos._edges.empty() )
4493       continue;
4494     // get neighbor faces, intersection with which should not be considered since
4495     // collisions are avoided by means of smoothing
4496     set< TGeomID > neighborFaces;
4497     if ( eos._hyp.ToSmooth() )
4498     {
4499       SMESH_subMeshIteratorPtr subIt =
4500         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4501       while ( subIt->more() )
4502       {
4503         SMESH_subMesh* sm = subIt->next();
4504         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4505         while ( const TopoDS_Shape* face = fIt->next() )
4506           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4507       }
4508     }
4509     // find intersections
4510     double thinkness = eos._hyp.GetTotalThickness();
4511     for ( size_t i = 0; i < eos._edges.size(); ++i )
4512     {
4513       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4514       eos._edges[i]->SetMaxLen( thinkness );
4515       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4516       if ( intersecDist > 0 && face )
4517       {
4518         data._geomSize = Min( data._geomSize, intersecDist );
4519         if ( !neighborFaces.count( face->getshapeId() ))
4520           eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4521       }
4522     }
4523   }
4524
4525   data._maxThickness = 0;
4526   data._minThickness = 1e100;
4527   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4528   for ( ; hyp != data._hyps.end(); ++hyp )
4529   {
4530     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4531     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4532   }
4533
4534   // Limit inflation step size by geometry size found by intersecting
4535   // normals of _LayerEdge's with mesh faces
4536   if ( data._stepSize > 0.3 * data._geomSize )
4537     limitStepSize( data, 0.3 * data._geomSize );
4538
4539   if ( data._stepSize > data._minThickness )
4540     limitStepSize( data, data._minThickness );
4541
4542
4543   // -------------------------------------------------------------------------
4544   // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4545   // so no need in detecting intersection at each inflation step
4546   // -------------------------------------------------------------------------
4547
4548   int nbSteps = data._maxThickness / data._stepSize;
4549   if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4550     return;
4551
4552   vector< const SMDS_MeshElement* > closeFaces;
4553   int nbDetected = 0;
4554
4555   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4556   {
4557     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4558     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4559       continue;
4560
4561     for ( size_t i = 0; i < eos.size(); ++i )
4562     {
4563       SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4564       double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4565       closeFaces.clear();
4566       searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4567
4568       bool toIgnore = true;
4569       for ( size_t iF = 0; iF < closeFaces.size()  && toIgnore; ++iF )
4570         if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4571                              data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4572         {
4573           // check if a _LayerEdge will inflate in a direction opposite to a direction
4574           // toward a close face
4575           bool allBehind = true;
4576           for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes()  && allBehind; ++iN )
4577           {
4578             SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4579             allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4580           }
4581           toIgnore = allBehind;
4582         }
4583
4584
4585       if ( toIgnore ) // no need to detect intersection
4586       {
4587         eos[i]->Set( _LayerEdge::INTERSECTED );
4588         ++nbDetected;
4589       }
4590     }
4591   }
4592
4593   debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4594
4595   return;
4596 }
4597
4598 //================================================================================
4599 /*!
4600  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4601  */
4602 //================================================================================
4603
4604 bool _ViscousBuilder::inflate(_SolidData& data)
4605 {
4606   SMESH_MesherHelper helper( *_mesh );
4607
4608   const double tgtThick = data._maxThickness;
4609
4610   if ( data._stepSize < 1. )
4611     data._epsilon = data._stepSize * 1e-7;
4612
4613   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4614   _pyDump->Pause();
4615
4616   findCollisionEdges( data, helper );
4617
4618   limitMaxLenByCurvature( data, helper );
4619
4620   _pyDump->Resume();
4621
4622   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4623   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4624     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4625          data._edgesOnShape[i]._edges.size() > 0 &&
4626          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4627     {
4628       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4629       data._edgesOnShape[i]._edges[0]->Block( data );
4630     }
4631
4632   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4633
4634   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4635   int nbSteps = 0, nbRepeats = 0;
4636   while ( avgThick < 0.99 )
4637   {
4638     // new target length
4639     double prevThick = curThick;
4640     curThick += data._stepSize;
4641     if ( curThick > tgtThick )
4642     {
4643       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4644       nbRepeats++;
4645     }
4646
4647     double stepSize = curThick - prevThick;
4648     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4649
4650     // Elongate _LayerEdge's
4651     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4652     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4653     {
4654       _EdgesOnShape& eos = data._edgesOnShape[iS];
4655       if ( eos._edges.empty() ) continue;
4656
4657       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4658       for ( size_t i = 0; i < eos._edges.size(); ++i )
4659       {
4660         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4661       }
4662     }
4663     dumpFunctionEnd();
4664
4665     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4666       return false;
4667
4668     // Improve and check quality
4669     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4670     {
4671       if ( nbSteps > 0 )
4672       {
4673 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4674         debugMsg("NOT INVALIDATED STEP!");
4675         return error("Smoothing failed", data._index);
4676 #endif
4677         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4678         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4679         {
4680           _EdgesOnShape& eos = data._edgesOnShape[iS];
4681           for ( size_t i = 0; i < eos._edges.size(); ++i )
4682             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4683         }
4684         dumpFunctionEnd();
4685       }
4686       break; // no more inflating possible
4687     }
4688     nbSteps++;
4689
4690     // Evaluate achieved thickness
4691     avgThick = 0;
4692     int nbActiveEdges = 0;
4693     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4694     {
4695       _EdgesOnShape& eos = data._edgesOnShape[iS];
4696       if ( eos._edges.empty() ) continue;
4697
4698       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4699       for ( size_t i = 0; i < eos._edges.size(); ++i )
4700       {
4701         if ( eos._edges[i]->_nodes.size() > 1 )
4702           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4703         else
4704           avgThick    += shapeTgtThick;
4705         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4706       }
4707     }
4708     avgThick /= data._n2eMap.size();
4709     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4710
4711 #ifdef BLOCK_INFLATION
4712     if ( nbActiveEdges == 0 )
4713     {
4714       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4715       break;
4716     }
4717 #else
4718     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4719     {
4720       debugMsg( "-- Stop inflation since "
4721                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4722                 << tgtThick * avgThick << " ) * " << safeFactor );
4723       break;
4724     }
4725 #endif
4726
4727     // new step size
4728     limitStepSize( data, 0.25 * distToIntersection );
4729     if ( data._stepSizeNodes[0] )
4730       data._stepSize = data._stepSizeCoeff *
4731         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4732
4733   } // while ( avgThick < 0.99 )
4734
4735   if ( nbSteps == 0 )
4736     return error("failed at the very first inflation step", data._index);
4737
4738   if ( avgThick < 0.99 )
4739   {
4740     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4741     {
4742       data._proxyMesh->_warning.reset
4743         ( new SMESH_ComputeError (COMPERR_WARNING,
4744                                   SMESH_Comment("Thickness ") << tgtThick <<
4745                                   " of viscous layers not reached,"
4746                                   " average reached thickness is " << avgThick*tgtThick));
4747     }
4748   }
4749
4750   // Restore position of src nodes moved by inflation on _noShrinkShapes
4751   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4752   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4753   {
4754     _EdgesOnShape& eos = data._edgesOnShape[iS];
4755     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4756       for ( size_t i = 0; i < eos._edges.size(); ++i )
4757       {
4758         restoreNoShrink( *eos._edges[ i ] );
4759       }
4760   }
4761   dumpFunctionEnd();
4762
4763   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4764 }
4765
4766 //================================================================================
4767 /*!
4768  * \brief Improve quality of layer inner surface and check intersection
4769  */
4770 //================================================================================
4771
4772 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4773                                      const int   infStep,
4774                                      double &    distToIntersection)
4775 {
4776   if ( data._nbShapesToSmooth == 0 )
4777     return true; // no shapes needing smoothing
4778
4779   bool moved, improved;
4780   double vol;
4781   vector< _LayerEdge* >    movedEdges, badEdges;
4782   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4783   vector< bool >           isConcaveFace;
4784
4785   SMESH_MesherHelper helper(*_mesh);
4786   Handle(ShapeAnalysis_Surface) surface;
4787   TopoDS_Face F;
4788
4789   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4790   {
4791     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4792
4793     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4794     {
4795       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4796       if ( !eos._toSmooth ||
4797            eos.ShapeType() != shapeType ||
4798            eos._edges.empty() )
4799         continue;
4800
4801       // already smoothed?
4802       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4803       // if ( !toSmooth ) continue;
4804
4805       if ( !eos._hyp.ToSmooth() )
4806       {
4807         // smooth disabled by the user; check validy only
4808         if ( !isFace ) continue;
4809         badEdges.clear();
4810         for ( size_t i = 0; i < eos._edges.size(); ++i )
4811         {
4812           _LayerEdge* edge = eos._edges[i];
4813           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4814             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4815             {
4816               // debugMsg( "-- Stop inflation. Bad simplex ("
4817               //           << " "<< edge->_nodes[0]->GetID()
4818               //           << " "<< edge->_nodes.back()->GetID()
4819               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4820               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4821               // return false;
4822               badEdges.push_back( edge );
4823             }
4824         }
4825         if ( !badEdges.empty() )
4826         {
4827           eosC1.resize(1);
4828           eosC1[0] = &eos;
4829           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4830           if ( nbBad > 0 )
4831             return false;
4832         }
4833         continue; // goto the next EDGE or FACE
4834       }
4835
4836       // prepare data
4837       if ( eos.SWOLType() == TopAbs_FACE )
4838       {
4839         if ( !F.IsSame( eos._sWOL )) {
4840           F = TopoDS::Face( eos._sWOL );
4841           helper.SetSubShape( F );
4842           surface = helper.GetSurface( F );
4843         }
4844       }
4845       else
4846       {
4847         F.Nullify(); surface.Nullify();
4848       }
4849       const TGeomID sInd = eos._shapeID;
4850
4851       // perform smoothing
4852
4853       if ( eos.ShapeType() == TopAbs_EDGE )
4854       {
4855         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4856
4857         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4858         {
4859           // smooth on EDGE's (normally we should not get here)
4860           int step = 0;
4861           do {
4862             moved = false;
4863             for ( size_t i = 0; i < eos._edges.size(); ++i )
4864             {
4865               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4866             }
4867             dumpCmd( SMESH_Comment("# end step ")<<step);
4868           }
4869           while ( moved && step++ < 5 );
4870         }
4871         dumpFunctionEnd();
4872       }
4873
4874       else // smooth on FACE
4875       {
4876         eosC1.clear();
4877         eosC1.push_back( & eos );
4878         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4879
4880         movedEdges.clear();
4881         isConcaveFace.resize( eosC1.size() );
4882         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4883         {
4884           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4885           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4886           for ( size_t i = 0; i < edges.size(); ++i )
4887             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4888                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4889               movedEdges.push_back( edges[i] );
4890
4891           makeOffsetSurface( *eosC1[ iEOS ], helper );
4892         }
4893
4894         int step = 0, stepLimit = 5, nbBad = 0;
4895         while (( ++step <= stepLimit ) || improved )
4896         {
4897           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4898                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4899           int oldBadNb = nbBad;
4900           badEdges.clear();
4901
4902 #ifdef INCREMENTAL_SMOOTH
4903           bool findBest = false; // ( step == stepLimit );
4904           for ( size_t i = 0; i < movedEdges.size(); ++i )
4905           {
4906             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4907             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4908               badEdges.push_back( movedEdges[i] );
4909           }
4910 #else
4911           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4912           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4913           {
4914             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4915             for ( size_t i = 0; i < edges.size(); ++i )
4916             {
4917               edges[i]->Unset( _LayerEdge::SMOOTHED );
4918               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4919                 badEdges.push_back( eos._edges[i] );
4920             }
4921           }
4922 #endif
4923           nbBad = badEdges.size();
4924
4925           if ( nbBad > 0 )
4926             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4927
4928           if ( !badEdges.empty() && step >= stepLimit / 2 )
4929           {
4930             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4931               stepLimit = 9;
4932
4933             // resolve hard smoothing situation around concave VERTEXes
4934             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4935             {
4936               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4937               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4938                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4939                                                          step, badEdges );
4940             }
4941             // look for the best smooth of _LayerEdge's neighboring badEdges
4942             nbBad = 0;
4943             for ( size_t i = 0; i < badEdges.size(); ++i )
4944             {
4945               _LayerEdge* ledge = badEdges[i];
4946               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4947               {
4948                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4949                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4950               }
4951               ledge->Unset( _LayerEdge::SMOOTHED );
4952               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4953             }
4954             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4955           }
4956
4957           if ( nbBad == oldBadNb  &&
4958                nbBad > 0 &&
4959                step < stepLimit ) // smooth w/o check of validity
4960           {
4961             dumpFunctionEnd();
4962             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4963                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4964             for ( size_t i = 0; i < movedEdges.size(); ++i )
4965             {
4966               movedEdges[i]->SmoothWoCheck();
4967             }
4968             if ( stepLimit < 9 )
4969               stepLimit++;
4970           }
4971
4972           improved = ( nbBad < oldBadNb );
4973
4974           dumpFunctionEnd();
4975
4976           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4977             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4978             {
4979               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4980             }
4981
4982         } // smoothing steps
4983
4984         // project -- to prevent intersections or fix bad simplices
4985         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4986         {
4987           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4988             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4989         }
4990
4991         //if ( !badEdges.empty() )
4992         {
4993           badEdges.clear();
4994           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4995           {
4996             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4997             {
4998               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4999
5000               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5001               edge->CheckNeiborsOnBoundary( & badEdges );
5002               if (( nbBad > 0 ) ||
5003                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
5004               {
5005                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5006                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
5007                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5008                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5009                   {
5010                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
5011                              << " "<< tgtXYZ._node->GetID()
5012                              << " "<< edge->_simplices[j]._nPrev->GetID()
5013                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5014                     badEdges.push_back( edge );
5015                     break;
5016                   }
5017               }
5018             }
5019           }
5020
5021           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5022           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5023
5024           if ( nbBad > 0 )
5025             return false;
5026         }
5027
5028       } // // smooth on FACE's
5029     } // loop on shapes
5030   } // smooth on [ EDGEs, FACEs ]
5031
5032   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
5033   eosC1.resize(1);
5034   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5035   {
5036     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5037     if ( eos.ShapeType() == TopAbs_FACE ||
5038          eos._edges.empty() ||
5039          !eos._sWOL.IsNull() )
5040       continue;
5041
5042     badEdges.clear();
5043     for ( size_t i = 0; i < eos._edges.size(); ++i )
5044     {
5045       _LayerEdge*      edge = eos._edges[i];
5046       if ( edge->_nodes.size() < 2 ) continue;
5047       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5048       //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
5049       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
5050       //const gp_XYZ& prevXYZ = edge->PrevPos();
5051       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5052         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5053         {
5054           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
5055                    << " "<< tgtXYZ._node->GetID()
5056                    << " "<< edge->_simplices[j]._nPrev->GetID()
5057                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5058           badEdges.push_back( edge );
5059           break;
5060         }
5061     }
5062
5063     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5064     eosC1[0] = &eos;
5065     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5066     if ( nbBad > 0 )
5067       return false;
5068   }
5069
5070
5071   // Check if the last segments of _LayerEdge intersects 2D elements;
5072   // checked elements are either temporary faces or faces on surfaces w/o the layers
5073
5074   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5075     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
5076                                            data._proxyMesh->GetFaces( data._solid )) );
5077
5078 #ifdef BLOCK_INFLATION
5079   const bool toBlockInfaltion = true;
5080 #else
5081   const bool toBlockInfaltion = false;
5082 #endif
5083   distToIntersection = Precision::Infinite();
5084   double dist;
5085   const SMDS_MeshElement* intFace = 0;
5086   const SMDS_MeshElement* closestFace = 0;
5087   _LayerEdge* le = 0;
5088   bool is1stBlocked = true; // dbg
5089   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5090   {
5091     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5092     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5093       continue;
5094     for ( size_t i = 0; i < eos._edges.size(); ++i )
5095     {
5096       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5097            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5098         continue;
5099       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5100       {
5101         return false;
5102         // commented due to "Illegal hash-positionPosition" error in NETGEN
5103         // on Debian60 on viscous_layers_01/B2 case
5104         // Collision; try to deflate _LayerEdge's causing it
5105         // badEdges.clear();
5106         // badEdges.push_back( eos._edges[i] );
5107         // eosC1[0] = & eos;
5108         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5109         // if ( nbBad > 0 )
5110         //   return false;
5111
5112         // badEdges.clear();
5113         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5114         // {
5115         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5116         //   {
5117         //     const SMDS_MeshElement* srcFace =
5118         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5119         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5120         //     while ( nIt->more() )
5121         //     {
5122         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5123         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5124         //       if ( n2e != data._n2eMap.end() )
5125         //         badEdges.push_back( n2e->second );
5126         //     }
5127         //     eosC1[0] = eof;
5128         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5129         //     if ( nbBad > 0 )
5130         //       return false;
5131         //   }
5132         // }
5133         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5134         //   return false;
5135         // else
5136         //   continue;
5137       }
5138       if ( !intFace )
5139       {
5140         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5141         debugMsg( msg );
5142         continue;
5143       }
5144
5145       const bool isShorterDist = ( distToIntersection > dist );
5146       if ( toBlockInfaltion || isShorterDist )
5147       {
5148         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5149         // lying on this _ConvexFace
5150         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5151           if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5152             continue;
5153
5154         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5155         // ( avoid limiting the thickness on the case of issue 22576)
5156         if ( intFace->getshapeId() == eos._shapeID  )
5157           continue;
5158
5159         // ignore intersection with intFace of an adjacent FACE
5160         if ( dist > 0.1 * eos._edges[i]->_len )
5161         {
5162           bool toIgnore = false;
5163           if (  eos._toSmooth )
5164           {
5165             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5166             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5167             {
5168               TopExp_Explorer sub( eos._shape,
5169                                    eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5170               for ( ; !toIgnore && sub.More(); sub.Next() )
5171                 // is adjacent - has a common EDGE or VERTEX
5172                 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5173
5174               if ( toIgnore ) // check angle between normals
5175               {
5176                 gp_XYZ normal;
5177                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5178                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
5179               }
5180             }
5181           }
5182           if ( !toIgnore ) // check if the edge is a neighbor of intFace
5183           {
5184             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
5185             {
5186               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5187               toIgnore = ( nInd >= 0 );
5188             }
5189           }
5190           if ( toIgnore )
5191             continue;
5192         }
5193
5194         // intersection not ignored
5195
5196         if ( toBlockInfaltion &&
5197              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5198         {
5199           if ( is1stBlocked ) { is1stBlocked = false; // debug
5200             dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5201           }
5202           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5203           eos._edges[i]->Block( data );                  // not to inflate
5204
5205           //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5206           {
5207             // block _LayerEdge's, on top of which intFace is
5208             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5209             {
5210               const SMDS_MeshElement* srcFace = f->_srcFace;
5211               SMDS_ElemIteratorPtr        nIt = srcFace->nodesIterator();
5212               while ( nIt->more() )
5213               {
5214                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5215                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5216                 if ( n2e != data._n2eMap.end() )
5217                   n2e->second->Block( data );
5218               }
5219             }
5220           }
5221         }
5222
5223         if ( isShorterDist )
5224         {
5225           distToIntersection = dist;
5226           le = eos._edges[i];
5227           closestFace = intFace;
5228         }
5229
5230       } // if ( toBlockInfaltion || isShorterDist )
5231     } // loop on eos._edges
5232   } // loop on data._edgesOnShape
5233
5234   if ( !is1stBlocked )
5235     dumpFunctionEnd();
5236
5237   if ( closestFace && le )
5238   {
5239 #ifdef __myDEBUG
5240     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5241     cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5242          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5243          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5244          << ") distance = " << distToIntersection<< endl;
5245 #endif
5246   }
5247
5248   return true;
5249 }
5250
5251 //================================================================================
5252 /*!
5253  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5254  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5255  *  \return int - resulting nb of bad _LayerEdge's
5256  */
5257 //================================================================================
5258
5259 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5260                                           SMESH_MesherHelper&       helper,
5261                                           vector< _LayerEdge* >&    badSmooEdges,
5262                                           vector< _EdgesOnShape* >& eosC1,
5263                                           const int                 infStep )
5264 {
5265   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5266
5267   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5268
5269   enum {
5270     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5271     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5272     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5273   };
5274   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5275
5276   double vol;
5277   bool haveInvalidated = true;
5278   while ( haveInvalidated )
5279   {
5280     haveInvalidated = false;
5281     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5282     {
5283       _LayerEdge*   edge = badSmooEdges[i];
5284       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5285       edge->Set( ADDED );
5286       bool invalidated = false;
5287       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5288       {
5289         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5290         edge->Block( data );
5291         edge->Set( INVALIDATED );
5292         edge->Unset( TO_INVALIDATE );
5293         invalidated = true;
5294         haveInvalidated = true;
5295       }
5296
5297       // look for _LayerEdge's of bad _simplices
5298       int nbBad = 0;
5299       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5300       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5301       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5302       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5303       {
5304         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5305             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5306           continue;
5307
5308         bool isBad = true;
5309         _LayerEdge* ee[2] = { 0,0 };
5310         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5311           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5312             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5313
5314         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5315         while ( maxNbSteps > edge->NbSteps() && isBad )
5316         {
5317           --maxNbSteps;
5318           for ( int iE = 0; iE < 2; ++iE )
5319           {
5320             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5321                  ee[ iE ]->NbSteps() > 1 )
5322             {
5323               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5324               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5325               ee[ iE ]->Block( data );
5326               ee[ iE ]->Set( INVALIDATED );
5327               haveInvalidated = true;
5328             }
5329           }
5330           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5331               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5332             isBad = false;
5333         }
5334         nbBad += isBad;
5335         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5336         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5337         ee[0]->Set( ADDED );
5338         ee[1]->Set( ADDED );
5339         if ( isBad )
5340         {
5341           ee[0]->Set( TO_INVALIDATE );
5342           ee[1]->Set( TO_INVALIDATE );
5343         }
5344       }
5345
5346       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5347       {
5348         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5349         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5350         edge->Block( data );
5351         edge->Set( INVALIDATED );
5352         edge->Unset( TO_INVALIDATE );
5353         haveInvalidated = true;
5354       }
5355     } // loop on badSmooEdges
5356   } // while ( haveInvalidated )
5357
5358   // re-smooth on analytical EDGEs
5359   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5360   {
5361     _LayerEdge* edge = badSmooEdges[i];
5362     if ( !edge->Is( INVALIDATED )) continue;
5363
5364     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5365     if ( eos->ShapeType() == TopAbs_VERTEX )
5366     {
5367       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5368       while ( const TopoDS_Shape* e = eIt->next() )
5369         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5370           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5371           {
5372             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5373             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5374             //   F       = TopoDS::Face( eoe->_sWOL );
5375             //   surface = helper.GetSurface( F );
5376             // }
5377             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5378             eoe->_edgeSmoother->_anaCurve.Nullify();
5379           }
5380     }
5381   }
5382
5383
5384   // check result of invalidation
5385
5386   int nbBad = 0;
5387   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5388   {
5389     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5390     {
5391       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5392       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5393       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5394       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5395       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5396         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5397         {
5398           ++nbBad;
5399           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5400                    << " "<< tgtXYZ._node->GetID()
5401                    << " "<< edge->_simplices[j]._nPrev->GetID()
5402                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5403         }
5404     }
5405   }
5406   dumpFunctionEnd();
5407
5408   return nbBad;
5409 }
5410
5411 //================================================================================
5412 /*!
5413  * \brief Create an offset surface
5414  */
5415 //================================================================================
5416
5417 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5418 {
5419   if ( eos._offsetSurf.IsNull() ||
5420        eos._edgeForOffset == 0 ||
5421        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5422     return;
5423
5424   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5425
5426   // find offset
5427   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5428   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5429   double offset = baseSurface->Gap();
5430
5431   eos._offsetSurf.Nullify();
5432
5433   try
5434   {
5435     BRepOffsetAPI_MakeOffsetShape offsetMaker;
5436     offsetMaker.PerformByJoin( eos._shape, -offset, Precision::Confusion() );
5437     if ( !offsetMaker.IsDone() ) return;
5438
5439     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5440     if ( !fExp.More() ) return;
5441
5442     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5443     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5444     if ( surf.IsNull() ) return;
5445
5446     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5447   }
5448   catch ( Standard_Failure )
5449   {
5450   }
5451 }
5452
5453 //================================================================================
5454 /*!
5455  * \brief Put nodes of a curved FACE to its offset surface
5456  */
5457 //================================================================================
5458
5459 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5460                                           int                       infStep,
5461                                           vector< _EdgesOnShape* >& eosC1,
5462                                           int                       smooStep,
5463                                           int                       moveAll )
5464 {
5465   _EdgesOnShape * eof = & eos;
5466   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5467   {
5468     eof = 0;
5469     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5470     {
5471       if ( eosC1[i]->_offsetSurf.IsNull() ||
5472            eosC1[i]->ShapeType() != TopAbs_FACE ||
5473            eosC1[i]->_edgeForOffset == 0 ||
5474            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5475         continue;
5476       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5477         eof = eosC1[i];
5478     }
5479   }
5480   if ( !eof ||
5481        eof->_offsetSurf.IsNull() ||
5482        eof->ShapeType() != TopAbs_FACE ||
5483        eof->_edgeForOffset == 0 ||
5484        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5485     return;
5486
5487   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5488   for ( size_t i = 0; i < eos._edges.size(); ++i )
5489   {
5490     _LayerEdge* edge = eos._edges[i];
5491     edge->Unset( _LayerEdge::MARKED );
5492     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5493       continue;
5494     if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5495     {
5496       if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5497         continue;
5498     }
5499     else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5500       continue;
5501
5502     int nbBlockedAround = 0;
5503     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5504       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5505     if ( nbBlockedAround > 1 )
5506       continue;
5507
5508     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5509     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5510     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5511     edge->_curvature->_uv = uv;
5512     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5513
5514     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5515     gp_XYZ prevP = edge->PrevCheckPos();
5516     bool      ok = true;
5517     if ( !moveAll )
5518       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5519       {
5520         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5521       }
5522     if ( ok )
5523     {
5524       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5525       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5526       edge->_pos.back() = newP;
5527
5528       edge->Set( _LayerEdge::MARKED );
5529       if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5530       {
5531         edge->_normal = ( newP - prevP ).Normalized();
5532       }
5533     }
5534   }
5535
5536
5537
5538 #ifdef _DEBUG_
5539   // dumpMove() for debug
5540   size_t i = 0;
5541   for ( ; i < eos._edges.size(); ++i )
5542     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5543       break;
5544   if ( i < eos._edges.size() )
5545   {
5546     dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5547                  << "_InfStep" << infStep << "_" << smooStep );
5548     for ( ; i < eos._edges.size(); ++i )
5549     {
5550       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5551         dumpMove( eos._edges[i]->_nodes.back() );
5552     }
5553     dumpFunctionEnd();
5554   }
5555 #endif
5556
5557   _ConvexFace* cnvFace;
5558   if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5559        eos.ShapeType() == TopAbs_FACE &&
5560        (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5561        !cnvFace->_normalsFixedOnBorders )
5562   {
5563     // put on the surface nodes built on FACE boundaries
5564     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5565     while ( smIt->more() )
5566     {
5567       SMESH_subMesh* sm = smIt->next();
5568       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5569       if ( !subEOS->_sWOL.IsNull() ) continue;
5570       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5571
5572       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5573     }
5574     cnvFace->_normalsFixedOnBorders = true;
5575   }
5576 }
5577
5578 //================================================================================
5579 /*!
5580  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5581  *        _LayerEdge's to be in a consequent order
5582  */
5583 //================================================================================
5584
5585 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5586                                                 _EdgesOnShape&      eos,
5587                                                 SMESH_MesherHelper& helper)
5588 {
5589   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5590
5591   TopLoc_Location loc; double f,l;
5592
5593   Handle(Geom_Line)   line;
5594   Handle(Geom_Circle) circle;
5595   bool isLine, isCirc;
5596   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5597   {
5598     // check if the EDGE is a line
5599     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5600     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5601       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5602
5603     line   = Handle(Geom_Line)::DownCast( curve );
5604     circle = Handle(Geom_Circle)::DownCast( curve );
5605     isLine = (!line.IsNull());
5606     isCirc = (!circle.IsNull());
5607
5608     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5609     {
5610       isLine = SMESH_Algo::IsStraight( E );
5611
5612       if ( isLine )
5613         line = new Geom_Line( gp::OX() ); // only type does matter
5614     }
5615     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5616     {
5617       // TODO
5618     }
5619   }
5620   else //////////////////////////////////////////////////////////////////////// 2D case
5621   {
5622     if ( !eos._isRegularSWOL ) // 23190
5623       return NULL;
5624
5625     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5626
5627     // check if the EDGE is a line
5628     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5629     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5630       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5631
5632     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5633     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5634     isLine = (!line2d.IsNull());
5635     isCirc = (!circle2d.IsNull());
5636
5637     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5638     {
5639       Bnd_B2d bndBox;
5640       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5641       while ( nIt->more() )
5642         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5643       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5644
5645       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5646       for ( int i = 0; i < 2 && !isLine; ++i )
5647         isLine = ( size.Coord( i+1 ) <= lineTol );
5648     }
5649     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5650     {
5651       // TODO
5652     }
5653     if ( isLine )
5654     {
5655       line = new Geom_Line( gp::OX() ); // only type does matter
5656     }
5657     else if ( isCirc )
5658     {
5659       gp_Pnt2d p = circle2d->Location();
5660       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5661       circle = new Geom_Circle( ax, 1.); // only center position does matter
5662     }
5663   }
5664
5665   if ( isLine )
5666     return line;
5667   if ( isCirc )
5668     return circle;
5669
5670   return Handle(Geom_Curve)();
5671 }
5672
5673 //================================================================================
5674 /*!
5675  * \brief Smooth edges on EDGE
5676  */
5677 //================================================================================
5678
5679 bool _Smoother1D::Perform(_SolidData&                    data,
5680                           Handle(ShapeAnalysis_Surface)& surface,
5681                           const TopoDS_Face&             F,
5682                           SMESH_MesherHelper&            helper )
5683 {
5684   if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5685     prepare( data );
5686
5687   findEdgesToSmooth();
5688   if ( isAnalytic() )
5689     return smoothAnalyticEdge( data, surface, F, helper );
5690   else
5691     return smoothComplexEdge ( data, surface, F, helper );
5692 }
5693
5694 //================================================================================
5695 /*!
5696  * \brief Find edges to smooth
5697  */
5698 //================================================================================
5699
5700 void _Smoother1D::findEdgesToSmooth()
5701 {
5702   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5703   for ( int iEnd = 0; iEnd < 2; ++iEnd )
5704     if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5705       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5706
5707   _eToSmooth[0].first = _eToSmooth[0].second = 0;
5708
5709   for ( size_t i = 0; i < _eos.size(); ++i )
5710   {
5711     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5712     {
5713       if ( needSmoothing( _leOnV[0]._cosin,
5714                           _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
5715            isToSmooth( i )
5716            )
5717         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5718       else
5719         break;
5720     }
5721     _eToSmooth[0].second = i+1;
5722   }
5723
5724   _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5725
5726   for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5727   {
5728     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5729     {
5730       if ( needSmoothing( _leOnV[1]._cosin,
5731                           _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
5732            isToSmooth( i ))
5733         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5734       else
5735         break;
5736     }
5737     _eToSmooth[1].first = i;
5738   }
5739 }
5740
5741 //================================================================================
5742 /*!
5743  * \brief Check if iE-th _LayerEdge needs smoothing
5744  */
5745 //================================================================================
5746
5747 bool _Smoother1D::isToSmooth( int iE )
5748 {
5749   SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5750   SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5751   SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5752   gp_XYZ       seg0 = pi - p0;
5753   gp_XYZ       seg1 = p1 - pi;
5754   gp_XYZ    tangent =  seg0 + seg1;
5755   double tangentLen = tangent.Modulus();
5756   double  segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5757   if ( tangentLen < std::numeric_limits<double>::min() )
5758     return false;
5759   tangent /= tangentLen;
5760
5761   for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5762   {
5763     _LayerEdge* ne = _eos[iE]->_neibors[i];
5764     if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5765          ne->_nodes.size() < 2 ||
5766          ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5767       continue;
5768     gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5769     double    proj = edgeVec * tangent;
5770     if ( needSmoothing( 1., proj, segMinLen ))
5771       return true;
5772   }
5773   return false;
5774 }
5775
5776 //================================================================================
5777 /*!
5778  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5779  */
5780 //================================================================================
5781
5782 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5783                                       Handle(ShapeAnalysis_Surface)& surface,
5784                                       const TopoDS_Face&             F,
5785                                       SMESH_MesherHelper&            helper)
5786 {
5787   if ( !isAnalytic() ) return false;
5788
5789   size_t iFrom = 0, iTo = _eos._edges.size();
5790
5791   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5792   {
5793     if ( F.IsNull() ) // 3D
5794     {
5795       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5796       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5797       //const   gp_XYZ lineDir = pSrc1 - pSrc0;
5798       //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5799       //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5800       // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5801       //                    vLE0->Is( _LayerEdge::BLOCKED ) ||
5802       //                    vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5803       //                    vLE1->Is( _LayerEdge::BLOCKED ));
5804       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5805       {
5806         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5807         if ( iFrom >= iTo ) continue;
5808         SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5809         SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5810         double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5811         double param1 = _leParams[ iTo ];
5812         for ( size_t i = iFrom; i < iTo; ++i )
5813         {
5814           _LayerEdge*       edge = _eos[i];
5815           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5816           double           param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5817           gp_XYZ          newPos = p0 * ( 1. - param ) + p1 * param;
5818
5819           // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5820           // {
5821           //   gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5822           //   double  shift = ( lineDir * ( newPos - pSrc0 ) -
5823           //                     lineDir * ( curPos - pSrc0 ));
5824           //   newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5825           // }
5826           if ( edge->Is( _LayerEdge::BLOCKED ))
5827           {
5828             SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5829             double curThick = pSrc.SquareDistance( tgtNode );
5830             double newThink = ( pSrc - newPos ).SquareModulus();
5831             if ( newThink > curThick )
5832               continue;
5833           }
5834           edge->_pos.back() = newPos;
5835           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5836           dumpMove( tgtNode );
5837         }
5838       }
5839     }
5840     else // 2D
5841     {
5842       _LayerEdge* eV0 = getLEdgeOnV( 0 );
5843       _LayerEdge* eV1 = getLEdgeOnV( 1 );
5844       gp_XY      uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5845       gp_XY      uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5846       if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5847       {
5848         int iPeriodic = helper.GetPeriodicIndex();
5849         if ( iPeriodic == 1 || iPeriodic == 2 )
5850         {
5851           uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5852           if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5853             std::swap( uvV0, uvV1 );
5854         }
5855       }
5856       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5857       {
5858         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5859         if ( iFrom >= iTo ) continue;
5860         _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5861         _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5862         gp_XY      uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5863         gp_XY      uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5864         double  param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5865         double  param1 = _leParams[ iTo ];
5866         gp_XY  rangeUV = uv1 - uv0;
5867         for ( size_t i = iFrom; i < iTo; ++i )
5868         {
5869           if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5870           double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5871           gp_XY newUV = uv0 + param * rangeUV;
5872
5873           gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5874           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5875           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5876           dumpMove( tgtNode );
5877
5878           SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5879           pos->SetUParameter( newUV.X() );
5880           pos->SetVParameter( newUV.Y() );
5881
5882           gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5883
5884           if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5885           {
5886             _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5887             if ( _eos[i]->_pos.size() > 2 )
5888             {
5889               // modify previous positions to make _LayerEdge less sharply bent
5890               vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5891               const gp_XYZ  uvShift = newUV0 - uvVec.back();
5892               const double     len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5893               int iPrev = uvVec.size() - 2;
5894               while ( iPrev > 0 )
5895               {
5896                 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5897                 uvVec[ iPrev ] += uvShift * r;
5898                 --iPrev;
5899               }
5900             }
5901           }
5902           _eos[i]->_pos.back() = newUV0;
5903         }
5904       }
5905     }
5906     return true;
5907   }
5908
5909   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5910   {
5911     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5912     gp_Pnt center3D = circle->Location();
5913
5914     if ( F.IsNull() ) // 3D
5915     {
5916       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5917         return true; // closed EDGE - nothing to do
5918
5919       // circle is a real curve of EDGE
5920       gp_Circ circ = circle->Circ();
5921
5922       // new center is shifted along its axis
5923       const gp_Dir& axis = circ.Axis().Direction();
5924       _LayerEdge*     e0 = getLEdgeOnV(0);
5925       _LayerEdge*     e1 = getLEdgeOnV(1);
5926       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5927       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5928       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5929       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5930       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5931
5932       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5933
5934       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5935       gp_Circ newCirc( newAxis, newRadius );
5936       gp_Vec  vecC1  ( newCenter, p1 );
5937
5938       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5939       if ( uLast < 0 )
5940         uLast += 2 * M_PI;
5941       
5942       for ( size_t i = 0; i < _eos.size(); ++i )
5943       {
5944         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5945         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5946         double u = uLast * _leParams[i];
5947         gp_Pnt p = ElCLib::Value( u, newCirc );
5948         _eos._edges[i]->_pos.back() = p.XYZ();
5949
5950         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5951         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5952         dumpMove( tgtNode );
5953       }
5954       return true;
5955     }
5956     else // 2D
5957     {
5958       const gp_XY center( center3D.X(), center3D.Y() );
5959
5960       _LayerEdge* e0 = getLEdgeOnV(0);
5961       _LayerEdge* eM = _eos._edges[ 0 ];
5962       _LayerEdge* e1 = getLEdgeOnV(1);
5963       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5964       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5965       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5966       gp_Vec2d vec0( center, uv0 );
5967       gp_Vec2d vecM( center, uvM );
5968       gp_Vec2d vec1( center, uv1 );
5969       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5970       double uMidl = vec0.Angle( vecM );
5971       if ( uLast * uMidl <= 0. )
5972         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5973       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5974
5975       gp_Ax2d   axis( center, vec0 );
5976       gp_Circ2d circ( axis, radius );
5977       for ( size_t i = 0; i < _eos.size(); ++i )
5978       {
5979         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5980         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5981         double    newU = uLast * _leParams[i];
5982         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5983         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5984
5985         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5986         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5987         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5988         dumpMove( tgtNode );
5989
5990         SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5991         pos->SetUParameter( newUV.X() );
5992         pos->SetVParameter( newUV.Y() );
5993
5994         _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5995       }
5996     }
5997     return true;
5998   }
5999
6000   return false;
6001 }
6002
6003 //================================================================================
6004 /*!
6005  * \brief smooth _LayerEdge's on a an EDGE
6006  */
6007 //================================================================================
6008
6009 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
6010                                      Handle(ShapeAnalysis_Surface)& surface,
6011                                      const TopoDS_Face&             F,
6012                                      SMESH_MesherHelper&            helper)
6013 {
6014   if ( _offPoints.empty() )
6015     return false;
6016
6017   // ----------------------------------------------
6018   // move _offPoints along normals of _LayerEdge's
6019   // ----------------------------------------------
6020
6021   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6022   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
6023     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
6024   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
6025     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
6026   _leOnV[0]._len = e[0]->_len;
6027   _leOnV[1]._len = e[1]->_len;
6028   for ( size_t i = 0; i < _offPoints.size(); i++ )
6029   {
6030     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6031     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6032     const double w0 = _offPoints[i]._2edges._wgt[0];
6033     const double w1 = _offPoints[i]._2edges._wgt[1];
6034     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
6035     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
6036     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
6037     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6038          e1->Is( _LayerEdge::NORMAL_UPDATED ))
6039       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
6040
6041     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
6042     _offPoints[i]._len  = avgLen;
6043   }
6044
6045   double fTol = 0;
6046   if ( !surface.IsNull() ) // project _offPoints to the FACE
6047   {
6048     fTol = 100 * BRep_Tool::Tolerance( F );
6049     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
6050
6051     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
6052     //if ( surface->Gap() < 0.5 * segLen )
6053       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
6054
6055     for ( size_t i = 1; i < _offPoints.size(); ++i )
6056     {
6057       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
6058       //if ( surface->Gap() < 0.5 * segLen )
6059         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
6060     }
6061   }
6062
6063   // -----------------------------------------------------------------
6064   // project tgt nodes of extreme _LayerEdge's to the offset segments
6065   // -----------------------------------------------------------------
6066
6067   const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
6068   if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
6069   if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
6070
6071   gp_Pnt pExtreme[2], pProj[2];
6072   bool isProjected[2];
6073   for ( int is2nd = 0; is2nd < 2; ++is2nd )
6074   {
6075     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
6076     int  i = _iSeg[ is2nd ];
6077     int di = is2nd ? -1 : +1;
6078     bool & projected = isProjected[ is2nd ];
6079     projected = false;
6080     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
6081     int nbWorse = 0;
6082     do {
6083       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
6084       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
6085       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
6086       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
6087       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
6088       if ( dist < distMin || projected )
6089       {
6090         _iSeg[ is2nd ] = i;
6091         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6092         distMin = dist;
6093       }
6094       else if ( dist > distPrev )
6095       {
6096         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6097           break;
6098       }
6099       distPrev = dist;
6100       i += di;
6101     }
6102     while ( !projected &&
6103             i >= 0 && i+1 < (int)_offPoints.size() );
6104
6105     if ( !projected )
6106     {
6107       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6108       {
6109         _iSeg[0] = 0;
6110         _iSeg[1] = _offPoints.size()-2;
6111         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6112         return false;
6113       }
6114     }
6115   }
6116   if ( _iSeg[0] > _iSeg[1] )
6117   {
6118     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6119     return false;
6120   }
6121
6122   // adjust length of extreme LE (test viscous_layers_01/B7)
6123   gp_Vec vDiv0( pExtreme[0], pProj[0] );
6124   gp_Vec vDiv1( pExtreme[1], pProj[1] );
6125   double d0 = vDiv0.Magnitude();
6126   double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6127   if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6128     if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6129     else                                   e[0]->_len -= d0;
6130   }
6131   if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6132     if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6133     else                                   e[1]->_len -= d1;
6134   }
6135
6136   // ---------------------------------------------------------------------------------
6137   // compute normalized length of the offset segments located between the projections
6138   // ---------------------------------------------------------------------------------
6139
6140   // temporary replace extreme _offPoints by pExtreme
6141   gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0]   ]._xyz,
6142                       _offPoints[ _iSeg[1]+1 ]._xyz };
6143   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
6144   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6145
6146   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6147   vector< double > len( nbSeg + 1 );
6148   len[ iSeg++ ] = 0;
6149   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6150   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6151   {
6152     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6153   }
6154   // if ( isProjected[ 1 ])
6155   //   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6156   // else
6157   //   len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6158
6159   double fullLen = len.back() - d0 - d1;
6160   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6161     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6162
6163   // -------------------------------------------------------------
6164   // distribute tgt nodes of _LayerEdge's between the projections
6165   // -------------------------------------------------------------
6166
6167   iSeg = 0;
6168   for ( size_t i = 0; i < _eos.size(); ++i )
6169   {
6170     if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6171     //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6172     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6173       iSeg++;
6174     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6175     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
6176                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6177
6178     if ( surface.IsNull() )
6179     {
6180       _eos[i]->_pos.back() = p;
6181     }
6182     else // project a new node position to a FACE
6183     {
6184       gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6185       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6186
6187       p = surface->Value( uv2 ).XYZ();
6188       _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6189     }
6190     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6191     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6192     dumpMove( tgtNode );
6193   }
6194
6195   _offPoints[ _iSeg[0]   ]._xyz = opXYZ[0];
6196   _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6197
6198   return true;
6199 }
6200
6201 //================================================================================
6202 /*!
6203  * \brief Prepare for smoothing
6204  */
6205 //================================================================================
6206
6207 void _Smoother1D::prepare(_SolidData& data)
6208 {
6209   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6210   _curveLen = SMESH_Algo::EdgeLength( E );
6211
6212   // sort _LayerEdge's by position on the EDGE
6213   data.SortOnEdge( E, _eos._edges );
6214
6215   // compute normalized param of _eos._edges on EDGE
6216   _leParams.resize( _eos._edges.size() + 1 );
6217   {
6218     double curLen;
6219     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6220     _leParams[0] = 0;
6221     for ( size_t i = 0; i < _eos._edges.size(); ++i )
6222     {
6223       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6224       curLen         = p.Distance( pPrev );
6225       _leParams[i+1] = _leParams[i] + curLen;
6226       pPrev          = p;
6227     }
6228     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6229     for ( size_t i = 0; i < _leParams.size()-1; ++i )
6230       _leParams[i] = _leParams[i+1] / fullLen;
6231     _leParams.back() = 1.;
6232   }
6233
6234   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6235
6236   // get cosin to use in findEdgesToSmooth()
6237   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6238   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6239   _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6240   _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6241   if ( _eos._sWOL.IsNull() ) // 3D
6242     for ( int iEnd = 0; iEnd < 2; ++iEnd )
6243       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6244
6245   if ( isAnalytic() )
6246     return;
6247
6248   // divide E to have offset segments with low deflection
6249   BRepAdaptor_Curve c3dAdaptor( E );
6250   const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6251   const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6252   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6253   if ( discret.NbPoints() <= 2 )
6254   {
6255     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6256     return;
6257   }
6258
6259   const double u0 = c3dAdaptor.FirstParameter();
6260   gp_Pnt p; gp_Vec tangent;
6261   if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6262   {
6263     _offPoints.resize( discret.NbPoints() );
6264     for ( size_t i = 0; i < _offPoints.size(); i++ )
6265     {
6266       double u = discret.Parameter( i+1 );
6267       c3dAdaptor.D1( u, p, tangent );
6268       _offPoints[i]._xyz     = p.XYZ();
6269       _offPoints[i]._edgeDir = tangent.XYZ();
6270       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6271     }
6272   }
6273   else
6274   {
6275     std::vector< double > params( _eos.size() + 2 );
6276
6277     params[0]     = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6278     params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6279     for ( size_t i = 0; i < _eos.size(); i++ )
6280       params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6281
6282     if ( params[1] > params[ _eos.size() ] )
6283       std::reverse( params.begin() + 1, params.end() - 1 );
6284
6285     _offPoints.resize( _eos.size() + 2 );
6286     for ( size_t i = 0; i < _offPoints.size(); i++ )
6287     {
6288       const double u = params[i];
6289       c3dAdaptor.D1( u, p, tangent );
6290       _offPoints[i]._xyz     = p.XYZ();
6291       _offPoints[i]._edgeDir = tangent.XYZ();
6292       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6293     }
6294   }
6295
6296   // set _2edges
6297   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6298   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6299   _2NearEdges tmp2edges;
6300   tmp2edges._edges[1] = _eos._edges[0];
6301   _leOnV[0]._2neibors = & tmp2edges;
6302   _leOnV[0]._nodes    = leOnV[0]->_nodes;
6303   _leOnV[1]._nodes    = leOnV[1]->_nodes;
6304   _LayerEdge* eNext, *ePrev = & _leOnV[0];
6305   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6306   {
6307     // find _LayerEdge's located before and after an offset point
6308     // (_eos._edges[ iLE ] is next after ePrev)
6309     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6310       ePrev = _eos._edges[ iLE++ ];
6311     eNext = ePrev->_2neibors->_edges[1];
6312
6313     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6314     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6315     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6316     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6317   }
6318
6319   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6320   for ( size_t i = 0; i < _offPoints.size(); i++ )
6321     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6322       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6323     else break;
6324   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6325     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6326       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6327     else break;
6328
6329   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6330
6331   int iLBO = _offPoints.size() - 2; // last but one
6332
6333   if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6334     _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6335   else
6336     _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal,       _edgeDir[0] );
6337   if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6338     _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6339   else
6340     _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal,           _edgeDir[1] );
6341   _leOnV[ 0 ]._len = 0;
6342   _leOnV[ 1 ]._len = 0;
6343   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
6344   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6345
6346   _iSeg[0] = 0;
6347   _iSeg[1] = _offPoints.size()-2;
6348
6349   // initialize OffPnt::_len
6350   for ( size_t i = 0; i < _offPoints.size(); ++i )
6351     _offPoints[i]._len = 0;
6352
6353   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6354   {
6355     _leOnV[0]._len = leOnV[0]->_len;
6356     _leOnV[1]._len = leOnV[1]->_len;
6357     for ( size_t i = 0; i < _offPoints.size(); i++ )
6358     {
6359       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6360       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6361       const double w0 = _offPoints[i]._2edges._wgt[0];
6362       const double w1 = _offPoints[i]._2edges._wgt[1];
6363       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
6364       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6365                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6366       _offPoints[i]._xyz = avgXYZ;
6367       _offPoints[i]._len = avgLen;
6368     }
6369   }
6370 }
6371
6372 //================================================================================
6373 /*!
6374  * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6375  */
6376 //================================================================================
6377
6378 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6379                                      const gp_XYZ&  edgeDir)
6380 {
6381   gp_XYZ cross = normal ^ edgeDir;
6382   gp_XYZ  norm = edgeDir ^ cross;
6383   double  size = norm.Modulus();
6384
6385   // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6386   //   return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6387
6388   return norm / size;
6389 }
6390
6391 //================================================================================
6392 /*!
6393  * \brief Writes a script creating a mesh composed of _offPoints
6394  */
6395 //================================================================================
6396
6397 void _Smoother1D::offPointsToPython() const
6398 {
6399   const char* fname = "/tmp/offPoints.py";
6400   cout << "execfile('"<<fname<<"')"<<endl;
6401   ofstream py(fname);
6402   py << "import SMESH" << endl
6403      << "from salome.smesh import smeshBuilder" << endl
6404      << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
6405      << "mesh   = smesh.Mesh( 'offPoints' )"<<endl;
6406   for ( size_t i = 0; i < _offPoints.size(); i++ )
6407   {
6408     py << "mesh.AddNode( "
6409        << _offPoints[i]._xyz.X() << ", "
6410        << _offPoints[i]._xyz.Y() << ", "
6411        << _offPoints[i]._xyz.Z() << " )" << endl;
6412   }
6413 }
6414
6415 //================================================================================
6416 /*!
6417  * \brief Sort _LayerEdge's by a parameter on a given EDGE
6418  */
6419 //================================================================================
6420
6421 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
6422                              vector< _LayerEdge* >& edges)
6423 {
6424   map< double, _LayerEdge* > u2edge;
6425   for ( size_t i = 0; i < edges.size(); ++i )
6426     u2edge.insert( u2edge.end(),
6427                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6428
6429   ASSERT( u2edge.size() == edges.size() );
6430   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6431   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6432     edges[i] = u2e->second;
6433
6434   Sort2NeiborsOnEdge( edges );
6435 }
6436
6437 //================================================================================
6438 /*!
6439  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6440  */
6441 //================================================================================
6442
6443 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6444 {
6445   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6446
6447   for ( size_t i = 0; i < edges.size()-1; ++i )
6448     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6449       edges[i]->_2neibors->reverse();
6450
6451   const size_t iLast = edges.size() - 1;
6452   if ( edges.size() > 1 &&
6453        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6454     edges[iLast]->_2neibors->reverse();
6455 }
6456
6457 //================================================================================
6458 /*!
6459  * \brief Return _EdgesOnShape* corresponding to the shape
6460  */
6461 //================================================================================
6462
6463 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6464 {
6465   if ( shapeID < (int)_edgesOnShape.size() &&
6466        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6467     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6468
6469   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6470     if ( _edgesOnShape[i]._shapeID == shapeID )
6471       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6472
6473   return 0;
6474 }
6475
6476 //================================================================================
6477 /*!
6478  * \brief Return _EdgesOnShape* corresponding to the shape
6479  */
6480 //================================================================================
6481
6482 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6483 {
6484   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6485   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6486 }
6487
6488 //================================================================================
6489 /*!
6490  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6491  */
6492 //================================================================================
6493
6494 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6495 {
6496   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6497
6498   set< TGeomID > vertices;
6499   TopoDS_Face F;
6500   if ( eos->ShapeType() == TopAbs_FACE )
6501   {
6502     // check FACE concavity and get concave VERTEXes
6503     F = TopoDS::Face( eos->_shape );
6504     if ( isConcave( F, helper, &vertices ))
6505       _concaveFaces.insert( eos->_shapeID );
6506
6507     // set eos._eosConcaVer
6508     eos->_eosConcaVer.clear();
6509     eos->_eosConcaVer.reserve( vertices.size() );
6510     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6511     {
6512       _EdgesOnShape* eov = GetShapeEdges( *v );
6513       if ( eov && eov->_edges.size() == 1 )
6514       {
6515         eos->_eosConcaVer.push_back( eov );
6516         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6517           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6518       }
6519     }
6520
6521     // SetSmooLen() to _LayerEdge's on FACE
6522     // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6523     // {
6524     //   eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6525     // }
6526     // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6527     // while ( smIt->more() ) // loop on sub-shapes of the FACE
6528     // {
6529     //   _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6530     //   if ( !eoe ) continue;
6531
6532     //   vector<_LayerEdge*>& eE = eoe->_edges;
6533     //   for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6534     //   {
6535     //     if ( eE[iE]->_cosin <= theMinSmoothCosin )
6536     //       continue;
6537
6538     //     SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6539     //     while ( segIt->more() )
6540     //     {
6541     //       const SMDS_MeshElement* seg = segIt->next();
6542     //       if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6543     //         continue;
6544     //       if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6545     //         continue; // not to check a seg twice
6546     //       for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6547     //       {
6548     //         _LayerEdge* eN = eE[iE]->_neibors[iN];
6549     //         if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6550     //           continue;
6551     //         double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6552     //         double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6553     //         eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6554     //         eN->Set( _LayerEdge::NEAR_BOUNDARY );
6555     //       }
6556     //     }
6557     //   }
6558     // }
6559   } // if ( eos->ShapeType() == TopAbs_FACE )
6560
6561   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6562   {
6563     eos->_edges[i]->_smooFunction = 0;
6564     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6565   }
6566   bool isCurved = false;
6567   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6568   {
6569     _LayerEdge* edge = eos->_edges[i];
6570
6571     // get simplices sorted
6572     _Simplex::SortSimplices( edge->_simplices );
6573
6574     // smoothing function
6575     edge->ChooseSmooFunction( vertices, _n2eMap );
6576
6577     // set _curvature
6578     double avgNormProj = 0, avgLen = 0;
6579     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6580     {
6581       _Simplex& s = edge->_simplices[iS];
6582
6583       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6584       avgNormProj += edge->_normal * vec;
6585       avgLen      += vec.Modulus();
6586       if ( substituteSrcNodes )
6587       {
6588         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6589         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6590       }
6591     }
6592     avgNormProj /= edge->_simplices.size();
6593     avgLen      /= edge->_simplices.size();
6594     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6595     {
6596       edge->Set( _LayerEdge::SMOOTHED_C1 );
6597       isCurved = true;
6598       SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6599       if ( !fPos )
6600         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6601           fPos = edge->_simplices[iS]._nPrev->GetPosition();
6602       if ( fPos )
6603         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6604     }
6605   }
6606
6607   // prepare for putOnOffsetSurface()
6608   if (( eos->ShapeType() == TopAbs_FACE ) &&
6609       ( isCurved || !eos->_eosConcaVer.empty() ))
6610   {
6611     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6612     eos->_edgeForOffset = 0;
6613
6614     double maxCosin = -1;
6615     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6616     {
6617       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6618       if ( !eoe || eoe->_edges.empty() ) continue;
6619
6620       vector<_LayerEdge*>& eE = eoe->_edges;
6621       _LayerEdge* e = eE[ eE.size() / 2 ];
6622       if ( e->_cosin > maxCosin )
6623       {
6624         eos->_edgeForOffset = e;
6625         maxCosin = e->_cosin;
6626       }
6627     }
6628   }
6629 }
6630
6631 //================================================================================
6632 /*!
6633  * \brief Add faces for smoothing
6634  */
6635 //================================================================================
6636
6637 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6638                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6639 {
6640   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6641   for ( ; eos != eosToSmooth.end(); ++eos )
6642   {
6643     if ( !*eos || (*eos)->_toSmooth ) continue;
6644
6645     (*eos)->_toSmooth = true;
6646
6647     if ( (*eos)->ShapeType() == TopAbs_FACE )
6648     {
6649       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6650       (*eos)->_toSmooth = true;
6651     }
6652   }
6653
6654   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6655   if ( edgesNoAnaSmooth )
6656     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6657     {
6658       if ( (*eos)->_edgeSmoother )
6659         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6660     }
6661 }
6662
6663 //================================================================================
6664 /*!
6665  * \brief Limit _LayerEdge::_maxLen according to local curvature
6666  */
6667 //================================================================================
6668
6669 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6670 {
6671   // find intersection of neighbor _LayerEdge's to limit _maxLen
6672   // according to local curvature (IPAL52648)
6673
6674   // This method must be called after findCollisionEdges() where _LayerEdge's
6675   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6676
6677   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6678   {
6679     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6680     if ( eosI._edges.empty() ) continue;
6681     if ( !eosI._hyp.ToSmooth() )
6682     {
6683       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6684       {
6685         _LayerEdge* eI = eosI._edges[i];
6686         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6687         {
6688           _LayerEdge* eN = eI->_neibors[iN];
6689           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6690           {
6691             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6692             limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
6693           }
6694         }
6695       }
6696     }
6697     else if ( eosI.ShapeType() == TopAbs_EDGE )
6698     {
6699       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6700       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6701
6702       _LayerEdge* e0 = eosI._edges[0];
6703       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6704       {
6705         _LayerEdge* eI = eosI._edges[i];
6706         limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
6707         e0 = eI;
6708       }
6709     }
6710   }
6711 }
6712
6713 //================================================================================
6714 /*!
6715  * \brief Limit _LayerEdge::_maxLen according to local curvature
6716  */
6717 //================================================================================
6718
6719 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*    e1,
6720                                               _LayerEdge*    e2,
6721                                               _EdgesOnShape& eos1,
6722                                               _EdgesOnShape& eos2,
6723                                               const bool     isSmoothable )
6724 {
6725   if (( e1->_nodes[0]->GetPosition()->GetDim() !=
6726         e2->_nodes[0]->GetPosition()->GetDim() ) &&
6727       ( e1->_cosin < 0.75 ))
6728     return; // angle > 90 deg at e1
6729
6730   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6731   double norSize = plnNorm.SquareModulus();
6732   if ( norSize < std::numeric_limits<double>::min() )
6733     return; // parallel normals
6734
6735   // find closest points of skew _LayerEdge's
6736   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6737   gp_XYZ dir12 = src2 - src1;
6738   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6739   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6740   double  dot1 = perp2 * e1->_normal;
6741   double  dot2 = perp1 * e2->_normal;
6742   double    u1 =   ( perp2 * dir12 ) / dot1;
6743   double    u2 = - ( perp1 * dir12 ) / dot2;
6744   if ( u1 > 0 && u2 > 0 )
6745   {
6746     double ovl = ( u1 * e1->_normal * dir12 -
6747                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6748     if ( ovl > theSmoothThickToElemSizeRatio )
6749     {
6750       const double coef = 0.75;
6751       e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
6752       e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
6753     }
6754   }
6755 }
6756
6757 //================================================================================
6758 /*!
6759  * \brief Fill data._collisionEdges
6760  */
6761 //================================================================================
6762
6763 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6764 {
6765   data._collisionEdges.clear();
6766
6767   // set the full thickness of the layers to LEs
6768   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6769   {
6770     _EdgesOnShape& eos = data._edgesOnShape[iS];
6771     if ( eos._edges.empty() ) continue;
6772     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6773     if ( !eos._sWOL.IsNull() ) continue; // PAL23566
6774
6775     for ( size_t i = 0; i < eos._edges.size(); ++i )
6776     {
6777       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6778       double maxLen = eos._edges[i]->_maxLen;
6779       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6780       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6781       eos._edges[i]->_maxLen = maxLen;
6782     }
6783   }
6784
6785   // make temporary quadrangles got by extrusion of
6786   // mesh edges along _LayerEdge._normal's
6787
6788   vector< const SMDS_MeshElement* > tmpFaces;
6789
6790   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6791   {
6792     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6793     if ( eos.ShapeType() != TopAbs_EDGE )
6794       continue;
6795     if ( eos._edges.empty() )
6796     {
6797       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6798       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6799       while ( smIt->more() )
6800         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6801           if ( eov->_edges.size() == 1 )
6802             edge[ bool( edge[0]) ] = eov->_edges[0];
6803
6804       if ( edge[1] )
6805       {
6806         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6807         tmpFaces.push_back( f );
6808       }
6809     }
6810     for ( size_t i = 0; i < eos._edges.size(); ++i )
6811     {
6812       _LayerEdge* edge = eos._edges[i];
6813       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6814       {
6815         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6816         if ( src2->GetPosition()->GetDim() > 0 &&
6817              src2->GetID() < edge->_nodes[0]->GetID() )
6818           continue; // avoid using same segment twice
6819
6820         // a _LayerEdge containing tgt2
6821         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6822
6823         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6824         tmpFaces.push_back( f );
6825       }
6826     }
6827   }
6828
6829   // Find _LayerEdge's intersecting tmpFaces.
6830
6831   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6832                                                             tmpFaces.end()));
6833   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6834     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6835
6836   double dist1, dist2, segLen, eps = 0.5;
6837   _CollisionEdges collEdges;
6838   vector< const SMDS_MeshElement* > suspectFaces;
6839   const double angle45 = Cos( 45. * M_PI / 180. );
6840
6841   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6842   {
6843     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6844     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6845       continue;
6846     // find sub-shapes whose VL can influence VL on eos
6847     set< TGeomID > neighborShapes;
6848     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6849     while ( const TopoDS_Shape* face = fIt->next() )
6850     {
6851       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6852       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6853       {
6854         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6855         while ( subIt->more() )
6856           neighborShapes.insert( subIt->next()->GetId() );
6857       }
6858     }
6859     if ( eos.ShapeType() == TopAbs_VERTEX )
6860     {
6861       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6862       while ( const TopoDS_Shape* edge = eIt->next() )
6863         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6864     }
6865     // find intersecting _LayerEdge's
6866     for ( size_t i = 0; i < eos._edges.size(); ++i )
6867     {
6868       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6869       _LayerEdge*   edge = eos._edges[i];
6870       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6871       segLen *= 1.2;
6872
6873       gp_Vec eSegDir0, eSegDir1;
6874       if ( edge->IsOnEdge() )
6875       {
6876         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6877         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6878         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6879       }
6880       suspectFaces.clear();
6881       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6882                                      SMDSAbs_Face, suspectFaces );
6883       collEdges._intEdges.clear();
6884       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6885       {
6886         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6887         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6888         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6889         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6890         if ( edge->IsOnEdge() ) {
6891           if ( edge->_2neibors->include( f->_le1 ) ||
6892                edge->_2neibors->include( f->_le2 )) continue;
6893         }
6894         else {
6895           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6896               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6897         }
6898         dist1 = dist2 = Precision::Infinite();
6899         if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
6900           dist1 = Precision::Infinite();
6901         if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
6902           dist2 = Precision::Infinite();
6903         if (( dist1 > segLen ) && ( dist2 > segLen ))
6904           continue;
6905
6906         if ( edge->IsOnEdge() )
6907         {
6908           // skip perpendicular EDGEs
6909           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
6910           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6911                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6912                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6913                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6914           if ( !isParallel )
6915             continue;
6916         }
6917
6918         // either limit inflation of edges or remember them for updating _normal
6919         // double dot = edge->_normal * f->GetDir();
6920         // if ( dot > 0.1 )
6921         {
6922           collEdges._intEdges.push_back( f->_le1 );
6923           collEdges._intEdges.push_back( f->_le2 );
6924         }
6925         // else
6926         // {
6927         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6928         //   edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
6929         // }
6930       }
6931
6932       if ( !collEdges._intEdges.empty() )
6933       {
6934         collEdges._edge = edge;
6935         data._collisionEdges.push_back( collEdges );
6936       }
6937     }
6938   }
6939
6940   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6941     delete tmpFaces[i];
6942
6943   // restore the zero thickness
6944   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6945   {
6946     _EdgesOnShape& eos = data._edgesOnShape[iS];
6947     if ( eos._edges.empty() ) continue;
6948     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6949
6950     for ( size_t i = 0; i < eos._edges.size(); ++i )
6951     {
6952       eos._edges[i]->InvalidateStep( 1, eos );
6953       eos._edges[i]->_len = 0;
6954     }
6955   }
6956 }
6957
6958 //================================================================================
6959 /*!
6960  * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
6961  *        will be updated at each inflation step
6962  */
6963 //================================================================================
6964
6965 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
6966                                                              _SolidData&         data,
6967                                                              SMESH_MesherHelper& helper )
6968 {
6969   const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
6970   const double       preci = BRep_Tool::Tolerance( convFace._face );
6971   Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
6972
6973   bool edgesToUpdateFound = false;
6974
6975   map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6976   for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6977   {
6978     _EdgesOnShape& eos = * id2eos->second;
6979     if ( !eos._sWOL.IsNull() ) continue;
6980     if ( !eos._hyp.ToSmooth() ) continue;
6981     for ( size_t i = 0; i < eos._edges.size(); ++i )
6982     {
6983       _LayerEdge* ledge = eos._edges[ i ];
6984       if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
6985       if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
6986
6987       gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
6988                         ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
6989
6990       // the normal must be updated if distance from tgtPos to surface is less than
6991       // target thickness
6992
6993       // find an initial UV for search of a projection of tgtPos to surface
6994       const SMDS_MeshNode* nodeInFace = 0;
6995       SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6996       while ( fIt->more() && !nodeInFace )
6997       {
6998         const SMDS_MeshElement* f = fIt->next();
6999         if ( convFaceID != f->getshapeId() ) continue;
7000
7001         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7002         while ( nIt->more() && !nodeInFace )
7003         {
7004           const SMDS_MeshElement* n = nIt->next();
7005           if ( n->getshapeId() == convFaceID )
7006             nodeInFace = static_cast< const SMDS_MeshNode* >( n );
7007         }
7008       }
7009       if ( !nodeInFace )
7010         continue;
7011       gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
7012
7013       // projection
7014       surface->NextValueOfUV( uv, tgtPos, preci );
7015       double  dist = surface->Gap();
7016       if ( dist < 0.95 * ledge->_maxLen )
7017       {
7018         ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
7019         if ( !ledge->_curvature ) ledge->_curvature = _Factory::NewCurvature();
7020         ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
7021         edgesToUpdateFound = true;
7022       }
7023     }
7024   }
7025
7026   if ( !convFace._isTooCurved && edgesToUpdateFound )
7027   {
7028     data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
7029   }
7030 }
7031
7032 //================================================================================
7033 /*!
7034  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
7035  * _LayerEdge's on neighbor EDGE's
7036  */
7037 //================================================================================
7038
7039 bool _ViscousBuilder::updateNormals( _SolidData&         data,
7040                                      SMESH_MesherHelper& helper,
7041                                      int                 stepNb,
7042                                      double              stepSize)
7043 {
7044   updateNormalsOfC1Vertices( data );
7045
7046   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
7047     return false;
7048
7049   // map to store new _normal and _cosin for each intersected edge
7050   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
7051   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
7052   _LayerEdge zeroEdge;
7053   zeroEdge._normal.SetCoord( 0,0,0 );
7054   zeroEdge._maxLen = Precision::Infinite();
7055   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
7056
7057   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
7058
7059   double segLen, dist1, dist2, dist;
7060   vector< pair< _LayerEdge*, double > > intEdgesDist;
7061   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
7062
7063   for ( int iter = 0; iter < 5; ++iter )
7064   {
7065     edge2newEdge.clear();
7066
7067     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
7068     {
7069       _CollisionEdges& ce = data._collisionEdges[iE];
7070       _LayerEdge*   edge1 = ce._edge;
7071       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
7072       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7073       if ( !eos1 ) continue;
7074
7075       // detect intersections
7076       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
7077       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
7078       double     eps = 0.5;
7079       intEdgesDist.clear();
7080       double minIntDist = Precision::Infinite();
7081       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
7082       {
7083         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7084              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
7085              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
7086           continue;
7087         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
7088         double fact = ( 1.1 + dot * dot );
7089         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7090         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7091         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7092         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7093         dist1 = dist2 = Precision::Infinite();
7094         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
7095              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7096           continue;
7097         dist = dist1;
7098         if ( dist > testLen || dist <= 0 )
7099         {
7100           dist = dist2;
7101           if ( dist > testLen || dist <= 0 )
7102             continue;
7103         }
7104         // choose a closest edge
7105         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7106         double d1 = intP.SquareDistance( pSrc0 );
7107         double d2 = intP.SquareDistance( pSrc1 );
7108         int iClose = i + ( d2 < d1 );
7109         _LayerEdge* edge2 = ce._intEdges[iClose];
7110         edge2->Unset( _LayerEdge::MARKED );
7111
7112         // choose a closest edge among neighbors
7113         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7114         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7115         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7116         {
7117           _LayerEdge * edgeJ = intEdgesDist[j].first;
7118           if ( edge2->IsNeiborOnEdge( edgeJ ))
7119           {
7120             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7121             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7122           }
7123         }
7124         intEdgesDist.push_back( make_pair( edge2, dist ));
7125         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7126         // {
7127         //   iClose = i + !( d2 < d1 );
7128         //   intEdges.push_back( ce._intEdges[iClose] );
7129         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7130         // }
7131         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7132       }
7133
7134       //ce._edge = 0;
7135
7136       // compute new _normals
7137       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7138       {
7139         _LayerEdge* edge2   = intEdgesDist[i].first;
7140         double      distWgt = edge1->_len / intEdgesDist[i].second;
7141         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7142         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
7143         if ( edge2->Is( _LayerEdge::MARKED )) continue;
7144         edge2->Set( _LayerEdge::MARKED );
7145
7146         // get a new normal
7147         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7148
7149         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7150         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7151         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7152         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
7153         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7154         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7155         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7156         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7157         newNormal.Normalize();
7158
7159         // get new cosin
7160         double newCos;
7161         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7162         if ( cos1 < theMinSmoothCosin )
7163         {
7164           newCos = cos2 * sgn1;
7165         }
7166         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7167         {
7168           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7169         }
7170         else
7171         {
7172           newCos = edge1->_cosin;
7173         }
7174
7175         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7176         e2neIt->second._normal += distWgt * newNormal;
7177         e2neIt->second._cosin   = newCos;
7178         e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7179         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7180           e2neIt->second._normal += dir2;
7181
7182         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7183         e2neIt->second._normal += distWgt * newNormal;
7184         if ( Precision::IsInfinite( zeroEdge._maxLen ))
7185         {
7186           e2neIt->second._cosin  = edge2->_cosin;
7187           e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7188         }
7189         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7190           e2neIt->second._normal += dir1;
7191       }
7192     }
7193
7194     if ( edge2newEdge.empty() )
7195       break; //return true;
7196
7197     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7198
7199     // Update data of edges depending on a new _normal
7200
7201     data.UnmarkEdges();
7202     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7203     {
7204       _LayerEdge*    edge = e2neIt->first;
7205       _LayerEdge& newEdge = e2neIt->second;
7206       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
7207       if ( edge->Is( _LayerEdge::BLOCKED && newEdge._maxLen > edge->_len ))
7208         continue;
7209
7210       // Check if a new _normal is OK:
7211       newEdge._normal.Normalize();
7212       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7213       {
7214         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7215         {
7216           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7217           edge->SetMaxLen( newEdge._maxLen );
7218           edge->SetNewLength( newEdge._maxLen, *eos, helper );
7219         }
7220         continue; // the new _normal is bad
7221       }
7222       // the new _normal is OK
7223
7224       // find shapes that need smoothing due to change of _normal
7225       if ( edge->_cosin   < theMinSmoothCosin &&
7226            newEdge._cosin > theMinSmoothCosin )
7227       {
7228         if ( eos->_sWOL.IsNull() )
7229         {
7230           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7231           while ( fIt->more() )
7232             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7233         }
7234         else // edge inflates along a FACE
7235         {
7236           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7237           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7238           while ( const TopoDS_Shape* E = eIt->next() )
7239           {
7240             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7241             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7242             if ( angle < M_PI / 2 )
7243               shapesToSmooth.insert( data.GetShapeEdges( *E ));
7244           }
7245         }
7246       }
7247
7248       double len = edge->_len;
7249       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7250       edge->SetNormal( newEdge._normal );
7251       edge->SetCosin( newEdge._cosin );
7252       edge->SetNewLength( len, *eos, helper );
7253       edge->Set( _LayerEdge::MARKED );
7254       edge->Set( _LayerEdge::NORMAL_UPDATED );
7255       edgesNoAnaSmooth.insert( eos );
7256     }
7257
7258     // Update normals and other dependent data of not intersecting _LayerEdge's
7259     // neighboring the intersecting ones
7260
7261     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7262     {
7263       _LayerEdge*   edge1 = e2neIt->first;
7264       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7265       if ( !edge1->Is( _LayerEdge::MARKED ))
7266         continue;
7267
7268       if ( edge1->IsOnEdge() )
7269       {
7270         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7271         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7272         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7273       }
7274
7275       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7276         continue;
7277       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7278       {
7279         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7280         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7281           continue; // j-th neighbor is also intersected
7282         _LayerEdge* prevEdge = edge1;
7283         const int nbSteps = 10;
7284         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7285         {
7286           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7287                neighbor->Is( _LayerEdge::MARKED ))
7288             break;
7289           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7290           if ( !eos ) continue;
7291           _LayerEdge* nextEdge = neighbor;
7292           if ( neighbor->_2neibors )
7293           {
7294             int iNext = 0;
7295             nextEdge = neighbor->_2neibors->_edges[iNext];
7296             if ( nextEdge == prevEdge )
7297               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7298           }
7299           double r = double(step-1)/nbSteps/(iter+1);
7300           if ( !nextEdge->_2neibors )
7301             r = Min( r, 0.5 );
7302
7303           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7304           newNorm.Normalize();
7305           if ( !isNewNormalOk( data, *neighbor, newNorm ))
7306             break;
7307
7308           double len = neighbor->_len;
7309           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7310           neighbor->SetNormal( newNorm );
7311           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7312           if ( neighbor->_2neibors )
7313             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7314           neighbor->SetNewLength( len, *eos, helper );
7315           neighbor->Set( _LayerEdge::MARKED );
7316           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7317           edgesNoAnaSmooth.insert( eos );
7318
7319           if ( !neighbor->_2neibors )
7320             break; // neighbor is on VERTEX
7321
7322           // goto the next neighbor
7323           prevEdge = neighbor;
7324           neighbor = nextEdge;
7325         }
7326       }
7327     }
7328     dumpFunctionEnd();
7329   } // iterations
7330
7331   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7332
7333   return true;
7334 }
7335
7336 //================================================================================
7337 /*!
7338  * \brief Check if a new normal is OK
7339  */
7340 //================================================================================
7341
7342 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
7343                                      _LayerEdge&   edge,
7344                                      const gp_XYZ& newNormal)
7345 {
7346   // check a min angle between the newNormal and surrounding faces
7347   vector<_Simplex> simplices;
7348   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7349   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7350   double newMinDot = 1, curMinDot = 1;
7351   for ( size_t i = 0; i < simplices.size(); ++i )
7352   {
7353     n1.Set( simplices[i]._nPrev );
7354     n2.Set( simplices[i]._nNext );
7355     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7356     double normLen2 = normFace.SquareModulus();
7357     if ( normLen2 < std::numeric_limits<double>::min() )
7358       continue;
7359     normFace /= Sqrt( normLen2 );
7360     newMinDot = Min( newNormal    * normFace, newMinDot );
7361     curMinDot = Min( edge._normal * normFace, curMinDot );
7362   }
7363   bool ok = true;
7364   if ( newMinDot < 0.5 )
7365   {
7366     ok = ( newMinDot >= curMinDot * 0.9 );
7367     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7368     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7369     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7370   }
7371
7372   return ok;
7373 }
7374
7375 //================================================================================
7376 /*!
7377  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7378  */
7379 //================================================================================
7380
7381 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
7382                                                SMESH_MesherHelper& helper,
7383                                                const int           nbSteps,
7384                                                const double        stepSize )
7385 {
7386   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7387     return true; // no shapes needing smoothing
7388
7389   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7390   {
7391     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7392     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
7393          !eos._hyp.ToSmooth() ||
7394          eos.ShapeType() != TopAbs_FACE ||
7395          eos._edges.empty() )
7396       continue;
7397
7398     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7399     if ( !toSmooth ) continue;
7400
7401     for ( size_t i = 0; i < eos._edges.size(); ++i )
7402     {
7403       _LayerEdge* edge = eos._edges[i];
7404       if ( !edge->Is( _LayerEdge::SMOOTHED ))
7405         continue;
7406       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7407         continue;
7408
7409       const gp_XYZ& pPrev = edge->PrevPos();
7410       const gp_XYZ& pLast = edge->_pos.back();
7411       gp_XYZ      stepVec = pLast - pPrev;
7412       double realStepSize = stepVec.Modulus();
7413       if ( realStepSize < numeric_limits<double>::min() )
7414         continue;
7415
7416       edge->_lenFactor = realStepSize / stepSize;
7417       edge->_normal    = stepVec / realStepSize;
7418       edge->Set( _LayerEdge::NORMAL_UPDATED );
7419     }
7420   }
7421
7422   return true;
7423 }
7424
7425 //================================================================================
7426 /*!
7427  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7428  */
7429 //================================================================================
7430
7431 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7432 {
7433   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7434   {
7435     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7436     if ( eov._eosC1.empty() ||
7437          eov.ShapeType() != TopAbs_VERTEX ||
7438          eov._edges.empty() )
7439       continue;
7440
7441     gp_XYZ newNorm   = eov._edges[0]->_normal;
7442     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7443     bool normChanged = false;
7444
7445     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7446     {
7447       _EdgesOnShape*   eoe = eov._eosC1[i];
7448       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7449       const double    eLen = SMESH_Algo::EdgeLength( e );
7450       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
7451       if ( oppV.IsSame( eov._shape ))
7452         oppV = SMESH_MesherHelper::IthVertex( 1, e );
7453       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7454       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7455       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7456
7457       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7458       if ( curThickOpp + curThick < eLen )
7459         continue;
7460
7461       double wgt = 2. * curThick / eLen;
7462       newNorm += wgt * eovOpp->_edges[0]->_normal;
7463       normChanged = true;
7464     }
7465     if ( normChanged )
7466     {
7467       eov._edges[0]->SetNormal( newNorm.Normalized() );
7468       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7469     }
7470   }
7471 }
7472
7473 //================================================================================
7474 /*!
7475  * \brief Modify normals of _LayerEdge's on _ConvexFace's
7476  */
7477 //================================================================================
7478
7479 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
7480                                                   SMESH_MesherHelper& helper,
7481                                                   int                 stepNb )
7482 {
7483   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7484   bool isOK;
7485
7486   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7487   for ( ; id2face != data._convexFaces.end(); ++id2face )
7488   {
7489     _ConvexFace & convFace = (*id2face).second;
7490     convFace._normalsFixedOnBorders = false; // to update at each inflation step
7491
7492     if ( convFace._normalsFixed )
7493       continue; // already fixed
7494     if ( convFace.CheckPrisms() )
7495       continue; // nothing to fix
7496
7497     convFace._normalsFixed = true;
7498
7499     BRepAdaptor_Surface surface ( convFace._face, false );
7500     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
7501
7502     // check if the convex FACE is of spherical shape
7503
7504     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7505     Bnd_B3d nodesBox;
7506     gp_Pnt  center;
7507
7508     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7509     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7510     {
7511       _EdgesOnShape& eos = *(id2eos->second);
7512       if ( eos.ShapeType() == TopAbs_VERTEX )
7513       {
7514         _LayerEdge* ledge = eos._edges[ 0 ];
7515         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7516           centersBox.Add( center );
7517       }
7518       for ( size_t i = 0; i < eos._edges.size(); ++i )
7519         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7520     }
7521     if ( centersBox.IsVoid() )
7522     {
7523       debugMsg( "Error: centersBox.IsVoid()" );
7524       return false;
7525     }
7526     const bool isSpherical =
7527       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7528
7529     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7530     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7531
7532     if ( isSpherical )
7533     {
7534       // set _LayerEdge::_normal as average of all normals
7535
7536       // WARNING: different density of nodes on EDGEs is not taken into account that
7537       // can lead to an improper new normal
7538
7539       gp_XYZ avgNormal( 0,0,0 );
7540       nbEdges = 0;
7541       id2eos = convFace._subIdToEOS.begin();
7542       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7543       {
7544         _EdgesOnShape& eos = *(id2eos->second);
7545         // set data of _CentralCurveOnEdge
7546         if ( eos.ShapeType() == TopAbs_EDGE )
7547         {
7548           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7549           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7550           if ( !eos._sWOL.IsNull() )
7551             ceCurve._adjFace.Nullify();
7552           else
7553             ceCurve._ledges.insert( ceCurve._ledges.end(),
7554                                     eos._edges.begin(), eos._edges.end());
7555         }
7556         // summarize normals
7557         for ( size_t i = 0; i < eos._edges.size(); ++i )
7558           avgNormal += eos._edges[ i ]->_normal;
7559       }
7560       double normSize = avgNormal.SquareModulus();
7561       if ( normSize < 1e-200 )
7562       {
7563         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7564         return false;
7565       }
7566       avgNormal /= Sqrt( normSize );
7567
7568       // compute new _LayerEdge::_cosin on EDGEs
7569       double avgCosin = 0;
7570       int     nbCosin = 0;
7571       gp_Vec inFaceDir;
7572       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7573       {
7574         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7575         if ( ceCurve._adjFace.IsNull() )
7576           continue;
7577         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7578         {
7579           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7580           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7581           if ( isOK )
7582           {
7583             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7584             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7585             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7586             nbCosin++;
7587           }
7588         }
7589       }
7590       if ( nbCosin > 0 )
7591         avgCosin /= nbCosin;
7592
7593       // set _LayerEdge::_normal = avgNormal
7594       id2eos = convFace._subIdToEOS.begin();
7595       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7596       {
7597         _EdgesOnShape& eos = *(id2eos->second);
7598         if ( eos.ShapeType() != TopAbs_EDGE )
7599           for ( size_t i = 0; i < eos._edges.size(); ++i )
7600             eos._edges[ i ]->_cosin = avgCosin;
7601
7602         for ( size_t i = 0; i < eos._edges.size(); ++i )
7603         {
7604           eos._edges[ i ]->SetNormal( avgNormal );
7605           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7606         }
7607       }
7608     }
7609     else // if ( isSpherical )
7610     {
7611       // We suppose that centers of curvature at all points of the FACE
7612       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7613       // having a common center of curvature we define the same new normal
7614       // as a sum of normals of _LayerEdge's on EDGEs among them.
7615
7616       // get all centers of curvature for each EDGE
7617
7618       helper.SetSubShape( convFace._face );
7619       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7620
7621       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7622       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7623       {
7624         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7625
7626         // set adjacent FACE
7627         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7628
7629         // get _LayerEdge's of the EDGE
7630         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7631         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7632         if ( !eos || eos->_edges.empty() )
7633         {
7634           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7635           for ( int iV = 0; iV < 2; ++iV )
7636           {
7637             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7638             TGeomID     vID = meshDS->ShapeToIndex( v );
7639             eos = data.GetShapeEdges( vID );
7640             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7641           }
7642           edgeLEdge    = &vertexLEdges[0];
7643           edgeLEdgeEnd = edgeLEdge + 2;
7644
7645           centerCurves[ iE ]._adjFace.Nullify();
7646         }
7647         else
7648         {
7649           if ( ! eos->_toSmooth )
7650             data.SortOnEdge( edge, eos->_edges );
7651           edgeLEdge    = &eos->_edges[ 0 ];
7652           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7653           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7654           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7655
7656           if ( ! eos->_sWOL.IsNull() )
7657             centerCurves[ iE ]._adjFace.Nullify();
7658         }
7659
7660         // Get curvature centers
7661
7662         centersBox.Clear();
7663
7664         if ( edgeLEdge[0]->IsOnEdge() &&
7665              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7666         { // 1st VERTEX
7667           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7668           centersBox.Add( center );
7669         }
7670         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7671           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7672           { // EDGE or VERTEXes
7673             centerCurves[ iE ].Append( center, *edgeLEdge );
7674             centersBox.Add( center );
7675           }
7676         if ( edgeLEdge[-1]->IsOnEdge() &&
7677              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7678         { // 2nd VERTEX
7679           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7680           centersBox.Add( center );
7681         }
7682         centerCurves[ iE ]._isDegenerated =
7683           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7684
7685       } // loop on EDGES of convFace._face to set up data of centerCurves
7686
7687       // Compute new normals for _LayerEdge's on EDGEs
7688
7689       double avgCosin = 0;
7690       int     nbCosin = 0;
7691       gp_Vec inFaceDir;
7692       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7693       {
7694         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7695         if ( ceCurve._isDegenerated )
7696           continue;
7697         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7698         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7699         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7700         {
7701           isOK = false;
7702           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7703           {
7704             if ( iE1 != iE2 )
7705               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7706           }
7707           if ( isOK && !ceCurve._adjFace.IsNull() )
7708           {
7709             // compute new _LayerEdge::_cosin
7710             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7711             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7712             if ( isOK )
7713             {
7714               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7715               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7716               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7717               nbCosin++;
7718             }
7719           }
7720         }
7721       }
7722       // set new normals to _LayerEdge's of NOT degenerated central curves
7723       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7724       {
7725         if ( centerCurves[ iE ]._isDegenerated )
7726           continue;
7727         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7728         {
7729           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7730           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7731         }
7732       }
7733       // set new normals to _LayerEdge's of     degenerated central curves
7734       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7735       {
7736         if ( !centerCurves[ iE ]._isDegenerated ||
7737              centerCurves[ iE ]._ledges.size() < 3 )
7738           continue;
7739         // new normal is an average of new normals at VERTEXes that
7740         // was computed on non-degenerated _CentralCurveOnEdge's
7741         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7742                            centerCurves[ iE ]._ledges.back ()->_normal );
7743         double sz = newNorm.Modulus();
7744         if ( sz < 1e-200 )
7745           continue;
7746         newNorm /= sz;
7747         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7748                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7749         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7750         {
7751           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7752           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7753           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7754         }
7755       }
7756
7757       // Find new normals for _LayerEdge's based on FACE
7758
7759       if ( nbCosin > 0 )
7760         avgCosin /= nbCosin;
7761       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7762       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7763       if ( id2eos != convFace._subIdToEOS.end() )
7764       {
7765         int iE = 0;
7766         gp_XYZ newNorm;
7767         _EdgesOnShape& eos = * ( id2eos->second );
7768         for ( size_t i = 0; i < eos._edges.size(); ++i )
7769         {
7770           _LayerEdge* ledge = eos._edges[ i ];
7771           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7772             continue;
7773           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7774           {
7775             iE = iE % centerCurves.size();
7776             if ( centerCurves[ iE ]._isDegenerated )
7777               continue;
7778             newNorm.SetCoord( 0,0,0 );
7779             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7780             {
7781               ledge->SetNormal( newNorm );
7782               ledge->_cosin  = avgCosin;
7783               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7784               break;
7785             }
7786           }
7787         }
7788       }
7789
7790     } // not a quasi-spherical FACE
7791
7792     // Update _LayerEdge's data according to a new normal
7793
7794     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7795                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7796
7797     id2eos = convFace._subIdToEOS.begin();
7798     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7799     {
7800       _EdgesOnShape& eos = * ( id2eos->second );
7801       for ( size_t i = 0; i < eos._edges.size(); ++i )
7802       {
7803         _LayerEdge* & ledge = eos._edges[ i ];
7804         double len = ledge->_len;
7805         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7806         ledge->SetCosin( ledge->_cosin );
7807         ledge->SetNewLength( len, eos, helper );
7808       }
7809       if ( eos.ShapeType() != TopAbs_FACE )
7810         for ( size_t i = 0; i < eos._edges.size(); ++i )
7811         {
7812           _LayerEdge* ledge = eos._edges[ i ];
7813           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7814           {
7815             _LayerEdge* neibor = ledge->_neibors[iN];
7816             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7817             {
7818               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7819               neibor->Set( _LayerEdge::MOVED );
7820               neibor->SetSmooLen( neibor->_len );
7821             }
7822           }
7823         }
7824     } // loop on sub-shapes of convFace._face
7825
7826     // Find FACEs adjacent to convFace._face that got necessity to smooth
7827     // as a result of normals modification
7828
7829     set< _EdgesOnShape* > adjFacesToSmooth;
7830     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7831     {
7832       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7833            centerCurves[ iE ]._adjFaceToSmooth )
7834         continue;
7835       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7836       {
7837         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7838         {
7839           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7840           break;
7841         }
7842       }
7843     }
7844     data.AddShapesToSmooth( adjFacesToSmooth );
7845
7846     dumpFunctionEnd();
7847
7848
7849   } // loop on data._convexFaces
7850
7851   return true;
7852 }
7853
7854 //================================================================================
7855 /*!
7856  * \brief Return max curvature of a FACE
7857  */
7858 //================================================================================
7859
7860 double _ConvexFace::GetMaxCurvature( _SolidData&         data,
7861                                      _EdgesOnShape&      eof,
7862                                      BRepLProp_SLProps&  surfProp,
7863                                      SMESH_MesherHelper& helper)
7864 {
7865   double maxCurvature = 0;
7866
7867   TopoDS_Face F = TopoDS::Face( eof._shape );
7868
7869   const int           nbTestPnt = 5;
7870   const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7871   SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7872   while ( smIt->more() )
7873   {
7874     SMESH_subMesh* sm = smIt->next();
7875     const TGeomID subID = sm->GetId();
7876
7877     // find _LayerEdge's of a sub-shape
7878     _EdgesOnShape* eos;
7879     if (( eos = data.GetShapeEdges( subID )))
7880       this->_subIdToEOS.insert( make_pair( subID, eos ));
7881     else
7882       continue;
7883
7884     // check concavity and curvature and limit data._stepSize
7885     const double minCurvature =
7886       1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7887     size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7888     for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7889     {
7890       gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7891       surfProp.SetParameters( uv.X(), uv.Y() );
7892       if ( surfProp.IsCurvatureDefined() )
7893       {
7894         double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7895                                 surfProp.MinCurvature() * oriFactor );
7896         maxCurvature = Max( maxCurvature, curvature );
7897
7898         if ( curvature > minCurvature )
7899           this->_isTooCurved = true;
7900       }
7901     }
7902   } // loop on sub-shapes of the FACE
7903
7904   return maxCurvature;
7905 }
7906
7907 //================================================================================
7908 /*!
7909  * \brief Finds a center of curvature of a surface at a _LayerEdge
7910  */
7911 //================================================================================
7912
7913 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7914                                         BRepLProp_SLProps&  surfProp,
7915                                         SMESH_MesherHelper& helper,
7916                                         gp_Pnt &            center ) const
7917 {
7918   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7919   surfProp.SetParameters( uv.X(), uv.Y() );
7920   if ( !surfProp.IsCurvatureDefined() )
7921     return false;
7922
7923   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7924   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7925   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7926   if ( surfCurvatureMin > surfCurvatureMax )
7927     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7928   else
7929     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7930
7931   return true;
7932 }
7933
7934 //================================================================================
7935 /*!
7936  * \brief Check that prisms are not distorted
7937  */
7938 //================================================================================
7939
7940 bool _ConvexFace::CheckPrisms() const
7941 {
7942   double vol = 0;
7943   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7944   {
7945     const _LayerEdge* edge = _simplexTestEdges[i];
7946     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7947     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7948       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7949       {
7950         debugMsg( "Bad simplex of _simplexTestEdges ("
7951                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7952                   << " "<< edge->_simplices[j]._nPrev->GetID()
7953                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7954         return false;
7955       }
7956   }
7957   return true;
7958 }
7959
7960 //================================================================================
7961 /*!
7962  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7963  *        stored in this _CentralCurveOnEdge.
7964  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7965  *  \param [in,out] newNormal - current normal at this point, to be redefined
7966  *  \return bool - true if succeeded.
7967  */
7968 //================================================================================
7969
7970 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7971 {
7972   if ( this->_isDegenerated )
7973     return false;
7974
7975   // find two centers the given one lies between
7976
7977   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7978   {
7979     double sl2 = 1.001 * _segLength2[ i ];
7980
7981     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7982     if ( d1 > sl2 )
7983       continue;
7984     
7985     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7986     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7987       continue;
7988
7989     d1 = Sqrt( d1 );
7990     d2 = Sqrt( d2 );
7991     double r = d1 / ( d1 + d2 );
7992     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7993                    (      r ) * _ledges[ i+1 ]->_normal );
7994     norm.Normalize();
7995
7996     newNormal += norm;
7997     double sz = newNormal.Modulus();
7998     if ( sz < 1e-200 )
7999       break;
8000     newNormal /= sz;
8001     return true;
8002   }
8003   return false;
8004 }
8005
8006 //================================================================================
8007 /*!
8008  * \brief Set shape members
8009  */
8010 //================================================================================
8011
8012 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
8013                                      const _ConvexFace&  convFace,
8014                                      _SolidData&         data,
8015                                      SMESH_MesherHelper& helper)
8016 {
8017   _edge = edge;
8018
8019   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
8020   while ( const TopoDS_Shape* F = fIt->next())
8021     if ( !convFace._face.IsSame( *F ))
8022     {
8023       _adjFace = TopoDS::Face( *F );
8024       _adjFaceToSmooth = false;
8025       // _adjFace already in a smoothing queue ?
8026       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
8027         _adjFaceToSmooth = eos->_toSmooth;
8028       break;
8029     }
8030 }
8031
8032 //================================================================================
8033 /*!
8034  * \brief Looks for intersection of it's last segment with faces
8035  *  \param distance - returns shortest distance from the last node to intersection
8036  */
8037 //================================================================================
8038
8039 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
8040                                    double &                 distance,
8041                                    const double&            epsilon,
8042                                    _EdgesOnShape&           eos,
8043                                    const SMDS_MeshElement** intFace)
8044 {
8045   vector< const SMDS_MeshElement* > suspectFaces;
8046   double segLen;
8047   gp_Ax1 lastSegment = LastSegment( segLen, eos );
8048   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
8049
8050   bool segmentIntersected = false;
8051   distance = Precision::Infinite();
8052   int iFace = -1; // intersected face
8053   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
8054   {
8055     const SMDS_MeshElement* face = suspectFaces[j];
8056     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
8057          face->GetNodeIndex( _nodes[0]     ) >= 0 )
8058       continue; // face sharing _LayerEdge node
8059     const int nbNodes = face->NbCornerNodes();
8060     bool intFound = false;
8061     double dist;
8062     SMDS_MeshElement::iterator nIt = face->begin_nodes();
8063     if ( nbNodes == 3 )
8064     {
8065       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
8066     }
8067     else
8068     {
8069       const SMDS_MeshNode* tria[3];
8070       tria[0] = *nIt++;
8071       tria[1] = *nIt++;
8072       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
8073       {
8074         tria[2] = *nIt++;
8075         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
8076         tria[1] = tria[2];
8077       }
8078     }
8079     if ( intFound )
8080     {
8081       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
8082         segmentIntersected = true;
8083       if ( distance > dist )
8084         distance = dist, iFace = j;
8085     }
8086   }
8087   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8088
8089   distance -= segLen;
8090
8091   if ( segmentIntersected )
8092   {
8093 #ifdef __myDEBUG
8094     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8095     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8096     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8097          << ", intersection with face ("
8098          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8099          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8100          << ") distance = " << distance << endl;
8101 #endif
8102   }
8103
8104   return segmentIntersected;
8105 }
8106
8107 //================================================================================
8108 /*!
8109  * \brief Returns a point used to check orientation of _simplices
8110  */
8111 //================================================================================
8112
8113 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8114 {
8115   size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8116
8117   if ( !eos || eos->_sWOL.IsNull() )
8118     return _pos[ i ];
8119
8120   if ( eos->SWOLType() == TopAbs_EDGE )
8121   {
8122     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8123   }
8124   //else //  TopAbs_FACE
8125
8126   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8127 }
8128
8129 //================================================================================
8130 /*!
8131  * \brief Returns size and direction of the last segment
8132  */
8133 //================================================================================
8134
8135 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8136 {
8137   // find two non-coincident positions
8138   gp_XYZ orig = _pos.back();
8139   gp_XYZ vec;
8140   int iPrev = _pos.size() - 2;
8141   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8142   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8143   while ( iPrev >= 0 )
8144   {
8145     vec = orig - _pos[iPrev];
8146     if ( vec.SquareModulus() > tol*tol )
8147       break;
8148     else
8149       iPrev--;
8150   }
8151
8152   // make gp_Ax1
8153   gp_Ax1 segDir;
8154   if ( iPrev < 0 )
8155   {
8156     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8157     segDir.SetDirection( _normal );
8158     segLen = 0;
8159   }
8160   else
8161   {
8162     gp_Pnt pPrev = _pos[ iPrev ];
8163     if ( !eos._sWOL.IsNull() )
8164     {
8165       TopLoc_Location loc;
8166       if ( eos.SWOLType() == TopAbs_EDGE )
8167       {
8168         double f,l;
8169         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8170         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8171       }
8172       else
8173       {
8174         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8175         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8176       }
8177       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8178     }
8179     segDir.SetLocation( pPrev );
8180     segDir.SetDirection( vec );
8181     segLen = vec.Modulus();
8182   }
8183
8184   return segDir;
8185 }
8186
8187 //================================================================================
8188 /*!
8189  * \brief Return the last (or \a which) position of the target node on a FACE. 
8190  *  \param [in] F - the FACE this _LayerEdge is inflated along
8191  *  \param [in] which - index of position
8192  *  \return gp_XY - result UV
8193  */
8194 //================================================================================
8195
8196 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8197 {
8198   if ( F.IsSame( eos._sWOL )) // F is my FACE
8199     return gp_XY( _pos.back().X(), _pos.back().Y() );
8200
8201   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8202     return gp_XY( 1e100, 1e100 );
8203
8204   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8205   double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8206   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8207   if ( !C2d.IsNull() && f <= u && u <= l )
8208     return C2d->Value( u ).XY();
8209
8210   return gp_XY( 1e100, 1e100 );
8211 }
8212
8213 //================================================================================
8214 /*!
8215  * \brief Test intersection of the last segment with a given triangle
8216  *   using Moller-Trumbore algorithm
8217  * Intersection is detected if distance to intersection is less than _LayerEdge._len
8218  */
8219 //================================================================================
8220
8221 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8222                                const gp_XYZ& vert0,
8223                                const gp_XYZ& vert1,
8224                                const gp_XYZ& vert2,
8225                                double&       t,
8226                                const double& EPSILON) const
8227 {
8228   const gp_Pnt& orig = lastSegment.Location();
8229   const gp_Dir& dir  = lastSegment.Direction();
8230
8231   /* calculate distance from vert0 to ray origin */
8232   //gp_XYZ tvec = orig.XYZ() - vert0;
8233
8234   //if ( tvec * dir > EPSILON )
8235     // intersected face is at back side of the temporary face this _LayerEdge belongs to
8236     //return false;
8237
8238   gp_XYZ edge1 = vert1 - vert0;
8239   gp_XYZ edge2 = vert2 - vert0;
8240
8241   /* begin calculating determinant - also used to calculate U parameter */
8242   gp_XYZ pvec = dir.XYZ() ^ edge2;
8243
8244   /* if determinant is near zero, ray lies in plane of triangle */
8245   double det = edge1 * pvec;
8246
8247   const double ANGL_EPSILON = 1e-12;
8248   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8249     return false;
8250
8251   /* calculate distance from vert0 to ray origin */
8252   gp_XYZ tvec = orig.XYZ() - vert0;
8253
8254   /* calculate U parameter and test bounds */
8255   double u = ( tvec * pvec ) / det;
8256   //if (u < 0.0 || u > 1.0)
8257   if ( u < -EPSILON || u > 1.0 + EPSILON )
8258     return false;
8259
8260   /* prepare to test V parameter */
8261   gp_XYZ qvec = tvec ^ edge1;
8262
8263   /* calculate V parameter and test bounds */
8264   double v = (dir.XYZ() * qvec) / det;
8265   //if ( v < 0.0 || u + v > 1.0 )
8266   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8267     return false;
8268
8269   /* calculate t, ray intersects triangle */
8270   t = (edge2 * qvec) / det;
8271
8272   //return true;
8273   return t > 0.;
8274 }
8275
8276 //================================================================================
8277 /*!
8278  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8279  *        neighbor _LayerEdge's by it's own inflation vector.
8280  *  \param [in] eov - EOS of the VERTEX
8281  *  \param [in] eos - EOS of the FACE
8282  *  \param [in] step - inflation step
8283  *  \param [in,out] badSmooEdges - tangled _LayerEdge's
8284  */
8285 //================================================================================
8286
8287 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
8288                                    const _EdgesOnShape*    eos,
8289                                    const int               step,
8290                                    vector< _LayerEdge* > & badSmooEdges )
8291 {
8292   // check if any of _neibors is in badSmooEdges
8293   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8294                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8295     return;
8296
8297   // get all edges to move
8298
8299   set< _LayerEdge* > edges;
8300
8301   // find a distance between _LayerEdge on VERTEX and its neighbors
8302   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
8303   double dist2 = 0;
8304   for ( size_t i = 0; i < _neibors.size(); ++i )
8305   {
8306     _LayerEdge* nEdge = _neibors[i];
8307     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8308     {
8309       edges.insert( nEdge );
8310       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8311     }
8312   }
8313   // add _LayerEdge's close to curPosV
8314   size_t nbE;
8315   do {
8316     nbE = edges.size();
8317     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8318     {
8319       _LayerEdge* edgeF = *e;
8320       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8321       {
8322         _LayerEdge* nEdge = edgeF->_neibors[i];
8323         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8324              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8325           edges.insert( nEdge );
8326       }
8327     }
8328   }
8329   while ( nbE < edges.size() );
8330
8331   // move the target node of the got edges
8332
8333   gp_XYZ prevPosV = PrevPos();
8334   if ( eov->SWOLType() == TopAbs_EDGE )
8335   {
8336     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8337     prevPosV = curve.Value( prevPosV.X() ).XYZ();
8338   }
8339   else if ( eov->SWOLType() == TopAbs_FACE )
8340   {
8341     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8342     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8343   }
8344
8345   SMDS_FacePositionPtr fPos;
8346   //double r = 1. - Min( 0.9, step / 10. );
8347   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8348   {
8349     _LayerEdge*       edgeF = *e;
8350     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
8351     const gp_XYZ    newPosF = curPosV + prevVF;
8352     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8353     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8354     edgeF->_pos.back() = newPosF;
8355     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8356
8357     // set _curvature to make edgeF updated by putOnOffsetSurface()
8358     if ( !edgeF->_curvature )
8359       if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8360       {
8361         edgeF->_curvature = _Factory::NewCurvature();
8362         edgeF->_curvature->_r = 0;
8363         edgeF->_curvature->_k = 0;
8364         edgeF->_curvature->_h2lenRatio = 0;
8365         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8366       }
8367   }
8368   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8369   //                      SMESH_TNodeXYZ( _nodes[0]    ));
8370   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8371   // {
8372   //   _LayerEdge*      edgeF = *e;
8373   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8374   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8375   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8376   //   edgeF->_pos.back() = newPosF;
8377   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8378   // }
8379
8380   // smooth _LayerEdge's around moved nodes
8381   //size_t nbBadBefore = badSmooEdges.size();
8382   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8383   {
8384     _LayerEdge* edgeF = *e;
8385     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8386       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8387         //&& !edges.count( edgeF->_neibors[j] ))
8388       {
8389         _LayerEdge* edgeFN = edgeF->_neibors[j];
8390         edgeFN->Unset( SMOOTHED );
8391         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8392         // if ( nbBad > 0 )
8393         // {
8394         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8395         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8396         //   int        nbBadAfter = edgeFN->_simplices.size();
8397         //   double vol;
8398         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8399         //   {
8400         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8401         //   }
8402         //   if ( nbBadAfter <= nbBad )
8403         //   {
8404         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8405         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8406         //     edgeF->_pos.back() = newPosF;
8407         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8408         //     nbBad = nbBadAfter;
8409         //   }
8410         // }
8411         if ( nbBad > 0 )
8412           badSmooEdges.push_back( edgeFN );
8413       }
8414   }
8415     // move a bit not smoothed around moved nodes
8416   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8417   //   {
8418   //   _LayerEdge*      edgeF = badSmooEdges[i];
8419   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8420   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8421   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8422   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8423   //   edgeF->_pos.back() = newPosF;
8424   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8425   // }
8426 }
8427
8428 //================================================================================
8429 /*!
8430  * \brief Perform smooth of _LayerEdge's based on EDGE's
8431  *  \retval bool - true if node has been moved
8432  */
8433 //================================================================================
8434
8435 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8436                               const TopoDS_Face&             F,
8437                               SMESH_MesherHelper&            helper)
8438 {
8439   ASSERT( IsOnEdge() );
8440
8441   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8442   SMESH_TNodeXYZ oldPos( tgtNode );
8443   double dist01, distNewOld;
8444   
8445   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8446   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8447   dist01 = p0.Distance( _2neibors->tgtNode(1) );
8448
8449   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8450   double lenDelta = 0;
8451   if ( _curvature )
8452   {
8453     //lenDelta = _curvature->lenDelta( _len );
8454     lenDelta = _curvature->lenDeltaByDist( dist01 );
8455     newPos.ChangeCoord() += _normal * lenDelta;
8456   }
8457
8458   distNewOld = newPos.Distance( oldPos );
8459
8460   if ( F.IsNull() )
8461   {
8462     if ( _2neibors->_plnNorm )
8463     {
8464       // put newPos on the plane defined by source node and _plnNorm
8465       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8466       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8467       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8468     }
8469     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8470     _pos.back() = newPos.XYZ();
8471   }
8472   else
8473   {
8474     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8475     gp_XY uv( Precision::Infinite(), 0 );
8476     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8477     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8478
8479     newPos = surface->Value( uv );
8480     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8481   }
8482
8483   // commented for IPAL0052478
8484   // if ( _curvature && lenDelta < 0 )
8485   // {
8486   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8487   //   _len -= prevPos.Distance( oldPos );
8488   //   _len += prevPos.Distance( newPos );
8489   // }
8490   bool moved = distNewOld > dist01/50;
8491   //if ( moved )
8492   dumpMove( tgtNode ); // debug
8493
8494   return moved;
8495 }
8496
8497 //================================================================================
8498 /*!
8499  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8500  */
8501 //================================================================================
8502
8503 void _LayerEdge::SmoothWoCheck()
8504 {
8505   if ( Is( DIFFICULT ))
8506     return;
8507
8508   bool moved = Is( SMOOTHED );
8509   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
8510     moved = _neibors[i]->Is( SMOOTHED );
8511   if ( !moved )
8512     return;
8513
8514   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8515
8516   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8517   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8518   _pos.back() = newPos;
8519
8520   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8521 }
8522
8523 //================================================================================
8524 /*!
8525  * \brief Checks validity of _neibors on EDGEs and VERTEXes
8526  */
8527 //================================================================================
8528
8529 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8530 {
8531   if ( ! Is( NEAR_BOUNDARY ))
8532     return 0;
8533
8534   int nbBad = 0;
8535   double vol;
8536   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8537   {
8538     _LayerEdge* eN = _neibors[iN];
8539     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8540       continue;
8541     if ( needSmooth )
8542       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8543                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8544                        eN->_pos.size() != _pos.size() );
8545
8546     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8547     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8548     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8549       if ( eN->_nodes.size() > 1 &&
8550            eN->_simplices[i].Includes( _nodes.back() ) &&
8551            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8552       {
8553         ++nbBad;
8554         if ( badNeibors )
8555         {
8556           badNeibors->push_back( eN );
8557           debugMsg("Bad boundary simplex ( "
8558                    << " "<< eN->_nodes[0]->GetID()
8559                    << " "<< eN->_nodes.back()->GetID()
8560                    << " "<< eN->_simplices[i]._nPrev->GetID()
8561                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8562         }
8563         else
8564         {
8565           break;
8566         }
8567       }
8568   }
8569   return nbBad;
8570 }
8571
8572 //================================================================================
8573 /*!
8574  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8575  *  \retval int - nb of bad simplices around this _LayerEdge
8576  */
8577 //================================================================================
8578
8579 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8580 {
8581   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8582     return 0; // shape of simplices not changed
8583   if ( _simplices.size() < 2 )
8584     return 0; // _LayerEdge inflated along EDGE or FACE
8585
8586   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8587     findBest = true;
8588
8589   const gp_XYZ& curPos  = _pos.back();
8590   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8591
8592   // quality metrics (orientation) of tetras around _tgtNode
8593   int nbOkBefore = 0;
8594   double vol, minVolBefore = 1e100;
8595   for ( size_t i = 0; i < _simplices.size(); ++i )
8596   {
8597     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8598     minVolBefore = Min( minVolBefore, vol );
8599   }
8600   int nbBad = _simplices.size() - nbOkBefore;
8601
8602   bool bndNeedSmooth = false;
8603   if ( nbBad == 0 )
8604     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8605   if ( nbBad > 0 )
8606     Set( DISTORTED );
8607
8608   // evaluate min angle
8609   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8610   {
8611     size_t nbGoodAngles = _simplices.size();
8612     double angle;
8613     for ( size_t i = 0; i < _simplices.size(); ++i )
8614     {
8615       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8616         --nbGoodAngles;
8617     }
8618     if ( nbGoodAngles == _simplices.size() )
8619     {
8620       Unset( MOVED );
8621       return 0;
8622     }
8623   }
8624   if ( Is( ON_CONCAVE_FACE ))
8625     findBest = true;
8626
8627   if ( step % 2 == 0 )
8628     findBest = false;
8629
8630   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8631   {
8632     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8633       _smooFunction = _funs[ FUN_CENTROIDAL ];
8634     else
8635       _smooFunction = _funs[ FUN_LAPLACIAN ];
8636   }
8637
8638   // compute new position for the last _pos using different _funs
8639   gp_XYZ newPos;
8640   bool moved = false;
8641   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8642   {
8643     if ( iFun < 0 )
8644       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8645     else if ( _funs[ iFun ] == _smooFunction )
8646       continue; // _smooFunction again
8647     else if ( step > 1 )
8648       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8649     else
8650       break; // let "easy" functions improve elements around distorted ones
8651
8652     if ( _curvature )
8653     {
8654       double delta  = _curvature->lenDelta( _len );
8655       if ( delta > 0 )
8656         newPos += _normal * delta;
8657       else
8658       {
8659         double segLen = _normal * ( newPos - prevPos );
8660         if ( segLen + delta > 0 )
8661           newPos += _normal * delta;
8662       }
8663       // double segLenChange = _normal * ( curPos - newPos );
8664       // newPos += 0.5 * _normal * segLenChange;
8665     }
8666
8667     int nbOkAfter = 0;
8668     double minVolAfter = 1e100;
8669     for ( size_t i = 0; i < _simplices.size(); ++i )
8670     {
8671       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8672       minVolAfter = Min( minVolAfter, vol );
8673     }
8674     // get worse?
8675     if ( nbOkAfter < nbOkBefore )
8676       continue;
8677
8678     if (( findBest ) &&
8679         ( nbOkAfter == nbOkBefore ) &&
8680         ( minVolAfter <= minVolBefore ))
8681       continue;
8682
8683     nbBad        = _simplices.size() - nbOkAfter;
8684     minVolBefore = minVolAfter;
8685     nbOkBefore   = nbOkAfter;
8686     moved        = true;
8687
8688     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8689     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8690     _pos.back() = newPos;
8691
8692     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8693                   << (nbBad ? " --BAD" : ""));
8694
8695     if ( iFun > -1 )
8696     {
8697       continue; // look for a better function
8698     }
8699
8700     if ( !findBest )
8701       break;
8702
8703   } // loop on smoothing functions
8704
8705   if ( moved ) // notify _neibors
8706   {
8707     Set( SMOOTHED );
8708     for ( size_t i = 0; i < _neibors.size(); ++i )
8709       if ( !_neibors[i]->Is( MOVED ))
8710       {
8711         _neibors[i]->Set( MOVED );
8712         toSmooth.push_back( _neibors[i] );
8713       }
8714   }
8715
8716   return nbBad;
8717 }
8718
8719 //================================================================================
8720 /*!
8721  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8722  *  \retval int - nb of bad simplices around this _LayerEdge
8723  */
8724 //================================================================================
8725
8726 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8727 {
8728   if ( !_smooFunction )
8729     return 0; // _LayerEdge inflated along EDGE or FACE
8730   if ( Is( BLOCKED ))
8731     return 0; // not inflated
8732
8733   const gp_XYZ& curPos  = _pos.back();
8734   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8735
8736   // quality metrics (orientation) of tetras around _tgtNode
8737   int nbOkBefore = 0;
8738   double vol, minVolBefore = 1e100;
8739   for ( size_t i = 0; i < _simplices.size(); ++i )
8740   {
8741     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8742     minVolBefore = Min( minVolBefore, vol );
8743   }
8744   int nbBad = _simplices.size() - nbOkBefore;
8745
8746   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8747   {
8748     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8749       _smooFunction = _funs[ FUN_LAPLACIAN ];
8750     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8751       _smooFunction = _funs[ FUN_CENTROIDAL ];
8752   }
8753
8754   // compute new position for the last _pos using different _funs
8755   gp_XYZ newPos;
8756   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8757   {
8758     if ( iFun < 0 )
8759       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8760     else if ( _funs[ iFun ] == _smooFunction )
8761       continue; // _smooFunction again
8762     else if ( step > 1 )
8763       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8764     else
8765       break; // let "easy" functions improve elements around distorted ones
8766
8767     if ( _curvature )
8768     {
8769       double delta  = _curvature->lenDelta( _len );
8770       if ( delta > 0 )
8771         newPos += _normal * delta;
8772       else
8773       {
8774         double segLen = _normal * ( newPos - prevPos );
8775         if ( segLen + delta > 0 )
8776           newPos += _normal * delta;
8777       }
8778       // double segLenChange = _normal * ( curPos - newPos );
8779       // newPos += 0.5 * _normal * segLenChange;
8780     }
8781
8782     int nbOkAfter = 0;
8783     double minVolAfter = 1e100;
8784     for ( size_t i = 0; i < _simplices.size(); ++i )
8785     {
8786       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8787       minVolAfter = Min( minVolAfter, vol );
8788     }
8789     // get worse?
8790     if ( nbOkAfter < nbOkBefore )
8791       continue;
8792     if (( isConcaveFace || findBest ) &&
8793         ( nbOkAfter == nbOkBefore ) &&
8794         ( minVolAfter <= minVolBefore )
8795         )
8796       continue;
8797
8798     nbBad        = _simplices.size() - nbOkAfter;
8799     minVolBefore = minVolAfter;
8800     nbOkBefore   = nbOkAfter;
8801
8802     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8803     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8804     _pos.back() = newPos;
8805
8806     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8807                   << ( nbBad ? "--BAD" : ""));
8808
8809     // commented for IPAL0052478
8810     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8811     // _len += prevPos.Distance(newPos);
8812
8813     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8814     {
8815       //_smooFunction = _funs[ iFun ];
8816       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8817       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8818       // << " minVol: " << minVolAfter
8819       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8820       // << endl;
8821       continue; // look for a better function
8822     }
8823
8824     if ( !findBest )
8825       break;
8826
8827   } // loop on smoothing functions
8828
8829   return nbBad;
8830 }
8831
8832 //================================================================================
8833 /*!
8834  * \brief Chooses a smoothing technique giving a position most close to an initial one.
8835  *        For a correct result, _simplices must contain nodes lying on geometry.
8836  */
8837 //================================================================================
8838
8839 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8840                                      const TNode2Edge&     n2eMap)
8841 {
8842   if ( _smooFunction ) return;
8843
8844   // use smoothNefPolygon() near concaveVertices
8845   if ( !concaveVertices.empty() )
8846   {
8847     _smooFunction = _funs[ FUN_CENTROIDAL ];
8848
8849     Set( ON_CONCAVE_FACE );
8850
8851     for ( size_t i = 0; i < _simplices.size(); ++i )
8852     {
8853       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8854       {
8855         _smooFunction = _funs[ FUN_NEFPOLY ];
8856
8857         // set FUN_CENTROIDAL to neighbor edges
8858         for ( i = 0; i < _neibors.size(); ++i )
8859         {
8860           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8861           {
8862             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8863           }
8864         }
8865         return;
8866       }
8867     }
8868
8869     // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8870     // // where the nodes are smoothed too far along a sphere thus creating
8871     // // inverted _simplices
8872     // double dist[theNbSmooFuns];
8873     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8874     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8875
8876     // double minDist = Precision::Infinite();
8877     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8878     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8879     // {
8880     //   gp_Pnt newP = (this->*_funs[i])();
8881     //   dist[i] = p.SquareDistance( newP );
8882     //   if ( dist[i]*coef[i] < minDist )
8883     //   {
8884     //     _smooFunction = _funs[i];
8885     //     minDist = dist[i]*coef[i];
8886     //   }
8887     // }
8888   }
8889   else
8890   {
8891     _smooFunction = _funs[ FUN_LAPLACIAN ];
8892   }
8893   // int minDim = 3;
8894   // for ( size_t i = 0; i < _simplices.size(); ++i )
8895   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8896   // if ( minDim == 0 )
8897   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8898   // else if ( minDim == 1 )
8899   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8900
8901
8902   // int iMin;
8903   // for ( int i = 0; i < FUN_NB; ++i )
8904   // {
8905   //   //cout << dist[i] << " ";
8906   //   if ( _smooFunction == _funs[i] ) {
8907   //     iMin = i;
8908   //     //debugMsg( fNames[i] );
8909   //     break;
8910   //   }
8911   // }
8912   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8913 }
8914
8915 //================================================================================
8916 /*!
8917  * \brief Returns a name of _SmooFunction
8918  */
8919 //================================================================================
8920
8921 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8922 {
8923   if ( !fun )
8924     fun = _smooFunction;
8925   for ( int i = 0; i < theNbSmooFuns; ++i )
8926     if ( fun == _funs[i] )
8927       return i;
8928
8929   return theNbSmooFuns;
8930 }
8931
8932 //================================================================================
8933 /*!
8934  * \brief Computes a new node position using Laplacian smoothing
8935  */
8936 //================================================================================
8937
8938 gp_XYZ _LayerEdge::smoothLaplacian()
8939 {
8940   gp_XYZ newPos (0,0,0);
8941   for ( size_t i = 0; i < _simplices.size(); ++i )
8942     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8943   newPos /= _simplices.size();
8944
8945   return newPos;
8946 }
8947
8948 //================================================================================
8949 /*!
8950  * \brief Computes a new node position using angular-based smoothing
8951  */
8952 //================================================================================
8953
8954 gp_XYZ _LayerEdge::smoothAngular()
8955 {
8956   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8957   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8958   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8959
8960   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8961   gp_XYZ pN( 0,0,0 );
8962   for ( size_t i = 0; i < _simplices.size(); ++i )
8963   {
8964     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8965     edgeDir.push_back( p - pPrev );
8966     edgeSize.push_back( edgeDir.back().Magnitude() );
8967     if ( edgeSize.back() < numeric_limits<double>::min() )
8968     {
8969       edgeDir.pop_back();
8970       edgeSize.pop_back();
8971     }
8972     else
8973     {
8974       edgeDir.back() /= edgeSize.back();
8975       points.push_back( p );
8976       pN += p;
8977     }
8978     pPrev = p;
8979   }
8980   edgeDir.push_back ( edgeDir[0] );
8981   edgeSize.push_back( edgeSize[0] );
8982   pN /= points.size();
8983
8984   gp_XYZ newPos(0,0,0);
8985   double sumSize = 0;
8986   for ( size_t i = 0; i < points.size(); ++i )
8987   {
8988     gp_Vec toN    = pN - points[i];
8989     double toNLen = toN.Magnitude();
8990     if ( toNLen < numeric_limits<double>::min() )
8991     {
8992       newPos += pN;
8993       continue;
8994     }
8995     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8996     double bisecLen = bisec.SquareMagnitude();
8997     if ( bisecLen < numeric_limits<double>::min() )
8998     {
8999       gp_Vec norm = edgeDir[i] ^ toN;
9000       bisec = norm ^ edgeDir[i];
9001       bisecLen = bisec.SquareMagnitude();
9002     }
9003     bisecLen = Sqrt( bisecLen );
9004     bisec /= bisecLen;
9005
9006 #if 1
9007     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
9008     sumSize += bisecLen;
9009 #else
9010     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
9011     sumSize += ( edgeSize[i] + edgeSize[i+1] );
9012 #endif
9013     newPos += pNew;
9014   }
9015   newPos /= sumSize;
9016
9017   // project newPos to an average plane
9018
9019   gp_XYZ norm(0,0,0); // plane normal
9020   points.push_back( points[0] );
9021   for ( size_t i = 1; i < points.size(); ++i )
9022   {
9023     gp_XYZ vec1 = points[ i-1 ] - pN;
9024     gp_XYZ vec2 = points[ i   ] - pN;
9025     gp_XYZ cross = vec1 ^ vec2;
9026     try {
9027       cross.Normalize();
9028       if ( cross * norm < numeric_limits<double>::min() )
9029         norm += cross.Reversed();
9030       else
9031         norm += cross;
9032     }
9033     catch (Standard_Failure) { // if |cross| == 0.
9034     }
9035   }
9036   gp_XYZ vec = newPos - pN;
9037   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
9038   newPos     = newPos - r * norm;
9039
9040   return newPos;
9041 }
9042
9043 //================================================================================
9044 /*!
9045  * \brief Computes a new node position using weighted node positions
9046  */
9047 //================================================================================
9048
9049 gp_XYZ _LayerEdge::smoothLengthWeighted()
9050 {
9051   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
9052   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
9053
9054   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9055   for ( size_t i = 0; i < _simplices.size(); ++i )
9056   {
9057     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9058     edgeSize.push_back( ( p - pPrev ).Modulus() );
9059     if ( edgeSize.back() < numeric_limits<double>::min() )
9060     {
9061       edgeSize.pop_back();
9062     }
9063     else
9064     {
9065       points.push_back( p );
9066     }
9067     pPrev = p;
9068   }
9069   edgeSize.push_back( edgeSize[0] );
9070
9071   gp_XYZ newPos(0,0,0);
9072   double sumSize = 0;
9073   for ( size_t i = 0; i < points.size(); ++i )
9074   {
9075     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
9076     sumSize += edgeSize[i] + edgeSize[i+1];
9077   }
9078   newPos /= sumSize;
9079   return newPos;
9080 }
9081
9082 //================================================================================
9083 /*!
9084  * \brief Computes a new node position using angular-based smoothing
9085  */
9086 //================================================================================
9087
9088 gp_XYZ _LayerEdge::smoothCentroidal()
9089 {
9090   gp_XYZ newPos(0,0,0);
9091   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9092   double sumSize = 0;
9093   for ( size_t i = 0; i < _simplices.size(); ++i )
9094   {
9095     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9096     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9097     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9098     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9099
9100     sumSize += size;
9101     newPos += gc * size;
9102   }
9103   newPos /= sumSize;
9104
9105   return newPos;
9106 }
9107
9108 //================================================================================
9109 /*!
9110  * \brief Computes a new node position located inside a Nef polygon
9111  */
9112 //================================================================================
9113
9114 gp_XYZ _LayerEdge::smoothNefPolygon()
9115 #ifdef OLD_NEF_POLYGON
9116 {
9117   gp_XYZ newPos(0,0,0);
9118
9119   // get a plane to search a solution on
9120
9121   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9122   size_t i;
9123   const double tol = numeric_limits<double>::min();
9124   gp_XYZ center(0,0,0);
9125   for ( i = 0; i < _simplices.size(); ++i )
9126   {
9127     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9128                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9129     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9130   }
9131   vecs.back() = vecs[0];
9132   center /= _simplices.size();
9133
9134   gp_XYZ zAxis(0,0,0);
9135   for ( i = 0; i < _simplices.size(); ++i )
9136     zAxis += vecs[i] ^ vecs[i+1];
9137
9138   gp_XYZ yAxis;
9139   for ( i = 0; i < _simplices.size(); ++i )
9140   {
9141     yAxis = vecs[i];
9142     if ( yAxis.SquareModulus() > tol )
9143       break;
9144   }
9145   gp_XYZ xAxis = yAxis ^ zAxis;
9146   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9147   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9148   //                             p0.Distance( _simplices[2]._nPrev ));
9149   // gp_XYZ center = smoothLaplacian();
9150   // gp_XYZ xAxis, yAxis, zAxis;
9151   // for ( i = 0; i < _simplices.size(); ++i )
9152   // {
9153   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9154   //   if ( xAxis.SquareModulus() > tol*tol )
9155   //     break;
9156   // }
9157   // for ( i = 1; i < _simplices.size(); ++i )
9158   // {
9159   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9160   //   zAxis = xAxis ^ yAxis;
9161   //   if ( zAxis.SquareModulus() > tol*tol )
9162   //     break;
9163   // }
9164   // if ( i == _simplices.size() ) return newPos;
9165
9166   yAxis = zAxis ^ xAxis;
9167   xAxis /= xAxis.Modulus();
9168   yAxis /= yAxis.Modulus();
9169
9170   // get half-planes of _simplices
9171
9172   vector< _halfPlane > halfPlns( _simplices.size() );
9173   int nbHP = 0;
9174   for ( size_t i = 0; i < _simplices.size(); ++i )
9175   {
9176     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9177     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9178     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9179     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9180     gp_XY  vec12 = p2 - p1;
9181     double dist12 = vec12.Modulus();
9182     if ( dist12 < tol )
9183       continue;
9184     vec12 /= dist12;
9185     halfPlns[ nbHP ]._pos = p1;
9186     halfPlns[ nbHP ]._dir = vec12;
9187     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9188     ++nbHP;
9189   }
9190
9191   // intersect boundaries of half-planes, define state of intersection points
9192   // in relation to all half-planes and calculate internal point of a 2D polygon
9193
9194   double sumLen = 0;
9195   gp_XY newPos2D (0,0);
9196
9197   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9198   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9199   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9200
9201   vector< vector< TIntPntState > > allIntPnts( nbHP );
9202   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9203   {
9204     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9205     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9206
9207     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9208     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9209
9210     int nbNotOut = 0;
9211     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9212
9213     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9214     {
9215       if ( iHP1 == iHP2 ) continue;
9216
9217       TIntPntState & ips1 = intPnts1[ iHP2 ];
9218       if ( ips1.second == UNDEF )
9219       {
9220         // find an intersection point of boundaries of iHP1 and iHP2
9221
9222         if ( iHP2 == iPrev ) // intersection with neighbors is known
9223           ips1.first = halfPlns[ iHP1 ]._pos;
9224         else if ( iHP2 == iNext )
9225           ips1.first = halfPlns[ iHP2 ]._pos;
9226         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9227           ips1.second = NO_INT;
9228
9229         // classify the found intersection point
9230         if ( ips1.second != NO_INT )
9231         {
9232           ips1.second = NOT_OUT;
9233           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9234             if ( i != iHP1 && i != iHP2 &&
9235                  halfPlns[ i ].IsOut( ips1.first, tol ))
9236               ips1.second = IS_OUT;
9237         }
9238         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9239         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9240         TIntPntState & ips2 = intPnts2[ iHP1 ];
9241         ips2 = ips1;
9242       }
9243       if ( ips1.second == NOT_OUT )
9244       {
9245         ++nbNotOut;
9246         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9247       }
9248     }
9249
9250     // find a NOT_OUT segment of boundary which is located between
9251     // two NOT_OUT int points
9252
9253     if ( nbNotOut < 2 )
9254       continue; // no such a segment
9255
9256     if ( nbNotOut > 2 )
9257     {
9258       // sort points along the boundary
9259       map< double, TIntPntState* > ipsByParam;
9260       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9261       {
9262         TIntPntState & ips1 = intPnts1[ iHP2 ];
9263         if ( ips1.second != NO_INT )
9264         {
9265           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9266           double param = op * halfPlns[ iHP1 ]._dir;
9267           ipsByParam.insert( make_pair( param, & ips1 ));
9268         }
9269       }
9270       // look for two neighboring NOT_OUT points
9271       nbNotOut = 0;
9272       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9273       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9274       {
9275         TIntPntState & ips1 = *(u2ips->second);
9276         if ( ips1.second == NOT_OUT )
9277           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9278         else if ( nbNotOut >= 2 )
9279           break;
9280         else
9281           nbNotOut = 0;
9282       }
9283     }
9284
9285     if ( nbNotOut >= 2 )
9286     {
9287       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9288       sumLen += len;
9289
9290       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9291     }
9292   }
9293
9294   if ( sumLen > 0 )
9295   {
9296     newPos2D /= sumLen;
9297     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9298   }
9299   else
9300   {
9301     newPos = center;
9302   }
9303
9304   return newPos;
9305 }
9306 #else // OLD_NEF_POLYGON
9307 { ////////////////////////////////// NEW
9308   gp_XYZ newPos(0,0,0);
9309
9310   // get a plane to search a solution on
9311
9312   size_t i;
9313   gp_XYZ center(0,0,0);
9314   for ( i = 0; i < _simplices.size(); ++i )
9315     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9316   center /= _simplices.size();
9317
9318   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9319   for ( i = 0; i < _simplices.size(); ++i )
9320     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9321   vecs.back() = vecs[0];
9322
9323   const double tol = numeric_limits<double>::min();
9324   gp_XYZ zAxis(0,0,0);
9325   for ( i = 0; i < _simplices.size(); ++i )
9326   {
9327     gp_XYZ cross = vecs[i] ^ vecs[i+1];
9328     try {
9329       cross.Normalize();
9330       if ( cross * zAxis < tol )
9331         zAxis += cross.Reversed();
9332       else
9333         zAxis += cross;
9334     }
9335     catch (Standard_Failure) { // if |cross| == 0.
9336     }
9337   }
9338
9339   gp_XYZ yAxis;
9340   for ( i = 0; i < _simplices.size(); ++i )
9341   {
9342     yAxis = vecs[i];
9343     if ( yAxis.SquareModulus() > tol )
9344       break;
9345   }
9346   gp_XYZ xAxis = yAxis ^ zAxis;
9347   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9348   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9349   //                             p0.Distance( _simplices[2]._nPrev ));
9350   // gp_XYZ center = smoothLaplacian();
9351   // gp_XYZ xAxis, yAxis, zAxis;
9352   // for ( i = 0; i < _simplices.size(); ++i )
9353   // {
9354   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9355   //   if ( xAxis.SquareModulus() > tol*tol )
9356   //     break;
9357   // }
9358   // for ( i = 1; i < _simplices.size(); ++i )
9359   // {
9360   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9361   //   zAxis = xAxis ^ yAxis;
9362   //   if ( zAxis.SquareModulus() > tol*tol )
9363   //     break;
9364   // }
9365   // if ( i == _simplices.size() ) return newPos;
9366
9367   yAxis = zAxis ^ xAxis;
9368   xAxis /= xAxis.Modulus();
9369   yAxis /= yAxis.Modulus();
9370
9371   // get half-planes of _simplices
9372
9373   vector< _halfPlane > halfPlns( _simplices.size() );
9374   int nbHP = 0;
9375   for ( size_t i = 0; i < _simplices.size(); ++i )
9376   {
9377     const gp_XYZ& OP1 = vecs[ i   ];
9378     const gp_XYZ& OP2 = vecs[ i+1 ];
9379     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9380     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9381     gp_XY  vec12 = p2 - p1;
9382     double dist12 = vec12.Modulus();
9383     if ( dist12 < tol )
9384       continue;
9385     vec12 /= dist12;
9386     halfPlns[ nbHP ]._pos = p1;
9387     halfPlns[ nbHP ]._dir = vec12;
9388     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9389     ++nbHP;
9390   }
9391
9392   // intersect boundaries of half-planes, define state of intersection points
9393   // in relation to all half-planes and calculate internal point of a 2D polygon
9394
9395   double sumLen = 0;
9396   gp_XY newPos2D (0,0);
9397
9398   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9399   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9400   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9401
9402   vector< vector< TIntPntState > > allIntPnts( nbHP );
9403   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9404   {
9405     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9406     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9407
9408     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9409     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9410
9411     int nbNotOut = 0;
9412     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9413
9414     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9415     {
9416       if ( iHP1 == iHP2 ) continue;
9417
9418       TIntPntState & ips1 = intPnts1[ iHP2 ];
9419       if ( ips1.second == UNDEF )
9420       {
9421         // find an intersection point of boundaries of iHP1 and iHP2
9422
9423         if ( iHP2 == iPrev ) // intersection with neighbors is known
9424           ips1.first = halfPlns[ iHP1 ]._pos;
9425         else if ( iHP2 == iNext )
9426           ips1.first = halfPlns[ iHP2 ]._pos;
9427         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9428           ips1.second = NO_INT;
9429
9430         // classify the found intersection point
9431         if ( ips1.second != NO_INT )
9432         {
9433           ips1.second = NOT_OUT;
9434           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9435             if ( i != iHP1 && i != iHP2 &&
9436                  halfPlns[ i ].IsOut( ips1.first, tol ))
9437               ips1.second = IS_OUT;
9438         }
9439         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9440         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9441         TIntPntState & ips2 = intPnts2[ iHP1 ];
9442         ips2 = ips1;
9443       }
9444       if ( ips1.second == NOT_OUT )
9445       {
9446         ++nbNotOut;
9447         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9448       }
9449     }
9450
9451     // find a NOT_OUT segment of boundary which is located between
9452     // two NOT_OUT int points
9453
9454     if ( nbNotOut < 2 )
9455       continue; // no such a segment
9456
9457     if ( nbNotOut > 2 )
9458     {
9459       // sort points along the boundary
9460       map< double, TIntPntState* > ipsByParam;
9461       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9462       {
9463         TIntPntState & ips1 = intPnts1[ iHP2 ];
9464         if ( ips1.second != NO_INT )
9465         {
9466           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9467           double param = op * halfPlns[ iHP1 ]._dir;
9468           ipsByParam.insert( make_pair( param, & ips1 ));
9469         }
9470       }
9471       // look for two neighboring NOT_OUT points
9472       nbNotOut = 0;
9473       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9474       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9475       {
9476         TIntPntState & ips1 = *(u2ips->second);
9477         if ( ips1.second == NOT_OUT )
9478           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9479         else if ( nbNotOut >= 2 )
9480           break;
9481         else
9482           nbNotOut = 0;
9483       }
9484     }
9485
9486     if ( nbNotOut >= 2 )
9487     {
9488       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9489       sumLen += len;
9490
9491       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9492     }
9493   }
9494
9495   if ( sumLen > 0 )
9496   {
9497     newPos2D /= sumLen;
9498     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9499   }
9500   else
9501   {
9502     newPos = center;
9503   }
9504
9505   return newPos;
9506 }
9507 #endif // OLD_NEF_POLYGON
9508
9509 //================================================================================
9510 /*!
9511  * \brief Add a new segment to _LayerEdge during inflation
9512  */
9513 //================================================================================
9514
9515 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9516 {
9517   if ( Is( BLOCKED ))
9518     return;
9519
9520   if ( len > _maxLen )
9521   {
9522     len = _maxLen;
9523     Block( eos.GetData() );
9524   }
9525   const double lenDelta = len - _len;
9526   if ( lenDelta < len * 1e-3  )
9527   {
9528     Block( eos.GetData() );
9529     return;
9530   }
9531
9532   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9533   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9534   gp_XYZ newXYZ;
9535   if ( eos._hyp.IsOffsetMethod() )
9536   {
9537     newXYZ = oldXYZ;
9538     gp_Vec faceNorm;
9539     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9540     while ( faceIt->more() )
9541     {
9542       const SMDS_MeshElement* face = faceIt->next();
9543       if ( !eos.GetNormal( face, faceNorm ))
9544         continue;
9545
9546       // translate plane of a face
9547       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9548
9549       // find point of intersection of the face plane located at baryCenter
9550       // and _normal located at newXYZ
9551       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9552       double dot =  ( faceNorm.XYZ() * _normal );
9553       if ( dot < std::numeric_limits<double>::min() )
9554         dot = lenDelta * 1e-3;
9555       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9556       newXYZ += step * _normal;
9557     }
9558     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9559   }
9560   else
9561   {
9562     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9563   }
9564
9565   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9566   _pos.push_back( newXYZ );
9567
9568   if ( !eos._sWOL.IsNull() )
9569   {
9570     double distXYZ[4];
9571     bool uvOK = false;
9572     if ( eos.SWOLType() == TopAbs_EDGE )
9573     {
9574       double u = Precision::Infinite(); // to force projection w/o distance check
9575       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9576                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9577       _pos.back().SetCoord( u, 0, 0 );
9578       if ( _nodes.size() > 1 && uvOK )
9579       {
9580         SMDS_EdgePositionPtr pos = n->GetPosition();
9581         pos->SetUParameter( u );
9582       }
9583     }
9584     else //  TopAbs_FACE
9585     {
9586       gp_XY uv( Precision::Infinite(), 0 );
9587       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9588                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9589       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9590       if ( _nodes.size() > 1 && uvOK )
9591       {
9592         SMDS_FacePositionPtr pos = n->GetPosition();
9593         pos->SetUParameter( uv.X() );
9594         pos->SetVParameter( uv.Y() );
9595       }
9596     }
9597     if ( uvOK )
9598     {
9599       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9600     }
9601     else
9602     {
9603       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9604       _pos.pop_back();
9605       Block( eos.GetData() );
9606       return;
9607     }
9608   }
9609
9610   _len = len;
9611
9612   // notify _neibors
9613   if ( eos.ShapeType() != TopAbs_FACE )
9614   {
9615     for ( size_t i = 0; i < _neibors.size(); ++i )
9616       //if (  _len > _neibors[i]->GetSmooLen() )
9617         _neibors[i]->Set( MOVED );
9618
9619     Set( MOVED );
9620   }
9621   dumpMove( n ); //debug
9622 }
9623
9624 //================================================================================
9625 /*!
9626  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9627  */
9628 //================================================================================
9629
9630 void _LayerEdge::Block( _SolidData& data )
9631 {
9632   //if ( Is( BLOCKED )) return;
9633   Set( BLOCKED );
9634
9635   SMESH_Comment msg( "#BLOCK shape=");
9636   msg << data.GetShapeEdges( this )->_shapeID
9637       << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9638   dumpCmd( msg + " -- BEGIN");
9639
9640   SetMaxLen( _len );
9641   std::queue<_LayerEdge*> queue;
9642   queue.push( this );
9643
9644   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9645   while ( !queue.empty() )
9646   {
9647     _LayerEdge* edge = queue.front(); queue.pop();
9648     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9649     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9650     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9651     {
9652       _LayerEdge* neibor = edge->_neibors[iN];
9653       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9654         continue;
9655       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9656       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9657       double minDist = pSrc.SquareDistance( pSrcN );
9658       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9659       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9660       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9661       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9662       //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9663       {
9664         //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9665         // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9666         //                   neibor->_lenFactor / edge->_lenFactor );
9667       }
9668       if ( neibor->_maxLen > newMaxLen )
9669       {
9670         neibor->SetMaxLen( newMaxLen );
9671         if ( neibor->_maxLen < neibor->_len )
9672         {
9673           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9674           int       lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
9675           while ( neibor->_len > neibor->_maxLen &&
9676                   neibor->NbSteps() > lastStep )
9677             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9678           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9679           //neibor->Block( data );
9680         }
9681         queue.push( neibor );
9682       }
9683     }
9684   }
9685   dumpCmd( msg + " -- END");
9686 }
9687
9688 //================================================================================
9689 /*!
9690  * \brief Remove last inflation step
9691  */
9692 //================================================================================
9693
9694 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9695 {
9696   if ( _pos.size() > curStep && _nodes.size() > 1 )
9697   {
9698     _pos.resize( curStep );
9699
9700     gp_Pnt      nXYZ = _pos.back();
9701     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9702     SMESH_TNodeXYZ curXYZ( n );
9703     if ( !eos._sWOL.IsNull() )
9704     {
9705       TopLoc_Location loc;
9706       if ( eos.SWOLType() == TopAbs_EDGE )
9707       {
9708         SMDS_EdgePositionPtr pos = n->GetPosition();
9709         pos->SetUParameter( nXYZ.X() );
9710         double f,l;
9711         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9712         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9713       }
9714       else
9715       {
9716         SMDS_FacePositionPtr pos = n->GetPosition();
9717         pos->SetUParameter( nXYZ.X() );
9718         pos->SetVParameter( nXYZ.Y() );
9719         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9720         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9721       }
9722     }
9723     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9724     dumpMove( n );
9725
9726     if ( restoreLength )
9727     {
9728       if ( NbSteps() == 0 )
9729         _len = 0.;
9730       else if ( IsOnFace() && Is( MOVED ))
9731         _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
9732       else
9733         _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9734     }
9735   }
9736   return;
9737 }
9738
9739 //================================================================================
9740 /*!
9741  * \brief Return index of a _pos distant from _normal
9742  */
9743 //================================================================================
9744
9745 int _LayerEdge::GetSmoothedPos( const double tol )
9746 {
9747   int iSmoothed = 0;
9748   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9749   {
9750     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9751     if ( normDist > tol * tol )
9752       iSmoothed = i;
9753   }
9754   return iSmoothed;
9755 }
9756
9757 //================================================================================
9758 /*!
9759  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9760  */
9761 //================================================================================
9762
9763 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9764 {
9765   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9766     return;
9767
9768   // find the 1st smoothed _pos
9769   int iSmoothed = GetSmoothedPos( tol );
9770   if ( !iSmoothed ) return;
9771
9772   gp_XYZ normal = _normal;
9773   if ( Is( NORMAL_UPDATED ))
9774   {
9775     double minDot = 1;
9776     for ( size_t i = 0; i < _neibors.size(); ++i )
9777     {
9778       if ( _neibors[i]->IsOnFace() )
9779       {
9780         double dot = _normal * _neibors[i]->_normal;
9781         if ( dot < minDot )
9782         {
9783           normal = _neibors[i]->_normal;
9784           minDot = dot;
9785         }
9786       }
9787     }
9788     if ( minDot == 1. )
9789       for ( size_t i = 1; i < _pos.size(); ++i )
9790       {
9791         normal = _pos[i] - _pos[0];
9792         double size = normal.Modulus();
9793         if ( size > RealSmall() )
9794         {
9795           normal /= size;
9796           break;
9797         }
9798       }
9799   }
9800   const double r = 0.2;
9801   for ( int iter = 0; iter < 50; ++iter )
9802   {
9803     double minDot = 1;
9804     for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9805     {
9806       gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9807       gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9808       _pos[i] = newPos;
9809       double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9810       double newLen = ( 1-r ) * midLen + r * segLen[i];
9811       const_cast< double& >( segLen[i] ) = newLen;
9812       // check angle between normal and (_pos[i+1], _pos[i] )
9813       gp_XYZ posDir = _pos[i+1] - _pos[i];
9814       double size   = posDir.SquareModulus();
9815       if ( size > RealSmall() )
9816         minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9817     }
9818     if ( minDot > 0.5 * 0.5 )
9819       break;
9820   }
9821   return;
9822 }
9823
9824 //================================================================================
9825 /*!
9826  * \brief Print flags
9827  */
9828 //================================================================================
9829
9830 std::string _LayerEdge::DumpFlags() const
9831 {
9832   SMESH_Comment dump;
9833   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9834     if ( _flags & flag )
9835     {
9836       EFlags f = (EFlags) flag;
9837       switch ( f ) {
9838       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
9839       case MOVED:           dump << "MOVED";           break;
9840       case SMOOTHED:        dump << "SMOOTHED";        break;
9841       case DIFFICULT:       dump << "DIFFICULT";       break;
9842       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9843       case BLOCKED:         dump << "BLOCKED";         break;
9844       case INTERSECTED:     dump << "INTERSECTED";     break;
9845       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
9846       case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9847       case MARKED:          dump << "MARKED";          break;
9848       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
9849       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
9850       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
9851       case DISTORTED:       dump << "DISTORTED";       break;
9852       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
9853       case SHRUNK:          dump << "SHRUNK";          break;
9854       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
9855       }
9856       dump << " ";
9857     }
9858   cout << dump << endl;
9859   return dump;
9860 }
9861
9862
9863 //================================================================================
9864 /*!
9865  * \brief Create layers of prisms
9866  */
9867 //================================================================================
9868
9869 bool _ViscousBuilder::refine(_SolidData& data)
9870 {
9871   SMESH_MesherHelper& helper = data.GetHelper();
9872   helper.SetElementsOnShape(false);
9873
9874   Handle(Geom_Curve) curve;
9875   Handle(ShapeAnalysis_Surface) surface;
9876   TopoDS_Edge geomEdge;
9877   TopoDS_Face geomFace;
9878   TopLoc_Location loc;
9879   double f,l, u = 0;
9880   gp_XY uv;
9881   vector< gp_XYZ > pos3D;
9882   bool isOnEdge, isTooConvexFace = false;
9883   TGeomID prevBaseId = -1;
9884   TNode2Edge* n2eMap = 0;
9885   TNode2Edge::iterator n2e;
9886
9887   // Create intermediate nodes on each _LayerEdge
9888
9889   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9890   {
9891     _EdgesOnShape& eos = data._edgesOnShape[iS];
9892     if ( eos._edges.empty() ) continue;
9893
9894     if ( eos._edges[0]->_nodes.size() < 2 )
9895       continue; // on _noShrinkShapes
9896
9897     // get data of a shrink shape
9898     isOnEdge = false;
9899     geomEdge.Nullify(); geomFace.Nullify();
9900     curve.Nullify(); surface.Nullify();
9901     if ( !eos._sWOL.IsNull() )
9902     {
9903       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9904       if ( isOnEdge )
9905       {
9906         geomEdge = TopoDS::Edge( eos._sWOL );
9907         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9908       }
9909       else
9910       {
9911         geomFace = TopoDS::Face( eos._sWOL );
9912         surface  = helper.GetSurface( geomFace );
9913       }
9914     }
9915     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9916     {
9917       geomFace = TopoDS::Face( eos._shape );
9918       surface  = helper.GetSurface( geomFace );
9919       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9920       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9921         eos._eosC1[ i ]->_toSmooth = true;
9922
9923       isTooConvexFace = false;
9924       if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
9925         isTooConvexFace = cf->_isTooCurved;
9926     }
9927
9928     vector< double > segLen;
9929     for ( size_t i = 0; i < eos._edges.size(); ++i )
9930     {
9931       _LayerEdge& edge = *eos._edges[i];
9932       if ( edge._pos.size() < 2 )
9933         continue;
9934
9935       // get accumulated length of segments
9936       segLen.resize( edge._pos.size() );
9937       segLen[0] = 0.0;
9938       if ( eos._sWOL.IsNull() )
9939       {
9940         bool useNormal = true;
9941         bool    usePos = false;
9942         bool  smoothed = false;
9943         double   preci = 0.1 * edge._len;
9944         if ( eos._toSmooth && edge._pos.size() > 2 )
9945         {
9946           smoothed = edge.GetSmoothedPos( preci );
9947         }
9948         if ( smoothed )
9949         {
9950           if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
9951           {
9952             useNormal = usePos = false;
9953             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9954             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9955             {
9956               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9957               if ( surface->Gap() < 2. * edge._len )
9958                 segLen[j] = surface->Gap();
9959               else
9960                 useNormal = true;
9961             }
9962           }
9963         }
9964         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9965         {
9966 #ifndef __NODES_AT_POS
9967           useNormal = usePos = false;
9968           edge._pos[1] = edge._pos.back();
9969           edge._pos.resize( 2 );
9970           segLen.resize( 2 );
9971           segLen[ 1 ] = edge._len;
9972 #endif
9973         }
9974         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9975         {
9976           useNormal = usePos = false;
9977           _LayerEdge tmpEdge; // get original _normal
9978           tmpEdge._nodes.push_back( edge._nodes[0] );
9979           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9980             usePos = true;
9981           else
9982             for ( size_t j = 1; j < edge._pos.size(); ++j )
9983               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9984         }
9985         if ( useNormal )
9986         {
9987           for ( size_t j = 1; j < edge._pos.size(); ++j )
9988             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9989         }
9990         if ( usePos )
9991         {
9992           for ( size_t j = 1; j < edge._pos.size(); ++j )
9993             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9994         }
9995         else
9996         {
9997           bool swapped = ( edge._pos.size() > 2 );
9998           while ( swapped )
9999           {
10000             swapped = false;
10001             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
10002               if ( segLen[j] > segLen.back() )
10003               {
10004                 segLen.erase( segLen.begin() + j );
10005                 edge._pos.erase( edge._pos.begin() + j );
10006                 --j;
10007               }
10008               else if ( segLen[j] < segLen[j-1] )
10009               {
10010                 std::swap( segLen[j], segLen[j-1] );
10011                 std::swap( edge._pos[j], edge._pos[j-1] );
10012                 swapped = true;
10013               }
10014           }
10015         }
10016         // smooth a path formed by edge._pos
10017 #ifndef __NODES_AT_POS
10018         if (( smoothed ) /*&&
10019             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
10020           edge.SmoothPos( segLen, preci );
10021 #endif
10022       }
10023       else if ( eos._isRegularSWOL ) // usual SWOL
10024       {
10025         if ( edge.Is( _LayerEdge::SMOOTHED ))
10026         {
10027           SMESH_NodeXYZ p0( edge._nodes[0] );
10028           for ( size_t j = 1; j < edge._pos.size(); ++j )
10029           {
10030             gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10031             segLen[j] = ( pj - p0 ) * edge._normal;
10032           }
10033         }
10034         else
10035         {
10036           for ( size_t j = 1; j < edge._pos.size(); ++j )
10037             segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
10038         }
10039       }
10040       else if ( !surface.IsNull() ) // SWOL surface with singularities
10041       {
10042         pos3D.resize( edge._pos.size() );
10043         for ( size_t j = 0; j < edge._pos.size(); ++j )
10044           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10045
10046         for ( size_t j = 1; j < edge._pos.size(); ++j )
10047           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
10048       }
10049
10050       // allocate memory for new nodes if it is not yet refined
10051       const SMDS_MeshNode* tgtNode = edge._nodes.back();
10052       if ( edge._nodes.size() == 2 )
10053       {
10054 #ifdef __NODES_AT_POS
10055         int nbNodes = edge._pos.size();
10056 #else
10057         int nbNodes = eos._hyp.GetNumberLayers() + 1;
10058 #endif
10059         edge._nodes.resize( nbNodes, 0 );
10060         edge._nodes[1] = 0;
10061         edge._nodes.back() = tgtNode;
10062       }
10063       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
10064       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
10065       if ( baseShapeId != prevBaseId )
10066       {
10067         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
10068         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
10069         prevBaseId = baseShapeId;
10070       }
10071       _LayerEdge* edgeOnSameNode = 0;
10072       bool        useExistingPos = false;
10073       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
10074       {
10075         edgeOnSameNode = n2e->second;
10076         useExistingPos = ( edgeOnSameNode->_len < edge._len );
10077         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
10078         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
10079         if ( isOnEdge )
10080         {
10081           SMDS_EdgePositionPtr epos = lastPos;
10082           epos->SetUParameter( otherTgtPos.X() );
10083         }
10084         else
10085         {
10086           SMDS_FacePositionPtr fpos = lastPos;
10087           fpos->SetUParameter( otherTgtPos.X() );
10088           fpos->SetVParameter( otherTgtPos.Y() );
10089         }
10090       }
10091       // calculate height of the first layer
10092       double h0;
10093       const double T = segLen.back(); //data._hyp.GetTotalThickness();
10094       const double f = eos._hyp.GetStretchFactor();
10095       const int    N = eos._hyp.GetNumberLayers();
10096       const double fPowN = pow( f, N );
10097       if ( fPowN - 1 <= numeric_limits<double>::min() )
10098         h0 = T / N;
10099       else
10100         h0 = T * ( f - 1 )/( fPowN - 1 );
10101
10102       const double zeroLen = std::numeric_limits<double>::min();
10103
10104       // create intermediate nodes
10105       double hSum = 0, hi = h0/f;
10106       size_t iSeg = 1;
10107       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10108       {
10109         // compute an intermediate position
10110         hi *= f;
10111         hSum += hi;
10112         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10113           ++iSeg;
10114         int iPrevSeg = iSeg-1;
10115         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10116           --iPrevSeg;
10117         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10118         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10119 #ifdef __NODES_AT_POS
10120         pos = edge._pos[ iStep ];
10121 #endif
10122         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10123         if ( !eos._sWOL.IsNull() )
10124         {
10125           // compute XYZ by parameters <pos>
10126           if ( isOnEdge )
10127           {
10128             u = pos.X();
10129             if ( !node )
10130               pos = curve->Value( u ).Transformed(loc);
10131           }
10132           else if ( eos._isRegularSWOL )
10133           {
10134             uv.SetCoord( pos.X(), pos.Y() );
10135             if ( !node )
10136               pos = surface->Value( pos.X(), pos.Y() );
10137           }
10138           else
10139           {
10140             uv.SetCoord( pos.X(), pos.Y() );
10141             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10142             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10143             if ( !node )
10144               pos = surface->Value( uv );
10145           }
10146         }
10147         // create or update the node
10148         if ( !node )
10149         {
10150           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10151           if ( !eos._sWOL.IsNull() )
10152           {
10153             if ( isOnEdge )
10154               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10155             else
10156               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10157           }
10158           else
10159           {
10160             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10161           }
10162         }
10163         else
10164         {
10165           if ( !eos._sWOL.IsNull() )
10166           {
10167             // make average pos from new and current parameters
10168             if ( isOnEdge )
10169             {
10170               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10171               if ( useExistingPos )
10172                 u = helper.GetNodeU( geomEdge, node );
10173               pos = curve->Value( u ).Transformed(loc);
10174
10175               SMDS_EdgePositionPtr epos = node->GetPosition();
10176               epos->SetUParameter( u );
10177             }
10178             else
10179             {
10180               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10181               if ( useExistingPos )
10182                 uv = helper.GetNodeUV( geomFace, node );
10183               pos = surface->Value( uv );
10184
10185               SMDS_FacePositionPtr fpos = node->GetPosition();
10186               fpos->SetUParameter( uv.X() );
10187               fpos->SetVParameter( uv.Y() );
10188             }
10189           }
10190           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10191         }
10192       } // loop on edge._nodes
10193
10194       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10195       {
10196         if ( isOnEdge )
10197           edge._pos.back().SetCoord( u, 0,0);
10198         else
10199           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10200
10201         if ( edgeOnSameNode )
10202           edgeOnSameNode->_pos.back() = edge._pos.back();
10203       }
10204
10205     } // loop on eos._edges to create nodes
10206
10207
10208     if ( !getMeshDS()->IsEmbeddedMode() )
10209       // Log node movement
10210       for ( size_t i = 0; i < eos._edges.size(); ++i )
10211       {
10212         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10213         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10214       }
10215   }
10216
10217
10218   // Create volumes
10219
10220   helper.SetElementsOnShape(true);
10221
10222   vector< vector<const SMDS_MeshNode*>* > nnVec;
10223   set< vector<const SMDS_MeshNode*>* >    nnSet;
10224   set< int >                       degenEdgeInd;
10225   vector<const SMDS_MeshElement*>     degenVols;
10226
10227   TopExp_Explorer exp( data._solid, TopAbs_FACE );
10228   for ( ; exp.More(); exp.Next() )
10229   {
10230     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10231     if ( data._ignoreFaceIds.count( faceID ))
10232       continue;
10233     const bool isReversedFace = data._reversedFaceIds.count( faceID );
10234     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
10235     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
10236     while ( fIt->more() )
10237     {
10238       const SMDS_MeshElement* face = fIt->next();
10239       const int            nbNodes = face->NbCornerNodes();
10240       nnVec.resize( nbNodes );
10241       nnSet.clear();
10242       degenEdgeInd.clear();
10243       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10244       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10245       for ( int iN = 0; iN < nbNodes; ++iN )
10246       {
10247         const SMDS_MeshNode* n = nIt->next();
10248         _LayerEdge*       edge = data._n2eMap[ n ];
10249         const int i = isReversedFace ? nbNodes-1-iN : iN;
10250         nnVec[ i ] = & edge->_nodes;
10251         maxZ = std::max( maxZ, nnVec[ i ]->size() );
10252         minZ = std::min( minZ, nnVec[ i ]->size() );
10253
10254         if ( helper.HasDegeneratedEdges() )
10255           nnSet.insert( nnVec[ i ]);
10256       }
10257
10258       if ( maxZ == 0 )
10259         continue;
10260       if ( 0 < nnSet.size() && nnSet.size() < 3 )
10261         continue;
10262
10263       switch ( nbNodes )
10264       {
10265       case 3: // TRIA
10266       {
10267         // PENTA
10268         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10269           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10270                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
10271
10272         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10273         {
10274           for ( int iN = 0; iN < nbNodes; ++iN )
10275             if ( nnVec[ iN ]->size() < iZ+1 )
10276               degenEdgeInd.insert( iN );
10277
10278           if ( degenEdgeInd.size() == 1 )  // PYRAM
10279           {
10280             int i2 = *degenEdgeInd.begin();
10281             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10282             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10283             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10284                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
10285           }
10286           else  // TETRA
10287           {
10288             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10289             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10290                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10291                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10292                               (*nnVec[ i3 ])[ iZ ]);
10293           }
10294         }
10295         break; // TRIA
10296       }
10297       case 4: // QUAD
10298       {
10299         // HEX
10300         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10301           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10302                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10303                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
10304                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
10305
10306         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10307         {
10308           for ( int iN = 0; iN < nbNodes; ++iN )
10309             if ( nnVec[ iN ]->size() < iZ+1 )
10310               degenEdgeInd.insert( iN );
10311
10312           switch ( degenEdgeInd.size() )
10313           {
10314           case 2: // PENTA
10315           {
10316             int i2 = *degenEdgeInd.begin();
10317             int i3 = *degenEdgeInd.rbegin();
10318             bool ok = ( i3 - i2 == 1 );
10319             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10320             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10321             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10322
10323             const SMDS_MeshElement* vol =
10324               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10325                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10326             if ( !ok && vol )
10327               degenVols.push_back( vol );
10328           }
10329           break;
10330
10331           default: // degen HEX
10332           {
10333             const SMDS_MeshElement* vol =
10334               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10335                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10336                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10337                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10338                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
10339                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
10340                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
10341                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
10342             degenVols.push_back( vol );
10343           }
10344           }
10345         }
10346         break; // HEX
10347       }
10348       default:
10349         return error("Not supported type of element", data._index);
10350
10351       } // switch ( nbNodes )
10352     } // while ( fIt->more() )
10353   } // loop on FACEs
10354
10355   if ( !degenVols.empty() )
10356   {
10357     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10358     if ( !err || err->IsOK() )
10359     {
10360       SMESH_BadInputElements* badElems =
10361         new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10362       badElems->myBadElements.insert( badElems->myBadElements.end(),
10363                                       degenVols.begin(),degenVols.end() );
10364       err.reset( badElems );
10365     }
10366   }
10367
10368   return true;
10369 }
10370
10371 namespace VISCOUS_3D
10372 {
10373   struct ShrinkFace;
10374   //--------------------------------------------------------------------------------
10375   /*!
10376    * \brief Pair of periodic FACEs
10377    */
10378   struct PeriodicFaces
10379   {
10380     typedef StdMeshers_ProjectionUtils::TrsfFinder3D Trsf;
10381
10382     ShrinkFace*  _shriFace[2];
10383     TNodeNodeMap _nnMap;
10384     Trsf         _trsf;
10385
10386     PeriodicFaces( ShrinkFace* sf1, ShrinkFace* sf2 ): _shriFace{ sf1, sf2 } {}
10387     bool IncludeShrunk( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces ) const;
10388     bool MoveNodes( const TopoDS_Face& tgtFace );
10389   };
10390
10391   //--------------------------------------------------------------------------------
10392   /*!
10393    * \brief Shrink FACE data used to find periodic FACEs
10394    */
10395   struct ShrinkFace
10396   {
10397     // ................................................................................
10398     struct BndPart //!< part of FACE boundary, either shrink or no-shrink
10399     {
10400       bool                         _isShrink, _isReverse;
10401       int                          _nbSegments;
10402       AverageHyp*                  _hyp;
10403       std::vector< SMESH_NodeXYZ > _nodes;
10404       TopAbs_ShapeEnum             _vertSWOLType[2]; // shrink part includes VERTEXes
10405       AverageHyp*                  _vertHyp[2];
10406
10407       BndPart():
10408         _isShrink(0), _isReverse(0), _nbSegments(0), _hyp(0),
10409         _vertSWOLType{ TopAbs_WIRE, TopAbs_WIRE }, _vertHyp{ 0, 0 }
10410       {}
10411
10412       bool operator==( const BndPart& other ) const
10413       {
10414         return ( _isShrink       == other._isShrink &&
10415                  _nbSegments     == other._nbSegments &&
10416                  _nodes.size()   == other._nodes.size() &&
10417                  vertSWOLType1() == other.vertSWOLType1() &&
10418                  vertSWOLType2() == other.vertSWOLType2() &&
10419                  (( !_isShrink ) ||
10420                   ( *_hyp        == *other._hyp &&
10421                     vertHyp1()   == other.vertHyp1() &&
10422                     vertHyp2()   == other.vertHyp2() ))
10423                  );
10424       }
10425       bool CanAppend( const BndPart& other )
10426       {
10427         return ( _isShrink  == other._isShrink  &&
10428                  (( !_isShrink ) ||
10429                   ( *_hyp        == *other._hyp &&
10430                     *_hyp        == vertHyp2()  &&
10431                     vertHyp2()   == other.vertHyp1() ))
10432                  );
10433       }
10434       void Append( const BndPart& other )
10435       {
10436         _nbSegments += other._nbSegments;
10437         bool hasCommonNode = ( _nodes.back()->GetID() == other._nodes.front()->GetID() );
10438         _nodes.insert( _nodes.end(), other._nodes.begin() + hasCommonNode, other._nodes.end() );
10439         _vertSWOLType[1] = other._vertSWOLType[1];
10440         if ( _isShrink )
10441           _vertHyp[1] = other._vertHyp[1];
10442       }
10443       const SMDS_MeshNode*    Node(size_t i)  const
10444       {
10445         return _nodes[ _isReverse ? ( _nodes.size() - 1 - i ) : i ]._node;
10446       }
10447       void Reverse() { _isReverse = !_isReverse; }
10448       const TopAbs_ShapeEnum& vertSWOLType1() const { return _vertSWOLType[ _isReverse  ]; }
10449       const TopAbs_ShapeEnum& vertSWOLType2() const { return _vertSWOLType[ !_isReverse ]; }
10450       const AverageHyp&       vertHyp1()      const { return *(_vertHyp[ _isReverse  ]); }
10451       const AverageHyp&       vertHyp2()      const { return *(_vertHyp[ !_isReverse ]); }
10452     };
10453     // ................................................................................
10454
10455     SMESH_subMesh*       _subMesh;
10456     _SolidData*          _data1;
10457     _SolidData*          _data2;
10458     //bool                 _isPeriodic;
10459
10460     std::list< BndPart > _boundary;
10461     int                  _boundarySize, _nbBoundaryParts;
10462
10463     void Init( SMESH_subMesh* sm, _SolidData* sd1, _SolidData* sd2 )
10464     {
10465       _subMesh = sm; _data1 = sd1; _data2 = sd2; //_isPeriodic = false;
10466     }
10467     bool IsSame( const TopoDS_Face& face ) const
10468     {
10469       return _subMesh->GetSubShape().IsSame( face );
10470     }
10471     bool IsShrunk( const TopTools_MapOfShape& shrunkFaces ) const
10472     {
10473       return shrunkFaces.Contains( _subMesh->GetSubShape() );
10474     }
10475
10476     //================================================================================
10477     /*!
10478      * Check if meshes on two FACEs are equal
10479      */
10480     bool IsPeriodic( ShrinkFace& other, PeriodicFaces& periodic )
10481     {
10482       if ( !IsSameNbElements( other ))
10483         return false;
10484
10485       this->SetBoundary();
10486       other.SetBoundary();
10487       if ( this->_boundarySize    != other._boundarySize ||
10488            this->_nbBoundaryParts != other._nbBoundaryParts )
10489         return false;
10490
10491       for ( int isReverse = 0; isReverse < 2; ++isReverse )
10492       {
10493         if ( isReverse )
10494           Reverse( _boundary );
10495
10496         // check boundaries
10497         bool equalBoundary = false;
10498         for ( int iP = 0; iP < _nbBoundaryParts &&  !equalBoundary; ++iP )
10499         {
10500           if ( ! ( equalBoundary = ( this->_boundary == other._boundary )))
10501             // set first part at end
10502             _boundary.splice( _boundary.end(), _boundary, _boundary.begin() );
10503         }
10504         if ( !equalBoundary )
10505           continue;
10506
10507         // check connectivity
10508         std::set<const SMDS_MeshElement*> elemsThis, elemsOther;
10509         this->GetElements( elemsThis  );
10510         other.GetElements( elemsOther );
10511         SMESH_MeshEditor::Sew_Error err =
10512           SMESH_MeshEditor::FindMatchingNodes( elemsThis, elemsOther,
10513                                                this->_boundary.front().Node(0),
10514                                                other._boundary.front().Node(0),
10515                                                this->_boundary.front().Node(1),
10516                                                other._boundary.front().Node(1),
10517                                                periodic._nnMap );
10518         if ( err != SMESH_MeshEditor::SEW_OK )
10519           continue;
10520
10521         // check node positions
10522         std::vector< gp_XYZ > srcPnts, tgtPnts;
10523         this->GetBoundaryPoints( srcPnts );
10524         other.GetBoundaryPoints( tgtPnts );
10525         if ( !periodic._trsf.Solve( srcPnts, tgtPnts )) {
10526           continue;
10527         }
10528         double tol = std::numeric_limits<double>::max();
10529         for ( size_t i = 1; i < srcPnts.size(); ++i ) {
10530           tol = Min( tol, ( srcPnts[i-1] - srcPnts[i] ).SquareModulus() );
10531         }
10532         tol = 0.01 * Sqrt( tol );
10533         bool nodeCoincide = true;
10534         TNodeNodeMap::iterator n2n = periodic._nnMap.begin();
10535         for ( ; n2n != periodic._nnMap.end() &&  nodeCoincide; ++n2n )
10536         {
10537           SMESH_NodeXYZ nSrc = n2n->first;
10538           SMESH_NodeXYZ nTgt = n2n->second;
10539           gp_XYZ pTgt = periodic._trsf.Transform( nSrc );
10540           nodeCoincide = (( pTgt - nTgt ).SquareModulus() < tol );
10541         }
10542         if ( nodeCoincide )
10543           return true;
10544       }
10545       return false;
10546     }
10547
10548     bool IsSameNbElements( ShrinkFace& other ) // check number of mesh faces
10549     {
10550       SMESHDS_SubMesh* sm1 = this->_subMesh->GetSubMeshDS();
10551       SMESHDS_SubMesh* sm2 = other._subMesh->GetSubMeshDS();
10552       return ( sm1->NbElements() == sm2->NbElements() &&
10553                sm1->NbNodes()    == sm2->NbNodes() );
10554     }
10555
10556     void Reverse( std::list< BndPart >& boundary )
10557     {
10558       boundary.reverse();
10559       for ( std::list< BndPart >::iterator part = boundary.begin(); part != boundary.end(); ++part )
10560         part->Reverse();
10561     }
10562
10563     void SetBoundary()
10564     {
10565       if ( !_boundary.empty() )
10566         return;
10567
10568       TopoDS_Face F = TopoDS::Face( _subMesh->GetSubShape() );
10569       if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
10570       std::list< TopoDS_Edge > edges;
10571       std::list< int > nbEdgesInWire;
10572       /*int nbWires =*/ SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
10573
10574       // std::list< TopoDS_Edge >::iterator edgesEnd = edges.end();
10575       // if ( nbWires > 1 ) {
10576       //   edgesEnd = edges.begin();
10577       //   std::advance( edgesEnd, nbEdgesInWire.front() );
10578       // }
10579       StdMeshers_FaceSide fSide( F, edges, _subMesh->GetFather(),
10580                                  /*fwd=*/true, /*skipMedium=*/true );
10581       _boundarySize = fSide.NbSegments();
10582
10583       //TopoDS_Vertex vv[2];
10584       //std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
10585       for ( int iE = 0; iE < nbEdgesInWire.front(); ++iE )
10586       {
10587         BndPart bndPart;
10588         _EdgesOnShape*  eos = _data1->GetShapeEdges( fSide.EdgeID( iE ));
10589
10590         bndPart._isShrink = ( eos->SWOLType() == TopAbs_FACE );
10591         if ( bndPart._isShrink )
10592           if ((           _data1->_noShrinkShapes.count( eos->_shapeID )) ||
10593               ( _data2 && _data2->_noShrinkShapes.count( eos->_shapeID )))
10594             bndPart._isShrink = false;
10595
10596         if ( bndPart._isShrink )
10597         {
10598           bndPart._hyp = & eos->_hyp;
10599           _EdgesOnShape* eov[2] = { _data1->GetShapeEdges( fSide.FirstVertex( iE )),
10600                                     _data1->GetShapeEdges( fSide.LastVertex ( iE )) };
10601           for ( int iV = 0; iV < 2; ++iV )
10602           {
10603             bndPart._vertHyp     [iV] = & eov[iV]->_hyp;
10604             bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
10605             if ( _data1->_noShrinkShapes.count( eov[iV]->_shapeID ))
10606               bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
10607             if ( _data2 && bndPart._vertSWOLType[iV] != TopAbs_SHAPE )
10608             {
10609               eov[iV] = _data2->GetShapeEdges( iV ? fSide.LastVertex(iE) : fSide.FirstVertex(iE ));
10610               if ( _data2->_noShrinkShapes.count( eov[iV]->_shapeID ))
10611                 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
10612               else if ( eov[iV]->SWOLType() > bndPart._vertSWOLType[iV] )
10613                 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
10614             }
10615           }
10616         }
10617         std::vector<const SMDS_MeshNode*> nodes = fSide.GetOrderedNodes( iE );
10618         bndPart._nodes.assign( nodes.begin(), nodes.end() );
10619         bndPart._nbSegments = bndPart._nodes.size() - 1;
10620
10621         if ( _boundary.empty() || ! _boundary.back().CanAppend( bndPart ))
10622           _boundary.push_back( bndPart );
10623         else
10624           _boundary.back().Append( bndPart );
10625       }
10626
10627       _nbBoundaryParts = _boundary.size();
10628       if ( _nbBoundaryParts > 1 && _boundary.front()._isShrink == _boundary.back()._isShrink )
10629       {
10630         _boundary.back().Append( _boundary.front() );
10631         _boundary.pop_front();
10632         --_nbBoundaryParts;
10633       }
10634     }
10635
10636     void GetElements( std::set<const SMDS_MeshElement*>& theElems)
10637     {
10638       if ( SMESHDS_SubMesh* sm = _subMesh->GetSubMeshDS() )
10639         for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
10640           theElems.insert( theElems.end(), fIt->next() );
10641
10642       return ;
10643     }
10644
10645     void GetBoundaryPoints( std::vector< gp_XYZ >& points )
10646     {
10647       points.reserve( _boundarySize );
10648       size_t  nb = _boundary.rbegin()->_nodes.size();
10649       int lastID = _boundary.rbegin()->Node( nb - 1 )->GetID();
10650       std::list< BndPart >::const_iterator part = _boundary.begin();
10651       for ( ; part != _boundary.end(); ++part )
10652       {
10653         size_t nb = part->_nodes.size();
10654         size_t iF = 0;
10655         size_t iR = nb - 1;
10656         size_t* i = part->_isReverse ? &iR : &iF;
10657         if ( part->_nodes[ *i ]->GetID() == lastID )
10658           ++iF, --iR;
10659         for ( ; iF < nb; ++iF, --iR )
10660           points.push_back( part->_nodes[ *i ]);
10661         --iF, ++iR;
10662         lastID = part->_nodes[ *i ]->GetID();
10663       }
10664     }
10665   }; // struct ShrinkFace
10666
10667   //--------------------------------------------------------------------------------
10668   /*!
10669    * \brief Periodic FACEs
10670    */
10671   struct Periodicity
10672   {
10673     std::vector< ShrinkFace >    _shrinkFaces;
10674     std::vector< PeriodicFaces > _periodicFaces;
10675
10676     PeriodicFaces* GetPeriodic( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces )
10677     {
10678       for ( size_t i = 0; i < _periodicFaces.size(); ++i )
10679         if ( _periodicFaces[ i ].IncludeShrunk( face, shrunkFaces ))
10680           return & _periodicFaces[ i ];
10681       return 0;
10682     }
10683   };
10684
10685   //================================================================================
10686   /*!
10687    * Check if a pair includes the given FACE and the other FACE is already shrunk
10688    */
10689   bool PeriodicFaces::IncludeShrunk( const TopoDS_Face&         face,
10690                                      const TopTools_MapOfShape& shrunkFaces ) const
10691   {
10692     return (( _shriFace[0]->IsSame( face ) && _shriFace[1]->IsShrunk( shrunkFaces )) ||
10693             ( _shriFace[1]->IsSame( face ) && _shriFace[0]->IsShrunk( shrunkFaces )));
10694   }
10695
10696   //================================================================================
10697   /*!
10698    * Make equal meshes on periodic faces by moving corresponding nodes
10699    */
10700   bool PeriodicFaces::MoveNodes( const TopoDS_Face& tgtFace )
10701   {
10702     int iTgt = _shriFace[1]->IsSame( tgtFace );
10703     int iSrc = 1 - iTgt;
10704
10705     _SolidData* dataSrc = _shriFace[iSrc]->_data1;
10706     _SolidData* dataTgt = _shriFace[iTgt]->_data1;
10707
10708     Trsf * trsf = & _trsf, trsfInverse;
10709     if ( iSrc != 0 )
10710     {
10711       trsfInverse = _trsf;
10712       trsfInverse.Invert();
10713       trsf = &trsfInverse;
10714     }
10715     SMESHDS_Mesh* meshDS = dataSrc->GetHelper().GetMeshDS();
10716
10717     TNode2Edge::iterator n2e;
10718     TNodeNodeMap::iterator n2n = _nnMap.begin();
10719     for ( ; n2n != _nnMap.end(); ++n2n )
10720     {
10721       const SMDS_MeshNode* const* nn = & n2n->first;
10722       const SMDS_MeshNode*      nSrc = nn[ iSrc ];
10723       const SMDS_MeshNode*      nTgt = nn[ iTgt ];
10724
10725       if (( nSrc->GetPosition()->GetDim() == 2 ) ||
10726           (( n2e = dataSrc->_n2eMap.find( nSrc )) == dataSrc->_n2eMap.end() ))
10727       {
10728         SMESH_NodeXYZ pSrc = nSrc;
10729         gp_XYZ pTgt = trsf->Transform( pSrc );
10730         meshDS->MoveNode( nTgt, pTgt.X(), pTgt.Y(), pTgt.Z() );
10731       }
10732       else
10733       {
10734         _LayerEdge* leSrc = n2e->second;
10735         n2e = dataTgt->_n2eMap.find( nTgt );
10736         if ( n2e == dataTgt->_n2eMap.end() )
10737           break;
10738         _LayerEdge* leTgt = n2e->second;
10739         if ( leSrc->_nodes.size() != leTgt->_nodes.size() )
10740           break;
10741         for ( size_t iN = 1; iN < leSrc->_nodes.size(); ++iN )
10742         {
10743           SMESH_NodeXYZ pSrc = leSrc->_nodes[ iN ];
10744           gp_XYZ pTgt = trsf->Transform( pSrc );
10745           meshDS->MoveNode( leTgt->_nodes[ iN ], pTgt.X(), pTgt.Y(), pTgt.Z() );
10746         }
10747       }
10748     }
10749     bool done = ( n2n == _nnMap.end() );
10750     // cout << "MMMMMMMOOOOOOOOOOVVVVVVVVVVVEEEEEEEE "
10751     //      << _shriFace[iSrc]->_subMesh->GetId() << " -> "
10752     //      << _shriFace[iTgt]->_subMesh->GetId() << " -- "
10753     //      << ( done ? "DONE" : "FAIL") << endl;
10754
10755     return done;
10756   }
10757 } // namespace VISCOUS_3D; Periodicity part
10758
10759
10760 //================================================================================
10761 /*!
10762  * \brief Find FACEs to shrink, that are equally meshed before shrink (i.e. periodic)
10763  *        and should remain equal after shrink
10764  */
10765 //================================================================================
10766
10767 void _ViscousBuilder::findPeriodicFaces()
10768 {
10769   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10770   // _LayerEdge's inflated along FACE or EDGE)
10771   std::map< TGeomID, std::list< _SolidData* > > id2sdMap;
10772   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10773   {
10774     _SolidData& data = _sdVec[i];
10775     std::map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10776     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10777       if ( s2s->second.ShapeType() == TopAbs_FACE )
10778         id2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10779   }
10780
10781   _periodicity.reset( new Periodicity );
10782   _periodicity->_shrinkFaces.resize( id2sdMap.size() );
10783
10784   std::map< TGeomID, std::list< _SolidData* > >::iterator id2sdIt = id2sdMap.begin();
10785   for ( size_t i = 0; i < id2sdMap.size(); ++i, ++id2sdIt )
10786   {
10787     _SolidData* sd1 = id2sdIt->second.front();
10788     _SolidData* sd2 = id2sdIt->second.back();
10789     _periodicity->_shrinkFaces[ i ].Init( _mesh->GetSubMeshContaining( id2sdIt->first ), sd1, sd2 );
10790   }
10791
10792   for (   size_t i1 = 0;      i1 < _periodicity->_shrinkFaces.size(); ++i1 )
10793     for ( size_t i2 = i1 + 1; i2 < _periodicity->_shrinkFaces.size(); ++i2 )
10794     {
10795       PeriodicFaces pf( & _periodicity->_shrinkFaces[ i1 ],
10796                         & _periodicity->_shrinkFaces[ i2 ]);
10797       if ( pf._shriFace[0]->IsPeriodic( *pf._shriFace[1], pf ))
10798       {
10799         _periodicity->_periodicFaces.push_back( pf );
10800       }
10801     }
10802   return;
10803 }
10804
10805 //================================================================================
10806 /*!
10807  * \brief Shrink 2D mesh on faces to let space for inflated layers
10808  */
10809 //================================================================================
10810
10811 bool _ViscousBuilder::shrink(_SolidData& theData)
10812 {
10813   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10814   // _LayerEdge's inflated along FACE or EDGE)
10815   map< TGeomID, list< _SolidData* > > f2sdMap;
10816   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10817   {
10818     _SolidData& data = _sdVec[i];
10819     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10820     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10821       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrunkFaces.Contains( s2s->second ))
10822       {
10823         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10824
10825         // Put mesh faces on the shrunk FACE to the proxy sub-mesh to avoid
10826         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10827         // by StdMeshers_QuadToTriaAdaptor
10828         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10829         {
10830           SMESH_ProxyMesh::SubMesh* proxySub =
10831             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10832           if ( proxySub->NbElements() == 0 )
10833           {
10834             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10835             while ( fIt->more() )
10836             {
10837               const SMDS_MeshElement* f = fIt->next();
10838               // as a result 3D algo will use elements from proxySub and not from smDS
10839               proxySub->AddElement( f );
10840               f->setIsMarked( true );
10841
10842               // Mark nodes on the FACE to discriminate them from nodes
10843               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10844               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10845               {
10846                 const SMDS_MeshNode* n = f->GetNode( iN );
10847                 if ( n->GetPosition()->GetDim() == 2 )
10848                   n->setIsMarked( true );
10849               }
10850             }
10851           }
10852         }
10853       }
10854   }
10855
10856   SMESH_MesherHelper helper( *_mesh );
10857   helper.ToFixNodeParameters( true );
10858
10859   // EDGEs to shrink
10860   map< TGeomID, _Shrinker1D > e2shrMap;
10861   vector< _EdgesOnShape* > subEOS;
10862   vector< _LayerEdge* > lEdges;
10863
10864   // loop on FACEs to shrink mesh on
10865   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10866   for ( ; f2sd != f2sdMap.end(); ++f2sd )
10867   {
10868     list< _SolidData* > & dataList = f2sd->second;
10869     if ( dataList.front()->_n2eMap.empty() ||
10870          dataList.back() ->_n2eMap.empty() )
10871       continue; // not yet computed
10872     if ( dataList.front() != &theData &&
10873          dataList.back()  != &theData )
10874       continue;
10875
10876     _SolidData&      data = *dataList.front();
10877     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
10878     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10879     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
10880     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10881
10882     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10883
10884     _shrunkFaces.Add( F );
10885     helper.SetSubShape( F );
10886
10887     // ==============================
10888     // Use periodicity to move nodes
10889     // ==============================
10890
10891     PeriodicFaces* periodic = _periodicity->GetPeriodic( F, _shrunkFaces );
10892     bool movedByPeriod = ( periodic && periodic->MoveNodes( F ));
10893
10894     // ===========================
10895     // Prepare data for shrinking
10896     // ===========================
10897
10898     // Collect nodes to smooth (they are marked at the beginning of this method)
10899     vector < const SMDS_MeshNode* > smoothNodes;
10900
10901     if ( !movedByPeriod )
10902     {
10903       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
10904       while ( nIt->more() )
10905       {
10906         const SMDS_MeshNode* n = nIt->next();
10907         if ( n->isMarked() )
10908           smoothNodes.push_back( n );
10909       }
10910     }
10911     // Find out face orientation
10912     double refSign = 1;
10913     const set<TGeomID> ignoreShapes;
10914     bool isOkUV;
10915     if ( !smoothNodes.empty() )
10916     {
10917       vector<_Simplex> simplices;
10918       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
10919       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
10920       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
10921       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
10922       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
10923         refSign = -1;
10924     }
10925
10926     // Find _LayerEdge's inflated along F
10927     subEOS.clear();
10928     lEdges.clear();
10929     {
10930       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
10931                                                                 /*complexFirst=*/true); //!!!
10932       while ( subIt->more() )
10933       {
10934         const TGeomID subID = subIt->next()->GetId();
10935         if ( data._noShrinkShapes.count( subID ))
10936           continue;
10937         _EdgesOnShape* eos = data.GetShapeEdges( subID );
10938         if ( !eos || eos->_sWOL.IsNull() )
10939           if ( data2 ) // check in adjacent SOLID
10940           {
10941             eos = data2->GetShapeEdges( subID );
10942             if ( !eos || eos->_sWOL.IsNull() )
10943               continue;
10944           }
10945         subEOS.push_back( eos );
10946
10947         if ( !movedByPeriod )
10948           for ( size_t i = 0; i < eos->_edges.size(); ++i )
10949           {
10950             lEdges.push_back( eos->_edges[ i ] );
10951             prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
10952           }
10953       }
10954     }
10955
10956     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
10957     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10958     while ( fIt->more() )
10959       if ( const SMDS_MeshElement* f = fIt->next() )
10960         dumpChangeNodes( f );
10961     dumpFunctionEnd();
10962
10963     // Replace source nodes by target nodes in mesh faces to shrink
10964     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
10965     const SMDS_MeshNode* nodes[20];
10966     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10967     {
10968       _EdgesOnShape& eos = * subEOS[ iS ];
10969       for ( size_t i = 0; i < eos._edges.size(); ++i )
10970       {
10971         _LayerEdge& edge = *eos._edges[i];
10972         const SMDS_MeshNode* srcNode = edge._nodes[0];
10973         const SMDS_MeshNode* tgtNode = edge._nodes.back();
10974         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
10975         while ( fIt->more() )
10976         {
10977           const SMDS_MeshElement* f = fIt->next();
10978           if ( !smDS->Contains( f ) || !f->isMarked() )
10979             continue;
10980           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
10981           for ( int iN = 0; nIt->more(); ++iN )
10982           {
10983             const SMDS_MeshNode* n = nIt->next();
10984             nodes[iN] = ( n == srcNode ? tgtNode : n );
10985           }
10986           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
10987           dumpChangeNodes( f );
10988         }
10989       }
10990     }
10991     dumpFunctionEnd();
10992
10993     // find out if a FACE is concave
10994     const bool isConcaveFace = isConcave( F, helper );
10995
10996     // Create _SmoothNode's on face F
10997     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
10998     {
10999       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
11000       const bool sortSimplices = isConcaveFace;
11001       for ( size_t i = 0; i < smoothNodes.size(); ++i )
11002       {
11003         const SMDS_MeshNode* n = smoothNodes[i];
11004         nodesToSmooth[ i ]._node = n;
11005         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
11006         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
11007         // fix up incorrect uv of nodes on the FACE
11008         helper.GetNodeUV( F, n, 0, &isOkUV);
11009         dumpMove( n );
11010       }
11011       dumpFunctionEnd();
11012     }
11013     //if ( nodesToSmooth.empty() ) continue;
11014
11015     // Find EDGE's to shrink and set simpices to LayerEdge's
11016     set< _Shrinker1D* > eShri1D;
11017     {
11018       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11019       {
11020         _EdgesOnShape& eos = * subEOS[ iS ];
11021         if ( eos.SWOLType() == TopAbs_EDGE )
11022         {
11023           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
11024           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
11025           if ( !movedByPeriod )
11026           {
11027             _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
11028             eShri1D.insert( & shrinker );
11029             shrinker.AddEdge( eos._edges[0], eos, helper );
11030             // restore params of nodes on EDGE if the EDGE has been already
11031             // shrunk while shrinking other FACE
11032             shrinker.RestoreParams();
11033           }
11034         }
11035         for ( size_t i = 0; i < eos._edges.size(); ++i )
11036         {
11037           _LayerEdge& edge = * eos._edges[i];
11038           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
11039
11040           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
11041           // not-marked nodes are those added by refine()
11042           edge._nodes.back()->setIsMarked( true );
11043         }
11044       }
11045     }
11046
11047     bool toFixTria = false; // to improve quality of trias by diagonal swap
11048     if ( isConcaveFace && !movedByPeriod )
11049     {
11050       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
11051       if ( hasTria != hasQuad ) {
11052         toFixTria = hasTria;
11053       }
11054       else {
11055         set<int> nbNodesSet;
11056         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11057         while ( fIt->more() && nbNodesSet.size() < 2 )
11058           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
11059         toFixTria = ( *nbNodesSet.begin() == 3 );
11060       }
11061     }
11062
11063     // ==================
11064     // Perform shrinking
11065     // ==================
11066
11067     bool shrunk = !movedByPeriod;
11068     int nbBad, shriStep=0, smooStep=0;
11069     _SmoothNode::SmoothType smoothType
11070       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
11071     SMESH_Comment errMsg;
11072     while ( shrunk )
11073     {
11074       shriStep++;
11075       // Move boundary nodes (actually just set new UV)
11076       // -----------------------------------------------
11077       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
11078       shrunk = false;
11079       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11080       {
11081         _EdgesOnShape& eos = * subEOS[ iS ];
11082         for ( size_t i = 0; i < eos._edges.size(); ++i )
11083         {
11084           shrunk |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
11085         }
11086       }
11087       dumpFunctionEnd();
11088
11089       // Move nodes on EDGE's
11090       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
11091       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
11092       for ( ; shr != eShri1D.end(); ++shr )
11093         (*shr)->Compute( /*set3D=*/false, helper );
11094
11095       // Smoothing in 2D
11096       // -----------------
11097       int nbNoImpSteps = 0;
11098       bool       moved = true;
11099       nbBad = 1;
11100       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
11101       {
11102         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11103
11104         int oldBadNb = nbBad;
11105         nbBad = 0;
11106         moved = false;
11107         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
11108         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
11109         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11110         {
11111           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
11112                                             smooTy, /*set3D=*/isConcaveFace);
11113         }
11114         if ( nbBad < oldBadNb )
11115           nbNoImpSteps = 0;
11116         else
11117           nbNoImpSteps++;
11118
11119         dumpFunctionEnd();
11120       }
11121
11122       errMsg.clear();
11123       if ( nbBad > 0 )
11124         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
11125       if ( shriStep > 200 )
11126         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
11127       if ( !errMsg.empty() )
11128         break;
11129
11130       // Fix narrow triangles by swapping diagonals
11131       // ---------------------------------------
11132       if ( toFixTria )
11133       {
11134         set<const SMDS_MeshNode*> usedNodes;
11135         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
11136
11137         // update working data
11138         set<const SMDS_MeshNode*>::iterator n;
11139         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
11140         {
11141           n = usedNodes.find( nodesToSmooth[ i ]._node );
11142           if ( n != usedNodes.end())
11143           {
11144             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
11145                                     nodesToSmooth[ i ]._simplices,
11146                                     ignoreShapes, NULL,
11147                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
11148             usedNodes.erase( n );
11149           }
11150         }
11151         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
11152         {
11153           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
11154           if ( n != usedNodes.end())
11155           {
11156             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
11157                                     lEdges[i]->_simplices,
11158                                     ignoreShapes );
11159             usedNodes.erase( n );
11160           }
11161         }
11162       }
11163       // TODO: check effect of this additional smooth
11164       // additional laplacian smooth to increase allowed shrink step
11165       // for ( int st = 1; st; --st )
11166       // {
11167       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11168       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11169       //   {
11170       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11171       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
11172       //   }
11173       // }
11174
11175     } // while ( shrunk )
11176
11177     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
11178     {
11179       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
11180
11181       // remove faces
11182       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
11183       {
11184         vector< const SMDS_MeshElement* > facesToRm;
11185         if ( psm )
11186         {
11187           facesToRm.reserve( psm->NbElements() );
11188           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
11189             facesToRm.push_back( ite->next() );
11190
11191           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11192             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11193               psm->Clear();
11194         }
11195         for ( size_t i = 0; i < facesToRm.size(); ++i )
11196           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
11197       }
11198       // remove nodes
11199       {
11200         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
11201         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
11202           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11203             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
11204                                 subEOS[iS]->_edges[i]->_nodes.end() );
11205         }
11206         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
11207         while ( itn->more() ) {
11208           const SMDS_MeshNode* n = itn->next();
11209           if ( !nodesToKeep.count( n ))
11210             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
11211         }
11212       }
11213       // restore position and UV of target nodes
11214       gp_Pnt p;
11215       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11216         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11217         {
11218           _LayerEdge*       edge = subEOS[iS]->_edges[i];
11219           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
11220           if ( edge->_pos.empty() ||
11221                edge->Is( _LayerEdge::SHRUNK )) continue;
11222           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
11223           {
11224             SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11225             pos->SetUParameter( edge->_pos[0].X() );
11226             pos->SetVParameter( edge->_pos[0].Y() );
11227             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
11228           }
11229           else
11230           {
11231             SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11232             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
11233             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
11234           }
11235           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11236           dumpMove( tgtNode );
11237         }
11238       // shrink EDGE sub-meshes and set proxy sub-meshes
11239       UVPtStructVec uvPtVec;
11240       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
11241       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
11242       {
11243         _Shrinker1D* shr = (*shrIt);
11244         shr->Compute( /*set3D=*/true, helper );
11245
11246         // set proxy mesh of EDGEs w/o layers
11247         map< double, const SMDS_MeshNode* > nodes;
11248         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
11249         // remove refinement nodes
11250         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
11251         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
11252         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
11253         if ( u2n->second == sn0 || u2n->second == sn1 )
11254         {
11255           while ( u2n->second != tn0 && u2n->second != tn1 )
11256             ++u2n;
11257           nodes.erase( nodes.begin(), u2n );
11258         }
11259         u2n = --nodes.end();
11260         if ( u2n->second == sn0 || u2n->second == sn1 )
11261         {
11262           while ( u2n->second != tn0 && u2n->second != tn1 )
11263             --u2n;
11264           nodes.erase( ++u2n, nodes.end() );
11265         }
11266         // set proxy sub-mesh
11267         uvPtVec.resize( nodes.size() );
11268         u2n = nodes.begin();
11269         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
11270         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
11271         {
11272           uvPtVec[ i ].node = u2n->second;
11273           uvPtVec[ i ].param = u2n->first;
11274           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
11275         }
11276         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
11277         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11278       }
11279
11280       // set proxy mesh of EDGEs with layers
11281       vector< _LayerEdge* > edges;
11282       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11283       {
11284         _EdgesOnShape& eos = * subEOS[ iS ];
11285         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
11286
11287         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
11288         data.SortOnEdge( E, eos._edges );
11289
11290         edges.clear();
11291         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
11292           if ( !eov->_edges.empty() )
11293             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
11294
11295         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
11296
11297         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
11298           if ( !eov->_edges.empty() )
11299             edges.push_back( eov->_edges[0] ); // on last VERTEX
11300
11301         uvPtVec.resize( edges.size() );
11302         for ( size_t i = 0; i < edges.size(); ++i )
11303         {
11304           uvPtVec[ i ].node = edges[i]->_nodes.back();
11305           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
11306           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
11307         }
11308         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
11309         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
11310         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11311       }
11312       // temporary clear the FACE sub-mesh from faces made by refine()
11313       vector< const SMDS_MeshElement* > elems;
11314       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
11315       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11316         elems.push_back( ite->next() );
11317       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
11318         elems.push_back( ite->next() );
11319       smDS->Clear();
11320
11321       // compute the mesh on the FACE
11322       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
11323       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
11324
11325       // re-fill proxy sub-meshes of the FACE
11326       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11327         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11328           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11329             psm->AddElement( ite->next() );
11330
11331       // re-fill smDS
11332       for ( size_t i = 0; i < elems.size(); ++i )
11333         smDS->AddElement( elems[i] );
11334
11335       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
11336         return error( errMsg );
11337
11338     } // end of re-meshing in case of failed smoothing
11339     else if ( !movedByPeriod )
11340     {
11341       // No wrongly shaped faces remain; final smooth. Set node XYZ.
11342       bool isStructuredFixed = false;
11343       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
11344         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
11345       if ( !isStructuredFixed )
11346       {
11347         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
11348           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
11349
11350         for ( int st = 3; st; --st )
11351         {
11352           switch( st ) {
11353           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
11354           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
11355           case 3: smoothType = _SmoothNode::ANGULAR; break;
11356           }
11357           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11358           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11359           {
11360             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11361                                      smoothType,/*set3D=*/st==1 );
11362           }
11363           dumpFunctionEnd();
11364         }
11365       }
11366       if ( !getMeshDS()->IsEmbeddedMode() )
11367         // Log node movement
11368         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11369         {
11370           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
11371           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
11372         }
11373     }
11374
11375     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
11376     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
11377     if ( data2 )
11378       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
11379
11380   } // loop on FACES to shrink mesh on
11381
11382
11383   // Replace source nodes by target nodes in shrunk mesh edges
11384
11385   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
11386   for ( ; e2shr != e2shrMap.end(); ++e2shr )
11387     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
11388
11389   return true;
11390 }
11391
11392 //================================================================================
11393 /*!
11394  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
11395  */
11396 //================================================================================
11397
11398 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
11399                                            _EdgesOnShape&         eos,
11400                                            SMESH_MesherHelper&    helper,
11401                                            const SMESHDS_SubMesh* faceSubMesh)
11402 {
11403   const SMDS_MeshNode* srcNode = edge._nodes[0];
11404   const SMDS_MeshNode* tgtNode = edge._nodes.back();
11405
11406   if ( eos.SWOLType() == TopAbs_FACE )
11407   {
11408     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
11409     {
11410       edge._pos.clear();
11411       edge.Set( _LayerEdge::SHRUNK );
11412       return srcNode == tgtNode;
11413     }
11414     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
11415     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
11416     gp_Vec2d uvDir( srcUV, tgtUV );
11417     double uvLen = uvDir.Magnitude();
11418     uvDir /= uvLen;
11419     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
11420     edge._len = uvLen;
11421
11422     //edge._pos.resize(1);
11423     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
11424
11425     // set UV of source node to target node
11426     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11427     pos->SetUParameter( srcUV.X() );
11428     pos->SetVParameter( srcUV.Y() );
11429   }
11430   else // _sWOL is TopAbs_EDGE
11431   {
11432     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
11433     {
11434       edge._pos.clear();
11435       edge.Set( _LayerEdge::SHRUNK );
11436       return srcNode == tgtNode;
11437     }
11438     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
11439     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
11440     if ( !edgeSM || edgeSM->NbElements() == 0 )
11441       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11442
11443     const SMDS_MeshNode* n2 = 0;
11444     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11445     while ( eIt->more() && !n2 )
11446     {
11447       const SMDS_MeshElement* e = eIt->next();
11448       if ( !edgeSM->Contains(e)) continue;
11449       n2 = e->GetNode( 0 );
11450       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
11451     }
11452     if ( !n2 )
11453       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11454
11455     double uSrc = helper.GetNodeU( E, srcNode, n2 );
11456     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
11457     double u2   = helper.GetNodeU( E, n2,      srcNode );
11458
11459     //edge._pos.clear();
11460
11461     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
11462     {
11463       // tgtNode is located so that it does not make faces with wrong orientation
11464       edge.Set( _LayerEdge::SHRUNK );
11465       return true;
11466     }
11467     //edge._pos.resize(1);
11468     edge._pos[0].SetCoord( U_TGT, uTgt );
11469     edge._pos[0].SetCoord( U_SRC, uSrc );
11470     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
11471
11472     edge._simplices.resize( 1 );
11473     edge._simplices[0]._nPrev = n2;
11474
11475     // set U of source node to the target node
11476     SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11477     pos->SetUParameter( uSrc );
11478   }
11479   return true;
11480 }
11481
11482 //================================================================================
11483 /*!
11484  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
11485  */
11486 //================================================================================
11487
11488 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
11489 {
11490   if ( edge._nodes.size() == 1 )
11491   {
11492     edge._pos.clear();
11493     edge._len = 0;
11494
11495     const SMDS_MeshNode* srcNode = edge._nodes[0];
11496     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
11497     if ( S.IsNull() ) return;
11498
11499     gp_Pnt p;
11500
11501     switch ( S.ShapeType() )
11502     {
11503     case TopAbs_EDGE:
11504     {
11505       double f,l;
11506       TopLoc_Location loc;
11507       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
11508       if ( curve.IsNull() ) return;
11509       SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
11510       p = curve->Value( ePos->GetUParameter() );
11511       break;
11512     }
11513     case TopAbs_VERTEX:
11514     {
11515       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
11516       break;
11517     }
11518     default: return;
11519     }
11520     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
11521     dumpMove( srcNode );
11522   }
11523 }
11524
11525 //================================================================================
11526 /*!
11527  * \brief Try to fix triangles with high aspect ratio by swapping diagonals
11528  */
11529 //================================================================================
11530
11531 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
11532                                   SMESH_MesherHelper&         helper,
11533                                   const bool                  is2D,
11534                                   const int                   step,
11535                                   set<const SMDS_MeshNode*> * involvedNodes)
11536 {
11537   SMESH::Controls::AspectRatio qualifier;
11538   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
11539   const double maxAspectRatio = is2D ? 4. : 2;
11540   _NodeCoordHelper xyz( F, helper, is2D );
11541
11542   // find bad triangles
11543
11544   vector< const SMDS_MeshElement* > badTrias;
11545   vector< double >                  badAspects;
11546   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
11547   SMDS_ElemIteratorPtr fIt = sm->GetElements();
11548   while ( fIt->more() )
11549   {
11550     const SMDS_MeshElement * f = fIt->next();
11551     if ( f->NbCornerNodes() != 3 ) continue;
11552     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
11553     double aspect = qualifier.GetValue( points );
11554     if ( aspect > maxAspectRatio )
11555     {
11556       badTrias.push_back( f );
11557       badAspects.push_back( aspect );
11558     }
11559   }
11560   if ( step == 1 )
11561   {
11562     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
11563     SMDS_ElemIteratorPtr fIt = sm->GetElements();
11564     while ( fIt->more() )
11565     {
11566       const SMDS_MeshElement * f = fIt->next();
11567       if ( f->NbCornerNodes() == 3 )
11568         dumpChangeNodes( f );
11569     }
11570     dumpFunctionEnd();
11571   }
11572   if ( badTrias.empty() )
11573     return;
11574
11575   // find couples of faces to swap diagonal
11576
11577   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
11578   vector< T2Trias > triaCouples; 
11579
11580   TIDSortedElemSet involvedFaces, emptySet;
11581   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
11582   {
11583     T2Trias trias    [3];
11584     double  aspRatio [3];
11585     int i1, i2, i3;
11586
11587     if ( !involvedFaces.insert( badTrias[iTia] ).second )
11588       continue;
11589     for ( int iP = 0; iP < 3; ++iP )
11590       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
11591
11592     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
11593     int bestCouple = -1;
11594     for ( int iSide = 0; iSide < 3; ++iSide )
11595     {
11596       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
11597       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
11598       trias [iSide].first  = badTrias[iTia];
11599       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
11600                                                              & i1, & i2 );
11601       if (( ! trias[iSide].second ) ||
11602           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
11603           ( ! sm->Contains( trias[iSide].second )))
11604         continue;
11605
11606       // aspect ratio of an adjacent tria
11607       for ( int iP = 0; iP < 3; ++iP )
11608         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
11609       double aspectInit = qualifier.GetValue( points2 );
11610
11611       // arrange nodes as after diag-swaping
11612       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
11613         i3 = helper.WrapIndex( i1-1, 3 );
11614       else
11615         i3 = helper.WrapIndex( i1+1, 3 );
11616       points1 = points;
11617       points1( 1+ iSide ) = points2( 1+ i3 );
11618       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
11619
11620       // aspect ratio after diag-swaping
11621       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
11622       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
11623         continue;
11624
11625       // prevent inversion of a triangle
11626       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
11627       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
11628       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
11629         continue;
11630
11631       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
11632         bestCouple = iSide;
11633     }
11634
11635     if ( bestCouple >= 0 )
11636     {
11637       triaCouples.push_back( trias[bestCouple] );
11638       involvedFaces.insert ( trias[bestCouple].second );
11639     }
11640     else
11641     {
11642       involvedFaces.erase( badTrias[iTia] );
11643     }
11644   }
11645   if ( triaCouples.empty() )
11646     return;
11647
11648   // swap diagonals
11649
11650   SMESH_MeshEditor editor( helper.GetMesh() );
11651   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11652   for ( size_t i = 0; i < triaCouples.size(); ++i )
11653   {
11654     dumpChangeNodes( triaCouples[i].first );
11655     dumpChangeNodes( triaCouples[i].second );
11656     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11657   }
11658
11659   if ( involvedNodes )
11660     for ( size_t i = 0; i < triaCouples.size(); ++i )
11661     {
11662       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11663                              triaCouples[i].first->end_nodes() );
11664       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11665                              triaCouples[i].second->end_nodes() );
11666     }
11667
11668   // just for debug dump resulting triangles
11669   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11670   for ( size_t i = 0; i < triaCouples.size(); ++i )
11671   {
11672     dumpChangeNodes( triaCouples[i].first );
11673     dumpChangeNodes( triaCouples[i].second );
11674   }
11675 }
11676
11677 //================================================================================
11678 /*!
11679  * \brief Move target node to it's final position on the FACE during shrinking
11680  */
11681 //================================================================================
11682
11683 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
11684                                  const TopoDS_Face&    F,
11685                                  _EdgesOnShape&        eos,
11686                                  SMESH_MesherHelper&   helper )
11687 {
11688   if ( Is( SHRUNK ))
11689     return false; // already at the target position
11690
11691   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11692
11693   if ( eos.SWOLType() == TopAbs_FACE )
11694   {
11695     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
11696     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11697     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11698     const double uvLen = tgtUV.Distance( curUV );
11699     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11700
11701     // Select shrinking step such that not to make faces with wrong orientation.
11702     double stepSize = 1e100;
11703     for ( size_t i = 0; i < _simplices.size(); ++i )
11704     {
11705       if ( !_simplices[i]._nPrev->isMarked() ||
11706            !_simplices[i]._nNext->isMarked() )
11707         continue; // simplex of quadrangle created by addBoundaryElements()
11708
11709       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11710       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11711       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11712       gp_XY dirN = uvN2 - uvN1;
11713       double det = uvDir.Crossed( dirN );
11714       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
11715       gp_XY dirN2Cur = curUV - uvN1;
11716       double step = dirN.Crossed( dirN2Cur ) / det;
11717       if ( step > 0 )
11718         stepSize = Min( step, stepSize );
11719     }
11720     gp_Pnt2d newUV;
11721     if ( uvLen <= stepSize )
11722     {
11723       newUV = tgtUV;
11724       Set( SHRUNK );
11725       //_pos.clear();
11726     }
11727     else if ( stepSize > 0 )
11728     {
11729       newUV = curUV + uvDir.XY() * stepSize * kSafe;
11730     }
11731     else
11732     {
11733       return true;
11734     }
11735     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11736     pos->SetUParameter( newUV.X() );
11737     pos->SetVParameter( newUV.Y() );
11738
11739 #ifdef __myDEBUG
11740     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11741     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11742     dumpMove( tgtNode );
11743 #endif
11744   }
11745   else // _sWOL is TopAbs_EDGE
11746   {
11747     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
11748     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
11749     SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
11750
11751     const double u2     = helper.GetNodeU( E, n2, tgtNode );
11752     const double uSrc   = _pos[0].Coord( U_SRC );
11753     const double lenTgt = _pos[0].Coord( LEN_TGT );
11754
11755     double newU = _pos[0].Coord( U_TGT );
11756     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11757     {
11758       Set( _LayerEdge::SHRUNK );
11759       //_pos.clear();
11760     }
11761     else
11762     {
11763       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11764     }
11765     tgtPos->SetUParameter( newU );
11766 #ifdef __myDEBUG
11767     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11768     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11769     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11770     dumpMove( tgtNode );
11771 #endif
11772   }
11773
11774   return true;
11775 }
11776
11777 //================================================================================
11778 /*!
11779  * \brief Perform smooth on the FACE
11780  *  \retval bool - true if the node has been moved
11781  */
11782 //================================================================================
11783
11784 bool _SmoothNode::Smooth(int&                  nbBad,
11785                          Handle(Geom_Surface)& surface,
11786                          SMESH_MesherHelper&   helper,
11787                          const double          refSign,
11788                          SmoothType            how,
11789                          bool                  set3D)
11790 {
11791   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11792
11793   // get uv of surrounding nodes
11794   vector<gp_XY> uv( _simplices.size() );
11795   for ( size_t i = 0; i < _simplices.size(); ++i )
11796     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11797
11798   // compute new UV for the node
11799   gp_XY newPos (0,0);
11800   if ( how == TFI && _simplices.size() == 4 )
11801   {
11802     gp_XY corners[4];
11803     for ( size_t i = 0; i < _simplices.size(); ++i )
11804       if ( _simplices[i]._nOpp )
11805         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11806       else
11807         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11808
11809     newPos = helper.calcTFI ( 0.5, 0.5,
11810                               corners[0], corners[1], corners[2], corners[3],
11811                               uv[1], uv[2], uv[3], uv[0] );
11812   }
11813   else if ( how == ANGULAR )
11814   {
11815     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11816   }
11817   else if ( how == CENTROIDAL && _simplices.size() > 3 )
11818   {
11819     // average centers of diagonals wieghted with their reciprocal lengths
11820     if ( _simplices.size() == 4 )
11821     {
11822       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11823       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11824       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11825     }
11826     else
11827     {
11828       double sumWeight = 0;
11829       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11830       for ( int i = 0; i < nb; ++i )
11831       {
11832         int iFrom = i + 2;
11833         int iTo   = i + _simplices.size() - 1;
11834         for ( int j = iFrom; j < iTo; ++j )
11835         {
11836           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11837           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11838           sumWeight += w;
11839           newPos += w * ( uv[i]+uv[i2] );
11840         }
11841       }
11842       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11843     }
11844   }
11845   else
11846   {
11847     // Laplacian smooth
11848     for ( size_t i = 0; i < _simplices.size(); ++i )
11849       newPos += uv[i];
11850     newPos /= _simplices.size();
11851   }
11852
11853   // count quality metrics (orientation) of triangles around the node
11854   int nbOkBefore = 0;
11855   gp_XY tgtUV = helper.GetNodeUV( face, _node );
11856   for ( size_t i = 0; i < _simplices.size(); ++i )
11857     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11858
11859   int nbOkAfter = 0;
11860   for ( size_t i = 0; i < _simplices.size(); ++i )
11861     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11862
11863   if ( nbOkAfter < nbOkBefore )
11864   {
11865     nbBad += _simplices.size() - nbOkBefore;
11866     return false;
11867   }
11868
11869   SMDS_FacePositionPtr pos = _node->GetPosition();
11870   pos->SetUParameter( newPos.X() );
11871   pos->SetVParameter( newPos.Y() );
11872
11873 #ifdef __myDEBUG
11874   set3D = true;
11875 #endif
11876   if ( set3D )
11877   {
11878     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
11879     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
11880     dumpMove( _node );
11881   }
11882
11883   nbBad += _simplices.size() - nbOkAfter;
11884   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
11885 }
11886
11887 //================================================================================
11888 /*!
11889  * \brief Computes new UV using angle based smoothing technique
11890  */
11891 //================================================================================
11892
11893 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
11894                                      const gp_XY&   uvToFix,
11895                                      const double   refSign)
11896 {
11897   uv.push_back( uv.front() );
11898
11899   vector< gp_XY >  edgeDir ( uv.size() );
11900   vector< double > edgeSize( uv.size() );
11901   for ( size_t i = 1; i < edgeDir.size(); ++i )
11902   {
11903     edgeDir [i-1] = uv[i] - uv[i-1];
11904     edgeSize[i-1] = edgeDir[i-1].Modulus();
11905     if ( edgeSize[i-1] < numeric_limits<double>::min() )
11906       edgeDir[i-1].SetX( 100 );
11907     else
11908       edgeDir[i-1] /= edgeSize[i-1] * refSign;
11909   }
11910   edgeDir.back()  = edgeDir.front();
11911   edgeSize.back() = edgeSize.front();
11912
11913   gp_XY  newPos(0,0);
11914   //int    nbEdges = 0;
11915   double sumSize = 0;
11916   for ( size_t i = 1; i < edgeDir.size(); ++i )
11917   {
11918     if ( edgeDir[i-1].X() > 1. ) continue;
11919     int i1 = i-1;
11920     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
11921     if ( i == edgeDir.size() ) break;
11922     gp_XY p = uv[i];
11923     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
11924     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
11925     gp_XY bisec = norm1 + norm2;
11926     double bisecSize = bisec.Modulus();
11927     if ( bisecSize < numeric_limits<double>::min() )
11928     {
11929       bisec = -edgeDir[i1] + edgeDir[i];
11930       bisecSize = bisec.Modulus();
11931     }
11932     bisec /= bisecSize;
11933
11934     gp_XY  dirToN  = uvToFix - p;
11935     double distToN = dirToN.Modulus();
11936     if ( bisec * dirToN < 0 )
11937       distToN = -distToN;
11938
11939     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
11940     //++nbEdges;
11941     sumSize += edgeSize[i1] + edgeSize[i];
11942   }
11943   newPos /= /*nbEdges * */sumSize;
11944   return newPos;
11945 }
11946
11947 //================================================================================
11948 /*!
11949  * \brief Keep a _LayerEdge inflated along the EDGE
11950  */
11951 //================================================================================
11952
11953 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
11954                            _EdgesOnShape&      eos,
11955                            SMESH_MesherHelper& helper )
11956 {
11957   // init
11958   if ( _nodes.empty() )
11959   {
11960     _edges[0] = _edges[1] = 0;
11961     _done = false;
11962   }
11963   // check _LayerEdge
11964   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
11965     return;
11966   if ( eos.SWOLType() != TopAbs_EDGE )
11967     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11968   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
11969     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11970
11971   // store _LayerEdge
11972   _geomEdge = TopoDS::Edge( eos._sWOL );
11973   double f,l;
11974   BRep_Tool::Range( _geomEdge, f,l );
11975   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
11976   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
11977
11978   // Update _nodes
11979
11980   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
11981   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
11982
11983   if ( _nodes.empty() )
11984   {
11985     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
11986     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
11987       return;
11988     TopLoc_Location loc;
11989     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
11990     GeomAdaptor_Curve aCurve(C, f,l);
11991     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
11992
11993     int nbExpectNodes = eSubMesh->NbNodes();
11994     _initU  .reserve( nbExpectNodes );
11995     _normPar.reserve( nbExpectNodes );
11996     _nodes  .reserve( nbExpectNodes );
11997     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
11998     while ( nIt->more() )
11999     {
12000       const SMDS_MeshNode* node = nIt->next();
12001
12002       // skip refinement nodes
12003       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
12004            node == tgtNode0 || node == tgtNode1 )
12005         continue;
12006       bool hasMarkedFace = false;
12007       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
12008       while ( fIt->more() && !hasMarkedFace )
12009         hasMarkedFace = fIt->next()->isMarked();
12010       if ( !hasMarkedFace )
12011         continue;
12012
12013       _nodes.push_back( node );
12014       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
12015       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
12016       _normPar.push_back(  len / totLen );
12017     }
12018   }
12019   else
12020   {
12021     // remove target node of the _LayerEdge from _nodes
12022     size_t nbFound = 0;
12023     for ( size_t i = 0; i < _nodes.size(); ++i )
12024       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
12025         _nodes[i] = 0, nbFound++;
12026     if ( nbFound == _nodes.size() )
12027       _nodes.clear();
12028   }
12029 }
12030
12031 //================================================================================
12032 /*!
12033  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
12034  */
12035 //================================================================================
12036
12037 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
12038 {
12039   if ( _done || _nodes.empty())
12040     return;
12041   const _LayerEdge* e = _edges[0];
12042   if ( !e ) e = _edges[1];
12043   if ( !e ) return;
12044
12045   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
12046             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
12047
12048   double f,l;
12049   if ( set3D || _done )
12050   {
12051     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
12052     GeomAdaptor_Curve aCurve(C, f,l);
12053
12054     if ( _edges[0] )
12055       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12056     if ( _edges[1] )
12057       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12058     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
12059
12060     for ( size_t i = 0; i < _nodes.size(); ++i )
12061     {
12062       if ( !_nodes[i] ) continue;
12063       double len = totLen * _normPar[i];
12064       GCPnts_AbscissaPoint discret( aCurve, len, f );
12065       if ( !discret.IsDone() )
12066         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
12067       double u = discret.Parameter();
12068       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12069       pos->SetUParameter( u );
12070       gp_Pnt p = C->Value( u );
12071       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
12072     }
12073   }
12074   else
12075   {
12076     BRep_Tool::Range( _geomEdge, f,l );
12077     if ( _edges[0] )
12078       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12079     if ( _edges[1] )
12080       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12081     
12082     for ( size_t i = 0; i < _nodes.size(); ++i )
12083     {
12084       if ( !_nodes[i] ) continue;
12085       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
12086       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12087       pos->SetUParameter( u );
12088     }
12089   }
12090 }
12091
12092 //================================================================================
12093 /*!
12094  * \brief Restore initial parameters of nodes on EDGE
12095  */
12096 //================================================================================
12097
12098 void _Shrinker1D::RestoreParams()
12099 {
12100   if ( _done )
12101     for ( size_t i = 0; i < _nodes.size(); ++i )
12102     {
12103       if ( !_nodes[i] ) continue;
12104       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12105       pos->SetUParameter( _initU[i] );
12106     }
12107   _done = false;
12108 }
12109
12110 //================================================================================
12111 /*!
12112  * \brief Replace source nodes by target nodes in shrunk mesh edges
12113  */
12114 //================================================================================
12115
12116 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
12117 {
12118   const SMDS_MeshNode* nodes[3];
12119   for ( int i = 0; i < 2; ++i )
12120   {
12121     if ( !_edges[i] ) continue;
12122
12123     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
12124     if ( !eSubMesh ) return;
12125     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
12126     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
12127     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
12128     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
12129     while ( eIt->more() )
12130     {
12131       const SMDS_MeshElement* e = eIt->next();
12132       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
12133           continue;
12134       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
12135       for ( int iN = 0; iN < e->NbNodes(); ++iN )
12136       {
12137         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
12138         nodes[iN] = ( n == srcNode ? tgtNode : n );
12139       }
12140       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
12141     }
12142   }
12143 }
12144
12145 //================================================================================
12146 /*!
12147  * \brief Creates 2D and 1D elements on boundaries of new prisms
12148  */
12149 //================================================================================
12150
12151 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
12152 {
12153   SMESH_MesherHelper helper( *_mesh );
12154
12155   vector< const SMDS_MeshNode* > faceNodes;
12156
12157   //for ( size_t i = 0; i < _sdVec.size(); ++i )
12158   {
12159     //_SolidData& data = _sdVec[i];
12160     TopTools_IndexedMapOfShape geomEdges;
12161     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
12162     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
12163     {
12164       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
12165       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
12166       if ( data._noShrinkShapes.count( edgeID ))
12167         continue;
12168
12169       // Get _LayerEdge's based on E
12170
12171       map< double, const SMDS_MeshNode* > u2nodes;
12172       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
12173         continue;
12174
12175       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
12176       TNode2Edge & n2eMap = data._n2eMap;
12177       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
12178       {
12179         //check if 2D elements are needed on E
12180         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
12181         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
12182         ledges.push_back( n2e->second );
12183         u2n++;
12184         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
12185           continue; // no layers on E
12186         ledges.push_back( n2eMap[ u2n->second ]);
12187
12188         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
12189         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
12190         int nbSharedPyram = 0;
12191         SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
12192         while ( vIt->more() )
12193         {
12194           const SMDS_MeshElement* v = vIt->next();
12195           nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
12196         }
12197         if ( nbSharedPyram > 1 )
12198           continue; // not free border of the pyramid
12199
12200         faceNodes.clear();
12201         faceNodes.push_back( ledges[0]->_nodes[0] );
12202         faceNodes.push_back( ledges[1]->_nodes[0] );
12203         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
12204         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
12205
12206         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
12207           continue; // faces already created
12208       }
12209       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
12210         ledges.push_back( n2eMap[ u2n->second ]);
12211
12212       // Find out orientation and type of face to create
12213
12214       bool reverse = false, isOnFace;
12215       TopoDS_Shape F;
12216
12217       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
12218       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
12219       {
12220         F = e2f->second.Oriented( TopAbs_FORWARD );
12221         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
12222         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
12223           reverse = !reverse, F.Reverse();
12224         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
12225           reverse = !reverse;
12226       }
12227       else if ( !data._ignoreFaceIds.count( e2f->first ))
12228       {
12229         // find FACE with layers sharing E
12230         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
12231         if ( fIt->more() )
12232           F = *( fIt->next() );
12233       }
12234       // Find the sub-mesh to add new faces
12235       SMESHDS_SubMesh* sm = 0;
12236       if ( isOnFace )
12237         sm = getMeshDS()->MeshElements( F );
12238       else
12239         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
12240       if ( !sm )
12241         return error("error in addBoundaryElements()", data._index);
12242
12243       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
12244       // faces for 3D meshing (PAL23414)
12245       SMESHDS_SubMesh* adjSM = 0;
12246       if ( isOnFace )
12247       {
12248         const TGeomID   faceID = sm->GetID();
12249         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
12250         while ( const TopoDS_Shape* solid = soIt->next() )
12251           if ( !solid->IsSame( data._solid ))
12252           {
12253             size_t iData = _solids.FindIndex( *solid ) - 1;
12254             if ( iData < _sdVec.size() &&
12255                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
12256                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
12257             {
12258               SMESH_ProxyMesh::SubMesh* proxySub =
12259                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
12260               if ( proxySub && proxySub->NbElements() > 0 )
12261                 adjSM = proxySub;
12262             }
12263           }
12264       }
12265
12266       // Make faces
12267       const int dj1 = reverse ? 0 : 1;
12268       const int dj2 = reverse ? 1 : 0;
12269       vector< const SMDS_MeshElement*> ff; // new faces row
12270       SMESHDS_Mesh* m = getMeshDS();
12271       for ( size_t j = 1; j < ledges.size(); ++j )
12272       {
12273         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
12274         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
12275         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
12276         if ( nn1.size() == nn2.size() )
12277         {
12278           if ( isOnFace )
12279             for ( size_t z = 1; z < nn1.size(); ++z )
12280               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12281           else
12282             for ( size_t z = 1; z < nn1.size(); ++z )
12283               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12284         }
12285         else if ( nn1.size() == 1 )
12286         {
12287           if ( isOnFace )
12288             for ( size_t z = 1; z < nn2.size(); ++z )
12289               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
12290           else
12291             for ( size_t z = 1; z < nn2.size(); ++z )
12292               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
12293         }
12294         else
12295         {
12296           if ( isOnFace )
12297             for ( size_t z = 1; z < nn1.size(); ++z )
12298               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
12299           else
12300             for ( size_t z = 1; z < nn1.size(); ++z )
12301               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
12302         }
12303
12304         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
12305         {
12306           for ( size_t z = 0; z < ff.size(); ++z )
12307             if ( ff[ z ])
12308               adjSM->AddElement( ff[ z ]);
12309           ff.clear();
12310         }
12311       }
12312
12313       // Make edges
12314       for ( int isFirst = 0; isFirst < 2; ++isFirst )
12315       {
12316         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
12317         _EdgesOnShape* eos = data.GetShapeEdges( edge );
12318         if ( eos && eos->SWOLType() == TopAbs_EDGE )
12319         {
12320           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
12321           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
12322             continue;
12323           helper.SetSubShape( eos->_sWOL );
12324           helper.SetElementsOnShape( true );
12325           for ( size_t z = 1; z < nn.size(); ++z )
12326             helper.AddEdge( nn[z-1], nn[z] );
12327         }
12328       }
12329
12330     } // loop on EDGE's
12331   } // loop on _SolidData's
12332
12333   return true;
12334 }