Salome HOME
Merge multi-study removal branch.
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "StdMeshers_FaceSide.hxx"
47 #include "StdMeshers_ViscousLayers2D.hxx"
48
49 #include <Adaptor3d_HSurface.hxx>
50 #include <BRepAdaptor_Curve.hxx>
51 #include <BRepAdaptor_Curve2d.hxx>
52 #include <BRepAdaptor_Surface.hxx>
53 //#include <BRepLProp_CLProps.hxx>
54 #include <BRepLProp_SLProps.hxx>
55 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B2d.hxx>
58 #include <Bnd_B3d.hxx>
59 #include <ElCLib.hxx>
60 #include <GCPnts_AbscissaPoint.hxx>
61 #include <GCPnts_TangentialDeflection.hxx>
62 #include <Geom2d_Circle.hxx>
63 #include <Geom2d_Line.hxx>
64 #include <Geom2d_TrimmedCurve.hxx>
65 #include <GeomAdaptor_Curve.hxx>
66 #include <GeomLib.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Geom_Line.hxx>
70 #include <Geom_TrimmedCurve.hxx>
71 #include <Precision.hxx>
72 #include <Standard_ErrorHandler.hxx>
73 #include <Standard_Failure.hxx>
74 #include <TColStd_Array1OfReal.hxx>
75 #include <TopExp.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_ListOfShape.hxx>
79 #include <TopTools_MapIteratorOfMapOfShape.hxx>
80 #include <TopTools_MapOfShape.hxx>
81 #include <TopoDS.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Vertex.hxx>
85 #include <gp_Ax1.hxx>
86 #include <gp_Cone.hxx>
87 #include <gp_Sphere.hxx>
88 #include <gp_Vec.hxx>
89 #include <gp_XY.hxx>
90
91 #include <cmath>
92 #include <limits>
93 #include <list>
94 #include <queue>
95 #include <string>
96
97 #ifdef _DEBUG_
98 #define __myDEBUG
99 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 //#define __NODES_AT_POS
101 #endif
102
103 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
104 #define BLOCK_INFLATION // of individual _LayerEdge's
105 #define OLD_NEF_POLYGON
106
107 using namespace std;
108
109 //================================================================================
110 namespace VISCOUS_3D
111 {
112   typedef int TGeomID;
113
114   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
115
116   const double theMinSmoothCosin = 0.1;
117   const double theSmoothThickToElemSizeRatio = 0.3;
118   const double theMinSmoothTriaAngle = 30;
119   const double theMinSmoothQuadAngle = 45;
120
121   // what part of thickness is allowed till intersection
122   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
123   const double theThickToIntersection = 1.5;
124
125   bool needSmoothing( double cosin, double tgtThick, double elemSize )
126   {
127     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
128   }
129   double getSmoothingThickness( double cosin, double elemSize )
130   {
131     return theSmoothThickToElemSizeRatio * elemSize / cosin;
132   }
133
134   /*!
135    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
136    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
137    */
138   struct _MeshOfSolid : public SMESH_ProxyMesh,
139                         public SMESH_subMeshEventListenerData
140   {
141     bool                  _n2nMapComputed;
142     SMESH_ComputeErrorPtr _warning;
143
144     _MeshOfSolid( SMESH_Mesh* mesh)
145       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
146     {
147       SMESH_ProxyMesh::setMesh( *mesh );
148     }
149
150     // returns submesh for a geom face
151     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
152     {
153       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
154       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
155     }
156     void setNode2Node(const SMDS_MeshNode*                 srcNode,
157                       const SMDS_MeshNode*                 proxyNode,
158                       const SMESH_ProxyMesh::SubMesh* subMesh)
159     {
160       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
161     }
162   };
163   //--------------------------------------------------------------------------------
164   /*!
165    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
166    * It is used to clear an inferior dim sub-meshes modified by viscous layers
167    */
168   class _ShrinkShapeListener : SMESH_subMeshEventListener
169   {
170     _ShrinkShapeListener()
171       : SMESH_subMeshEventListener(/*isDeletable=*/false,
172                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
173   public:
174     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
175     virtual void ProcessEvent(const int                       event,
176                               const int                       eventType,
177                               SMESH_subMesh*                  solidSM,
178                               SMESH_subMeshEventListenerData* data,
179                               const SMESH_Hypothesis*         hyp)
180     {
181       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
182       {
183         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
184       }
185     }
186   };
187   //--------------------------------------------------------------------------------
188   /*!
189    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
190    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
191    * delete the data as soon as it has been used
192    */
193   class _ViscousListener : SMESH_subMeshEventListener
194   {
195     _ViscousListener():
196       SMESH_subMeshEventListener(/*isDeletable=*/false,
197                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
198     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
199   public:
200     virtual void ProcessEvent(const int                       event,
201                               const int                       eventType,
202                               SMESH_subMesh*                  subMesh,
203                               SMESH_subMeshEventListenerData* data,
204                               const SMESH_Hypothesis*         hyp)
205     {
206       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
207           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
208             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
209       {
210         // delete SMESH_ProxyMesh containing temporary faces
211         subMesh->DeleteEventListener( this );
212       }
213     }
214     // Finds or creates proxy mesh of the solid
215     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
216                                       const TopoDS_Shape& solid,
217                                       bool                toCreate=false)
218     {
219       if ( !mesh ) return 0;
220       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
221       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
222       if ( !data && toCreate )
223       {
224         data = new _MeshOfSolid(mesh);
225         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
226         sm->SetEventListener( Get(), data, sm );
227       }
228       return data;
229     }
230     // Removes proxy mesh of the solid
231     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
232     {
233       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
234     }
235   };
236   
237   //================================================================================
238   /*!
239    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
240    * the main shape when sub-mesh of the main shape is cleared,
241    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
242    * is cleared
243    */
244   //================================================================================
245
246   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
247   {
248     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
249     SMESH_subMeshEventListenerData* data =
250       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
251     if ( data )
252     {
253       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
254            data->mySubMeshes.end())
255         data->mySubMeshes.push_back( sub );
256     }
257     else
258     {
259       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
260       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
261     }
262   }
263   struct _SolidData;
264   //--------------------------------------------------------------------------------
265   /*!
266    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
267    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
268    * The class is used to check validity of face or volumes around a smoothed node;
269    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
270    */
271   struct _Simplex
272   {
273     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
274     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
275     _Simplex(const SMDS_MeshNode* nPrev=0,
276              const SMDS_MeshNode* nNext=0,
277              const SMDS_MeshNode* nOpp=0)
278       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
279     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
280     {
281       const double M[3][3] =
282         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
283          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
284          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
285       vol = ( + M[0][0] * M[1][1] * M[2][2]
286               + M[0][1] * M[1][2] * M[2][0]
287               + M[0][2] * M[1][0] * M[2][1]
288               - M[0][0] * M[1][2] * M[2][1]
289               - M[0][1] * M[1][0] * M[2][2]
290               - M[0][2] * M[1][1] * M[2][0]);
291       return vol > 1e-100;
292     }
293     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
294     {
295       SMESH_TNodeXYZ pSrc( nSrc );
296       return IsForward( &pSrc, &pTgt, vol );
297     }
298     bool IsForward(const gp_XY&         tgtUV,
299                    const SMDS_MeshNode* smoothedNode,
300                    const TopoDS_Face&   face,
301                    SMESH_MesherHelper&  helper,
302                    const double         refSign) const
303     {
304       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
305       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
306       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
307       double d = v1 ^ v2;
308       return d*refSign > 1e-100;
309     }
310     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
311     {
312       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
313       if ( !_nOpp ) // triangle
314       {
315         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
316         double tp2 = tp.SquareMagnitude();
317         double pn2 = pn.SquareMagnitude();
318         double nt2 = nt.SquareMagnitude();
319
320         if ( tp2 < pn2 && tp2 < nt2 )
321           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
322         else if ( pn2 < nt2 )
323           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
324         else
325           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
326
327         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
328                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
329         return minAngle < theMaxCos2;
330       }
331       else // quadrangle
332       {
333         SMESH_TNodeXYZ pOpp( _nOpp );
334         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
335         double tp2 = tp.SquareMagnitude();
336         double po2 = po.SquareMagnitude();
337         double on2 = on.SquareMagnitude();
338         double nt2 = nt.SquareMagnitude();
339         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
340                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
341                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
342                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
343
344         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
345                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
346         return minAngle < theMaxCos2;
347       }
348     }
349     bool IsNeighbour(const _Simplex& other) const
350     {
351       return _nPrev == other._nNext || _nNext == other._nPrev;
352     }
353     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
354     static void GetSimplices( const SMDS_MeshNode* node,
355                               vector<_Simplex>&   simplices,
356                               const set<TGeomID>& ingnoreShapes,
357                               const _SolidData*   dataToCheckOri = 0,
358                               const bool          toSort = false);
359     static void SortSimplices(vector<_Simplex>& simplices);
360   };
361   //--------------------------------------------------------------------------------
362   /*!
363    * Structure used to take into account surface curvature while smoothing
364    */
365   struct _Curvature
366   {
367     double   _r; // radius
368     double   _k; // factor to correct node smoothed position
369     double   _h2lenRatio; // avgNormProj / (2*avgDist)
370     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
371   public:
372     static _Curvature* New( double avgNormProj, double avgDist )
373     {
374       _Curvature* c = 0;
375       if ( fabs( avgNormProj / avgDist ) > 1./200 )
376       {
377         c = new _Curvature;
378         c->_r = avgDist * avgDist / avgNormProj;
379         c->_k = avgDist * avgDist / c->_r / c->_r;
380         //c->_k = avgNormProj / c->_r;
381         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
382         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
383
384         c->_uv.SetCoord( 0., 0. );
385       }
386       return c;
387     }
388     double lenDelta(double len) const { return _k * ( _r + len ); }
389     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
390   };
391   //--------------------------------------------------------------------------------
392
393   struct _2NearEdges;
394   struct _LayerEdge;
395   struct _EdgesOnShape;
396   struct _Smoother1D;
397   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
398
399   //--------------------------------------------------------------------------------
400   /*!
401    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
402    * and a node of the most internal layer (_nodes.back())
403    */
404   struct _LayerEdge
405   {
406     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
407
408     vector< const SMDS_MeshNode*> _nodes;
409
410     gp_XYZ              _normal;    // to boundary of solid
411     vector<gp_XYZ>      _pos;       // points computed during inflation
412     double              _len;       // length achieved with the last inflation step
413     double              _maxLen;    // maximal possible length
414     double              _cosin;     // of angle (_normal ^ surface)
415     double              _minAngle;  // of _simplices
416     double              _lenFactor; // to compute _len taking _cosin into account
417     int                 _flags;
418
419     // simplices connected to the source node (_nodes[0]);
420     // used for smoothing and quality check of _LayerEdge's based on the FACE
421     vector<_Simplex>    _simplices;
422     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
423     PSmooFun            _smooFunction; // smoothing function
424     _Curvature*         _curvature;
425     // data for smoothing of _LayerEdge's based on the EDGE
426     _2NearEdges*        _2neibors;
427
428     enum EFlags { TO_SMOOTH       = 0x0000001,
429                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
430                   SMOOTHED        = 0x0000004, // set by _LayerEdge::Smooth()
431                   DIFFICULT       = 0x0000008, // near concave VERTEX
432                   ON_CONCAVE_FACE = 0x0000010,
433                   BLOCKED         = 0x0000020, // not to inflate any more
434                   INTERSECTED     = 0x0000040, // close intersection with a face found
435                   NORMAL_UPDATED  = 0x0000080,
436                   UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
437                   MARKED          = 0x0000200, // local usage
438                   MULTI_NORMAL    = 0x0000400, // a normal is invisible by some of surrounding faces
439                   NEAR_BOUNDARY   = 0x0000800, // is near FACE boundary forcing smooth
440                   SMOOTHED_C1     = 0x0001000, // is on _eosC1
441                   DISTORTED       = 0x0002000, // was bad before smoothing
442                   RISKY_SWOL      = 0x0004000, // SWOL is parallel to a source FACE
443                   SHRUNK          = 0x0008000, // target node reached a tgt position while shrink()
444                   UNUSED_FLAG     = 0x0100000  // to add user flags after
445     };
446     bool Is   ( int flag ) const { return _flags & flag; }
447     void Set  ( int flag ) { _flags |= flag; }
448     void Unset( int flag ) { _flags &= ~flag; }
449     std::string DumpFlags() const; // debug
450
451     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
452     bool SetNewLength2d( Handle(Geom_Surface)& surface,
453                          const TopoDS_Face&    F,
454                          _EdgesOnShape&        eos,
455                          SMESH_MesherHelper&   helper );
456     void SetDataByNeighbors( const SMDS_MeshNode* n1,
457                              const SMDS_MeshNode* n2,
458                              const _EdgesOnShape& eos,
459                              SMESH_MesherHelper&  helper);
460     void Block( _SolidData& data );
461     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
462     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
463                             const TNode2Edge&     n2eMap);
464     void SmoothPos( const vector< double >& segLen, const double tol );
465     int  GetSmoothedPos( const double tol );
466     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
467     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
468     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
469     void SmoothWoCheck();
470     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
471                       const TopoDS_Face&             F,
472                       SMESH_MesherHelper&            helper);
473     void MoveNearConcaVer( const _EdgesOnShape*    eov,
474                            const _EdgesOnShape*    eos,
475                            const int               step,
476                            vector< _LayerEdge* > & badSmooEdges);
477     bool FindIntersection( SMESH_ElementSearcher&   searcher,
478                            double &                 distance,
479                            const double&            epsilon,
480                            _EdgesOnShape&           eos,
481                            const SMDS_MeshElement** face = 0);
482     bool SegTriaInter( const gp_Ax1&        lastSegment,
483                        const gp_XYZ&        p0,
484                        const gp_XYZ&        p1,
485                        const gp_XYZ&        p2,
486                        double&              dist,
487                        const double&        epsilon) const;
488     bool SegTriaInter( const gp_Ax1&        lastSegment,
489                        const SMDS_MeshNode* n0,
490                        const SMDS_MeshNode* n1,
491                        const SMDS_MeshNode* n2,
492                        double&              dist,
493                        const double&        epsilon) const
494     { return SegTriaInter( lastSegment,
495                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
496                            dist, epsilon );
497     }
498     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
499     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
500     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
501     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
502     bool   IsOnEdge() const { return _2neibors; }
503     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
504     void   SetCosin( double cosin );
505     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
506     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
507     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
508     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
509       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
510     }
511     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
512
513     gp_XYZ smoothLaplacian();
514     gp_XYZ smoothAngular();
515     gp_XYZ smoothLengthWeighted();
516     gp_XYZ smoothCentroidal();
517     gp_XYZ smoothNefPolygon();
518
519     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
520     static const int theNbSmooFuns = FUN_NB;
521     static PSmooFun _funs[theNbSmooFuns];
522     static const char* _funNames[theNbSmooFuns+1];
523     int smooFunID( PSmooFun fun=0) const;
524   };
525   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
526                                                             &_LayerEdge::smoothLengthWeighted,
527                                                             &_LayerEdge::smoothCentroidal,
528                                                             &_LayerEdge::smoothNefPolygon,
529                                                             &_LayerEdge::smoothAngular };
530   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
531                                                          "LengthWeighted",
532                                                          "Centroidal",
533                                                          "NefPolygon",
534                                                          "Angular",
535                                                          "None"};
536   struct _LayerEdgeCmp
537   {
538     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
539     {
540       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
541       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
542     }
543   };
544   //--------------------------------------------------------------------------------
545   /*!
546    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
547    */
548   struct _halfPlane
549   {
550     gp_XY _pos, _dir, _inNorm;
551     bool IsOut( const gp_XY p, const double tol ) const
552     {
553       return _inNorm * ( p - _pos ) < -tol;
554     }
555     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
556     {
557       //const double eps = 1e-10;
558       double D = _dir.Crossed( hp._dir );
559       if ( fabs(D) < std::numeric_limits<double>::min())
560         return false;
561       gp_XY vec21 = _pos - hp._pos; 
562       double u = hp._dir.Crossed( vec21 ) / D; 
563       intPnt = _pos + _dir * u;
564       return true;
565     }
566   };
567   //--------------------------------------------------------------------------------
568   /*!
569    * Structure used to smooth a _LayerEdge based on an EDGE.
570    */
571   struct _2NearEdges
572   {
573     double               _wgt  [2]; // weights of _nodes
574     _LayerEdge*          _edges[2];
575
576      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
577     gp_XYZ*              _plnNorm;
578
579     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
580     const SMDS_MeshNode* tgtNode(bool is2nd) {
581       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
582     }
583     const SMDS_MeshNode* srcNode(bool is2nd) {
584       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
585     }
586     void reverse() {
587       std::swap( _wgt  [0], _wgt  [1] );
588       std::swap( _edges[0], _edges[1] );
589     }
590     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
591       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
592     }
593     bool include( const _LayerEdge* e ) {
594       return ( _edges[0] == e || _edges[1] == e );
595     }
596   };
597
598
599   //--------------------------------------------------------------------------------
600   /*!
601    * \brief Layers parameters got by averaging several hypotheses
602    */
603   struct AverageHyp
604   {
605     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
606       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
607     {
608       Add( hyp );
609     }
610     void Add( const StdMeshers_ViscousLayers* hyp )
611     {
612       if ( hyp )
613       {
614         _nbHyps++;
615         _nbLayers       = hyp->GetNumberLayers();
616         //_thickness     += hyp->GetTotalThickness();
617         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
618         _stretchFactor += hyp->GetStretchFactor();
619         _method         = hyp->GetMethod();
620       }
621     }
622     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
623     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
624     int    GetNumberLayers()   const { return _nbLayers; }
625     int    GetMethod()         const { return _method; }
626
627     bool   UseSurfaceNormal()  const
628     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
629     bool   ToSmooth()          const
630     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
631     bool   IsOffsetMethod()    const
632     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
633
634   private:
635     int     _nbLayers, _nbHyps, _method;
636     double  _thickness, _stretchFactor;
637   };
638
639   //--------------------------------------------------------------------------------
640   /*!
641    * \brief _LayerEdge's on a shape and other shape data
642    */
643   struct _EdgesOnShape
644   {
645     vector< _LayerEdge* > _edges;
646
647     TopoDS_Shape          _shape;
648     TGeomID               _shapeID;
649     SMESH_subMesh *       _subMesh;
650     // face or edge w/o layer along or near which _edges are inflated
651     TopoDS_Shape          _sWOL;
652     bool                  _isRegularSWOL; // w/o singularities
653     // averaged StdMeshers_ViscousLayers parameters
654     AverageHyp            _hyp;
655     bool                  _toSmooth;
656     _Smoother1D*          _edgeSmoother;
657     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
658     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
659
660     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
661     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
662
663     Handle(ShapeAnalysis_Surface) _offsetSurf;
664     _LayerEdge*                   _edgeForOffset;
665
666     _SolidData*            _data; // parent SOLID
667
668     _LayerEdge*      operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
669     size_t           size() const { return _edges.size(); }
670     TopAbs_ShapeEnum ShapeType() const
671     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
672     TopAbs_ShapeEnum SWOLType() const
673     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
674     bool             HasC1( const _EdgesOnShape* other ) const
675     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
676     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
677     _SolidData&      GetData() const { return *_data; }
678
679     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
680   };
681
682   //--------------------------------------------------------------------------------
683   /*!
684    * \brief Convex FACE whose radius of curvature is less than the thickness of
685    *        layers. It is used to detect distortion of prisms based on a convex
686    *        FACE and to update normals to enable further increasing the thickness
687    */
688   struct _ConvexFace
689   {
690     TopoDS_Face                     _face;
691
692     // edges whose _simplices are used to detect prism distortion
693     vector< _LayerEdge* >           _simplexTestEdges;
694
695     // map a sub-shape to _SolidData::_edgesOnShape
696     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
697
698     bool                            _isTooCurved;
699     bool                            _normalsFixed;
700     bool                            _normalsFixedOnBorders; // used in putOnOffsetSurface()
701
702     double GetMaxCurvature( _SolidData&         data,
703                             _EdgesOnShape&      eof,
704                             BRepLProp_SLProps&  surfProp,
705                             SMESH_MesherHelper& helper);
706
707     bool GetCenterOfCurvature( _LayerEdge*         ledge,
708                                BRepLProp_SLProps&  surfProp,
709                                SMESH_MesherHelper& helper,
710                                gp_Pnt &            center ) const;
711     bool CheckPrisms() const;
712   };
713
714   //--------------------------------------------------------------------------------
715   /*!
716    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
717    *        at inflation up to the full thickness. A detected collision
718    *        is fixed in updateNormals()
719    */
720   struct _CollisionEdges
721   {
722     _LayerEdge*           _edge;
723     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
724     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
725     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
726   };
727
728   //--------------------------------------------------------------------------------
729   /*!
730    * \brief Data of a SOLID
731    */
732   struct _SolidData
733   {
734     typedef const StdMeshers_ViscousLayers* THyp;
735     TopoDS_Shape                    _solid;
736     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
737     TGeomID                         _index; // SOLID id
738     _MeshOfSolid*                   _proxyMesh;
739     list< THyp >                    _hyps;
740     list< TopoDS_Shape >            _hypShapes;
741     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
742     set< TGeomID >                  _reversedFaceIds;
743     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
744
745     double                          _stepSize, _stepSizeCoeff, _geomSize;
746     const SMDS_MeshNode*            _stepSizeNodes[2];
747
748     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
749
750     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
751     map< TGeomID, TNode2Edge* >     _s2neMap;
752     // _LayerEdge's with underlying shapes
753     vector< _EdgesOnShape >         _edgesOnShape;
754
755     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
756     //        layers and a FACE w/o layers
757     // value: the shape (FACE or EDGE) to shrink mesh on.
758     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
759     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
760
761     // Convex FACEs whose radius of curvature is less than the thickness of layers
762     map< TGeomID, _ConvexFace >      _convexFaces;
763
764     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
765     // the adjacent SOLID
766     set< TGeomID >                   _noShrinkShapes;
767
768     int                              _nbShapesToSmooth;
769
770     vector< _CollisionEdges >        _collisionEdges;
771     set< TGeomID >                   _concaveFaces;
772
773     double                           _maxThickness; // of all _hyps
774     double                           _minThickness; // of all _hyps
775
776     double                           _epsilon; // precision for SegTriaInter()
777
778     SMESH_MesherHelper*              _helper;
779
780     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
781                _MeshOfSolid*       m=0)
782       :_solid(s), _proxyMesh(m), _helper(0) {}
783     ~_SolidData();
784
785     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
786     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
787
788     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
789       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
790       return id2face == _convexFaces.end() ? 0 : & id2face->second;
791     }
792     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
793     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
794     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
795     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
796
797     SMESH_MesherHelper& GetHelper() const { return *_helper; }
798
799     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
800       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
801         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
802           _edgesOnShape[i]._edges[j]->Unset( flag );
803     }
804     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
805                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
806
807     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
808   };
809   //--------------------------------------------------------------------------------
810   /*!
811    * \brief Offset plane used in getNormalByOffset()
812    */
813   struct _OffsetPlane
814   {
815     gp_Pln _plane;
816     int    _faceIndex;
817     int    _faceIndexNext[2];
818     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
819     bool   _isLineOK[2];
820     _OffsetPlane() {
821       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
822     }
823     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
824                                     const TopoDS_Edge&   E,
825                                     const TopoDS_Vertex& V );
826     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
827     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
828   };
829   //--------------------------------------------------------------------------------
830   /*!
831    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
832    */
833   struct _CentralCurveOnEdge
834   {
835     bool                  _isDegenerated;
836     vector< gp_Pnt >      _curvaCenters;
837     vector< _LayerEdge* > _ledges;
838     vector< gp_XYZ >      _normals; // new normal for each of _ledges
839     vector< double >      _segLength2;
840
841     TopoDS_Edge           _edge;
842     TopoDS_Face           _adjFace;
843     bool                  _adjFaceToSmooth;
844
845     void Append( const gp_Pnt& center, _LayerEdge* ledge )
846     {
847       if ( _curvaCenters.size() > 0 )
848         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
849       _curvaCenters.push_back( center );
850       _ledges.push_back( ledge );
851       _normals.push_back( ledge->_normal );
852     }
853     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
854     void SetShapes( const TopoDS_Edge&  edge,
855                     const _ConvexFace&  convFace,
856                     _SolidData&         data,
857                     SMESH_MesherHelper& helper);
858   };
859   //--------------------------------------------------------------------------------
860   /*!
861    * \brief Data of node on a shrinked FACE
862    */
863   struct _SmoothNode
864   {
865     const SMDS_MeshNode*         _node;
866     vector<_Simplex>             _simplices; // for quality check
867
868     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
869
870     bool Smooth(int&                  badNb,
871                 Handle(Geom_Surface)& surface,
872                 SMESH_MesherHelper&   helper,
873                 const double          refSign,
874                 SmoothType            how,
875                 bool                  set3D);
876
877     gp_XY computeAngularPos(vector<gp_XY>& uv,
878                             const gp_XY&   uvToFix,
879                             const double   refSign );
880   };
881   struct PyDump;
882   //--------------------------------------------------------------------------------
883   /*!
884    * \brief Builder of viscous layers
885    */
886   class _ViscousBuilder
887   {
888   public:
889     _ViscousBuilder();
890     // does it's job
891     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
892                                   const TopoDS_Shape& shape);
893     // check validity of hypotheses
894     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
895                                            const TopoDS_Shape& shape );
896
897     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
898     void RestoreListeners();
899
900     // computes SMESH_ProxyMesh::SubMesh::_n2n;
901     bool MakeN2NMap( _MeshOfSolid* pm );
902
903   private:
904
905     bool findSolidsWithLayers();
906     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
907     bool findFacesWithLayers(const bool onlyWith=false);
908     void getIgnoreFaces(const TopoDS_Shape&             solid,
909                         const StdMeshers_ViscousLayers* hyp,
910                         const TopoDS_Shape&             hypShape,
911                         set<TGeomID>&                   ignoreFaces);
912     bool makeLayer(_SolidData& data);
913     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
914     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
915                       SMESH_MesherHelper& helper, _SolidData& data);
916     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
917                          const TopoDS_Face&   face,
918                          SMESH_MesherHelper&  helper,
919                          bool&                isOK,
920                          bool                 shiftInside=false);
921     bool getFaceNormalAtSingularity(const gp_XY&        uv,
922                                     const TopoDS_Face&  face,
923                                     SMESH_MesherHelper& helper,
924                                     gp_Dir&             normal );
925     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
926     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
927                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
928                               int                              nbFaces,
929                               bool                             lastNoOffset = false);
930     bool findNeiborsOnEdge(const _LayerEdge*     edge,
931                            const SMDS_MeshNode*& n1,
932                            const SMDS_MeshNode*& n2,
933                            _EdgesOnShape&        eos,
934                            _SolidData&           data);
935     void findSimplexTestEdges( _SolidData&                    data,
936                                vector< vector<_LayerEdge*> >& edgesByGeom);
937     void computeGeomSize( _SolidData& data );
938     bool findShapesToSmooth( _SolidData& data);
939     void limitStepSizeByCurvature( _SolidData&  data );
940     void limitStepSize( _SolidData&             data,
941                         const SMDS_MeshElement* face,
942                         const _LayerEdge*       maxCosinEdge );
943     void limitStepSize( _SolidData& data, const double minSize);
944     bool inflate(_SolidData& data);
945     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
946     int  invalidateBadSmooth( _SolidData&               data,
947                               SMESH_MesherHelper&       helper,
948                               vector< _LayerEdge* >&    badSmooEdges,
949                               vector< _EdgesOnShape* >& eosC1,
950                               const int                 infStep );
951     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
952     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
953                              vector< _EdgesOnShape* >& eosC1,
954                              int smooStep=0, int moveAll=false );
955     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
956     void findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
957                                                 _SolidData&         data,
958                                                 SMESH_MesherHelper& helper );
959     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
960     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
961                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
962                                  SMESH_MesherHelper& helper );
963     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
964     bool updateNormalsOfConvexFaces( _SolidData&         data,
965                                      SMESH_MesherHelper& helper,
966                                      int                 stepNb );
967     void updateNormalsOfC1Vertices( _SolidData& data );
968     bool updateNormalsOfSmoothed( _SolidData&         data,
969                                   SMESH_MesherHelper& helper,
970                                   const int           nbSteps,
971                                   const double        stepSize );
972     bool isNewNormalOk( _SolidData&   data,
973                         _LayerEdge&   edge,
974                         const gp_XYZ& newNormal);
975     bool refine(_SolidData& data);
976     bool shrink(_SolidData& data);
977     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
978                               SMESH_MesherHelper& helper,
979                               const SMESHDS_SubMesh* faceSubMesh );
980     void restoreNoShrink( _LayerEdge& edge ) const;
981     void fixBadFaces(const TopoDS_Face&          F,
982                      SMESH_MesherHelper&         helper,
983                      const bool                  is2D,
984                      const int                   step,
985                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
986     bool addBoundaryElements(_SolidData& data);
987
988     bool error( const string& text, int solidID=-1 );
989     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
990
991     // debug
992     void makeGroupOfLE();
993
994     SMESH_Mesh*                _mesh;
995     SMESH_ComputeErrorPtr      _error;
996
997     vector<                    _SolidData >  _sdVec;
998     TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
999     TopTools_MapOfShape        _shrinkedFaces;
1000
1001     int                        _tmpFaceID;
1002     PyDump*                    _pyDump;
1003   };
1004   //--------------------------------------------------------------------------------
1005   /*!
1006    * \brief Shrinker of nodes on the EDGE
1007    */
1008   class _Shrinker1D
1009   {
1010     TopoDS_Edge                   _geomEdge;
1011     vector<double>                _initU;
1012     vector<double>                _normPar;
1013     vector<const SMDS_MeshNode*>  _nodes;
1014     const _LayerEdge*             _edges[2];
1015     bool                          _done;
1016   public:
1017     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1018     void Compute(bool set3D, SMESH_MesherHelper& helper);
1019     void RestoreParams();
1020     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1021     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1022     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1023     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1024     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1025     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1026   };
1027   //--------------------------------------------------------------------------------
1028   /*!
1029    * \brief Smoother of _LayerEdge's on EDGE.
1030    */
1031   struct _Smoother1D
1032   {
1033     struct OffPnt // point of the offsetted EDGE
1034     {
1035       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1036       double      _len;    // length reached at previous inflation step
1037       double      _param;  // on EDGE
1038       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1039       gp_XYZ      _edgeDir;// EDGE tangent at _param
1040       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1041     };
1042     vector< OffPnt >   _offPoints;
1043     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1044     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1045     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1046     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1047     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1048     _EdgesOnShape&     _eos;
1049     double             _curveLen; // length of the EDGE
1050     std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1051
1052     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1053                                               _EdgesOnShape&      eos,
1054                                               SMESH_MesherHelper& helper);
1055
1056     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1057                  _EdgesOnShape&     eos )
1058       : _anaCurve( curveForSmooth ), _eos( eos )
1059     {
1060     }
1061     bool Perform(_SolidData&                    data,
1062                  Handle(ShapeAnalysis_Surface)& surface,
1063                  const TopoDS_Face&             F,
1064                  SMESH_MesherHelper&            helper );
1065
1066     void prepare(_SolidData& data );
1067
1068     void findEdgesToSmooth();
1069
1070     bool isToSmooth( int iE );
1071
1072     bool smoothAnalyticEdge( _SolidData&                    data,
1073                              Handle(ShapeAnalysis_Surface)& surface,
1074                              const TopoDS_Face&             F,
1075                              SMESH_MesherHelper&            helper);
1076     bool smoothComplexEdge( _SolidData&                    data,
1077                             Handle(ShapeAnalysis_Surface)& surface,
1078                             const TopoDS_Face&             F,
1079                             SMESH_MesherHelper&            helper);
1080     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1081                             const gp_XYZ&  edgeDir);
1082     _LayerEdge* getLEdgeOnV( bool is2nd )
1083     {
1084       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1085     }
1086     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1087   };
1088   //--------------------------------------------------------------------------------
1089   /*!
1090    * \brief Class of temporary mesh face.
1091    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1092    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1093    */
1094   struct _TmpMeshFace : public SMDS_MeshElement
1095   {
1096     vector<const SMDS_MeshNode* > _nn;
1097     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1098                   int id, int faceID=-1, int idInFace=-1):
1099       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1100     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1101     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1102     virtual vtkIdType GetVtkType() const                      { return -1; }
1103     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1104     virtual SMDSAbs_GeometryType GetGeomType() const
1105     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1106     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1107     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1108   };
1109   //--------------------------------------------------------------------------------
1110   /*!
1111    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1112    */
1113   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1114   {
1115     _LayerEdge *_le1, *_le2;
1116     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1117       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1118     {
1119       _nn[0]=_le1->_nodes[0];
1120       _nn[1]=_le1->_nodes.back();
1121       _nn[2]=_le2->_nodes.back();
1122       _nn[3]=_le2->_nodes[0];
1123     }
1124     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1125     {
1126       SMESH_TNodeXYZ p0s( _nn[0] );
1127       SMESH_TNodeXYZ p0t( _nn[1] );
1128       SMESH_TNodeXYZ p1t( _nn[2] );
1129       SMESH_TNodeXYZ p1s( _nn[3] );
1130       gp_XYZ  v0 = p0t - p0s;
1131       gp_XYZ  v1 = p1t - p1s;
1132       gp_XYZ v01 = p1s - p0s;
1133       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1134       gp_XYZ   d = v01 ^ n;
1135       d.Normalize();
1136       return d;
1137     }
1138     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1139     {
1140       _nn[0]=le1->_nodes[0];
1141       _nn[1]=le1->_nodes.back();
1142       _nn[2]=le2->_nodes.back();
1143       _nn[3]=le2->_nodes[0];
1144       return GetDir();
1145     }
1146   };
1147   //--------------------------------------------------------------------------------
1148   /*!
1149    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1150    * \warning Location of a surface is ignored
1151    */
1152   struct _NodeCoordHelper
1153   {
1154     SMESH_MesherHelper&        _helper;
1155     const TopoDS_Face&         _face;
1156     Handle(Geom_Surface)       _surface;
1157     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1158
1159     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1160       : _helper( helper ), _face( F )
1161     {
1162       if ( is2D )
1163       {
1164         TopLoc_Location loc;
1165         _surface = BRep_Tool::Surface( _face, loc );
1166       }
1167       if ( _surface.IsNull() )
1168         _fun = & _NodeCoordHelper::direct;
1169       else
1170         _fun = & _NodeCoordHelper::byUV;
1171     }
1172     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1173
1174   private:
1175     gp_XYZ direct(const SMDS_MeshNode* n) const
1176     {
1177       return SMESH_TNodeXYZ( n );
1178     }
1179     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1180     {
1181       gp_XY uv = _helper.GetNodeUV( _face, n );
1182       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1183     }
1184   };
1185
1186   //================================================================================
1187   /*!
1188    * \brief Check angle between vectors 
1189    */
1190   //================================================================================
1191
1192   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1193   {
1194     double dot = v1 * v2; // cos * |v1| * |v2|
1195     double l1  = v1.SquareMagnitude();
1196     double l2  = v2.SquareMagnitude();
1197     return (( dot * cos >= 0 ) && 
1198             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1199   }
1200
1201 } // namespace VISCOUS_3D
1202
1203
1204
1205 //================================================================================
1206 // StdMeshers_ViscousLayers hypothesis
1207 //
1208 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1209   :SMESH_Hypothesis(hypId, gen),
1210    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1211    _method( SURF_OFFSET_SMOOTH )
1212 {
1213   _name = StdMeshers_ViscousLayers::GetHypType();
1214   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1215 } // --------------------------------------------------------------------------------
1216 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1217 {
1218   if ( faceIds != _shapeIds )
1219     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1220   if ( _isToIgnoreShapes != toIgnore )
1221     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1222 } // --------------------------------------------------------------------------------
1223 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1224 {
1225   if ( thickness != _thickness )
1226     _thickness = thickness, NotifySubMeshesHypothesisModification();
1227 } // --------------------------------------------------------------------------------
1228 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1229 {
1230   if ( _nbLayers != nb )
1231     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1232 } // --------------------------------------------------------------------------------
1233 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1234 {
1235   if ( _stretchFactor != factor )
1236     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1237 } // --------------------------------------------------------------------------------
1238 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1239 {
1240   if ( _method != method )
1241     _method = method, NotifySubMeshesHypothesisModification();
1242 } // --------------------------------------------------------------------------------
1243 SMESH_ProxyMesh::Ptr
1244 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1245                                   const TopoDS_Shape& theShape,
1246                                   const bool          toMakeN2NMap) const
1247 {
1248   using namespace VISCOUS_3D;
1249   _ViscousBuilder builder;
1250   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1251   if ( err && !err->IsOK() )
1252     return SMESH_ProxyMesh::Ptr();
1253
1254   vector<SMESH_ProxyMesh::Ptr> components;
1255   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1256   for ( ; exp.More(); exp.Next() )
1257   {
1258     if ( _MeshOfSolid* pm =
1259          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1260     {
1261       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1262         if ( !builder.MakeN2NMap( pm ))
1263           return SMESH_ProxyMesh::Ptr();
1264       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1265       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1266
1267       if ( pm->_warning && !pm->_warning->IsOK() )
1268       {
1269         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1270         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1271         if ( !smError || smError->IsOK() )
1272           smError = pm->_warning;
1273       }
1274     }
1275     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1276   }
1277   switch ( components.size() )
1278   {
1279   case 0: break;
1280
1281   case 1: return components[0];
1282
1283   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1284   }
1285   return SMESH_ProxyMesh::Ptr();
1286 } // --------------------------------------------------------------------------------
1287 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1288 {
1289   save << " " << _nbLayers
1290        << " " << _thickness
1291        << " " << _stretchFactor
1292        << " " << _shapeIds.size();
1293   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1294     save << " " << _shapeIds[i];
1295   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1296   save << " " << _method;
1297   return save;
1298 } // --------------------------------------------------------------------------------
1299 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1300 {
1301   int nbFaces, faceID, shapeToTreat, method;
1302   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1303   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1304     _shapeIds.push_back( faceID );
1305   if ( load >> shapeToTreat ) {
1306     _isToIgnoreShapes = !shapeToTreat;
1307     if ( load >> method )
1308       _method = (ExtrusionMethod) method;
1309   }
1310   else {
1311     _isToIgnoreShapes = true; // old behavior
1312   }
1313   return load;
1314 } // --------------------------------------------------------------------------------
1315 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1316                                                    const TopoDS_Shape& theShape)
1317 {
1318   // TODO
1319   return false;
1320 } // --------------------------------------------------------------------------------
1321 SMESH_ComputeErrorPtr
1322 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1323                                           const TopoDS_Shape&                  theShape,
1324                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1325 {
1326   VISCOUS_3D::_ViscousBuilder builder;
1327   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1328   if ( err && !err->IsOK() )
1329     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1330   else
1331     theStatus = SMESH_Hypothesis::HYP_OK;
1332
1333   return err;
1334 }
1335 // --------------------------------------------------------------------------------
1336 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1337 {
1338   bool isIn =
1339     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1340   return IsToIgnoreShapes() ? !isIn : isIn;
1341 }
1342 // END StdMeshers_ViscousLayers hypothesis
1343 //================================================================================
1344
1345 namespace VISCOUS_3D
1346 {
1347   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1348   {
1349     gp_Vec dir;
1350     double f,l;
1351     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1352     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1353     gp_Pnt p = BRep_Tool::Pnt( fromV );
1354     double distF = p.SquareDistance( c->Value( f ));
1355     double distL = p.SquareDistance( c->Value( l ));
1356     c->D1(( distF < distL ? f : l), p, dir );
1357     if ( distL < distF ) dir.Reverse();
1358     return dir.XYZ();
1359   }
1360   //--------------------------------------------------------------------------------
1361   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1362                      SMESH_MesherHelper& helper)
1363   {
1364     gp_Vec dir;
1365     double f,l; gp_Pnt p;
1366     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1367     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1368     double u = helper.GetNodeU( E, atNode );
1369     c->D1( u, p, dir );
1370     return dir.XYZ();
1371   }
1372   //--------------------------------------------------------------------------------
1373   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1374                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1375                      double* cosin=0);
1376   //--------------------------------------------------------------------------------
1377   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1378                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1379   {
1380     double f,l;
1381     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1382     if ( c.IsNull() )
1383     {
1384       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1385       return getFaceDir( F, v, node, helper, ok );
1386     }
1387     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1388     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1389     gp_Pnt p; gp_Vec du, dv, norm;
1390     surface->D1( uv.X(),uv.Y(), p, du,dv );
1391     norm = du ^ dv;
1392
1393     double u = helper.GetNodeU( fromE, node, 0, &ok );
1394     c->D1( u, p, du );
1395     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1396     if ( o == TopAbs_REVERSED )
1397       du.Reverse();
1398
1399     gp_Vec dir = norm ^ du;
1400
1401     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1402          helper.IsClosedEdge( fromE ))
1403     {
1404       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1405       else                        c->D1( f, p, dv );
1406       if ( o == TopAbs_REVERSED )
1407         dv.Reverse();
1408       gp_Vec dir2 = norm ^ dv;
1409       dir = dir.Normalized() + dir2.Normalized();
1410     }
1411     return dir.XYZ();
1412   }
1413   //--------------------------------------------------------------------------------
1414   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1415                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1416                      bool& ok, double* cosin)
1417   {
1418     TopoDS_Face faceFrw = F;
1419     faceFrw.Orientation( TopAbs_FORWARD );
1420     //double f,l; TopLoc_Location loc;
1421     TopoDS_Edge edges[2]; // sharing a vertex
1422     size_t nbEdges = 0;
1423     {
1424       TopoDS_Vertex VV[2];
1425       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1426       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1427       {
1428         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1429         if ( SMESH_Algo::isDegenerated( e )) continue;
1430         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1431         if ( VV[1].IsSame( fromV )) {
1432           nbEdges += edges[ 0 ].IsNull();
1433           edges[ 0 ] = e;
1434         }
1435         else if ( VV[0].IsSame( fromV )) {
1436           nbEdges += edges[ 1 ].IsNull();
1437           edges[ 1 ] = e;
1438         }
1439       }
1440     }
1441     gp_XYZ dir(0,0,0), edgeDir[2];
1442     if ( nbEdges == 2 )
1443     {
1444       // get dirs of edges going fromV
1445       ok = true;
1446       for ( size_t i = 0; i < nbEdges && ok; ++i )
1447       {
1448         edgeDir[i] = getEdgeDir( edges[i], fromV );
1449         double size2 = edgeDir[i].SquareModulus();
1450         if (( ok = size2 > numeric_limits<double>::min() ))
1451           edgeDir[i] /= sqrt( size2 );
1452       }
1453       if ( !ok ) return dir;
1454
1455       // get angle between the 2 edges
1456       gp_Vec faceNormal;
1457       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1458       if ( Abs( angle ) < 5 * M_PI/180 )
1459       {
1460         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1461       }
1462       else
1463       {
1464         dir = edgeDir[0] + edgeDir[1];
1465         if ( angle < 0 )
1466           dir.Reverse();
1467       }
1468       if ( cosin ) {
1469         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1470         *cosin = Cos( angle );
1471       }
1472     }
1473     else if ( nbEdges == 1 )
1474     {
1475       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1476       if ( cosin ) *cosin = 1.;
1477     }
1478     else
1479     {
1480       ok = false;
1481     }
1482
1483     return dir;
1484   }
1485
1486   //================================================================================
1487   /*!
1488    * \brief Finds concave VERTEXes of a FACE
1489    */
1490   //================================================================================
1491
1492   bool getConcaveVertices( const TopoDS_Face&  F,
1493                            SMESH_MesherHelper& helper,
1494                            set< TGeomID >*     vertices = 0)
1495   {
1496     // check angles at VERTEXes
1497     TError error;
1498     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1499     for ( size_t iW = 0; iW < wires.size(); ++iW )
1500     {
1501       const int nbEdges = wires[iW]->NbEdges();
1502       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1503         continue;
1504       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1505       {
1506         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1507         int iE2 = ( iE1 + 1 ) % nbEdges;
1508         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1509           iE2 = ( iE2 + 1 ) % nbEdges;
1510         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1511         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1512                                         wires[iW]->Edge( iE2 ), F, V );
1513         if ( angle < -5. * M_PI / 180. )
1514         {
1515           if ( !vertices )
1516             return true;
1517           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1518         }
1519       }
1520     }
1521     return vertices ? !vertices->empty() : false;
1522   }
1523
1524   //================================================================================
1525   /*!
1526    * \brief Returns true if a FACE is bound by a concave EDGE
1527    */
1528   //================================================================================
1529
1530   bool isConcave( const TopoDS_Face&  F,
1531                   SMESH_MesherHelper& helper,
1532                   set< TGeomID >*     vertices = 0 )
1533   {
1534     bool isConcv = false;
1535     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1536     //   return true;
1537     gp_Vec2d drv1, drv2;
1538     gp_Pnt2d p;
1539     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1540     for ( ; eExp.More(); eExp.Next() )
1541     {
1542       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1543       if ( SMESH_Algo::isDegenerated( E )) continue;
1544       // check if 2D curve is concave
1545       BRepAdaptor_Curve2d curve( E, F );
1546       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1547       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1548       curve.Intervals( intervals, GeomAbs_C2 );
1549       bool isConvex = true;
1550       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1551       {
1552         double u1 = intervals( i );
1553         double u2 = intervals( i+1 );
1554         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1555         double cross = drv1 ^ drv2;
1556         if ( E.Orientation() == TopAbs_REVERSED )
1557           cross = -cross;
1558         isConvex = ( cross > -1e-9 ); // 0.1 );
1559       }
1560       if ( !isConvex )
1561       {
1562         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1563         isConcv = true;
1564         if ( vertices )
1565           break;
1566         else
1567           return true;
1568       }
1569     }
1570
1571     // check angles at VERTEXes
1572     if ( getConcaveVertices( F, helper, vertices ))
1573       isConcv = true;
1574
1575     return isConcv;
1576   }
1577
1578   //================================================================================
1579   /*!
1580    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1581    *  \param [in] face - the mesh face to treat
1582    *  \param [in] nodeOnEdge - a node on the EDGE
1583    *  \param [out] faceSize - the computed distance
1584    *  \return bool - true if faceSize computed
1585    */
1586   //================================================================================
1587
1588   bool getDistFromEdge( const SMDS_MeshElement* face,
1589                         const SMDS_MeshNode*    nodeOnEdge,
1590                         double &                faceSize )
1591   {
1592     faceSize = Precision::Infinite();
1593     bool done = false;
1594
1595     int nbN  = face->NbCornerNodes();
1596     int iOnE = face->GetNodeIndex( nodeOnEdge );
1597     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1598                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1599     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1600                                       face->GetNode( iNext[1] ) };
1601     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1602     double segLen = -1.;
1603     // look for two neighbor not in-FACE nodes of face
1604     for ( int i = 0; i < 2; ++i )
1605     {
1606       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1607            nNext[i]->GetID() < nodeOnEdge->GetID() )
1608       {
1609         // look for an in-FACE node
1610         for ( int iN = 0; iN < nbN; ++iN )
1611         {
1612           if ( iN == iOnE || iN == iNext[i] )
1613             continue;
1614           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1615           gp_XYZ v = pInFace - segEnd;
1616           if ( segLen < 0 )
1617           {
1618             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1619             segLen = segVec.Modulus();
1620           }
1621           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1622           faceSize = Min( faceSize, distToSeg );
1623           done = true;
1624         }
1625         segLen = -1;
1626       }
1627     }
1628     return done;
1629   }
1630   //================================================================================
1631   /*!
1632    * \brief Return direction of axis or revolution of a surface
1633    */
1634   //================================================================================
1635
1636   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1637                           gp_Dir &                 axis )
1638   {
1639     switch ( surface.GetType() ) {
1640     case GeomAbs_Cone:
1641     {
1642       gp_Cone cone = surface.Cone();
1643       axis = cone.Axis().Direction();
1644       break;
1645     }
1646     case GeomAbs_Sphere:
1647     {
1648       gp_Sphere sphere = surface.Sphere();
1649       axis = sphere.Position().Direction();
1650       break;
1651     }
1652     case GeomAbs_SurfaceOfRevolution:
1653     {
1654       axis = surface.AxeOfRevolution().Direction();
1655       break;
1656     }
1657     //case GeomAbs_SurfaceOfExtrusion:
1658     case GeomAbs_OffsetSurface:
1659     {
1660       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1661       return getRovolutionAxis( base->Surface(), axis );
1662     }
1663     default: return false;
1664     }
1665     return true;
1666   }
1667
1668   //--------------------------------------------------------------------------------
1669   // DEBUG. Dump intermediate node positions into a python script
1670   // HOWTO use: run python commands written in a console to see
1671   //  construction steps of viscous layers
1672 #ifdef __myDEBUG
1673   ostream* py;
1674   int      theNbPyFunc;
1675   struct PyDump
1676   {
1677     PyDump(SMESH_Mesh& m) {
1678       int tag = 3 + m.GetId();
1679       const char* fname = "/tmp/viscous.py";
1680       cout << "execfile('"<<fname<<"')"<<endl;
1681       py = _pyStream = new ofstream(fname);
1682       *py << "import SMESH" << endl
1683           << "from salome.smesh import smeshBuilder" << endl
1684           << "smesh  = smeshBuilder.New()" << endl
1685           << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1686           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1687       theNbPyFunc = 0;
1688     }
1689     void Finish() {
1690       if (py) {
1691         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1692           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1693         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1694           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1695       }
1696       delete py; py=0;
1697     }
1698     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1699     struct MyStream : public ostream
1700     {
1701       template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1702     };
1703     void Pause() { py = &_mystream; }
1704     void Resume() { py = _pyStream; }
1705     MyStream _mystream;
1706     ostream* _pyStream;
1707   };
1708 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1709 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1710 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1711 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1712   void _dumpFunction(const string& fun, int ln)
1713   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1714   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1715   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1716                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1717   void _dumpCmd(const string& txt, int ln)
1718   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1719   void dumpFunctionEnd()
1720   { if (py) *py<< "  return"<< endl; }
1721   void dumpChangeNodes( const SMDS_MeshElement* f )
1722   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1723       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1724       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1725 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1726
1727 #else
1728
1729   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1730 #define dumpFunction(f) f
1731 #define dumpMove(n)
1732 #define dumpMoveComm(n,txt)
1733 #define dumpCmd(txt)
1734 #define dumpFunctionEnd()
1735 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1736 #define debugMsg( txt ) {}
1737
1738 #endif
1739 }
1740
1741 using namespace VISCOUS_3D;
1742
1743 //================================================================================
1744 /*!
1745  * \brief Constructor of _ViscousBuilder
1746  */
1747 //================================================================================
1748
1749 _ViscousBuilder::_ViscousBuilder()
1750 {
1751   _error = SMESH_ComputeError::New(COMPERR_OK);
1752   _tmpFaceID = 0;
1753 }
1754
1755 //================================================================================
1756 /*!
1757  * \brief Stores error description and returns false
1758  */
1759 //================================================================================
1760
1761 bool _ViscousBuilder::error(const string& text, int solidId )
1762 {
1763   const string prefix = string("Viscous layers builder: ");
1764   _error->myName    = COMPERR_ALGO_FAILED;
1765   _error->myComment = prefix + text;
1766   if ( _mesh )
1767   {
1768     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1769     if ( !sm && !_sdVec.empty() )
1770       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1771     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1772     {
1773       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1774       if ( smError && smError->myAlgo )
1775         _error->myAlgo = smError->myAlgo;
1776       smError = _error;
1777       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1778     }
1779     // set KO to all solids
1780     for ( size_t i = 0; i < _sdVec.size(); ++i )
1781     {
1782       if ( _sdVec[i]._index == solidId )
1783         continue;
1784       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1785       if ( !sm->IsEmpty() )
1786         continue;
1787       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1788       if ( !smError || smError->IsOK() )
1789       {
1790         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1791         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1792       }
1793     }
1794   }
1795   makeGroupOfLE(); // debug
1796
1797   return false;
1798 }
1799
1800 //================================================================================
1801 /*!
1802  * \brief At study restoration, restore event listeners used to clear an inferior
1803  *  dim sub-mesh modified by viscous layers
1804  */
1805 //================================================================================
1806
1807 void _ViscousBuilder::RestoreListeners()
1808 {
1809   // TODO
1810 }
1811
1812 //================================================================================
1813 /*!
1814  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1815  */
1816 //================================================================================
1817
1818 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1819 {
1820   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1821   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1822   for ( ; fExp.More(); fExp.Next() )
1823   {
1824     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1825     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1826
1827     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1828       continue;
1829     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1830       continue;
1831
1832     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1833       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1834
1835     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1836     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1837     while( prxIt->more() )
1838     {
1839       const SMDS_MeshElement* fSrc = srcIt->next();
1840       const SMDS_MeshElement* fPrx = prxIt->next();
1841       if ( fSrc->NbNodes() != fPrx->NbNodes())
1842         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1843       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1844         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1845     }
1846   }
1847   pm->_n2nMapComputed = true;
1848   return true;
1849 }
1850
1851 //================================================================================
1852 /*!
1853  * \brief Does its job
1854  */
1855 //================================================================================
1856
1857 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1858                                                const TopoDS_Shape& theShape)
1859 {
1860   _mesh = & theMesh;
1861
1862   // check if proxy mesh already computed
1863   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1864   if ( !exp.More() )
1865     return error("No SOLID's in theShape"), _error;
1866
1867   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1868     return SMESH_ComputeErrorPtr(); // everything already computed
1869
1870   PyDump debugDump( theMesh );
1871   _pyDump = &debugDump;
1872
1873   // TODO: ignore already computed SOLIDs 
1874   if ( !findSolidsWithLayers())
1875     return _error;
1876
1877   if ( !findFacesWithLayers() )
1878     return _error;
1879
1880   for ( size_t i = 0; i < _sdVec.size(); ++i )
1881   {
1882     size_t iSD = 0;
1883     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1884       if ( _sdVec[iSD]._before.IsEmpty() &&
1885            !_sdVec[iSD]._solid.IsNull() &&
1886            _sdVec[iSD]._n2eMap.empty() )
1887         break;
1888
1889     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1890       return _error;
1891
1892     if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1893     {
1894       _sdVec[iSD]._solid.Nullify();
1895       continue;
1896     }
1897
1898     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
1899       return _error;
1900
1901     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
1902       return _error;
1903
1904     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
1905       return _error;
1906
1907     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1908
1909     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1910     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1911       _sdVec[iSD]._before.Remove( solid );
1912   }
1913
1914   makeGroupOfLE(); // debug
1915   debugDump.Finish();
1916
1917   return _error;
1918 }
1919
1920 //================================================================================
1921 /*!
1922  * \brief Check validity of hypotheses
1923  */
1924 //================================================================================
1925
1926 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1927                                                         const TopoDS_Shape& shape )
1928 {
1929   _mesh = & mesh;
1930
1931   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1932     return SMESH_ComputeErrorPtr(); // everything already computed
1933
1934
1935   findSolidsWithLayers();
1936   bool ok = findFacesWithLayers( true );
1937
1938   // remove _MeshOfSolid's of _SolidData's
1939   for ( size_t i = 0; i < _sdVec.size(); ++i )
1940     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1941
1942   if ( !ok )
1943     return _error;
1944
1945   return SMESH_ComputeErrorPtr();
1946 }
1947
1948 //================================================================================
1949 /*!
1950  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1951  */
1952 //================================================================================
1953
1954 bool _ViscousBuilder::findSolidsWithLayers()
1955 {
1956   // get all solids
1957   TopTools_IndexedMapOfShape allSolids;
1958   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1959   _sdVec.reserve( allSolids.Extent());
1960
1961   SMESH_HypoFilter filter;
1962   for ( int i = 1; i <= allSolids.Extent(); ++i )
1963   {
1964     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1965     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1966     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1967       continue; // solid is already meshed
1968     SMESH_Algo* algo = sm->GetAlgo();
1969     if ( !algo ) continue;
1970     // TODO: check if algo is hidden
1971     const list <const SMESHDS_Hypothesis *> & allHyps =
1972       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1973     _SolidData* soData = 0;
1974     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1975     const StdMeshers_ViscousLayers* viscHyp = 0;
1976     for ( ; hyp != allHyps.end(); ++hyp )
1977       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1978       {
1979         TopoDS_Shape hypShape;
1980         filter.Init( filter.Is( viscHyp ));
1981         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1982
1983         if ( !soData )
1984         {
1985           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1986                                                                     allSolids(i),
1987                                                                     /*toCreate=*/true);
1988           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1989           soData = & _sdVec.back();
1990           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1991           soData->_helper = new SMESH_MesherHelper( *_mesh );
1992           soData->_helper->SetSubShape( allSolids(i) );
1993           _solids.Add( allSolids(i) );
1994         }
1995         soData->_hyps.push_back( viscHyp );
1996         soData->_hypShapes.push_back( hypShape );
1997       }
1998   }
1999   if ( _sdVec.empty() )
2000     return error
2001       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2002
2003   return true;
2004 }
2005
2006 //================================================================================
2007 /*!
2008  * \brief Set a _SolidData to be computed before another
2009  */
2010 //================================================================================
2011
2012 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2013 {
2014   // check possibility to set this order; get all solids before solidBefore
2015   TopTools_IndexedMapOfShape allSolidsBefore;
2016   allSolidsBefore.Add( solidBefore._solid );
2017   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2018   {
2019     int iSD = _solids.FindIndex( allSolidsBefore(i) );
2020     if ( iSD )
2021     {
2022       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2023       for ( ; soIt.More(); soIt.Next() )
2024         allSolidsBefore.Add( soIt.Value() );
2025     }
2026   }
2027   if ( allSolidsBefore.Contains( solidAfter._solid ))
2028     return false;
2029
2030   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2031     solidAfter._before.Add( allSolidsBefore(i) );
2032
2033   return true;
2034 }
2035
2036 //================================================================================
2037 /*!
2038  * \brief
2039  */
2040 //================================================================================
2041
2042 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2043 {
2044   SMESH_MesherHelper helper( *_mesh );
2045   TopExp_Explorer exp;
2046
2047   // collect all faces-to-ignore defined by hyp
2048   for ( size_t i = 0; i < _sdVec.size(); ++i )
2049   {
2050     // get faces-to-ignore defined by each hyp
2051     typedef const StdMeshers_ViscousLayers* THyp;
2052     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2053     list< TFacesOfHyp > ignoreFacesOfHyps;
2054     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2055     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2056     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2057     {
2058       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2059       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2060     }
2061
2062     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2063     const int nbHyps = _sdVec[i]._hyps.size();
2064     if ( nbHyps > 1 )
2065     {
2066       // check if two hypotheses define different parameters for the same FACE
2067       list< TFacesOfHyp >::iterator igFacesOfHyp;
2068       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2069       {
2070         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2071         THyp hyp = 0;
2072         igFacesOfHyp = ignoreFacesOfHyps.begin();
2073         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2074           if ( ! igFacesOfHyp->first.count( faceID ))
2075           {
2076             if ( hyp )
2077               return error(SMESH_Comment("Several hypotheses define "
2078                                          "Viscous Layers on the face #") << faceID );
2079             hyp = igFacesOfHyp->second;
2080           }
2081         if ( hyp )
2082           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2083         else
2084           _sdVec[i]._ignoreFaceIds.insert( faceID );
2085       }
2086
2087       // check if two hypotheses define different number of viscous layers for
2088       // adjacent faces of a solid
2089       set< int > nbLayersSet;
2090       igFacesOfHyp = ignoreFacesOfHyps.begin();
2091       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2092       {
2093         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2094       }
2095       if ( nbLayersSet.size() > 1 )
2096       {
2097         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2098         {
2099           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2100           THyp hyp1 = 0, hyp2 = 0;
2101           while( const TopoDS_Shape* face = fIt->next() )
2102           {
2103             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2104             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2105             if ( f2h != _sdVec[i]._face2hyp.end() )
2106             {
2107               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2108             }
2109           }
2110           if ( hyp1 && hyp2 &&
2111                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2112           {
2113             return error("Two hypotheses define different number of "
2114                          "viscous layers on adjacent faces");
2115           }
2116         }
2117       }
2118     } // if ( nbHyps > 1 )
2119     else
2120     {
2121       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2122     }
2123   } // loop on _sdVec
2124
2125   if ( onlyWith ) // is called to check hypotheses compatibility only
2126     return true;
2127
2128   // fill _SolidData::_reversedFaceIds
2129   for ( size_t i = 0; i < _sdVec.size(); ++i )
2130   {
2131     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2132     for ( ; exp.More(); exp.Next() )
2133     {
2134       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2135       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2136       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2137           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2138           helper.IsReversedSubMesh( face ))
2139       {
2140         _sdVec[i]._reversedFaceIds.insert( faceID );
2141       }
2142     }
2143   }
2144
2145   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2146   TopTools_IndexedMapOfShape shapes;
2147   std::string structAlgoName = "Hexa_3D";
2148   for ( size_t i = 0; i < _sdVec.size(); ++i )
2149   {
2150     shapes.Clear();
2151     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2152     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2153     {
2154       const TopoDS_Shape& edge = shapes(iE);
2155       // find 2 FACEs sharing an EDGE
2156       TopoDS_Shape FF[2];
2157       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2158       while ( fIt->more())
2159       {
2160         const TopoDS_Shape* f = fIt->next();
2161         FF[ int( !FF[0].IsNull()) ] = *f;
2162       }
2163       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2164
2165       // check presence of layers on them
2166       int ignore[2];
2167       for ( int j = 0; j < 2; ++j )
2168         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2169       if ( ignore[0] == ignore[1] )
2170         continue; // nothing interesting
2171       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2172
2173       // add EDGE to maps
2174       if ( !fWOL.IsNull())
2175       {
2176         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2177         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2178       }
2179     }
2180   }
2181
2182   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2183
2184   for ( size_t i = 0; i < _sdVec.size(); ++i )
2185   {
2186     shapes.Clear();
2187     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2188     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2189     {
2190       const TopoDS_Shape& vertex = shapes(iV);
2191       // find faces WOL sharing the vertex
2192       vector< TopoDS_Shape > facesWOL;
2193       size_t totalNbFaces = 0;
2194       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2195       while ( fIt->more())
2196       {
2197         const TopoDS_Shape* f = fIt->next();
2198         totalNbFaces++;
2199         const int fID = getMeshDS()->ShapeToIndex( *f );
2200         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2201           facesWOL.push_back( *f );
2202       }
2203       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2204         continue; // no layers at this vertex or no WOL
2205       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2206       switch ( facesWOL.size() )
2207       {
2208       case 1:
2209       {
2210         helper.SetSubShape( facesWOL[0] );
2211         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2212         {
2213           TopoDS_Shape seamEdge;
2214           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2215           while ( eIt->more() && seamEdge.IsNull() )
2216           {
2217             const TopoDS_Shape* e = eIt->next();
2218             if ( helper.IsRealSeam( *e ) )
2219               seamEdge = *e;
2220           }
2221           if ( !seamEdge.IsNull() )
2222           {
2223             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2224             break;
2225           }
2226         }
2227         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2228         break;
2229       }
2230       case 2:
2231       {
2232         // find an edge shared by 2 faces
2233         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2234         while ( eIt->more())
2235         {
2236           const TopoDS_Shape* e = eIt->next();
2237           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2238                helper.IsSubShape( *e, facesWOL[1]))
2239           {
2240             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2241           }
2242         }
2243         break;
2244       }
2245       default:
2246         return error("Not yet supported case", _sdVec[i]._index);
2247       }
2248     }
2249   }
2250
2251   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2252   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2253   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2254   for ( size_t i = 0; i < _sdVec.size(); ++i )
2255   {
2256     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2257     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2258     {
2259       const TopoDS_Shape& fWOL = e2f->second;
2260       const TGeomID     edgeID = e2f->first;
2261       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2262       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2263       if ( edge.ShapeType() != TopAbs_EDGE )
2264         continue; // shrink shape is VERTEX
2265
2266       TopoDS_Shape solid;
2267       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2268       while ( soIt->more() && solid.IsNull() )
2269       {
2270         const TopoDS_Shape* so = soIt->next();
2271         if ( !so->IsSame( _sdVec[i]._solid ))
2272           solid = *so;
2273       }
2274       if ( solid.IsNull() )
2275         continue;
2276
2277       bool noShrinkE = false;
2278       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2279       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2280       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2281       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2282       {
2283         // the adjacent SOLID has NO layers on fWOL;
2284         // shrink allowed if
2285         // - there are layers on the EDGE in the adjacent SOLID
2286         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2287         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2288         bool shrinkAllowed = (( hasWLAdj ) ||
2289                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2290         noShrinkE = !shrinkAllowed;
2291       }
2292       else if ( iSolid < _sdVec.size() )
2293       {
2294         // the adjacent SOLID has layers on fWOL;
2295         // check if SOLID's mesh is unstructured and then try to set it
2296         // to be computed after the i-th solid
2297         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2298           noShrinkE = true; // don't shrink fWOL
2299       }
2300       else
2301       {
2302         // the adjacent SOLID has NO layers at all
2303         noShrinkE = isStructured;
2304       }
2305
2306       if ( noShrinkE )
2307       {
2308         _sdVec[i]._noShrinkShapes.insert( edgeID );
2309
2310         // check if there is a collision with to-shrink-from EDGEs in iSolid
2311         // if ( iSolid < _sdVec.size() )
2312         // {
2313         //   shapes.Clear();
2314         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2315         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2316         //   {
2317         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2318         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2319         //     if ( eID == edgeID ||
2320         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2321         //          _sdVec[i]._noShrinkShapes.count( eID ))
2322         //       continue;
2323         //     for ( int is1st = 0; is1st < 2; ++is1st )
2324         //     {
2325         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2326         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2327         //       {
2328         //         return error("No way to make a conformal mesh with "
2329         //                      "the given set of faces with layers", _sdVec[i]._index);
2330         //       }
2331         //     }
2332         //   }
2333         // }
2334       }
2335
2336       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2337       // _shrinkShape2Shape is different in the adjacent SOLID
2338       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2339       {
2340         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2341         bool noShrinkV = false;
2342
2343         if ( iSolid < _sdVec.size() )
2344         {
2345           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2346           {
2347             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2348             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2349             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2350             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2351               noShrinkV = ( i2S->second.ShapeType() == TopAbs_EDGE || isStructured );
2352             else
2353               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2354           }
2355           else
2356           {
2357             noShrinkV = noShrinkE;
2358           }
2359         }
2360         else
2361         {
2362           // the adjacent SOLID has NO layers at all
2363           noShrinkV = ( isStructured ||
2364                         _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2365         }
2366         if ( noShrinkV )
2367           _sdVec[i]._noShrinkShapes.insert( vID );
2368       }
2369
2370     } // loop on _sdVec[i]._shrinkShape2Shape
2371   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2372
2373
2374     // add FACEs of other SOLIDs to _ignoreFaceIds
2375   for ( size_t i = 0; i < _sdVec.size(); ++i )
2376   {
2377     shapes.Clear();
2378     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2379
2380     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2381     {
2382       if ( !shapes.Contains( exp.Current() ))
2383         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2384     }
2385   }
2386
2387   return true;
2388 }
2389
2390 //================================================================================
2391 /*!
2392  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2393  */
2394 //================================================================================
2395
2396 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2397                                      const StdMeshers_ViscousLayers* hyp,
2398                                      const TopoDS_Shape&             hypShape,
2399                                      set<TGeomID>&                   ignoreFaceIds)
2400 {
2401   TopExp_Explorer exp;
2402
2403   vector<TGeomID> ids = hyp->GetBndShapes();
2404   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2405   {
2406     for ( size_t ii = 0; ii < ids.size(); ++ii )
2407     {
2408       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2409       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2410         ignoreFaceIds.insert( ids[ii] );
2411     }
2412   }
2413   else // FACEs with layers are given
2414   {
2415     exp.Init( solid, TopAbs_FACE );
2416     for ( ; exp.More(); exp.Next() )
2417     {
2418       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2419       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2420         ignoreFaceIds.insert( faceInd );
2421     }
2422   }
2423
2424   // ignore internal FACEs if inlets and outlets are specified
2425   if ( hyp->IsToIgnoreShapes() )
2426   {
2427     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2428     TopExp::MapShapesAndAncestors( hypShape,
2429                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2430
2431     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2432     {
2433       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2434       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2435         continue;
2436
2437       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2438       if ( nbSolids > 1 )
2439         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2440     }
2441   }
2442 }
2443
2444 //================================================================================
2445 /*!
2446  * \brief Create the inner surface of the viscous layer and prepare data for infation
2447  */
2448 //================================================================================
2449
2450 bool _ViscousBuilder::makeLayer(_SolidData& data)
2451 {
2452   // get all sub-shapes to make layers on
2453   set<TGeomID> subIds, faceIds;
2454   subIds = data._noShrinkShapes;
2455   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2456   for ( ; exp.More(); exp.Next() )
2457   {
2458     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2459     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2460       faceIds.insert( fSubM->GetId() );
2461   }
2462
2463   // make a map to find new nodes on sub-shapes shared with other SOLID
2464   map< TGeomID, TNode2Edge* >::iterator s2ne;
2465   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2466   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2467   {
2468     TGeomID shapeInd = s2s->first;
2469     for ( size_t i = 0; i < _sdVec.size(); ++i )
2470     {
2471       if ( _sdVec[i]._index == data._index ) continue;
2472       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2473       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2474            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2475       {
2476         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2477         break;
2478       }
2479     }
2480   }
2481
2482   // Create temporary faces and _LayerEdge's
2483
2484   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2485
2486   data._stepSize = Precision::Infinite();
2487   data._stepSizeNodes[0] = 0;
2488
2489   SMESH_MesherHelper helper( *_mesh );
2490   helper.SetSubShape( data._solid );
2491   helper.SetElementsOnShape( true );
2492
2493   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2494   TNode2Edge::iterator n2e2;
2495
2496   // collect _LayerEdge's of shapes they are based on
2497   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2498   const int nbShapes = getMeshDS()->MaxShapeIndex();
2499   edgesByGeom.resize( nbShapes+1 );
2500
2501   // set data of _EdgesOnShape's
2502   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2503   {
2504     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2505     while ( smIt->more() )
2506     {
2507       sm = smIt->next();
2508       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2509            !faceIds.count( sm->GetId() ))
2510         continue;
2511       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2512     }
2513   }
2514   // make _LayerEdge's
2515   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2516   {
2517     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2518     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2519     SMESH_ProxyMesh::SubMesh* proxySub =
2520       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2521
2522     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2523     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2524
2525     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2526     while ( eIt->more() )
2527     {
2528       const SMDS_MeshElement* face = eIt->next();
2529       double          faceMaxCosin = -1;
2530       _LayerEdge*     maxCosinEdge = 0;
2531       int             nbDegenNodes = 0;
2532
2533       newNodes.resize( face->NbCornerNodes() );
2534       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2535       {
2536         const SMDS_MeshNode* n = face->GetNode( i );
2537         const int      shapeID = n->getshapeId();
2538         const bool onDegenShap = helper.IsDegenShape( shapeID );
2539         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2540         if ( onDegenShap )
2541         {
2542           if ( onDegenEdge )
2543           {
2544             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2545             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2546             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2547             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2548               n = vN;
2549               nbDegenNodes++;
2550             }
2551           }
2552           else
2553           {
2554             nbDegenNodes++;
2555           }
2556         }
2557         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2558         if ( !(*n2e).second )
2559         {
2560           // add a _LayerEdge
2561           _LayerEdge* edge = new _LayerEdge();
2562           edge->_nodes.push_back( n );
2563           n2e->second = edge;
2564           edgesByGeom[ shapeID ]._edges.push_back( edge );
2565           const bool noShrink = data._noShrinkShapes.count( shapeID );
2566
2567           SMESH_TNodeXYZ xyz( n );
2568
2569           // set edge data or find already refined _LayerEdge and get data from it
2570           if (( !noShrink                                                     ) &&
2571               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2572               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2573               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2574           {
2575             _LayerEdge* foundEdge = (*n2e2).second;
2576             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2577             foundEdge->_pos.push_back( lastPos );
2578             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2579             const_cast< SMDS_MeshNode* >
2580               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2581           }
2582           else
2583           {
2584             if ( !noShrink )
2585             {
2586               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2587             }
2588             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2589               return false;
2590
2591             if ( edge->_nodes.size() < 2 )
2592               edge->Block( data );
2593               //data._noShrinkShapes.insert( shapeID );
2594           }
2595           dumpMove(edge->_nodes.back());
2596
2597           if ( edge->_cosin > faceMaxCosin )
2598           {
2599             faceMaxCosin = edge->_cosin;
2600             maxCosinEdge = edge;
2601           }
2602         }
2603         newNodes[ i ] = n2e->second->_nodes.back();
2604
2605         if ( onDegenEdge )
2606           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2607       }
2608       if ( newNodes.size() - nbDegenNodes < 2 )
2609         continue;
2610
2611       // create a temporary face
2612       const SMDS_MeshElement* newFace =
2613         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2614       proxySub->AddElement( newFace );
2615
2616       // compute inflation step size by min size of element on a convex surface
2617       if ( faceMaxCosin > theMinSmoothCosin )
2618         limitStepSize( data, face, maxCosinEdge );
2619
2620     } // loop on 2D elements on a FACE
2621   } // loop on FACEs of a SOLID to create _LayerEdge's
2622
2623
2624   // Set _LayerEdge::_neibors
2625   TNode2Edge::iterator n2e;
2626   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2627   {
2628     _EdgesOnShape& eos = data._edgesOnShape[iS];
2629     for ( size_t i = 0; i < eos._edges.size(); ++i )
2630     {
2631       _LayerEdge* edge = eos._edges[i];
2632       TIDSortedNodeSet nearNodes;
2633       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2634       while ( fIt->more() )
2635       {
2636         const SMDS_MeshElement* f = fIt->next();
2637         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2638           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2639       }
2640       nearNodes.erase( edge->_nodes[0] );
2641       edge->_neibors.reserve( nearNodes.size() );
2642       TIDSortedNodeSet::iterator node = nearNodes.begin();
2643       for ( ; node != nearNodes.end(); ++node )
2644         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2645           edge->_neibors.push_back( n2e->second );
2646     }
2647   }
2648
2649   data._epsilon = 1e-7;
2650   if ( data._stepSize < 1. )
2651     data._epsilon *= data._stepSize;
2652
2653   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2654     return false;
2655
2656   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2657   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2658
2659   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2660   const SMDS_MeshNode* nn[2];
2661   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2662   {
2663     _EdgesOnShape& eos = data._edgesOnShape[iS];
2664     for ( size_t i = 0; i < eos._edges.size(); ++i )
2665     {
2666       _LayerEdge* edge = eos._edges[i];
2667       if ( edge->IsOnEdge() )
2668       {
2669         // get neighbor nodes
2670         bool hasData = ( edge->_2neibors->_edges[0] );
2671         if ( hasData ) // _LayerEdge is a copy of another one
2672         {
2673           nn[0] = edge->_2neibors->srcNode(0);
2674           nn[1] = edge->_2neibors->srcNode(1);
2675         }
2676         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2677         {
2678           return false;
2679         }
2680         // set neighbor _LayerEdge's
2681         for ( int j = 0; j < 2; ++j )
2682         {
2683           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2684             return error("_LayerEdge not found by src node", data._index);
2685           edge->_2neibors->_edges[j] = n2e->second;
2686         }
2687         if ( !hasData )
2688           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2689       }
2690
2691       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2692       {
2693         _Simplex& s = edge->_simplices[j];
2694         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2695         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2696       }
2697
2698       // For an _LayerEdge on a degenerated EDGE, copy some data from
2699       // a corresponding _LayerEdge on a VERTEX
2700       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2701       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2702       {
2703         // Generally we should not get here
2704         if ( eos.ShapeType() != TopAbs_EDGE )
2705           continue;
2706         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2707         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2708         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2709           continue;
2710         const _LayerEdge* vEdge = n2e->second;
2711         edge->_normal    = vEdge->_normal;
2712         edge->_lenFactor = vEdge->_lenFactor;
2713         edge->_cosin     = vEdge->_cosin;
2714       }
2715
2716     } // loop on data._edgesOnShape._edges
2717   } // loop on data._edgesOnShape
2718
2719   // fix _LayerEdge::_2neibors on EDGEs to smooth
2720   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2721   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2722   //   if ( !e2c->second.IsNull() )
2723   //   {
2724   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2725   //       data.Sort2NeiborsOnEdge( eos->_edges );
2726   //   }
2727
2728   dumpFunctionEnd();
2729   return true;
2730 }
2731
2732 //================================================================================
2733 /*!
2734  * \brief Compute inflation step size by min size of element on a convex surface
2735  */
2736 //================================================================================
2737
2738 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2739                                      const SMDS_MeshElement* face,
2740                                      const _LayerEdge*       maxCosinEdge )
2741 {
2742   int iN = 0;
2743   double minSize = 10 * data._stepSize;
2744   const int nbNodes = face->NbCornerNodes();
2745   for ( int i = 0; i < nbNodes; ++i )
2746   {
2747     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2748     const SMDS_MeshNode*  curN = face->GetNode( i );
2749     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2750          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2751     {
2752       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2753       if ( dist < minSize )
2754         minSize = dist, iN = i;
2755     }
2756   }
2757   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2758   if ( newStep < data._stepSize )
2759   {
2760     data._stepSize = newStep;
2761     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2762     data._stepSizeNodes[0] = face->GetNode( iN );
2763     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2764   }
2765 }
2766
2767 //================================================================================
2768 /*!
2769  * \brief Compute inflation step size by min size of element on a convex surface
2770  */
2771 //================================================================================
2772
2773 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2774 {
2775   if ( minSize < data._stepSize )
2776   {
2777     data._stepSize = minSize;
2778     if ( data._stepSizeNodes[0] )
2779     {
2780       double dist =
2781         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2782       data._stepSizeCoeff = data._stepSize / dist;
2783     }
2784   }
2785 }
2786
2787 //================================================================================
2788 /*!
2789  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2790  */
2791 //================================================================================
2792
2793 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2794 {
2795   SMESH_MesherHelper helper( *_mesh );
2796
2797   BRepLProp_SLProps surfProp( 2, 1e-6 );
2798   data._convexFaces.clear();
2799
2800   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2801   {
2802     _EdgesOnShape& eof = data._edgesOnShape[iS];
2803     if ( eof.ShapeType() != TopAbs_FACE ||
2804          data._ignoreFaceIds.count( eof._shapeID ))
2805       continue;
2806
2807     TopoDS_Face        F = TopoDS::Face( eof._shape );
2808     const TGeomID faceID = eof._shapeID;
2809
2810     BRepAdaptor_Surface surface( F, false );
2811     surfProp.SetSurface( surface );
2812
2813     _ConvexFace cnvFace;
2814     cnvFace._face = F;
2815     cnvFace._normalsFixed = false;
2816     cnvFace._isTooCurved = false;
2817
2818     double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2819     if ( maxCurvature > 0 )
2820     {
2821       limitStepSize( data, 0.9 / maxCurvature );
2822       findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2823     }
2824     if ( !cnvFace._isTooCurved ) continue;
2825
2826     _ConvexFace & convFace =
2827       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2828
2829     // skip a closed surface (data._convexFaces is useful anyway)
2830     bool isClosedF = false;
2831     helper.SetSubShape( F );
2832     if ( helper.HasRealSeam() )
2833     {
2834       // in the closed surface there must be a closed EDGE
2835       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2836         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2837     }
2838     if ( isClosedF )
2839     {
2840       // limit _LayerEdge::_maxLen on the FACE
2841       const double oriFactor    = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2842       const double minCurvature =
2843         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2844       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2845       if ( id2eos != cnvFace._subIdToEOS.end() )
2846       {
2847         _EdgesOnShape& eos = * id2eos->second;
2848         for ( size_t i = 0; i < eos._edges.size(); ++i )
2849         {
2850           _LayerEdge* ledge = eos._edges[ i ];
2851           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2852           surfProp.SetParameters( uv.X(), uv.Y() );
2853           if ( surfProp.IsCurvatureDefined() )
2854           {
2855             double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2856                                     surfProp.MinCurvature() * oriFactor );
2857             if ( curvature > minCurvature )
2858               ledge->_maxLen = Min( ledge->_maxLen, 1. / curvature );
2859           }
2860         }
2861       }
2862       continue;
2863     }
2864
2865     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2866     // prism distortion.
2867     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2868     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2869     {
2870       // there are _LayerEdge's on the FACE it-self;
2871       // select _LayerEdge's near EDGEs
2872       _EdgesOnShape& eos = * id2eos->second;
2873       for ( size_t i = 0; i < eos._edges.size(); ++i )
2874       {
2875         _LayerEdge* ledge = eos._edges[ i ];
2876         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2877           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2878           {
2879             convFace._simplexTestEdges.push_back( ledge );
2880             break;
2881           }
2882       }
2883     }
2884     else
2885     {
2886       // where there are no _LayerEdge's on a _ConvexFace,
2887       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2888       // so that collision of viscous internal faces is not detected by check of
2889       // intersection of _LayerEdge's with the viscous internal faces.
2890
2891       set< const SMDS_MeshNode* > usedNodes;
2892
2893       // look for _LayerEdge's with null _sWOL
2894       id2eos = convFace._subIdToEOS.begin();
2895       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2896       {
2897         _EdgesOnShape& eos = * id2eos->second;
2898         if ( !eos._sWOL.IsNull() )
2899           continue;
2900         for ( size_t i = 0; i < eos._edges.size(); ++i )
2901         {
2902           _LayerEdge* ledge = eos._edges[ i ];
2903           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2904           if ( !usedNodes.insert( srcNode ).second ) continue;
2905
2906           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2907           {
2908             usedNodes.insert( ledge->_simplices[i]._nPrev );
2909             usedNodes.insert( ledge->_simplices[i]._nNext );
2910           }
2911           convFace._simplexTestEdges.push_back( ledge );
2912         }
2913       }
2914     }
2915   } // loop on FACEs of data._solid
2916 }
2917
2918 //================================================================================
2919 /*!
2920  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2921  */
2922 //================================================================================
2923
2924 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2925 {
2926   // define allowed thickness
2927   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2928
2929   data._maxThickness = 0;
2930   data._minThickness = 1e100;
2931   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2932   for ( ; hyp != data._hyps.end(); ++hyp )
2933   {
2934     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2935     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2936   }
2937   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2938
2939   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2940   // boundary inclined to the shape at a sharp angle
2941
2942   //list< TGeomID > shapesToSmooth;
2943   TopTools_MapOfShape edgesOfSmooFaces;
2944
2945   SMESH_MesherHelper helper( *_mesh );
2946   bool ok = true;
2947
2948   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2949   data._nbShapesToSmooth = 0;
2950
2951   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2952   {
2953     _EdgesOnShape& eos = edgesByGeom[iS];
2954     eos._toSmooth = false;
2955     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2956       continue;
2957
2958     double tgtThick = eos._hyp.GetTotalThickness();
2959     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2960     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2961     {
2962       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2963       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2964       if ( eE.empty() ) continue;
2965
2966       double faceSize;
2967       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2968         if ( eE[i]->_cosin > theMinSmoothCosin )
2969         {
2970           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2971           while ( fIt->more() && !eos._toSmooth )
2972           {
2973             const SMDS_MeshElement* face = fIt->next();
2974             if ( face->getshapeId() == eos._shapeID &&
2975                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2976             {
2977               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2978             }
2979           }
2980         }
2981     }
2982     if ( eos._toSmooth )
2983     {
2984       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2985         edgesOfSmooFaces.Add( eExp.Current() );
2986
2987       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2988     }
2989     data._nbShapesToSmooth += eos._toSmooth;
2990
2991   }  // check FACEs
2992
2993   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2994   {
2995     _EdgesOnShape& eos = edgesByGeom[iS];
2996     eos._edgeSmoother = NULL;
2997     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2998     if ( !eos._hyp.ToSmooth() ) continue;
2999
3000     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3001     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3002       continue;
3003
3004     double tgtThick = eos._hyp.GetTotalThickness();
3005     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3006     {
3007       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3008       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3009       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3010       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3011       double angle    = eDir.Angle( eV[0]->_normal );
3012       double cosin    = Cos( angle );
3013       double cosinAbs = Abs( cosin );
3014       if ( cosinAbs > theMinSmoothCosin )
3015       {
3016         // always smooth analytic EDGEs
3017         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3018         eos._toSmooth = ! curve.IsNull();
3019
3020         // compare tgtThick with the length of an end segment
3021         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3022         while ( eIt->more() && !eos._toSmooth )
3023         {
3024           const SMDS_MeshElement* endSeg = eIt->next();
3025           if ( endSeg->getshapeId() == (int) iS )
3026           {
3027             double segLen =
3028               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3029             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3030           }
3031         }
3032         if ( eos._toSmooth )
3033         {
3034           eos._edgeSmoother = new _Smoother1D( curve, eos );
3035
3036           // for ( size_t i = 0; i < eos._edges.size(); ++i )
3037           //   eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3038         }
3039       }
3040     }
3041     data._nbShapesToSmooth += eos._toSmooth;
3042
3043   } // check EDGEs
3044
3045   // Reset _cosin if no smooth is allowed by the user
3046   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3047   {
3048     _EdgesOnShape& eos = edgesByGeom[iS];
3049     if ( eos._edges.empty() ) continue;
3050
3051     if ( !eos._hyp.ToSmooth() )
3052       for ( size_t i = 0; i < eos._edges.size(); ++i )
3053         eos._edges[i]->SetCosin( 0 );
3054   }
3055
3056
3057   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3058
3059   TopTools_MapOfShape c1VV;
3060
3061   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3062   {
3063     _EdgesOnShape& eos = edgesByGeom[iS];
3064     if ( eos._edges.empty() ||
3065          eos.ShapeType() != TopAbs_FACE ||
3066          !eos._toSmooth )
3067       continue;
3068
3069     // check EDGEs of a FACE
3070     TopTools_MapOfShape checkedEE, allVV;
3071     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3072     while ( !smQueue.empty() )
3073     {
3074       SMESH_subMesh* sm = smQueue.front();
3075       smQueue.pop_front();
3076       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3077       while ( smIt->more() )
3078       {
3079         sm = smIt->next();
3080         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3081           allVV.Add( sm->GetSubShape() );
3082         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3083              !checkedEE.Add( sm->GetSubShape() ))
3084           continue;
3085
3086         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3087         vector<_LayerEdge*>& eE = eoe->_edges;
3088         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3089           continue;
3090
3091         bool isC1 = true; // check continuity along an EDGE
3092         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3093           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3094         if ( !isC1 )
3095           continue;
3096
3097         // check that mesh faces are C1 as well
3098         {
3099           gp_XYZ norm1, norm2;
3100           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3101           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3102           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3103             continue;
3104           while ( fIt->more() && isC1 )
3105             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3106                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3107           if ( !isC1 )
3108             continue;
3109         }
3110
3111         // add the EDGE and an adjacent FACE to _eosC1
3112         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3113         while ( const TopoDS_Shape* face = fIt->next() )
3114         {
3115           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3116           if ( !eof ) continue; // other solid
3117           if ( !eos.HasC1( eoe ))
3118           {
3119             eos._eosC1.push_back( eoe );
3120             eoe->_toSmooth = false;
3121             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3122           }
3123           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3124           {
3125             eos._eosC1.push_back( eof );
3126             eof->_toSmooth = false;
3127             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3128             smQueue.push_back( eof->_subMesh );
3129           }
3130         }
3131       }
3132     }
3133     if ( eos._eosC1.empty() )
3134       continue;
3135
3136     // check VERTEXes of C1 FACEs
3137     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3138     for ( ; vIt.More(); vIt.Next() )
3139     {
3140       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3141       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3142         continue;
3143
3144       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3145       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3146       while ( const TopoDS_Shape* face = fIt->next() )
3147       {
3148         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3149         if ( !eof ) continue; // other solid
3150         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3151         if ( !isC1 )
3152           break;
3153       }
3154       if ( isC1 )
3155       {
3156         eos._eosC1.push_back( eov );
3157         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3158         c1VV.Add( eov->_shape );
3159       }
3160     }
3161
3162   } // fill _eosC1 of FACEs
3163
3164
3165   // Find C1 EDGEs
3166
3167   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3168
3169   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3170   {
3171     _EdgesOnShape& eov = edgesByGeom[iS];
3172     if ( eov._edges.empty() ||
3173          eov.ShapeType() != TopAbs_VERTEX ||
3174          c1VV.Contains( eov._shape ))
3175       continue;
3176     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3177
3178     // get directions of surrounding EDGEs
3179     dirOfEdges.clear();
3180     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3181     while ( const TopoDS_Shape* e = fIt->next() )
3182     {
3183       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3184       if ( !eoe ) continue; // other solid
3185       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3186       if ( !Precision::IsInfinite( eDir.X() ))
3187         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3188     }
3189
3190     // find EDGEs with C1 directions
3191     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3192       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3193         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3194         {
3195           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3196           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3197           if ( isC1 )
3198           {
3199             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3200             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3201             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3202             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3203             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3204             dirOfEdges[i].first = 0;
3205             dirOfEdges[j].first = 0;
3206           }
3207         }
3208   } // fill _eosC1 of VERTEXes
3209
3210
3211
3212   return ok;
3213 }
3214
3215 //================================================================================
3216 /*!
3217  * \brief initialize data of _EdgesOnShape
3218  */
3219 //================================================================================
3220
3221 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3222                                     SMESH_subMesh* sm,
3223                                     _SolidData&    data )
3224 {
3225   if ( !eos._shape.IsNull() ||
3226        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3227     return;
3228
3229   SMESH_MesherHelper helper( *_mesh );
3230
3231   eos._subMesh = sm;
3232   eos._shapeID = sm->GetId();
3233   eos._shape   = sm->GetSubShape();
3234   if ( eos.ShapeType() == TopAbs_FACE )
3235     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3236   eos._toSmooth = false;
3237   eos._data = &data;
3238
3239   // set _SWOL
3240   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3241     data._shrinkShape2Shape.find( eos._shapeID );
3242   if ( s2s != data._shrinkShape2Shape.end() )
3243     eos._sWOL = s2s->second;
3244
3245   eos._isRegularSWOL = true;
3246   if ( eos.SWOLType() == TopAbs_FACE )
3247   {
3248     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3249     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3250     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3251   }
3252
3253   // set _hyp
3254   if ( data._hyps.size() == 1 )
3255   {
3256     eos._hyp = data._hyps.back();
3257   }
3258   else
3259   {
3260     // compute average StdMeshers_ViscousLayers parameters
3261     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3262     if ( eos.ShapeType() == TopAbs_FACE )
3263     {
3264       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3265         eos._hyp = f2hyp->second;
3266     }
3267     else
3268     {
3269       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3270       while ( const TopoDS_Shape* face = fIt->next() )
3271       {
3272         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3273         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3274           eos._hyp.Add( f2hyp->second );
3275       }
3276     }
3277   }
3278
3279   // set _faceNormals
3280   if ( ! eos._hyp.UseSurfaceNormal() )
3281   {
3282     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3283     {
3284       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3285       eos._faceNormals.resize( smDS->NbElements() );
3286
3287       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3288       for ( int iF = 0; eIt->more(); ++iF )
3289       {
3290         const SMDS_MeshElement* face = eIt->next();
3291         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3292           eos._faceNormals[iF].SetCoord( 0,0,0 );
3293       }
3294
3295       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3296         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3297           eos._faceNormals[iF].Reverse();
3298     }
3299     else // find EOS of adjacent FACEs
3300     {
3301       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3302       while ( const TopoDS_Shape* face = fIt->next() )
3303       {
3304         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3305         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3306         if ( eos._faceEOS.back()->_shape.IsNull() )
3307           // avoid using uninitialised _shapeID in GetNormal()
3308           eos._faceEOS.back()->_shapeID = faceID;
3309       }
3310     }
3311   }
3312 }
3313
3314 //================================================================================
3315 /*!
3316  * \brief Returns normal of a face
3317  */
3318 //================================================================================
3319
3320 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3321 {
3322   bool ok = false;
3323   const _EdgesOnShape* eos = 0;
3324
3325   if ( face->getshapeId() == _shapeID )
3326   {
3327     eos = this;
3328   }
3329   else
3330   {
3331     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3332       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3333         eos = _faceEOS[ iF ];
3334   }
3335
3336   if (( eos ) &&
3337       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3338   {
3339     norm = eos->_faceNormals[ face->getIdInShape() ];
3340   }
3341   else if ( !eos )
3342   {
3343     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3344               << " on _shape #" << _shapeID );
3345   }
3346   return ok;
3347 }
3348
3349
3350 //================================================================================
3351 /*!
3352  * \brief Set data of _LayerEdge needed for smoothing
3353  */
3354 //================================================================================
3355
3356 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3357                                   _EdgesOnShape&      eos,
3358                                   SMESH_MesherHelper& helper,
3359                                   _SolidData&         data)
3360 {
3361   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3362
3363   edge._len       = 0;
3364   edge._maxLen    = Precision::Infinite();
3365   edge._minAngle  = 0;
3366   edge._2neibors  = 0;
3367   edge._curvature = 0;
3368   edge._flags     = 0;
3369
3370   // --------------------------
3371   // Compute _normal and _cosin
3372   // --------------------------
3373
3374   edge._cosin     = 0;
3375   edge._lenFactor = 1.;
3376   edge._normal.SetCoord(0,0,0);
3377   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3378
3379   int totalNbFaces = 0;
3380   TopoDS_Face F;
3381   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3382   gp_Vec geomNorm;
3383   bool normOK = true;
3384
3385   const bool onShrinkShape = !eos._sWOL.IsNull();
3386   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3387                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3388
3389   // get geom FACEs the node lies on
3390   //if ( useGeometry )
3391   {
3392     set<TGeomID> faceIds;
3393     if  ( eos.ShapeType() == TopAbs_FACE )
3394     {
3395       faceIds.insert( eos._shapeID );
3396     }
3397     else
3398     {
3399       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3400       while ( fIt->more() )
3401         faceIds.insert( fIt->next()->getshapeId() );
3402     }
3403     set<TGeomID>::iterator id = faceIds.begin();
3404     for ( ; id != faceIds.end(); ++id )
3405     {
3406       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3407       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3408         continue;
3409       F = TopoDS::Face( s );
3410       face2Norm[ totalNbFaces ].first = F;
3411       totalNbFaces++;
3412     }
3413   }
3414
3415   // find _normal
3416   bool fromVonF = false;
3417   if ( useGeometry )
3418   {
3419     fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3420                  eos.SWOLType()  == TopAbs_FACE  &&
3421                  totalNbFaces > 1 );
3422
3423     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3424     {
3425       if ( eos.SWOLType() == TopAbs_EDGE )
3426       {
3427         // inflate from VERTEX along EDGE
3428         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3429       }
3430       else if ( eos.ShapeType() == TopAbs_VERTEX )
3431       {
3432         // inflate from VERTEX along FACE
3433         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3434                                    node, helper, normOK, &edge._cosin);
3435       }
3436       else
3437       {
3438         // inflate from EDGE along FACE
3439         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3440                                    node, helper, normOK);
3441       }
3442     }
3443     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3444     {
3445       if ( fromVonF )
3446         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3447
3448       int nbOkNorms = 0;
3449       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3450       {
3451         F = face2Norm[ iF ].first;
3452         geomNorm = getFaceNormal( node, F, helper, normOK );
3453         if ( !normOK ) continue;
3454         nbOkNorms++;
3455
3456         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3457           geomNorm.Reverse();
3458         face2Norm[ iF ].second = geomNorm.XYZ();
3459         edge._normal += geomNorm.XYZ();
3460       }
3461       if ( nbOkNorms == 0 )
3462         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3463
3464       if ( totalNbFaces >= 3 )
3465       {
3466         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3467       }
3468
3469       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3470       {
3471         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3472         edge._normal.SetCoord( 0,0,0 );
3473         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3474         {
3475           const TopoDS_Face& F = face2Norm[iF].first;
3476           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3477           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3478             geomNorm.Reverse();
3479           if ( normOK )
3480             face2Norm[ iF ].second = geomNorm.XYZ();
3481           edge._normal += face2Norm[ iF ].second;
3482         }
3483       }
3484     }
3485   }
3486   else // !useGeometry - get _normal using surrounding mesh faces
3487   {
3488     edge._normal = getWeigthedNormal( &edge );
3489
3490     // set<TGeomID> faceIds;
3491     //
3492     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3493     // while ( fIt->more() )
3494     // {
3495     //   const SMDS_MeshElement* face = fIt->next();
3496     //   if ( eos.GetNormal( face, geomNorm ))
3497     //   {
3498     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3499     //       continue; // use only one mesh face on FACE
3500     //     edge._normal += geomNorm.XYZ();
3501     //     totalNbFaces++;
3502     //   }
3503     // }
3504   }
3505
3506   // compute _cosin
3507   //if ( eos._hyp.UseSurfaceNormal() )
3508   {
3509     switch ( eos.ShapeType() )
3510     {
3511     case TopAbs_FACE: {
3512       edge._cosin = 0;
3513       break;
3514     }
3515     case TopAbs_EDGE: {
3516       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3517       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3518       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3519       edge._cosin      = Cos( angle );
3520       break;
3521     }
3522     case TopAbs_VERTEX: {
3523       if ( fromVonF )
3524       {
3525         getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3526                     node, helper, normOK, &edge._cosin );
3527       }
3528       else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3529       {
3530         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3531         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3532         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3533         edge._cosin      = Cos( angle );
3534         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3535           for ( int iF = 1; iF < totalNbFaces; ++iF )
3536           {
3537             F = face2Norm[ iF ].first;
3538             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3539             if ( normOK ) {
3540               double angle = inFaceDir.Angle( edge._normal );
3541               double cosin = Cos( angle );
3542               if ( Abs( cosin ) > Abs( edge._cosin ))
3543                 edge._cosin = cosin;
3544             }
3545           }
3546       }
3547       break;
3548     }
3549     default:
3550       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3551     }
3552   }
3553
3554   double normSize = edge._normal.SquareModulus();
3555   if ( normSize < numeric_limits<double>::min() )
3556     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3557
3558   edge._normal /= sqrt( normSize );
3559
3560   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3561   {
3562     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3563     edge._nodes.resize( 1 );
3564     edge._normal.SetCoord( 0,0,0 );
3565     edge._maxLen = 0;
3566   }
3567
3568   // Set the rest data
3569   // --------------------
3570
3571   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3572
3573   if ( onShrinkShape )
3574   {
3575     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3576     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3577       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3578
3579     // set initial position which is parameters on _sWOL in this case
3580     if ( eos.SWOLType() == TopAbs_EDGE )
3581     {
3582       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3583       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3584       if ( edge._nodes.size() > 1 )
3585         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3586     }
3587     else // eos.SWOLType() == TopAbs_FACE
3588     {
3589       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3590       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3591       if ( edge._nodes.size() > 1 )
3592         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3593     }
3594
3595     if ( edge._nodes.size() > 1 )
3596     {
3597       // check if an angle between a FACE with layers and SWOL is sharp,
3598       // else the edge should not inflate
3599       F.Nullify();
3600       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3601         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3602           F = face2Norm[iF].first;
3603       if ( !F.IsNull())
3604       {
3605         geomNorm = getFaceNormal( node, F, helper, normOK );
3606         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3607           geomNorm.Reverse(); // inside the SOLID
3608         if ( geomNorm * edge._normal < -0.001 )
3609         {
3610           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3611           edge._nodes.resize( 1 );
3612         }
3613         else if ( edge._lenFactor > 3 )
3614         {
3615           edge._lenFactor = 2;
3616           edge.Set( _LayerEdge::RISKY_SWOL );
3617         }
3618       }
3619     }
3620   }
3621   else
3622   {
3623     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3624
3625     if ( eos.ShapeType() == TopAbs_FACE )
3626     {
3627       double angle;
3628       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3629       {
3630         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3631         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3632       }
3633     }
3634   }
3635
3636   // Set neighbor nodes for a _LayerEdge based on EDGE
3637
3638   if ( eos.ShapeType() == TopAbs_EDGE /*||
3639        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3640   {
3641     edge._2neibors = new _2NearEdges;
3642     // target nodes instead of source ones will be set later
3643   }
3644
3645   return true;
3646 }
3647
3648 //================================================================================
3649 /*!
3650  * \brief Return normal to a FACE at a node
3651  *  \param [in] n - node
3652  *  \param [in] face - FACE
3653  *  \param [in] helper - helper
3654  *  \param [out] isOK - true or false
3655  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3656  *  \return gp_XYZ - normal
3657  */
3658 //================================================================================
3659
3660 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3661                                       const TopoDS_Face&   face,
3662                                       SMESH_MesherHelper&  helper,
3663                                       bool&                isOK,
3664                                       bool                 shiftInside)
3665 {
3666   gp_XY uv;
3667   if ( shiftInside )
3668   {
3669     // get a shifted position
3670     gp_Pnt p = SMESH_TNodeXYZ( node );
3671     gp_XYZ shift( 0,0,0 );
3672     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3673     switch ( S.ShapeType() ) {
3674     case TopAbs_VERTEX:
3675     {
3676       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3677       break;
3678     }
3679     case TopAbs_EDGE:
3680     {
3681       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3682       break;
3683     }
3684     default:
3685       isOK = false;
3686     }
3687     if ( isOK )
3688       shift.Normalize();
3689     p.Translate( shift * 1e-5 );
3690
3691     TopLoc_Location loc;
3692     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3693
3694     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3695     
3696     projector.Perform( p );
3697     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3698     {
3699       isOK = false;
3700       return p.XYZ();
3701     }
3702     Quantity_Parameter U,V;
3703     projector.LowerDistanceParameters(U,V);
3704     uv.SetCoord( U,V );
3705   }
3706   else
3707   {
3708     uv = helper.GetNodeUV( face, node, 0, &isOK );
3709   }
3710
3711   gp_Dir normal;
3712   isOK = false;
3713
3714   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3715
3716   if ( !shiftInside &&
3717        helper.IsDegenShape( node->getshapeId() ) &&
3718        getFaceNormalAtSingularity( uv, face, helper, normal ))
3719   {
3720     isOK = true;
3721     return normal.XYZ();
3722   }
3723
3724   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3725   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3726
3727   if ( pointKind == IMPOSSIBLE &&
3728        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3729   {
3730     // probably NormEstim() failed due to a too high tolerance
3731     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3732     isOK = ( pointKind < IMPOSSIBLE );
3733   }
3734   if ( pointKind < IMPOSSIBLE )
3735   {
3736     if ( pointKind != REGULAR &&
3737          !shiftInside &&
3738          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3739     {
3740       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3741       if ( normShift * normal.XYZ() < 0. )
3742         normal = normShift;
3743     }
3744     isOK = true;
3745   }
3746
3747   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3748   {
3749     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3750
3751     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3752     while ( fIt->more() )
3753     {
3754       const SMDS_MeshElement* f = fIt->next();
3755       if ( f->getshapeId() == faceID )
3756       {
3757         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3758         if ( isOK )
3759         {
3760           TopoDS_Face ff = face;
3761           ff.Orientation( TopAbs_FORWARD );
3762           if ( helper.IsReversedSubMesh( ff ))
3763             normal.Reverse();
3764           break;
3765         }
3766       }
3767     }
3768   }
3769   return normal.XYZ();
3770 }
3771
3772 //================================================================================
3773 /*!
3774  * \brief Try to get normal at a singularity of a surface basing on it's nature
3775  */
3776 //================================================================================
3777
3778 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3779                                                   const TopoDS_Face&  face,
3780                                                   SMESH_MesherHelper& helper,
3781                                                   gp_Dir&             normal )
3782 {
3783   BRepAdaptor_Surface surface( face );
3784   gp_Dir axis;
3785   if ( !getRovolutionAxis( surface, axis ))
3786     return false;
3787
3788   double f,l, d, du, dv;
3789   f = surface.FirstUParameter();
3790   l = surface.LastUParameter();
3791   d = ( uv.X() - f ) / ( l - f );
3792   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3793   f = surface.FirstVParameter();
3794   l = surface.LastVParameter();
3795   d = ( uv.Y() - f ) / ( l - f );
3796   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3797
3798   gp_Dir refDir;
3799   gp_Pnt2d testUV = uv;
3800   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3801   double tol = 1e-5;
3802   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3803   for ( int iLoop = 0; true ; ++iLoop )
3804   {
3805     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3806     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3807       break;
3808     if ( iLoop > 20 )
3809       return false;
3810     tol /= 10.;
3811   }
3812
3813   if ( axis * refDir < 0. )
3814     axis.Reverse();
3815
3816   normal = axis;
3817
3818   return true;
3819 }
3820
3821 //================================================================================
3822 /*!
3823  * \brief Return a normal at a node weighted with angles taken by faces
3824  */
3825 //================================================================================
3826
3827 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3828 {
3829   const SMDS_MeshNode* n = edge->_nodes[0];
3830
3831   gp_XYZ resNorm(0,0,0);
3832   SMESH_TNodeXYZ p0( n ), pP, pN;
3833   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3834   {
3835     pP.Set( edge->_simplices[i]._nPrev );
3836     pN.Set( edge->_simplices[i]._nNext );
3837     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3838     double l0P = v0P.SquareMagnitude();
3839     double l0N = v0N.SquareMagnitude();
3840     double lPN = vPN.SquareMagnitude();
3841     if ( l0P < std::numeric_limits<double>::min() ||
3842          l0N < std::numeric_limits<double>::min() ||
3843          lPN < std::numeric_limits<double>::min() )
3844       continue;
3845     double lNorm = norm.SquareMagnitude();
3846     double  sin2 = lNorm / l0P / l0N;
3847     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3848
3849     double weight = sin2 * angle / lPN;
3850     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3851   }
3852
3853   return resNorm;
3854 }
3855
3856 //================================================================================
3857 /*!
3858  * \brief Return a normal at a node by getting a common point of offset planes
3859  *        defined by the FACE normals
3860  */
3861 //================================================================================
3862
3863 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3864                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3865                                            int                              nbFaces,
3866                                            bool                             lastNoOffset)
3867 {
3868   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3869
3870   gp_XYZ resNorm(0,0,0);
3871   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3872   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3873   {
3874     for ( int i = 0; i < nbFaces; ++i )
3875       resNorm += f2Normal[i].second;
3876     return resNorm;
3877   }
3878
3879   // prepare _OffsetPlane's
3880   vector< _OffsetPlane > pln( nbFaces );
3881   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3882   {
3883     pln[i]._faceIndex = i;
3884     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3885   }
3886   if ( lastNoOffset )
3887   {
3888     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3889     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3890   }
3891
3892   // intersect neighboring OffsetPlane's
3893   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3894   while ( const TopoDS_Shape* edge = edgeIt->next() )
3895   {
3896     int f1 = -1, f2 = -1;
3897     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3898       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3899         (( f1 < 0 ) ? f1 : f2 ) = i;
3900
3901     if ( f2 >= 0 )
3902       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3903   }
3904
3905   // get a common point
3906   gp_XYZ commonPnt( 0, 0, 0 );
3907   int nbPoints = 0;
3908   bool isPointFound;
3909   for ( int i = 0; i < nbFaces; ++i )
3910   {
3911     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3912     nbPoints  += isPointFound;
3913   }
3914   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3915   if ( nbPoints == 0 )
3916     return wgtNorm;
3917
3918   commonPnt /= nbPoints;
3919   resNorm = commonPnt - p0;
3920   if ( lastNoOffset )
3921     return resNorm;
3922
3923   // choose the best among resNorm and wgtNorm
3924   resNorm.Normalize();
3925   wgtNorm.Normalize();
3926   double resMinDot = std::numeric_limits<double>::max();
3927   double wgtMinDot = std::numeric_limits<double>::max();
3928   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3929   {
3930     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3931     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3932   }
3933
3934   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3935   {
3936     edge->Set( _LayerEdge::MULTI_NORMAL );
3937   }
3938
3939   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3940 }
3941
3942 //================================================================================
3943 /*!
3944  * \brief Compute line of intersection of 2 planes
3945  */
3946 //================================================================================
3947
3948 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3949                                             const TopoDS_Edge&   E,
3950                                             const TopoDS_Vertex& V )
3951 {
3952   int iNext = bool( _faceIndexNext[0] >= 0 );
3953   _faceIndexNext[ iNext ] = pln._faceIndex;
3954
3955   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3956   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3957
3958   gp_XYZ lineDir = n1 ^ n2;
3959
3960   double x = Abs( lineDir.X() );
3961   double y = Abs( lineDir.Y() );
3962   double z = Abs( lineDir.Z() );
3963
3964   int cooMax; // max coordinate
3965   if (x > y) {
3966     if (x > z) cooMax = 1;
3967     else       cooMax = 3;
3968   }
3969   else {
3970     if (y > z) cooMax = 2;
3971     else       cooMax = 3;
3972   }
3973
3974   gp_Pnt linePos;
3975   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3976   {
3977     // parallel planes - intersection is an offset of the common EDGE
3978     gp_Pnt p = BRep_Tool::Pnt( V );
3979     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3980     lineDir  = getEdgeDir( E, V );
3981   }
3982   else
3983   {
3984     // the constants in the 2 plane equations
3985     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3986     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3987
3988     switch ( cooMax ) {
3989     case 1:
3990       linePos.SetX(  0 );
3991       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3992       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3993       break;
3994     case 2:
3995       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3996       linePos.SetY(  0 );
3997       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3998       break;
3999     case 3:
4000       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4001       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4002       linePos.SetZ(  0 );
4003     }
4004   }
4005   gp_Lin& line = _lines[ iNext ];
4006   line.SetDirection( lineDir );
4007   line.SetLocation ( linePos );
4008
4009   _isLineOK[ iNext ] = true;
4010
4011
4012   iNext = bool( pln._faceIndexNext[0] >= 0 );
4013   pln._lines        [ iNext ] = line;
4014   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4015   pln._isLineOK     [ iNext ] = true;
4016 }
4017
4018 //================================================================================
4019 /*!
4020  * \brief Computes intersection point of two _lines
4021  */
4022 //================================================================================
4023
4024 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4025                                     const TopoDS_Vertex & V) const
4026 {
4027   gp_XYZ p( 0,0,0 );
4028   isFound = false;
4029
4030   if ( NbLines() == 2 )
4031   {
4032     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4033     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4034     if ( Abs( dot01 ) > 0.05 )
4035     {
4036       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4037       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4038       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4039       isFound = true;
4040     }
4041     else
4042     {
4043       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4044       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4045       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4046       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4047       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4048       isFound = true;
4049     }
4050   }
4051
4052   return p;
4053 }
4054
4055 //================================================================================
4056 /*!
4057  * \brief Find 2 neigbor nodes of a node on EDGE
4058  */
4059 //================================================================================
4060
4061 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4062                                         const SMDS_MeshNode*& n1,
4063                                         const SMDS_MeshNode*& n2,
4064                                         _EdgesOnShape&        eos,
4065                                         _SolidData&           data)
4066 {
4067   const SMDS_MeshNode* node = edge->_nodes[0];
4068   const int        shapeInd = eos._shapeID;
4069   SMESHDS_SubMesh*   edgeSM = 0;
4070   if ( eos.ShapeType() == TopAbs_EDGE )
4071   {
4072     edgeSM = eos._subMesh->GetSubMeshDS();
4073     if ( !edgeSM || edgeSM->NbElements() == 0 )
4074       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4075   }
4076   int iN = 0;
4077   n2 = 0;
4078   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4079   while ( eIt->more() && !n2 )
4080   {
4081     const SMDS_MeshElement* e = eIt->next();
4082     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4083     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4084     if ( edgeSM )
4085     {
4086       if (!edgeSM->Contains(e)) continue;
4087     }
4088     else
4089     {
4090       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4091       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4092     }
4093     ( iN++ ? n2 : n1 ) = nNeibor;
4094   }
4095   if ( !n2 )
4096     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4097   return true;
4098 }
4099
4100 //================================================================================
4101 /*!
4102  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4103  */
4104 //================================================================================
4105
4106 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4107                                      const SMDS_MeshNode* n2,
4108                                      const _EdgesOnShape& eos,
4109                                      SMESH_MesherHelper&  helper)
4110 {
4111   if ( eos.ShapeType() != TopAbs_EDGE )
4112     return;
4113
4114   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4115   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4116   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4117
4118   // Set _curvature
4119
4120   double      sumLen = vec1.Modulus() + vec2.Modulus();
4121   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4122   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4123   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4124   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4125   if ( _curvature ) delete _curvature;
4126   _curvature = _Curvature::New( avgNormProj, avgLen );
4127   // if ( _curvature )
4128   //   debugMsg( _nodes[0]->GetID()
4129   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4130   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4131   //             << _curvature->lenDelta(0) );
4132
4133   // Set _plnNorm
4134
4135   if ( eos._sWOL.IsNull() )
4136   {
4137     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4138     // if ( SMESH_Algo::isDegenerated( E ))
4139     //   return;
4140     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4141     gp_XYZ plnNorm = dirE ^ _normal;
4142     double proj0   = plnNorm * vec1;
4143     double proj1   = plnNorm * vec2;
4144     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4145     {
4146       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4147       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4148     }
4149   }
4150 }
4151
4152 //================================================================================
4153 /*!
4154  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4155  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4156  */
4157 //================================================================================
4158
4159 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4160                          _EdgesOnShape&      eos,
4161                          SMESH_MesherHelper& helper )
4162 {
4163   _nodes     = other._nodes;
4164   _normal    = other._normal;
4165   _len       = 0;
4166   _lenFactor = other._lenFactor;
4167   _cosin     = other._cosin;
4168   _2neibors  = other._2neibors;
4169   _curvature = 0; std::swap( _curvature, other._curvature );
4170   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4171
4172   gp_XYZ lastPos( 0,0,0 );
4173   if ( eos.SWOLType() == TopAbs_EDGE )
4174   {
4175     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4176     _pos.push_back( gp_XYZ( u, 0, 0));
4177
4178     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4179     lastPos.SetX( u );
4180   }
4181   else // TopAbs_FACE
4182   {
4183     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4184     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4185
4186     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4187     lastPos.SetX( uv.X() );
4188     lastPos.SetY( uv.Y() );
4189   }
4190   return lastPos;
4191 }
4192
4193 //================================================================================
4194 /*!
4195  * \brief Set _cosin and _lenFactor
4196  */
4197 //================================================================================
4198
4199 void _LayerEdge::SetCosin( double cosin )
4200 {
4201   _cosin = cosin;
4202   cosin = Abs( _cosin );
4203   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4204   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4205 }
4206
4207 //================================================================================
4208 /*!
4209  * \brief Check if another _LayerEdge is a neighbor on EDGE
4210  */
4211 //================================================================================
4212
4213 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4214 {
4215   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4216           ( edge->_2neibors && edge->_2neibors->include( this )));
4217 }
4218
4219 //================================================================================
4220 /*!
4221  * \brief Fills a vector<_Simplex > 
4222  */
4223 //================================================================================
4224
4225 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4226                              vector<_Simplex>&    simplices,
4227                              const set<TGeomID>&  ingnoreShapes,
4228                              const _SolidData*    dataToCheckOri,
4229                              const bool           toSort)
4230 {
4231   simplices.clear();
4232   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4233   while ( fIt->more() )
4234   {
4235     const SMDS_MeshElement* f = fIt->next();
4236     const TGeomID    shapeInd = f->getshapeId();
4237     if ( ingnoreShapes.count( shapeInd )) continue;
4238     const int nbNodes = f->NbCornerNodes();
4239     const int  srcInd = f->GetNodeIndex( node );
4240     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4241     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4242     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4243     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4244       std::swap( nPrev, nNext );
4245     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4246   }
4247
4248   if ( toSort )
4249     SortSimplices( simplices );
4250 }
4251
4252 //================================================================================
4253 /*!
4254  * \brief Set neighbor simplices side by side
4255  */
4256 //================================================================================
4257
4258 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4259 {
4260   vector<_Simplex> sortedSimplices( simplices.size() );
4261   sortedSimplices[0] = simplices[0];
4262   size_t nbFound = 0;
4263   for ( size_t i = 1; i < simplices.size(); ++i )
4264   {
4265     for ( size_t j = 1; j < simplices.size(); ++j )
4266       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4267       {
4268         sortedSimplices[i] = simplices[j];
4269         nbFound++;
4270         break;
4271       }
4272   }
4273   if ( nbFound == simplices.size() - 1 )
4274     simplices.swap( sortedSimplices );
4275 }
4276
4277 //================================================================================
4278 /*!
4279  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4280  */
4281 //================================================================================
4282
4283 void _ViscousBuilder::makeGroupOfLE()
4284 {
4285 #ifdef _DEBUG_
4286   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4287   {
4288     if ( _sdVec[i]._n2eMap.empty() ) continue;
4289
4290     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4291     TNode2Edge::iterator n2e;
4292     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4293     {
4294       _LayerEdge* le = n2e->second;
4295       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4296       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4297       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4298       if ( le ) {
4299         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4300                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4301       }
4302     }
4303     dumpFunctionEnd();
4304
4305     dumpFunction( SMESH_Comment("makeNormals") << i );
4306     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4307     {
4308       _LayerEdge* edge = n2e->second;
4309       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4310       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4311       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4312               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4313     }
4314     dumpFunctionEnd();
4315
4316     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4317     dumpCmd( "faceId1 = mesh.NbElements()" );
4318     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4319     for ( ; fExp.More(); fExp.Next() )
4320     {
4321       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4322       {
4323         if ( sm->NbElements() == 0 ) continue;
4324         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4325         while ( fIt->more())
4326         {
4327           const SMDS_MeshElement* e = fIt->next();
4328           SMESH_Comment cmd("mesh.AddFace([");
4329           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4330             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4331           dumpCmd( cmd );
4332         }
4333       }
4334     }
4335     dumpCmd( "faceId2 = mesh.NbElements()" );
4336     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4337              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4338              << "'%s-%s' % (faceId1+1, faceId2))");
4339     dumpFunctionEnd();
4340   }
4341 #endif
4342 }
4343
4344 //================================================================================
4345 /*!
4346  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4347  */
4348 //================================================================================
4349
4350 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4351 {
4352   data._geomSize = Precision::Infinite();
4353   double intersecDist;
4354   const SMDS_MeshElement* face;
4355   SMESH_MesherHelper helper( *_mesh );
4356
4357   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4358     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4359                                            data._proxyMesh->GetFaces( data._solid )));
4360
4361   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4362   {
4363     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4364     if ( eos._edges.empty() )
4365       continue;
4366     // get neighbor faces intersection with which should not be considered since
4367     // collisions are avoided by means of smoothing
4368     set< TGeomID > neighborFaces;
4369     if ( eos._hyp.ToSmooth() )
4370     {
4371       SMESH_subMeshIteratorPtr subIt =
4372         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4373       while ( subIt->more() )
4374       {
4375         SMESH_subMesh* sm = subIt->next();
4376         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4377         while ( const TopoDS_Shape* face = fIt->next() )
4378           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4379       }
4380     }
4381     // find intersections
4382     double thinkness = eos._hyp.GetTotalThickness();
4383     for ( size_t i = 0; i < eos._edges.size(); ++i )
4384     {
4385       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4386       eos._edges[i]->_maxLen = thinkness;
4387       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4388       if ( intersecDist > 0 && face )
4389       {
4390         data._geomSize = Min( data._geomSize, intersecDist );
4391         if ( !neighborFaces.count( face->getshapeId() ))
4392           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4393       }
4394     }
4395   }
4396 }
4397
4398 //================================================================================
4399 /*!
4400  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4401  */
4402 //================================================================================
4403
4404 bool _ViscousBuilder::inflate(_SolidData& data)
4405 {
4406   SMESH_MesherHelper helper( *_mesh );
4407
4408   // Limit inflation step size by geometry size found by itersecting
4409   // normals of _LayerEdge's with mesh faces
4410   if ( data._stepSize > 0.3 * data._geomSize )
4411     limitStepSize( data, 0.3 * data._geomSize );
4412
4413   const double tgtThick = data._maxThickness;
4414   if ( data._stepSize > data._minThickness )
4415     limitStepSize( data, data._minThickness );
4416
4417   if ( data._stepSize < 1. )
4418     data._epsilon = data._stepSize * 1e-7;
4419
4420   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4421   _pyDump->Pause();
4422
4423   findCollisionEdges( data, helper );
4424
4425   limitMaxLenByCurvature( data, helper );
4426
4427   _pyDump->Resume();
4428
4429   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4430   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4431     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4432          data._edgesOnShape[i]._edges.size() > 0 &&
4433          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4434     {
4435       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4436       data._edgesOnShape[i]._edges[0]->Block( data );
4437     }
4438
4439   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4440
4441   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4442   int nbSteps = 0, nbRepeats = 0;
4443   while ( avgThick < 0.99 )
4444   {
4445     // new target length
4446     double prevThick = curThick;
4447     curThick += data._stepSize;
4448     if ( curThick > tgtThick )
4449     {
4450       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4451       nbRepeats++;
4452     }
4453
4454     double stepSize = curThick - prevThick;
4455     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4456
4457     // Elongate _LayerEdge's
4458     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4459     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4460     {
4461       _EdgesOnShape& eos = data._edgesOnShape[iS];
4462       if ( eos._edges.empty() ) continue;
4463
4464       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4465       for ( size_t i = 0; i < eos._edges.size(); ++i )
4466       {
4467         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4468       }
4469     }
4470     dumpFunctionEnd();
4471
4472     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4473       return false;
4474
4475     // Improve and check quality
4476     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4477     {
4478       if ( nbSteps > 0 )
4479       {
4480 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4481         debugMsg("NOT INVALIDATED STEP!");
4482         return error("Smoothing failed", data._index);
4483 #endif
4484         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4485         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4486         {
4487           _EdgesOnShape& eos = data._edgesOnShape[iS];
4488           for ( size_t i = 0; i < eos._edges.size(); ++i )
4489             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4490         }
4491         dumpFunctionEnd();
4492       }
4493       break; // no more inflating possible
4494     }
4495     nbSteps++;
4496
4497     // Evaluate achieved thickness
4498     avgThick = 0;
4499     int nbActiveEdges = 0;
4500     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4501     {
4502       _EdgesOnShape& eos = data._edgesOnShape[iS];
4503       if ( eos._edges.empty() ) continue;
4504
4505       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4506       for ( size_t i = 0; i < eos._edges.size(); ++i )
4507       {
4508         if ( eos._edges[i]->_nodes.size() > 1 )
4509           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4510         else
4511           avgThick    += shapeTgtThick;
4512         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4513       }
4514     }
4515     avgThick /= data._n2eMap.size();
4516     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4517
4518 #ifdef BLOCK_INFLATION
4519     if ( nbActiveEdges == 0 )
4520     {
4521       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4522       break;
4523     }
4524 #else
4525     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4526     {
4527       debugMsg( "-- Stop inflation since "
4528                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4529                 << tgtThick * avgThick << " ) * " << safeFactor );
4530       break;
4531     }
4532 #endif
4533     // new step size
4534     limitStepSize( data, 0.25 * distToIntersection );
4535     if ( data._stepSizeNodes[0] )
4536       data._stepSize = data._stepSizeCoeff *
4537         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4538
4539   } // while ( avgThick < 0.99 )
4540
4541   if ( nbSteps == 0 )
4542     return error("failed at the very first inflation step", data._index);
4543
4544   if ( avgThick < 0.99 )
4545   {
4546     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4547     {
4548       data._proxyMesh->_warning.reset
4549         ( new SMESH_ComputeError (COMPERR_WARNING,
4550                                   SMESH_Comment("Thickness ") << tgtThick <<
4551                                   " of viscous layers not reached,"
4552                                   " average reached thickness is " << avgThick*tgtThick));
4553     }
4554   }
4555
4556   // Restore position of src nodes moved by inflation on _noShrinkShapes
4557   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4558   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4559   {
4560     _EdgesOnShape& eos = data._edgesOnShape[iS];
4561     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4562       for ( size_t i = 0; i < eos._edges.size(); ++i )
4563       {
4564         restoreNoShrink( *eos._edges[ i ] );
4565       }
4566   }
4567   dumpFunctionEnd();
4568
4569   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4570 }
4571
4572 //================================================================================
4573 /*!
4574  * \brief Improve quality of layer inner surface and check intersection
4575  */
4576 //================================================================================
4577
4578 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4579                                      const int   infStep,
4580                                      double &    distToIntersection)
4581 {
4582   if ( data._nbShapesToSmooth == 0 )
4583     return true; // no shapes needing smoothing
4584
4585   bool moved, improved;
4586   double vol;
4587   vector< _LayerEdge* >    movedEdges, badEdges;
4588   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4589   vector< bool >           isConcaveFace;
4590
4591   SMESH_MesherHelper helper(*_mesh);
4592   Handle(ShapeAnalysis_Surface) surface;
4593   TopoDS_Face F;
4594
4595   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4596   {
4597     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4598
4599     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4600     {
4601       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4602       if ( !eos._toSmooth ||
4603            eos.ShapeType() != shapeType ||
4604            eos._edges.empty() )
4605         continue;
4606
4607       // already smoothed?
4608       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4609       // if ( !toSmooth ) continue;
4610
4611       if ( !eos._hyp.ToSmooth() )
4612       {
4613         // smooth disabled by the user; check validy only
4614         if ( !isFace ) continue;
4615         badEdges.clear();
4616         for ( size_t i = 0; i < eos._edges.size(); ++i )
4617         {
4618           _LayerEdge* edge = eos._edges[i];
4619           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4620             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4621             {
4622               // debugMsg( "-- Stop inflation. Bad simplex ("
4623               //           << " "<< edge->_nodes[0]->GetID()
4624               //           << " "<< edge->_nodes.back()->GetID()
4625               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4626               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4627               // return false;
4628               badEdges.push_back( edge );
4629             }
4630         }
4631         if ( !badEdges.empty() )
4632         {
4633           eosC1.resize(1);
4634           eosC1[0] = &eos;
4635           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4636           if ( nbBad > 0 )
4637             return false;
4638         }
4639         continue; // goto the next EDGE or FACE
4640       }
4641
4642       // prepare data
4643       if ( eos.SWOLType() == TopAbs_FACE )
4644       {
4645         if ( !F.IsSame( eos._sWOL )) {
4646           F = TopoDS::Face( eos._sWOL );
4647           helper.SetSubShape( F );
4648           surface = helper.GetSurface( F );
4649         }
4650       }
4651       else
4652       {
4653         F.Nullify(); surface.Nullify();
4654       }
4655       const TGeomID sInd = eos._shapeID;
4656
4657       // perform smoothing
4658
4659       if ( eos.ShapeType() == TopAbs_EDGE )
4660       {
4661         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4662
4663         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4664         {
4665           // smooth on EDGE's (normally we should not get here)
4666           int step = 0;
4667           do {
4668             moved = false;
4669             for ( size_t i = 0; i < eos._edges.size(); ++i )
4670             {
4671               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4672             }
4673             dumpCmd( SMESH_Comment("# end step ")<<step);
4674           }
4675           while ( moved && step++ < 5 );
4676         }
4677         dumpFunctionEnd();
4678       }
4679
4680       else // smooth on FACE
4681       {
4682         eosC1.clear();
4683         eosC1.push_back( & eos );
4684         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4685
4686         movedEdges.clear();
4687         isConcaveFace.resize( eosC1.size() );
4688         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4689         {
4690           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4691           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4692           for ( size_t i = 0; i < edges.size(); ++i )
4693             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4694                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4695               movedEdges.push_back( edges[i] );
4696
4697           makeOffsetSurface( *eosC1[ iEOS ], helper );
4698         }
4699
4700         int step = 0, stepLimit = 5, nbBad = 0;
4701         while (( ++step <= stepLimit ) || improved )
4702         {
4703           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4704                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4705           int oldBadNb = nbBad;
4706           badEdges.clear();
4707
4708 #ifdef INCREMENTAL_SMOOTH
4709           bool findBest = false; // ( step == stepLimit );
4710           for ( size_t i = 0; i < movedEdges.size(); ++i )
4711           {
4712             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4713             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4714               badEdges.push_back( movedEdges[i] );
4715           }
4716 #else
4717           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4718           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4719           {
4720             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4721             for ( size_t i = 0; i < edges.size(); ++i )
4722             {
4723               edges[i]->Unset( _LayerEdge::SMOOTHED );
4724               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4725                 badEdges.push_back( eos._edges[i] );
4726             }
4727           }
4728 #endif
4729           nbBad = badEdges.size();
4730
4731           if ( nbBad > 0 )
4732             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4733
4734           if ( !badEdges.empty() && step >= stepLimit / 2 )
4735           {
4736             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4737               stepLimit = 9;
4738
4739             // resolve hard smoothing situation around concave VERTEXes
4740             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4741             {
4742               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4743               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4744                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4745                                                          step, badEdges );
4746             }
4747             // look for the best smooth of _LayerEdge's neighboring badEdges
4748             nbBad = 0;
4749             for ( size_t i = 0; i < badEdges.size(); ++i )
4750             {
4751               _LayerEdge* ledge = badEdges[i];
4752               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4753               {
4754                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4755                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4756               }
4757               ledge->Unset( _LayerEdge::SMOOTHED );
4758               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4759             }
4760             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4761           }
4762
4763           if ( nbBad == oldBadNb  &&
4764                nbBad > 0 &&
4765                step < stepLimit ) // smooth w/o chech of validity
4766           {
4767             dumpFunctionEnd();
4768             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4769                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4770             for ( size_t i = 0; i < movedEdges.size(); ++i )
4771             {
4772               movedEdges[i]->SmoothWoCheck();
4773             }
4774             if ( stepLimit < 9 )
4775               stepLimit++;
4776           }
4777
4778           improved = ( nbBad < oldBadNb );
4779
4780           dumpFunctionEnd();
4781
4782           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4783             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4784             {
4785               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4786             }
4787
4788         } // smoothing steps
4789
4790         // project -- to prevent intersections or fix bad simplices
4791         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4792         {
4793           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4794             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4795         }
4796
4797         //if ( !badEdges.empty() )
4798         {
4799           badEdges.clear();
4800           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4801           {
4802             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4803             {
4804               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4805
4806               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4807               edge->CheckNeiborsOnBoundary( & badEdges );
4808               if (( nbBad > 0 ) ||
4809                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4810               {
4811                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4812                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4813                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4814                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4815                   {
4816                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4817                              << " "<< tgtXYZ._node->GetID()
4818                              << " "<< edge->_simplices[j]._nPrev->GetID()
4819                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4820                     badEdges.push_back( edge );
4821                     break;
4822                   }
4823               }
4824             }
4825           }
4826
4827           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4828           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4829
4830           if ( nbBad > 0 )
4831             return false;
4832         }
4833
4834       } // // smooth on FACE's
4835     } // loop on shapes
4836   } // smooth on [ EDGEs, FACEs ]
4837
4838   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4839   eosC1.resize(1);
4840   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4841   {
4842     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4843     if ( eos.ShapeType() == TopAbs_FACE ||
4844          eos._edges.empty() ||
4845          !eos._sWOL.IsNull() )
4846       continue;
4847
4848     badEdges.clear();
4849     for ( size_t i = 0; i < eos._edges.size(); ++i )
4850     {
4851       _LayerEdge*      edge = eos._edges[i];
4852       if ( edge->_nodes.size() < 2 ) continue;
4853       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4854       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4855       //const gp_XYZ& prevXYZ = edge->PrevPos();
4856       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4857         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4858         {
4859           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4860                    << " "<< tgtXYZ._node->GetID()
4861                    << " "<< edge->_simplices[j]._nPrev->GetID()
4862                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4863           badEdges.push_back( edge );
4864           break;
4865         }
4866     }
4867
4868     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4869     eosC1[0] = &eos;
4870     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4871     if ( nbBad > 0 )
4872       return false;
4873   }
4874
4875
4876   // Check if the last segments of _LayerEdge intersects 2D elements;
4877   // checked elements are either temporary faces or faces on surfaces w/o the layers
4878
4879   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4880     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4881                                            data._proxyMesh->GetFaces( data._solid )) );
4882
4883 #ifdef BLOCK_INFLATION
4884   const bool toBlockInfaltion = true;
4885 #else
4886   const bool toBlockInfaltion = false;
4887 #endif
4888   distToIntersection = Precision::Infinite();
4889   double dist;
4890   const SMDS_MeshElement* intFace = 0;
4891   const SMDS_MeshElement* closestFace = 0;
4892   _LayerEdge* le = 0;
4893   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4894   {
4895     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4896     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4897       continue;
4898     for ( size_t i = 0; i < eos._edges.size(); ++i )
4899     {
4900       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4901            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4902         continue;
4903       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4904       {
4905         return false;
4906         // commented due to "Illegal hash-positionPosition" error in NETGEN
4907         // on Debian60 on viscous_layers_01/B2 case
4908         // Collision; try to deflate _LayerEdge's causing it
4909         // badEdges.clear();
4910         // badEdges.push_back( eos._edges[i] );
4911         // eosC1[0] = & eos;
4912         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4913         // if ( nbBad > 0 )
4914         //   return false;
4915
4916         // badEdges.clear();
4917         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4918         // {
4919         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4920         //   {
4921         //     const SMDS_MeshElement* srcFace =
4922         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4923         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4924         //     while ( nIt->more() )
4925         //     {
4926         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4927         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4928         //       if ( n2e != data._n2eMap.end() )
4929         //         badEdges.push_back( n2e->second );
4930         //     }
4931         //     eosC1[0] = eof;
4932         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4933         //     if ( nbBad > 0 )
4934         //       return false;
4935         //   }
4936         // }
4937         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4938         //   return false;
4939         // else
4940         //   continue;
4941       }
4942       if ( !intFace )
4943       {
4944         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4945         debugMsg( msg );
4946         continue;
4947       }
4948
4949       const bool isShorterDist = ( distToIntersection > dist );
4950       if ( toBlockInfaltion || isShorterDist )
4951       {
4952         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4953         // lying on this _ConvexFace
4954         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4955           if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
4956             continue;
4957
4958         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4959         // ( avoid limiting the thickness on the case of issue 22576)
4960         if ( intFace->getshapeId() == eos._shapeID  )
4961           continue;
4962
4963         // ignore intersection with intFace of an adjacent FACE
4964         if ( dist > 0 )
4965         {
4966           bool toIgnore = false;
4967           if (  eos._toSmooth )
4968           {
4969             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4970             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4971             {
4972               TopExp_Explorer sub( eos._shape,
4973                                    eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
4974               for ( ; !toIgnore && sub.More(); sub.Next() )
4975                 // is adjacent - has a common EDGE or VERTEX
4976                 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
4977
4978               if ( toIgnore ) // check angle between normals
4979               {
4980                 gp_XYZ normal;
4981                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4982                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4983               }
4984             }
4985           }
4986           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4987           {
4988             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4989             {
4990               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4991               toIgnore = ( nInd >= 0 );
4992             }
4993           }
4994           if ( toIgnore )
4995             continue;
4996         }
4997
4998         // intersection not ignored
4999
5000         if ( toBlockInfaltion &&
5001              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5002         {
5003           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5004           eos._edges[i]->Block( data );                  // not to inflate
5005
5006           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5007           {
5008             // block _LayerEdge's, on top of which intFace is
5009             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5010             {
5011               const SMDS_MeshElement* srcFace =
5012                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5013               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5014               while ( nIt->more() )
5015               {
5016                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5017                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5018                 if ( n2e != data._n2eMap.end() )
5019                   n2e->second->Block( data );
5020               }
5021             }
5022           }
5023         }
5024
5025         if ( isShorterDist )
5026         {
5027           distToIntersection = dist;
5028           le = eos._edges[i];
5029           closestFace = intFace;
5030         }
5031
5032       } // if ( toBlockInfaltion || isShorterDist )
5033     } // loop on eos._edges
5034   } // loop on data._edgesOnShape
5035
5036   if ( closestFace && le )
5037   {
5038 #ifdef __myDEBUG
5039     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5040     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5041          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5042          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5043          << ") distance = " << distToIntersection<< endl;
5044 #endif
5045   }
5046
5047   return true;
5048 }
5049
5050 //================================================================================
5051 /*!
5052  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5053  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5054  *  \return int - resulting nb of bad _LayerEdge's
5055  */
5056 //================================================================================
5057
5058 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5059                                           SMESH_MesherHelper&       helper,
5060                                           vector< _LayerEdge* >&    badSmooEdges,
5061                                           vector< _EdgesOnShape* >& eosC1,
5062                                           const int                 infStep )
5063 {
5064   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5065
5066   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5067
5068   enum {
5069     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5070     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5071     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5072   };
5073   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5074
5075   double vol;
5076   bool haveInvalidated = true;
5077   while ( haveInvalidated )
5078   {
5079     haveInvalidated = false;
5080     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5081     {
5082       _LayerEdge*   edge = badSmooEdges[i];
5083       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5084       edge->Set( ADDED );
5085       bool invalidated = false;
5086       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5087       {
5088         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5089         edge->Block( data );
5090         edge->Set( INVALIDATED );
5091         edge->Unset( TO_INVALIDATE );
5092         invalidated = true;
5093         haveInvalidated = true;
5094       }
5095
5096       // look for _LayerEdge's of bad _simplices
5097       int nbBad = 0;
5098       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5099       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5100       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5101       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5102       {
5103         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5104             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5105           continue;
5106
5107         bool isBad = true;
5108         _LayerEdge* ee[2] = { 0,0 };
5109         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5110           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5111             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5112
5113         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5114         while ( maxNbSteps > edge->NbSteps() && isBad )
5115         {
5116           --maxNbSteps;
5117           for ( int iE = 0; iE < 2; ++iE )
5118           {
5119             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5120                  ee[ iE ]->NbSteps() > 1 )
5121             {
5122               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5123               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5124               ee[ iE ]->Block( data );
5125               ee[ iE ]->Set( INVALIDATED );
5126               haveInvalidated = true;
5127             }
5128           }
5129           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5130               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5131             isBad = false;
5132         }
5133         nbBad += isBad;
5134         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5135         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5136         ee[0]->Set( ADDED );
5137         ee[1]->Set( ADDED );
5138         if ( isBad )
5139         {
5140           ee[0]->Set( TO_INVALIDATE );
5141           ee[1]->Set( TO_INVALIDATE );
5142         }
5143       }
5144
5145       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5146       {
5147         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5148         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5149         edge->Block( data );
5150         edge->Set( INVALIDATED );
5151         edge->Unset( TO_INVALIDATE );
5152         haveInvalidated = true;
5153       }
5154     } // loop on badSmooEdges
5155   } // while ( haveInvalidated )
5156
5157   // re-smooth on analytical EDGEs
5158   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5159   {
5160     _LayerEdge* edge = badSmooEdges[i];
5161     if ( !edge->Is( INVALIDATED )) continue;
5162
5163     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5164     if ( eos->ShapeType() == TopAbs_VERTEX )
5165     {
5166       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5167       while ( const TopoDS_Shape* e = eIt->next() )
5168         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5169           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5170           {
5171             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5172             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5173             //   F       = TopoDS::Face( eoe->_sWOL );
5174             //   surface = helper.GetSurface( F );
5175             // }
5176             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5177             eoe->_edgeSmoother->_anaCurve.Nullify();
5178           }
5179     }
5180   }
5181
5182
5183   // check result of invalidation
5184
5185   int nbBad = 0;
5186   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5187   {
5188     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5189     {
5190       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5191       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5192       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5193       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5194       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5195         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5196         {
5197           ++nbBad;
5198           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5199                    << " "<< tgtXYZ._node->GetID()
5200                    << " "<< edge->_simplices[j]._nPrev->GetID()
5201                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5202         }
5203     }
5204   }
5205   dumpFunctionEnd();
5206
5207   return nbBad;
5208 }
5209
5210 //================================================================================
5211 /*!
5212  * \brief Create an offset surface
5213  */
5214 //================================================================================
5215
5216 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5217 {
5218   if ( eos._offsetSurf.IsNull() ||
5219        eos._edgeForOffset == 0 ||
5220        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5221     return;
5222
5223   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5224
5225   // find offset
5226   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5227   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5228   double offset = baseSurface->Gap();
5229
5230   eos._offsetSurf.Nullify();
5231
5232   try
5233   {
5234     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5235     if ( !offsetMaker.IsDone() ) return;
5236
5237     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5238     if ( !fExp.More() ) return;
5239
5240     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5241     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5242     if ( surf.IsNull() ) return;
5243
5244     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5245   }
5246   catch ( Standard_Failure )
5247   {
5248   }
5249 }
5250
5251 //================================================================================
5252 /*!
5253  * \brief Put nodes of a curved FACE to its offset surface
5254  */
5255 //================================================================================
5256
5257 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5258                                           int                       infStep,
5259                                           vector< _EdgesOnShape* >& eosC1,
5260                                           int                       smooStep,
5261                                           int                       moveAll )
5262 {
5263   _EdgesOnShape * eof = & eos;
5264   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5265   {
5266     eof = 0;
5267     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5268     {
5269       if ( eosC1[i]->_offsetSurf.IsNull() ||
5270            eosC1[i]->ShapeType() != TopAbs_FACE ||
5271            eosC1[i]->_edgeForOffset == 0 ||
5272            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5273         continue;
5274       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5275         eof = eosC1[i];
5276     }
5277   }
5278   if ( !eof ||
5279        eof->_offsetSurf.IsNull() ||
5280        eof->ShapeType() != TopAbs_FACE ||
5281        eof->_edgeForOffset == 0 ||
5282        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5283     return;
5284
5285   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5286   for ( size_t i = 0; i < eos._edges.size(); ++i )
5287   {
5288     _LayerEdge* edge = eos._edges[i];
5289     edge->Unset( _LayerEdge::MARKED );
5290     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5291       continue;
5292     if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5293     {
5294       if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5295         continue;
5296     }
5297     else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5298       continue;
5299
5300     int nbBlockedAround = 0;
5301     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5302       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5303     if ( nbBlockedAround > 1 )
5304       continue;
5305
5306     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5307     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5308     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5309     edge->_curvature->_uv = uv;
5310     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5311
5312     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5313     gp_XYZ prevP = edge->PrevCheckPos();
5314     bool      ok = true;
5315     if ( !moveAll )
5316       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5317       {
5318         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5319       }
5320     if ( ok )
5321     {
5322       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5323       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5324       edge->_pos.back() = newP;
5325
5326       edge->Set( _LayerEdge::MARKED );
5327       if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5328       {
5329         edge->_normal = ( newP - prevP ).Normalized();
5330       }
5331     }
5332   }
5333
5334
5335
5336 #ifdef _DEBUG_
5337   // dumpMove() for debug
5338   size_t i = 0;
5339   for ( ; i < eos._edges.size(); ++i )
5340     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5341       break;
5342   if ( i < eos._edges.size() )
5343   {
5344     dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5345                  << "_InfStep" << infStep << "_" << smooStep );
5346     for ( ; i < eos._edges.size(); ++i )
5347     {
5348       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5349         dumpMove( eos._edges[i]->_nodes.back() );
5350     }
5351     dumpFunctionEnd();
5352   }
5353 #endif
5354
5355   _ConvexFace* cnvFace;
5356   if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5357        eos.ShapeType() == TopAbs_FACE &&
5358        (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5359        !cnvFace->_normalsFixedOnBorders )
5360   {
5361     // put on the surface nodes built on FACE boundaries
5362     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5363     while ( smIt->more() )
5364     {
5365       SMESH_subMesh* sm = smIt->next();
5366       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5367       if ( !subEOS->_sWOL.IsNull() ) continue;
5368       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5369
5370       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5371     }
5372     cnvFace->_normalsFixedOnBorders = true;
5373   }
5374 }
5375
5376 //================================================================================
5377 /*!
5378  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5379  *        _LayerEdge's to be in a consequent order
5380  */
5381 //================================================================================
5382
5383 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5384                                                 _EdgesOnShape&      eos,
5385                                                 SMESH_MesherHelper& helper)
5386 {
5387   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5388
5389   TopLoc_Location loc; double f,l;
5390
5391   Handle(Geom_Line)   line;
5392   Handle(Geom_Circle) circle;
5393   bool isLine, isCirc;
5394   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5395   {
5396     // check if the EDGE is a line
5397     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5398     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5399       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5400
5401     line   = Handle(Geom_Line)::DownCast( curve );
5402     circle = Handle(Geom_Circle)::DownCast( curve );
5403     isLine = (!line.IsNull());
5404     isCirc = (!circle.IsNull());
5405
5406     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5407     {
5408       isLine = SMESH_Algo::IsStraight( E );
5409
5410       if ( isLine )
5411         line = new Geom_Line( gp::OX() ); // only type does matter
5412     }
5413     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5414     {
5415       // TODO
5416     }
5417   }
5418   else //////////////////////////////////////////////////////////////////////// 2D case
5419   {
5420     if ( !eos._isRegularSWOL ) // 23190
5421       return NULL;
5422
5423     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5424
5425     // check if the EDGE is a line
5426     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5427     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5428       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5429
5430     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5431     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5432     isLine = (!line2d.IsNull());
5433     isCirc = (!circle2d.IsNull());
5434
5435     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5436     {
5437       Bnd_B2d bndBox;
5438       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5439       while ( nIt->more() )
5440         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5441       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5442
5443       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5444       for ( int i = 0; i < 2 && !isLine; ++i )
5445         isLine = ( size.Coord( i+1 ) <= lineTol );
5446     }
5447     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5448     {
5449       // TODO
5450     }
5451     if ( isLine )
5452     {
5453       line = new Geom_Line( gp::OX() ); // only type does matter
5454     }
5455     else if ( isCirc )
5456     {
5457       gp_Pnt2d p = circle2d->Location();
5458       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5459       circle = new Geom_Circle( ax, 1.); // only center position does matter
5460     }
5461   }
5462
5463   if ( isLine )
5464     return line;
5465   if ( isCirc )
5466     return circle;
5467
5468   return Handle(Geom_Curve)();
5469 }
5470
5471 //================================================================================
5472 /*!
5473  * \brief Smooth edges on EDGE
5474  */
5475 //================================================================================
5476
5477 bool _Smoother1D::Perform(_SolidData&                    data,
5478                           Handle(ShapeAnalysis_Surface)& surface,
5479                           const TopoDS_Face&             F,
5480                           SMESH_MesherHelper&            helper )
5481 {
5482   if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5483     prepare( data );
5484
5485   findEdgesToSmooth();
5486   if ( isAnalytic() )
5487     return smoothAnalyticEdge( data, surface, F, helper );
5488   else
5489     return smoothComplexEdge ( data, surface, F, helper );
5490 }
5491
5492 //================================================================================
5493 /*!
5494  * \brief Find edges to smooth
5495  */
5496 //================================================================================
5497
5498 void _Smoother1D::findEdgesToSmooth()
5499 {
5500   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5501   for ( int iEnd = 0; iEnd < 2; ++iEnd )
5502     if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5503       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5504
5505   _eToSmooth[0].first = _eToSmooth[0].second = 0;
5506
5507   for ( size_t i = 0; i < _eos.size(); ++i )
5508   {
5509     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5510     {
5511       if ( needSmoothing( _leOnV[0]._cosin, _eos[i]->_len, _curveLen * _leParams[i] ) ||
5512            isToSmooth( i ))
5513         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5514       else
5515         break;
5516     }
5517     _eToSmooth[0].second = i+1;
5518   }
5519
5520   _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5521
5522   for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5523   {
5524     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5525     {
5526       if ( needSmoothing( _leOnV[1]._cosin, _eos[i]->_len, _curveLen * ( 1.-_leParams[i] )) ||
5527            isToSmooth( i ))
5528         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5529       else
5530         break;
5531     }
5532     _eToSmooth[1].first = i;
5533   }
5534 }
5535
5536 //================================================================================
5537 /*!
5538  * \brief Check if iE-th _LayerEdge needs smoothing
5539  */
5540 //================================================================================
5541
5542 bool _Smoother1D::isToSmooth( int iE )
5543 {
5544   SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5545   SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5546   SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5547   gp_XYZ       seg0 = pi - p0;
5548   gp_XYZ       seg1 = p1 - pi;
5549   gp_XYZ    tangent =  seg0 + seg1;
5550   double tangentLen = tangent.Modulus();
5551   double  segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5552   if ( tangentLen < std::numeric_limits<double>::min() )
5553     return false;
5554   tangent /= tangentLen;
5555
5556   for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5557   {
5558     _LayerEdge* ne = _eos[iE]->_neibors[i];
5559     if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5560          ne->_nodes.size() < 2 ||
5561          ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5562       continue;
5563     gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5564     double    proj = edgeVec * tangent;
5565     if ( needSmoothing( 1., proj, segMinLen ))
5566       return true;
5567   }
5568   return false;
5569 }
5570
5571 //================================================================================
5572 /*!
5573  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5574  */
5575 //================================================================================
5576
5577 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5578                                       Handle(ShapeAnalysis_Surface)& surface,
5579                                       const TopoDS_Face&             F,
5580                                       SMESH_MesherHelper&            helper)
5581 {
5582   if ( !isAnalytic() ) return false;
5583
5584   size_t iFrom = 0, iTo = _eos._edges.size();
5585
5586   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5587   {
5588     if ( F.IsNull() ) // 3D
5589     {
5590       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5591       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5592       //const   gp_XYZ lineDir = pSrc1 - pSrc0;
5593       //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5594       //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5595       // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5596       //                    vLE0->Is( _LayerEdge::BLOCKED ) ||
5597       //                    vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5598       //                    vLE1->Is( _LayerEdge::BLOCKED ));
5599       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5600       {
5601         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5602         if ( iFrom >= iTo ) continue;
5603         SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5604         SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5605         double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5606         double param1 = _leParams[ iTo ];
5607         for ( size_t i = iFrom; i < iTo; ++i )
5608         {
5609           _LayerEdge*       edge = _eos[i];
5610           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5611           double           param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5612           gp_XYZ          newPos = p0 * ( 1. - param ) + p1 * param;
5613
5614           // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5615           // {
5616           //   gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5617           //   double  shift = ( lineDir * ( newPos - pSrc0 ) -
5618           //                     lineDir * ( curPos - pSrc0 ));
5619           //   newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5620           // }
5621           if ( edge->Is( _LayerEdge::BLOCKED ))
5622           {
5623             SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5624             double curThick = pSrc.SquareDistance( tgtNode );
5625             double newThink = ( pSrc - newPos ).SquareModulus();
5626             if ( newThink > curThick )
5627               continue;
5628           }
5629           edge->_pos.back() = newPos;
5630           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5631           dumpMove( tgtNode );
5632         }
5633       }
5634     }
5635     else // 2D
5636     {
5637       _LayerEdge* eV0 = getLEdgeOnV( 0 );
5638       _LayerEdge* eV1 = getLEdgeOnV( 1 );
5639       gp_XY      uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5640       gp_XY      uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5641       if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5642       {
5643         int iPeriodic = helper.GetPeriodicIndex();
5644         if ( iPeriodic == 1 || iPeriodic == 2 )
5645         {
5646           uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5647           if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5648             std::swap( uvV0, uvV1 );
5649         }
5650       }
5651       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5652       {
5653         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5654         if ( iFrom >= iTo ) continue;
5655         _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5656         _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5657         gp_XY uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5658         gp_XY uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5659         double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5660         double param1 = _leParams[ iTo ];
5661         const gp_XY rangeUV = uv1 - uv0;
5662         for ( size_t i = iFrom; i < iTo; ++i )
5663         {
5664           if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5665           double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5666           gp_XY newUV = uv0 + param * rangeUV;
5667           _eos[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5668
5669           gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5670           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5671           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5672           dumpMove( tgtNode );
5673
5674           SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5675           pos->SetUParameter( newUV.X() );
5676           pos->SetVParameter( newUV.Y() );
5677         }
5678       }
5679     }
5680     return true;
5681   }
5682
5683   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5684   {
5685     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5686     gp_Pnt center3D = circle->Location();
5687
5688     if ( F.IsNull() ) // 3D
5689     {
5690       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5691         return true; // closed EDGE - nothing to do
5692
5693       // circle is a real curve of EDGE
5694       gp_Circ circ = circle->Circ();
5695
5696       // new center is shifted along its axis
5697       const gp_Dir& axis = circ.Axis().Direction();
5698       _LayerEdge*     e0 = getLEdgeOnV(0);
5699       _LayerEdge*     e1 = getLEdgeOnV(1);
5700       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5701       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5702       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5703       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5704       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5705
5706       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5707
5708       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5709       gp_Circ newCirc( newAxis, newRadius );
5710       gp_Vec  vecC1  ( newCenter, p1 );
5711
5712       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5713       if ( uLast < 0 )
5714         uLast += 2 * M_PI;
5715       
5716       for ( size_t i = 0; i < _eos.size(); ++i )
5717       {
5718         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5719         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5720         double u = uLast * _leParams[i];
5721         gp_Pnt p = ElCLib::Value( u, newCirc );
5722         _eos._edges[i]->_pos.back() = p.XYZ();
5723
5724         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5725         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5726         dumpMove( tgtNode );
5727       }
5728       return true;
5729     }
5730     else // 2D
5731     {
5732       const gp_XY center( center3D.X(), center3D.Y() );
5733
5734       _LayerEdge* e0 = getLEdgeOnV(0);
5735       _LayerEdge* eM = _eos._edges[ 0 ];
5736       _LayerEdge* e1 = getLEdgeOnV(1);
5737       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5738       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5739       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5740       gp_Vec2d vec0( center, uv0 );
5741       gp_Vec2d vecM( center, uvM );
5742       gp_Vec2d vec1( center, uv1 );
5743       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5744       double uMidl = vec0.Angle( vecM );
5745       if ( uLast * uMidl <= 0. )
5746         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5747       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5748
5749       gp_Ax2d   axis( center, vec0 );
5750       gp_Circ2d circ( axis, radius );
5751       for ( size_t i = 0; i < _eos.size(); ++i )
5752       {
5753         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5754         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5755         double    newU = uLast * _leParams[i];
5756         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5757         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5758
5759         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5760         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5761         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5762         dumpMove( tgtNode );
5763
5764         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5765         pos->SetUParameter( newUV.X() );
5766         pos->SetVParameter( newUV.Y() );
5767       }
5768     }
5769     return true;
5770   }
5771
5772   return false;
5773 }
5774
5775 //================================================================================
5776 /*!
5777  * \brief smooth _LayerEdge's on a an EDGE
5778  */
5779 //================================================================================
5780
5781 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5782                                      Handle(ShapeAnalysis_Surface)& surface,
5783                                      const TopoDS_Face&             F,
5784                                      SMESH_MesherHelper&            helper)
5785 {
5786   if ( _offPoints.empty() )
5787     return false;
5788
5789   // ----------------------------------------------
5790   // move _offPoints along normals of _LayerEdge's
5791   // ----------------------------------------------
5792
5793   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5794   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5795     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5796   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5797     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5798   _leOnV[0]._len = e[0]->_len;
5799   _leOnV[1]._len = e[1]->_len;
5800   for ( size_t i = 0; i < _offPoints.size(); i++ )
5801   {
5802     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5803     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5804     const double w0 = _offPoints[i]._2edges._wgt[0];
5805     const double w1 = _offPoints[i]._2edges._wgt[1];
5806     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5807     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5808     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5809     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5810          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5811       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5812
5813     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5814     _offPoints[i]._len  = avgLen;
5815   }
5816
5817   double fTol = 0;
5818   if ( !surface.IsNull() ) // project _offPoints to the FACE
5819   {
5820     fTol = 100 * BRep_Tool::Tolerance( F );
5821     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5822
5823     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5824     //if ( surface->Gap() < 0.5 * segLen )
5825       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5826
5827     for ( size_t i = 1; i < _offPoints.size(); ++i )
5828     {
5829       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5830       //if ( surface->Gap() < 0.5 * segLen )
5831         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5832     }
5833   }
5834
5835   // -----------------------------------------------------------------
5836   // project tgt nodes of extreme _LayerEdge's to the offset segments
5837   // -----------------------------------------------------------------
5838
5839   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5840   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5841
5842   gp_Pnt pExtreme[2], pProj[2];
5843   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5844   {
5845     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5846     int  i = _iSeg[ is2nd ];
5847     int di = is2nd ? -1 : +1;
5848     bool projected = false;
5849     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5850     int nbWorse = 0;
5851     do {
5852       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5853       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5854       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5855       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5856       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5857       if ( dist < distMin || projected )
5858       {
5859         _iSeg[ is2nd ] = i;
5860         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5861         distMin = dist;
5862       }
5863       else if ( dist > distPrev )
5864       {
5865         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5866           break;
5867       }
5868       distPrev = dist;
5869       i += di;
5870     }
5871     while ( !projected &&
5872             i >= 0 && i+1 < (int)_offPoints.size() );
5873
5874     if ( !projected )
5875     {
5876       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5877       {
5878         _iSeg[0] = 0;
5879         _iSeg[1] = _offPoints.size()-2;
5880         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5881         return false;
5882       }
5883     }
5884   }
5885   if ( _iSeg[0] > _iSeg[1] )
5886   {
5887     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5888     return false;
5889   }
5890
5891   // adjust length of extreme LE (test viscous_layers_01/B7)
5892   gp_Vec vDiv0( pExtreme[0], pProj[0] );
5893   gp_Vec vDiv1( pExtreme[1], pProj[1] );
5894   double d0 = vDiv0.Magnitude();
5895   double d1 = vDiv1.Magnitude();
5896   if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5897   else                                   e[0]->_len -= d0;
5898   if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5899   else                                   e[1]->_len -= d1;
5900
5901   // ---------------------------------------------------------------------------------
5902   // compute normalized length of the offset segments located between the projections
5903   // ---------------------------------------------------------------------------------
5904
5905   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5906   vector< double > len( nbSeg + 1 );
5907   len[ iSeg++ ] = 0;
5908   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5909   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5910   {
5911     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5912   }
5913   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5914
5915   // d0 *= e[0]->_lenFactor;
5916   // d1 *= e[1]->_lenFactor;
5917   double fullLen = len.back() - d0 - d1;
5918   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5919     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5920
5921   // temporary replace extreme _offPoints by pExtreme
5922   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5923                    _offPoints[ _iSeg[1]+1 ]._xyz };
5924   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5925   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5926
5927   // -------------------------------------------------------------
5928   // distribute tgt nodes of _LayerEdge's between the projections
5929   // -------------------------------------------------------------
5930
5931   iSeg = 0;
5932   for ( size_t i = 0; i < _eos.size(); ++i )
5933   {
5934     if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5935     //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
5936     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5937       iSeg++;
5938     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5939     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5940                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5941
5942     if ( surface.IsNull() )
5943     {
5944       _eos[i]->_pos.back() = p;
5945     }
5946     else // project a new node position to a FACE
5947     {
5948       gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
5949       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5950
5951       p = surface->Value( uv2 ).XYZ();
5952       _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5953     }
5954     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5955     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5956     dumpMove( tgtNode );
5957   }
5958
5959   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5960   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5961
5962   return true;
5963 }
5964
5965 //================================================================================
5966 /*!
5967  * \brief Prepare for smoothing
5968  */
5969 //================================================================================
5970
5971 void _Smoother1D::prepare(_SolidData& data)
5972 {
5973   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5974   _curveLen = SMESH_Algo::EdgeLength( E );
5975
5976   // sort _LayerEdge's by position on the EDGE
5977   data.SortOnEdge( E, _eos._edges );
5978
5979   // compute normalized param of _eos._edges on EDGE
5980   _leParams.resize( _eos._edges.size() + 1 );
5981   {
5982     double curLen;
5983     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5984     _leParams[0] = 0;
5985     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5986     {
5987       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5988       curLen         = p.Distance( pPrev );
5989       _leParams[i+1] = _leParams[i] + curLen;
5990       pPrev          = p;
5991     }
5992     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5993     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5994       _leParams[i] = _leParams[i+1] / fullLen;
5995     _leParams.back() = 1.;
5996   }
5997
5998   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5999
6000   // get cosin to use in findEdgesToSmooth()
6001   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6002   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6003   _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6004   _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6005   if ( _eos._sWOL.IsNull() ) // 3D
6006     for ( int iEnd = 0; iEnd < 2; ++iEnd )
6007       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6008
6009   if ( isAnalytic() )
6010     return;
6011
6012   // divide E to have offset segments with low deflection
6013   BRepAdaptor_Curve c3dAdaptor( E );
6014   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
6015   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
6016   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6017   if ( discret.NbPoints() <= 2 )
6018   {
6019     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6020     return;
6021   }
6022
6023   const double u0 = c3dAdaptor.FirstParameter();
6024   gp_Pnt p; gp_Vec tangent;
6025   _offPoints.resize( discret.NbPoints() );
6026   for ( size_t i = 0; i < _offPoints.size(); i++ )
6027   {
6028     double u = discret.Parameter( i+1 );
6029     c3dAdaptor.D1( u, p, tangent );
6030     _offPoints[i]._xyz     = p.XYZ();
6031     _offPoints[i]._edgeDir = tangent.XYZ();
6032     _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6033   }
6034
6035   // set _2edges
6036   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6037   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6038   _2NearEdges tmp2edges;
6039   tmp2edges._edges[1] = _eos._edges[0];
6040   _leOnV[0]._2neibors = & tmp2edges;
6041   _leOnV[0]._nodes    = leOnV[0]->_nodes;
6042   _leOnV[1]._nodes    = leOnV[1]->_nodes;
6043   _LayerEdge* eNext, *ePrev = & _leOnV[0];
6044   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6045   {
6046     // find _LayerEdge's located before and after an offset point
6047     // (_eos._edges[ iLE ] is next after ePrev)
6048     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6049       ePrev = _eos._edges[ iLE++ ];
6050     eNext = ePrev->_2neibors->_edges[1];
6051
6052     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6053     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6054     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6055     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6056   }
6057
6058   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6059   for ( size_t i = 0; i < _offPoints.size(); i++ )
6060     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6061       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6062     else break;
6063   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6064     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6065       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6066     else break;
6067
6068   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6069
6070   int iLBO = _offPoints.size() - 2; // last but one
6071
6072   _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
6073   _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
6074   _leOnV[ 0 ]._len = 0;
6075   _leOnV[ 1 ]._len = 0;
6076   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
6077   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6078
6079   _iSeg[0] = 0;
6080   _iSeg[1] = _offPoints.size()-2;
6081
6082   // initialize OffPnt::_len
6083   for ( size_t i = 0; i < _offPoints.size(); ++i )
6084     _offPoints[i]._len = 0;
6085
6086   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6087   {
6088     _leOnV[0]._len = leOnV[0]->_len;
6089     _leOnV[1]._len = leOnV[1]->_len;
6090     for ( size_t i = 0; i < _offPoints.size(); i++ )
6091     {
6092       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6093       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6094       const double w0 = _offPoints[i]._2edges._wgt[0];
6095       const double w1 = _offPoints[i]._2edges._wgt[1];
6096       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
6097       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6098                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6099       _offPoints[i]._xyz = avgXYZ;
6100       _offPoints[i]._len = avgLen;
6101     }
6102   }
6103 }
6104
6105 //================================================================================
6106 /*!
6107  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
6108  */
6109 //================================================================================
6110
6111 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6112                                      const gp_XYZ&  edgeDir)
6113 {
6114   gp_XYZ cross = normal ^ edgeDir;
6115   gp_XYZ  norm = edgeDir ^ cross;
6116   double  size = norm.Modulus();
6117
6118   return norm / size;
6119 }
6120
6121 //================================================================================
6122 /*!
6123  * \brief Sort _LayerEdge's by a parameter on a given EDGE
6124  */
6125 //================================================================================
6126
6127 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
6128                              vector< _LayerEdge* >& edges)
6129 {
6130   map< double, _LayerEdge* > u2edge;
6131   for ( size_t i = 0; i < edges.size(); ++i )
6132     u2edge.insert( u2edge.end(),
6133                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6134
6135   ASSERT( u2edge.size() == edges.size() );
6136   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6137   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6138     edges[i] = u2e->second;
6139
6140   Sort2NeiborsOnEdge( edges );
6141 }
6142
6143 //================================================================================
6144 /*!
6145  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6146  */
6147 //================================================================================
6148
6149 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6150 {
6151   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6152
6153   for ( size_t i = 0; i < edges.size()-1; ++i )
6154     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6155       edges[i]->_2neibors->reverse();
6156
6157   const size_t iLast = edges.size() - 1;
6158   if ( edges.size() > 1 &&
6159        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6160     edges[iLast]->_2neibors->reverse();
6161 }
6162
6163 //================================================================================
6164 /*!
6165  * \brief Return _EdgesOnShape* corresponding to the shape
6166  */
6167 //================================================================================
6168
6169 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6170 {
6171   if ( shapeID < (int)_edgesOnShape.size() &&
6172        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6173     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6174
6175   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6176     if ( _edgesOnShape[i]._shapeID == shapeID )
6177       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6178
6179   return 0;
6180 }
6181
6182 //================================================================================
6183 /*!
6184  * \brief Return _EdgesOnShape* corresponding to the shape
6185  */
6186 //================================================================================
6187
6188 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6189 {
6190   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6191   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6192 }
6193
6194 //================================================================================
6195 /*!
6196  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6197  */
6198 //================================================================================
6199
6200 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6201 {
6202   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6203
6204   set< TGeomID > vertices;
6205   TopoDS_Face F;
6206   if ( eos->ShapeType() == TopAbs_FACE )
6207   {
6208     // check FACE concavity and get concave VERTEXes
6209     F = TopoDS::Face( eos->_shape );
6210     if ( isConcave( F, helper, &vertices ))
6211       _concaveFaces.insert( eos->_shapeID );
6212
6213     // set eos._eosConcaVer
6214     eos->_eosConcaVer.clear();
6215     eos->_eosConcaVer.reserve( vertices.size() );
6216     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6217     {
6218       _EdgesOnShape* eov = GetShapeEdges( *v );
6219       if ( eov && eov->_edges.size() == 1 )
6220       {
6221         eos->_eosConcaVer.push_back( eov );
6222         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6223           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6224       }
6225     }
6226
6227     // SetSmooLen() to _LayerEdge's on FACE
6228     for ( size_t i = 0; i < eos->_edges.size(); ++i )
6229     {
6230       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6231     }
6232     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6233     while ( smIt->more() ) // loop on sub-shapes of the FACE
6234     {
6235       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6236       if ( !eoe ) continue;
6237
6238       vector<_LayerEdge*>& eE = eoe->_edges;
6239       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6240       {
6241         if ( eE[iE]->_cosin <= theMinSmoothCosin )
6242           continue;
6243
6244         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6245         while ( segIt->more() )
6246         {
6247           const SMDS_MeshElement* seg = segIt->next();
6248           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6249             continue;
6250           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6251             continue; // not to check a seg twice
6252           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6253           {
6254             _LayerEdge* eN = eE[iE]->_neibors[iN];
6255             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6256               continue;
6257             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6258             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6259             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6260             eN->Set( _LayerEdge::NEAR_BOUNDARY );
6261           }
6262         }
6263       }
6264     }
6265   } // if ( eos->ShapeType() == TopAbs_FACE )
6266
6267   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6268   {
6269     eos->_edges[i]->_smooFunction = 0;
6270     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6271   }
6272   bool isCurved = false;
6273   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6274   {
6275     _LayerEdge* edge = eos->_edges[i];
6276
6277     // get simplices sorted
6278     _Simplex::SortSimplices( edge->_simplices );
6279
6280     // smoothing function
6281     edge->ChooseSmooFunction( vertices, _n2eMap );
6282
6283     // set _curvature
6284     double avgNormProj = 0, avgLen = 0;
6285     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6286     {
6287       _Simplex& s = edge->_simplices[iS];
6288
6289       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6290       avgNormProj += edge->_normal * vec;
6291       avgLen      += vec.Modulus();
6292       if ( substituteSrcNodes )
6293       {
6294         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6295         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6296       }
6297     }
6298     avgNormProj /= edge->_simplices.size();
6299     avgLen      /= edge->_simplices.size();
6300     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6301     {
6302       isCurved = true;
6303       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6304       if ( !fPos )
6305         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6306           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6307       if ( fPos )
6308         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6309     }
6310   }
6311
6312   // prepare for putOnOffsetSurface()
6313   if (( eos->ShapeType() == TopAbs_FACE ) &&
6314       ( isCurved || !eos->_eosConcaVer.empty() ))
6315   {
6316     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6317     eos->_edgeForOffset = 0;
6318
6319     double maxCosin = -1;
6320     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6321     {
6322       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6323       if ( !eoe || eoe->_edges.empty() ) continue;
6324
6325       vector<_LayerEdge*>& eE = eoe->_edges;
6326       _LayerEdge* e = eE[ eE.size() / 2 ];
6327       if ( e->_cosin > maxCosin )
6328       {
6329         eos->_edgeForOffset = e;
6330         maxCosin = e->_cosin;
6331       }
6332     }
6333   }
6334 }
6335
6336 //================================================================================
6337 /*!
6338  * \brief Add faces for smoothing
6339  */
6340 //================================================================================
6341
6342 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6343                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6344 {
6345   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6346   for ( ; eos != eosToSmooth.end(); ++eos )
6347   {
6348     if ( !*eos || (*eos)->_toSmooth ) continue;
6349
6350     (*eos)->_toSmooth = true;
6351
6352     if ( (*eos)->ShapeType() == TopAbs_FACE )
6353     {
6354       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6355       (*eos)->_toSmooth = true;
6356     }
6357   }
6358
6359   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6360   if ( edgesNoAnaSmooth )
6361     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6362     {
6363       if ( (*eos)->_edgeSmoother )
6364         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6365     }
6366 }
6367
6368 //================================================================================
6369 /*!
6370  * \brief Limit _LayerEdge::_maxLen according to local curvature
6371  */
6372 //================================================================================
6373
6374 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6375 {
6376   // find intersection of neighbor _LayerEdge's to limit _maxLen
6377   // according to local curvature (IPAL52648)
6378
6379   // This method must be called after findCollisionEdges() where _LayerEdge's
6380   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6381
6382   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6383   {
6384     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6385     if ( eosI._edges.empty() ) continue;
6386     if ( !eosI._hyp.ToSmooth() )
6387     {
6388       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6389       {
6390         _LayerEdge* eI = eosI._edges[i];
6391         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6392         {
6393           _LayerEdge* eN = eI->_neibors[iN];
6394           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6395           {
6396             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6397             limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6398           }
6399         }
6400       }
6401     }
6402     else if ( eosI.ShapeType() == TopAbs_EDGE )
6403     {
6404       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6405       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6406
6407       _LayerEdge* e0 = eosI._edges[0];
6408       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6409       {
6410         _LayerEdge* eI = eosI._edges[i];
6411         limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6412         e0 = eI;
6413       }
6414     }
6415   }
6416 }
6417
6418 //================================================================================
6419 /*!
6420  * \brief Limit _LayerEdge::_maxLen according to local curvature
6421  */
6422 //================================================================================
6423
6424 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*         e1,
6425                                               _LayerEdge*         e2,
6426                                               _EdgesOnShape&      eos1,
6427                                               _EdgesOnShape&      eos2,
6428                                               SMESH_MesherHelper& helper )
6429 {
6430   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6431   double norSize = plnNorm.SquareModulus();
6432   if ( norSize < std::numeric_limits<double>::min() )
6433     return; // parallel normals
6434
6435   // find closest points of skew _LayerEdge's
6436   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6437   gp_XYZ dir12 = src2 - src1;
6438   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6439   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6440   double  dot1 = perp2 * e1->_normal;
6441   double  dot2 = perp1 * e2->_normal;
6442   double    u1 =   ( perp2 * dir12 ) / dot1;
6443   double    u2 = - ( perp1 * dir12 ) / dot2;
6444   if ( u1 > 0 && u2 > 0 )
6445   {
6446     double ovl = ( u1 * e1->_normal * dir12 -
6447                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6448     if ( ovl > theSmoothThickToElemSizeRatio )
6449     {    
6450       e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6451       e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6452     }
6453   }
6454 }
6455
6456 //================================================================================
6457 /*!
6458  * \brief Fill data._collisionEdges
6459  */
6460 //================================================================================
6461
6462 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6463 {
6464   data._collisionEdges.clear();
6465
6466   // set the full thickness of the layers to LEs
6467   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6468   {
6469     _EdgesOnShape& eos = data._edgesOnShape[iS];
6470     if ( eos._edges.empty() ) continue;
6471     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6472
6473     for ( size_t i = 0; i < eos._edges.size(); ++i )
6474     {
6475       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6476       double maxLen = eos._edges[i]->_maxLen;
6477       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6478       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6479       eos._edges[i]->_maxLen = maxLen;
6480     }
6481   }
6482
6483   // make temporary quadrangles got by extrusion of
6484   // mesh edges along _LayerEdge._normal's
6485
6486   vector< const SMDS_MeshElement* > tmpFaces;
6487
6488   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6489   {
6490     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6491     if ( eos.ShapeType() != TopAbs_EDGE )
6492       continue;
6493     if ( eos._edges.empty() )
6494     {
6495       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6496       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6497       while ( smIt->more() )
6498         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6499           if ( eov->_edges.size() == 1 )
6500             edge[ bool( edge[0]) ] = eov->_edges[0];
6501
6502       if ( edge[1] )
6503       {
6504         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6505         tmpFaces.push_back( f );
6506       }
6507     }
6508     for ( size_t i = 0; i < eos._edges.size(); ++i )
6509     {
6510       _LayerEdge* edge = eos._edges[i];
6511       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6512       {
6513         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6514         if ( src2->GetPosition()->GetDim() > 0 &&
6515              src2->GetID() < edge->_nodes[0]->GetID() )
6516           continue; // avoid using same segment twice
6517
6518         // a _LayerEdge containg tgt2
6519         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6520
6521         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6522         tmpFaces.push_back( f );
6523       }
6524     }
6525   }
6526
6527   // Find _LayerEdge's intersecting tmpFaces.
6528
6529   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6530                                                             tmpFaces.end()));
6531   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6532     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6533
6534   double dist1, dist2, segLen, eps = 0.5;
6535   _CollisionEdges collEdges;
6536   vector< const SMDS_MeshElement* > suspectFaces;
6537   const double angle45 = Cos( 45. * M_PI / 180. );
6538
6539   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6540   {
6541     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6542     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6543       continue;
6544     // find sub-shapes whose VL can influence VL on eos
6545     set< TGeomID > neighborShapes;
6546     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6547     while ( const TopoDS_Shape* face = fIt->next() )
6548     {
6549       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6550       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6551       {
6552         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6553         while ( subIt->more() )
6554           neighborShapes.insert( subIt->next()->GetId() );
6555       }
6556     }
6557     if ( eos.ShapeType() == TopAbs_VERTEX )
6558     {
6559       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6560       while ( const TopoDS_Shape* edge = eIt->next() )
6561         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6562     }
6563     // find intersecting _LayerEdge's
6564     for ( size_t i = 0; i < eos._edges.size(); ++i )
6565     {
6566       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6567       _LayerEdge*   edge = eos._edges[i];
6568       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6569       segLen *= 1.2;
6570
6571       gp_Vec eSegDir0, eSegDir1;
6572       if ( edge->IsOnEdge() )
6573       {
6574         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6575         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6576         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6577       }
6578       suspectFaces.clear();
6579       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6580                                      SMDSAbs_Face, suspectFaces );
6581       collEdges._intEdges.clear();
6582       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6583       {
6584         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6585         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6586         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6587         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6588         if ( edge->IsOnEdge() ) {
6589           if ( edge->_2neibors->include( f->_le1 ) ||
6590                edge->_2neibors->include( f->_le2 )) continue;
6591         }
6592         else {
6593           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6594               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6595         }
6596         dist1 = dist2 = Precision::Infinite();
6597         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6598           dist1 = Precision::Infinite();
6599         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6600           dist2 = Precision::Infinite();
6601         if (( dist1 > segLen ) && ( dist2 > segLen ))
6602           continue;
6603
6604         if ( edge->IsOnEdge() )
6605         {
6606           // skip perpendicular EDGEs
6607           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6608           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6609                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6610                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6611                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6612           if ( !isParallel )
6613             continue;
6614         }
6615
6616         // either limit inflation of edges or remember them for updating _normal
6617         // double dot = edge->_normal * f->GetDir();
6618         // if ( dot > 0.1 )
6619         {
6620           collEdges._intEdges.push_back( f->_le1 );
6621           collEdges._intEdges.push_back( f->_le2 );
6622         }
6623         // else
6624         // {
6625         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6626         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6627         // }
6628       }
6629
6630       if ( !collEdges._intEdges.empty() )
6631       {
6632         collEdges._edge = edge;
6633         data._collisionEdges.push_back( collEdges );
6634       }
6635     }
6636   }
6637
6638   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6639     delete tmpFaces[i];
6640
6641   // restore the zero thickness
6642   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6643   {
6644     _EdgesOnShape& eos = data._edgesOnShape[iS];
6645     if ( eos._edges.empty() ) continue;
6646     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6647
6648     for ( size_t i = 0; i < eos._edges.size(); ++i )
6649     {
6650       eos._edges[i]->InvalidateStep( 1, eos );
6651       eos._edges[i]->_len = 0;
6652     }
6653   }
6654 }
6655
6656 //================================================================================
6657 /*!
6658  * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
6659  *        will be updated at each inflation step
6660  */
6661 //================================================================================
6662
6663 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
6664                                                              _SolidData&         data,
6665                                                              SMESH_MesherHelper& helper )
6666 {
6667   const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
6668   const double       preci = BRep_Tool::Tolerance( convFace._face );
6669   Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
6670
6671   bool edgesToUpdateFound = false;
6672
6673   map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6674   for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6675   {
6676     _EdgesOnShape& eos = * id2eos->second;
6677     if ( !eos._sWOL.IsNull() ) continue;
6678     if ( !eos._hyp.ToSmooth() ) continue;
6679     for ( size_t i = 0; i < eos._edges.size(); ++i )
6680     {
6681       _LayerEdge* ledge = eos._edges[ i ];
6682       if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
6683       if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
6684
6685       gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
6686                         ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
6687
6688       // the normal must be updated if distance from tgtPos to surface is less than
6689       // target thickness
6690
6691       // find an initial UV for search of a projection of tgtPos to surface
6692       const SMDS_MeshNode* nodeInFace = 0;
6693       SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6694       while ( fIt->more() && !nodeInFace )
6695       {
6696         const SMDS_MeshElement* f = fIt->next();
6697         if ( convFaceID != f->getshapeId() ) continue;
6698
6699         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
6700         while ( nIt->more() && !nodeInFace )
6701         {
6702           const SMDS_MeshElement* n = nIt->next();
6703           if ( n->getshapeId() == convFaceID )
6704             nodeInFace = static_cast< const SMDS_MeshNode* >( n );
6705         }
6706       }
6707       if ( !nodeInFace )
6708         continue;
6709       gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
6710
6711       // projection
6712       surface->NextValueOfUV( uv, tgtPos, preci );
6713       double  dist = surface->Gap();
6714       if ( dist < 0.95 * ledge->_maxLen )
6715       {
6716         ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
6717         if ( !ledge->_curvature ) ledge->_curvature = new _Curvature;
6718         ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
6719         edgesToUpdateFound = true;
6720       }
6721     }
6722   }
6723
6724   if ( !convFace._isTooCurved && edgesToUpdateFound )
6725   {
6726     data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
6727   }
6728 }
6729
6730 //================================================================================
6731 /*!
6732  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6733  * _LayerEdge's on neighbor EDGE's
6734  */
6735 //================================================================================
6736
6737 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6738                                      SMESH_MesherHelper& helper,
6739                                      int                 stepNb,
6740                                      double              stepSize)
6741 {
6742   updateNormalsOfC1Vertices( data );
6743
6744   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6745     return false;
6746
6747   // map to store new _normal and _cosin for each intersected edge
6748   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6749   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6750   _LayerEdge zeroEdge;
6751   zeroEdge._normal.SetCoord( 0,0,0 );
6752   zeroEdge._maxLen = Precision::Infinite();
6753   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6754
6755   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6756
6757   double segLen, dist1, dist2, dist;
6758   vector< pair< _LayerEdge*, double > > intEdgesDist;
6759   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6760
6761   for ( int iter = 0; iter < 5; ++iter )
6762   {
6763     edge2newEdge.clear();
6764
6765     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6766     {
6767       _CollisionEdges& ce = data._collisionEdges[iE];
6768       _LayerEdge*   edge1 = ce._edge;
6769       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6770       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6771       if ( !eos1 ) continue;
6772
6773       // detect intersections
6774       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6775       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6776       double     eps = 0.5;
6777       intEdgesDist.clear();
6778       double minIntDist = Precision::Infinite();
6779       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6780       {
6781         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6782              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6783              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6784           continue;
6785         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6786         double fact = ( 1.1 + dot * dot );
6787         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6788         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6789         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6790         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6791         dist1 = dist2 = Precision::Infinite();
6792         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
6793              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6794           continue;
6795         dist = dist1;
6796         if ( dist > testLen || dist <= 0 )
6797         {
6798           dist = dist2;
6799           if ( dist > testLen || dist <= 0 )
6800             continue;
6801         }
6802         // choose a closest edge
6803         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6804         double d1 = intP.SquareDistance( pSrc0 );
6805         double d2 = intP.SquareDistance( pSrc1 );
6806         int iClose = i + ( d2 < d1 );
6807         _LayerEdge* edge2 = ce._intEdges[iClose];
6808         edge2->Unset( _LayerEdge::MARKED );
6809
6810         // choose a closest edge among neighbors
6811         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6812         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6813         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6814         {
6815           _LayerEdge * edgeJ = intEdgesDist[j].first;
6816           if ( edge2->IsNeiborOnEdge( edgeJ ))
6817           {
6818             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6819             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6820           }
6821         }
6822         intEdgesDist.push_back( make_pair( edge2, dist ));
6823         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6824         // {
6825         //   iClose = i + !( d2 < d1 );
6826         //   intEdges.push_back( ce._intEdges[iClose] );
6827         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6828         // }
6829         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6830       }
6831
6832       //ce._edge = 0;
6833
6834       // compute new _normals
6835       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6836       {
6837         _LayerEdge* edge2    = intEdgesDist[i].first;
6838         double       distWgt = edge1->_len / intEdgesDist[i].second;
6839         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6840         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
6841         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6842         edge2->Set( _LayerEdge::MARKED );
6843
6844         // get a new normal
6845         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6846
6847         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6848         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6849         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6850         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6851         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6852         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6853         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6854         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6855         newNormal.Normalize();
6856
6857         // get new cosin
6858         double newCos;
6859         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6860         if ( cos1 < theMinSmoothCosin )
6861         {
6862           newCos = cos2 * sgn1;
6863         }
6864         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6865         {
6866           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6867         }
6868         else
6869         {
6870           newCos = edge1->_cosin;
6871         }
6872
6873         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6874         e2neIt->second._normal += distWgt * newNormal;
6875         e2neIt->second._cosin   = newCos;
6876         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6877         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6878           e2neIt->second._normal += dir2;
6879         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6880         e2neIt->second._normal += distWgt * newNormal;
6881         e2neIt->second._cosin   = edge2->_cosin;
6882         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6883           e2neIt->second._normal += dir1;
6884       }
6885     }
6886
6887     if ( edge2newEdge.empty() )
6888       break; //return true;
6889
6890     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6891
6892     // Update data of edges depending on a new _normal
6893
6894     data.UnmarkEdges();
6895     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6896     {
6897       _LayerEdge*    edge = e2neIt->first;
6898       if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6899       _LayerEdge& newEdge = e2neIt->second;
6900       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6901
6902       // Check if a new _normal is OK:
6903       newEdge._normal.Normalize();
6904       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6905       {
6906         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6907         {
6908           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6909           edge->_maxLen = newEdge._maxLen;
6910           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6911         }
6912         continue; // the new _normal is bad
6913       }
6914       // the new _normal is OK
6915
6916       // find shapes that need smoothing due to change of _normal
6917       if ( edge->_cosin   < theMinSmoothCosin &&
6918            newEdge._cosin > theMinSmoothCosin )
6919       {
6920         if ( eos->_sWOL.IsNull() )
6921         {
6922           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6923           while ( fIt->more() )
6924             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6925         }
6926         else // edge inflates along a FACE
6927         {
6928           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6929           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
6930           while ( const TopoDS_Shape* E = eIt->next() )
6931           {
6932             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6933             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6934             if ( angle < M_PI / 2 )
6935               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6936           }
6937         }
6938       }
6939
6940       double len = edge->_len;
6941       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6942       edge->SetNormal( newEdge._normal );
6943       edge->SetCosin( newEdge._cosin );
6944       edge->SetNewLength( len, *eos, helper );
6945       edge->Set( _LayerEdge::MARKED );
6946       edge->Set( _LayerEdge::NORMAL_UPDATED );
6947       edgesNoAnaSmooth.insert( eos );
6948     }
6949
6950     // Update normals and other dependent data of not intersecting _LayerEdge's
6951     // neighboring the intersecting ones
6952
6953     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6954     {
6955       _LayerEdge*   edge1 = e2neIt->first;
6956       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6957       if ( !edge1->Is( _LayerEdge::MARKED ))
6958         continue;
6959
6960       if ( edge1->IsOnEdge() )
6961       {
6962         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6963         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6964         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6965       }
6966
6967       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6968         continue;
6969       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6970       {
6971         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6972         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6973           continue; // j-th neighbor is also intersected
6974         _LayerEdge* prevEdge = edge1;
6975         const int nbSteps = 10;
6976         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6977         {
6978           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6979                neighbor->Is( _LayerEdge::MARKED ))
6980             break;
6981           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6982           if ( !eos ) continue;
6983           _LayerEdge* nextEdge = neighbor;
6984           if ( neighbor->_2neibors )
6985           {
6986             int iNext = 0;
6987             nextEdge = neighbor->_2neibors->_edges[iNext];
6988             if ( nextEdge == prevEdge )
6989               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6990           }
6991           double r = double(step-1)/nbSteps/(iter+1);
6992           if ( !nextEdge->_2neibors )
6993             r = Min( r, 0.5 );
6994
6995           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6996           newNorm.Normalize();
6997           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6998             break;
6999
7000           double len = neighbor->_len;
7001           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7002           neighbor->SetNormal( newNorm );
7003           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7004           if ( neighbor->_2neibors )
7005             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7006           neighbor->SetNewLength( len, *eos, helper );
7007           neighbor->Set( _LayerEdge::MARKED );
7008           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7009           edgesNoAnaSmooth.insert( eos );
7010
7011           if ( !neighbor->_2neibors )
7012             break; // neighbor is on VERTEX
7013
7014           // goto the next neighbor
7015           prevEdge = neighbor;
7016           neighbor = nextEdge;
7017         }
7018       }
7019     }
7020     dumpFunctionEnd();
7021   } // iterations
7022
7023   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7024
7025   return true;
7026 }
7027
7028 //================================================================================
7029 /*!
7030  * \brief Check if a new normal is OK
7031  */
7032 //================================================================================
7033
7034 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
7035                                      _LayerEdge&   edge,
7036                                      const gp_XYZ& newNormal)
7037 {
7038   // check a min angle between the newNormal and surrounding faces
7039   vector<_Simplex> simplices;
7040   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7041   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7042   double newMinDot = 1, curMinDot = 1;
7043   for ( size_t i = 0; i < simplices.size(); ++i )
7044   {
7045     n1.Set( simplices[i]._nPrev );
7046     n2.Set( simplices[i]._nNext );
7047     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7048     double normLen2 = normFace.SquareModulus();
7049     if ( normLen2 < std::numeric_limits<double>::min() )
7050       continue;
7051     normFace /= Sqrt( normLen2 );
7052     newMinDot = Min( newNormal    * normFace, newMinDot );
7053     curMinDot = Min( edge._normal * normFace, curMinDot );
7054   }
7055   bool ok = true;
7056   if ( newMinDot < 0.5 )
7057   {
7058     ok = ( newMinDot >= curMinDot * 0.9 );
7059     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7060     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7061     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7062   }
7063
7064   return ok;
7065 }
7066
7067 //================================================================================
7068 /*!
7069  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7070  */
7071 //================================================================================
7072
7073 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
7074                                                SMESH_MesherHelper& helper,
7075                                                const int           nbSteps,
7076                                                const double        stepSize )
7077 {
7078   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7079     return true; // no shapes needing smoothing
7080
7081   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7082   {
7083     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7084     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
7085          !eos._hyp.ToSmooth() ||
7086          eos.ShapeType() != TopAbs_FACE ||
7087          eos._edges.empty() )
7088       continue;
7089
7090     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7091     if ( !toSmooth ) continue;
7092
7093     for ( size_t i = 0; i < eos._edges.size(); ++i )
7094     {
7095       _LayerEdge* edge = eos._edges[i];
7096       if ( !edge->Is( _LayerEdge::SMOOTHED ))
7097         continue;
7098       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7099         continue;
7100
7101       const gp_XYZ& pPrev = edge->PrevPos();
7102       const gp_XYZ& pLast = edge->_pos.back();
7103       gp_XYZ      stepVec = pLast - pPrev;
7104       double realStepSize = stepVec.Modulus();
7105       if ( realStepSize < numeric_limits<double>::min() )
7106         continue;
7107
7108       edge->_lenFactor = realStepSize / stepSize;
7109       edge->_normal    = stepVec / realStepSize;
7110       edge->Set( _LayerEdge::NORMAL_UPDATED );
7111     }
7112   }
7113
7114   return true;
7115 }
7116
7117 //================================================================================
7118 /*!
7119  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7120  */
7121 //================================================================================
7122
7123 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7124 {
7125   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7126   {
7127     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7128     if ( eov._eosC1.empty() ||
7129          eov.ShapeType() != TopAbs_VERTEX ||
7130          eov._edges.empty() )
7131       continue;
7132
7133     gp_XYZ newNorm   = eov._edges[0]->_normal;
7134     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7135     bool normChanged = false;
7136
7137     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7138     {
7139       _EdgesOnShape*   eoe = eov._eosC1[i];
7140       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7141       const double    eLen = SMESH_Algo::EdgeLength( e );
7142       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
7143       if ( oppV.IsSame( eov._shape ))
7144         oppV = SMESH_MesherHelper::IthVertex( 1, e );
7145       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7146       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7147       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7148
7149       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7150       if ( curThickOpp + curThick < eLen )
7151         continue;
7152
7153       double wgt = 2. * curThick / eLen;
7154       newNorm += wgt * eovOpp->_edges[0]->_normal;
7155       normChanged = true;
7156     }
7157     if ( normChanged )
7158     {
7159       eov._edges[0]->SetNormal( newNorm.Normalized() );
7160       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7161     }
7162   }
7163 }
7164
7165 //================================================================================
7166 /*!
7167  * \brief Modify normals of _LayerEdge's on _ConvexFace's
7168  */
7169 //================================================================================
7170
7171 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
7172                                                   SMESH_MesherHelper& helper,
7173                                                   int                 stepNb )
7174 {
7175   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7176   bool isOK;
7177
7178   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7179   for ( ; id2face != data._convexFaces.end(); ++id2face )
7180   {
7181     _ConvexFace & convFace = (*id2face).second;
7182     convFace._normalsFixedOnBorders = false; // to update at each inflation step
7183
7184     if ( convFace._normalsFixed )
7185       continue; // already fixed
7186     if ( convFace.CheckPrisms() )
7187       continue; // nothing to fix
7188
7189     convFace._normalsFixed = true;
7190
7191     BRepAdaptor_Surface surface ( convFace._face, false );
7192     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
7193
7194     // check if the convex FACE is of spherical shape
7195
7196     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7197     Bnd_B3d nodesBox;
7198     gp_Pnt  center;
7199
7200     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7201     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7202     {
7203       _EdgesOnShape& eos = *(id2eos->second);
7204       if ( eos.ShapeType() == TopAbs_VERTEX )
7205       {
7206         _LayerEdge* ledge = eos._edges[ 0 ];
7207         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7208           centersBox.Add( center );
7209       }
7210       for ( size_t i = 0; i < eos._edges.size(); ++i )
7211         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7212     }
7213     if ( centersBox.IsVoid() )
7214     {
7215       debugMsg( "Error: centersBox.IsVoid()" );
7216       return false;
7217     }
7218     const bool isSpherical =
7219       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7220
7221     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7222     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7223
7224     if ( isSpherical )
7225     {
7226       // set _LayerEdge::_normal as average of all normals
7227
7228       // WARNING: different density of nodes on EDGEs is not taken into account that
7229       // can lead to an improper new normal
7230
7231       gp_XYZ avgNormal( 0,0,0 );
7232       nbEdges = 0;
7233       id2eos = convFace._subIdToEOS.begin();
7234       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7235       {
7236         _EdgesOnShape& eos = *(id2eos->second);
7237         // set data of _CentralCurveOnEdge
7238         if ( eos.ShapeType() == TopAbs_EDGE )
7239         {
7240           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7241           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7242           if ( !eos._sWOL.IsNull() )
7243             ceCurve._adjFace.Nullify();
7244           else
7245             ceCurve._ledges.insert( ceCurve._ledges.end(),
7246                                     eos._edges.begin(), eos._edges.end());
7247         }
7248         // summarize normals
7249         for ( size_t i = 0; i < eos._edges.size(); ++i )
7250           avgNormal += eos._edges[ i ]->_normal;
7251       }
7252       double normSize = avgNormal.SquareModulus();
7253       if ( normSize < 1e-200 )
7254       {
7255         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7256         return false;
7257       }
7258       avgNormal /= Sqrt( normSize );
7259
7260       // compute new _LayerEdge::_cosin on EDGEs
7261       double avgCosin = 0;
7262       int     nbCosin = 0;
7263       gp_Vec inFaceDir;
7264       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7265       {
7266         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7267         if ( ceCurve._adjFace.IsNull() )
7268           continue;
7269         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7270         {
7271           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7272           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7273           if ( isOK )
7274           {
7275             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7276             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7277             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7278             nbCosin++;
7279           }
7280         }
7281       }
7282       if ( nbCosin > 0 )
7283         avgCosin /= nbCosin;
7284
7285       // set _LayerEdge::_normal = avgNormal
7286       id2eos = convFace._subIdToEOS.begin();
7287       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7288       {
7289         _EdgesOnShape& eos = *(id2eos->second);
7290         if ( eos.ShapeType() != TopAbs_EDGE )
7291           for ( size_t i = 0; i < eos._edges.size(); ++i )
7292             eos._edges[ i ]->_cosin = avgCosin;
7293
7294         for ( size_t i = 0; i < eos._edges.size(); ++i )
7295         {
7296           eos._edges[ i ]->SetNormal( avgNormal );
7297           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7298         }
7299       }
7300     }
7301     else // if ( isSpherical )
7302     {
7303       // We suppose that centers of curvature at all points of the FACE
7304       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7305       // having a common center of curvature we define the same new normal
7306       // as a sum of normals of _LayerEdge's on EDGEs among them.
7307
7308       // get all centers of curvature for each EDGE
7309
7310       helper.SetSubShape( convFace._face );
7311       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7312
7313       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7314       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7315       {
7316         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7317
7318         // set adjacent FACE
7319         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7320
7321         // get _LayerEdge's of the EDGE
7322         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7323         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7324         if ( !eos || eos->_edges.empty() )
7325         {
7326           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7327           for ( int iV = 0; iV < 2; ++iV )
7328           {
7329             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7330             TGeomID     vID = meshDS->ShapeToIndex( v );
7331             eos = data.GetShapeEdges( vID );
7332             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7333           }
7334           edgeLEdge    = &vertexLEdges[0];
7335           edgeLEdgeEnd = edgeLEdge + 2;
7336
7337           centerCurves[ iE ]._adjFace.Nullify();
7338         }
7339         else
7340         {
7341           if ( ! eos->_toSmooth )
7342             data.SortOnEdge( edge, eos->_edges );
7343           edgeLEdge    = &eos->_edges[ 0 ];
7344           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7345           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7346           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7347
7348           if ( ! eos->_sWOL.IsNull() )
7349             centerCurves[ iE ]._adjFace.Nullify();
7350         }
7351
7352         // Get curvature centers
7353
7354         centersBox.Clear();
7355
7356         if ( edgeLEdge[0]->IsOnEdge() &&
7357              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7358         { // 1st VERTEX
7359           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7360           centersBox.Add( center );
7361         }
7362         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7363           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7364           { // EDGE or VERTEXes
7365             centerCurves[ iE ].Append( center, *edgeLEdge );
7366             centersBox.Add( center );
7367           }
7368         if ( edgeLEdge[-1]->IsOnEdge() &&
7369              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7370         { // 2nd VERTEX
7371           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7372           centersBox.Add( center );
7373         }
7374         centerCurves[ iE ]._isDegenerated =
7375           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7376
7377       } // loop on EDGES of convFace._face to set up data of centerCurves
7378
7379       // Compute new normals for _LayerEdge's on EDGEs
7380
7381       double avgCosin = 0;
7382       int     nbCosin = 0;
7383       gp_Vec inFaceDir;
7384       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7385       {
7386         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7387         if ( ceCurve._isDegenerated )
7388           continue;
7389         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7390         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7391         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7392         {
7393           isOK = false;
7394           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7395           {
7396             if ( iE1 != iE2 )
7397               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7398           }
7399           if ( isOK && !ceCurve._adjFace.IsNull() )
7400           {
7401             // compute new _LayerEdge::_cosin
7402             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7403             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7404             if ( isOK )
7405             {
7406               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7407               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7408               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7409               nbCosin++;
7410             }
7411           }
7412         }
7413       }
7414       // set new normals to _LayerEdge's of NOT degenerated central curves
7415       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7416       {
7417         if ( centerCurves[ iE ]._isDegenerated )
7418           continue;
7419         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7420         {
7421           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7422           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7423         }
7424       }
7425       // set new normals to _LayerEdge's of     degenerated central curves
7426       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7427       {
7428         if ( !centerCurves[ iE ]._isDegenerated ||
7429              centerCurves[ iE ]._ledges.size() < 3 )
7430           continue;
7431         // new normal is an average of new normals at VERTEXes that
7432         // was computed on non-degenerated _CentralCurveOnEdge's
7433         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7434                            centerCurves[ iE ]._ledges.back ()->_normal );
7435         double sz = newNorm.Modulus();
7436         if ( sz < 1e-200 )
7437           continue;
7438         newNorm /= sz;
7439         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7440                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7441         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7442         {
7443           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7444           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7445           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7446         }
7447       }
7448
7449       // Find new normals for _LayerEdge's based on FACE
7450
7451       if ( nbCosin > 0 )
7452         avgCosin /= nbCosin;
7453       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7454       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7455       if ( id2eos != convFace._subIdToEOS.end() )
7456       {
7457         int iE = 0;
7458         gp_XYZ newNorm;
7459         _EdgesOnShape& eos = * ( id2eos->second );
7460         for ( size_t i = 0; i < eos._edges.size(); ++i )
7461         {
7462           _LayerEdge* ledge = eos._edges[ i ];
7463           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7464             continue;
7465           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7466           {
7467             iE = iE % centerCurves.size();
7468             if ( centerCurves[ iE ]._isDegenerated )
7469               continue;
7470             newNorm.SetCoord( 0,0,0 );
7471             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7472             {
7473               ledge->SetNormal( newNorm );
7474               ledge->_cosin  = avgCosin;
7475               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7476               break;
7477             }
7478           }
7479         }
7480       }
7481
7482     } // not a quasi-spherical FACE
7483
7484     // Update _LayerEdge's data according to a new normal
7485
7486     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7487                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7488
7489     id2eos = convFace._subIdToEOS.begin();
7490     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7491     {
7492       _EdgesOnShape& eos = * ( id2eos->second );
7493       for ( size_t i = 0; i < eos._edges.size(); ++i )
7494       {
7495         _LayerEdge* & ledge = eos._edges[ i ];
7496         double len = ledge->_len;
7497         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7498         ledge->SetCosin( ledge->_cosin );
7499         ledge->SetNewLength( len, eos, helper );
7500       }
7501       if ( eos.ShapeType() != TopAbs_FACE )
7502         for ( size_t i = 0; i < eos._edges.size(); ++i )
7503         {
7504           _LayerEdge* ledge = eos._edges[ i ];
7505           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7506           {
7507             _LayerEdge* neibor = ledge->_neibors[iN];
7508             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7509             {
7510               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7511               neibor->Set( _LayerEdge::MOVED );
7512               neibor->SetSmooLen( neibor->_len );
7513             }
7514           }
7515         }
7516     } // loop on sub-shapes of convFace._face
7517
7518     // Find FACEs adjacent to convFace._face that got necessity to smooth
7519     // as a result of normals modification
7520
7521     set< _EdgesOnShape* > adjFacesToSmooth;
7522     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7523     {
7524       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7525            centerCurves[ iE ]._adjFaceToSmooth )
7526         continue;
7527       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7528       {
7529         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7530         {
7531           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7532           break;
7533         }
7534       }
7535     }
7536     data.AddShapesToSmooth( adjFacesToSmooth );
7537
7538     dumpFunctionEnd();
7539
7540
7541   } // loop on data._convexFaces
7542
7543   return true;
7544 }
7545
7546 //================================================================================
7547 /*!
7548  * \brief Return max curvature of a FACE
7549  */
7550 //================================================================================
7551
7552 double _ConvexFace::GetMaxCurvature( _SolidData&         data,
7553                                      _EdgesOnShape&      eof,
7554                                      BRepLProp_SLProps&  surfProp,
7555                                      SMESH_MesherHelper& helper)
7556 {
7557   double maxCurvature = 0;
7558
7559   TopoDS_Face F = TopoDS::Face( eof._shape );
7560
7561   const int           nbTestPnt = 5;
7562   const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7563   SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7564   while ( smIt->more() )
7565   {
7566     SMESH_subMesh* sm = smIt->next();
7567     const TGeomID subID = sm->GetId();
7568
7569     // find _LayerEdge's of a sub-shape
7570     _EdgesOnShape* eos;
7571     if (( eos = data.GetShapeEdges( subID )))
7572       this->_subIdToEOS.insert( make_pair( subID, eos ));
7573     else
7574       continue;
7575
7576     // check concavity and curvature and limit data._stepSize
7577     const double minCurvature =
7578       1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7579     size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7580     for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7581     {
7582       gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7583       surfProp.SetParameters( uv.X(), uv.Y() );
7584       if ( surfProp.IsCurvatureDefined() )
7585       {
7586         double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7587                                 surfProp.MinCurvature() * oriFactor );
7588         maxCurvature = Max( maxCurvature, curvature );
7589
7590         if ( curvature > minCurvature )
7591           this->_isTooCurved = true;
7592       }
7593     }
7594   } // loop on sub-shapes of the FACE
7595
7596   return maxCurvature;
7597 }
7598
7599 //================================================================================
7600 /*!
7601  * \brief Finds a center of curvature of a surface at a _LayerEdge
7602  */
7603 //================================================================================
7604
7605 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7606                                         BRepLProp_SLProps&  surfProp,
7607                                         SMESH_MesherHelper& helper,
7608                                         gp_Pnt &            center ) const
7609 {
7610   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7611   surfProp.SetParameters( uv.X(), uv.Y() );
7612   if ( !surfProp.IsCurvatureDefined() )
7613     return false;
7614
7615   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7616   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7617   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7618   if ( surfCurvatureMin > surfCurvatureMax )
7619     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7620   else
7621     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7622
7623   return true;
7624 }
7625
7626 //================================================================================
7627 /*!
7628  * \brief Check that prisms are not distorted
7629  */
7630 //================================================================================
7631
7632 bool _ConvexFace::CheckPrisms() const
7633 {
7634   double vol = 0;
7635   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7636   {
7637     const _LayerEdge* edge = _simplexTestEdges[i];
7638     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7639     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7640       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7641       {
7642         debugMsg( "Bad simplex of _simplexTestEdges ("
7643                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7644                   << " "<< edge->_simplices[j]._nPrev->GetID()
7645                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7646         return false;
7647       }
7648   }
7649   return true;
7650 }
7651
7652 //================================================================================
7653 /*!
7654  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7655  *        stored in this _CentralCurveOnEdge.
7656  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7657  *  \param [in,out] newNormal - current normal at this point, to be redefined
7658  *  \return bool - true if succeeded.
7659  */
7660 //================================================================================
7661
7662 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7663 {
7664   if ( this->_isDegenerated )
7665     return false;
7666
7667   // find two centers the given one lies between
7668
7669   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7670   {
7671     double sl2 = 1.001 * _segLength2[ i ];
7672
7673     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7674     if ( d1 > sl2 )
7675       continue;
7676     
7677     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7678     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7679       continue;
7680
7681     d1 = Sqrt( d1 );
7682     d2 = Sqrt( d2 );
7683     double r = d1 / ( d1 + d2 );
7684     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7685                    (      r ) * _ledges[ i+1 ]->_normal );
7686     norm.Normalize();
7687
7688     newNormal += norm;
7689     double sz = newNormal.Modulus();
7690     if ( sz < 1e-200 )
7691       break;
7692     newNormal /= sz;
7693     return true;
7694   }
7695   return false;
7696 }
7697
7698 //================================================================================
7699 /*!
7700  * \brief Set shape members
7701  */
7702 //================================================================================
7703
7704 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7705                                      const _ConvexFace&  convFace,
7706                                      _SolidData&         data,
7707                                      SMESH_MesherHelper& helper)
7708 {
7709   _edge = edge;
7710
7711   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7712   while ( const TopoDS_Shape* F = fIt->next())
7713     if ( !convFace._face.IsSame( *F ))
7714     {
7715       _adjFace = TopoDS::Face( *F );
7716       _adjFaceToSmooth = false;
7717       // _adjFace already in a smoothing queue ?
7718       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7719         _adjFaceToSmooth = eos->_toSmooth;
7720       break;
7721     }
7722 }
7723
7724 //================================================================================
7725 /*!
7726  * \brief Looks for intersection of it's last segment with faces
7727  *  \param distance - returns shortest distance from the last node to intersection
7728  */
7729 //================================================================================
7730
7731 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7732                                    double &                 distance,
7733                                    const double&            epsilon,
7734                                    _EdgesOnShape&           eos,
7735                                    const SMDS_MeshElement** intFace)
7736 {
7737   vector< const SMDS_MeshElement* > suspectFaces;
7738   double segLen;
7739   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7740   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7741
7742   bool segmentIntersected = false;
7743   distance = Precision::Infinite();
7744   int iFace = -1; // intersected face
7745   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7746   {
7747     const SMDS_MeshElement* face = suspectFaces[j];
7748     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7749          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7750       continue; // face sharing _LayerEdge node
7751     const int nbNodes = face->NbCornerNodes();
7752     bool intFound = false;
7753     double dist;
7754     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7755     if ( nbNodes == 3 )
7756     {
7757       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7758     }
7759     else
7760     {
7761       const SMDS_MeshNode* tria[3];
7762       tria[0] = *nIt++;
7763       tria[1] = *nIt++;
7764       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7765       {
7766         tria[2] = *nIt++;
7767         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7768         tria[1] = tria[2];
7769       }
7770     }
7771     if ( intFound )
7772     {
7773       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7774         segmentIntersected = true;
7775       if ( distance > dist )
7776         distance = dist, iFace = j;
7777     }
7778   }
7779   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7780
7781   distance -= segLen;
7782
7783   if ( segmentIntersected )
7784   {
7785 #ifdef __myDEBUG
7786     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7787     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7788     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7789          << ", intersection with face ("
7790          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7791          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7792          << ") distance = " << distance << endl;
7793 #endif
7794   }
7795
7796   return segmentIntersected;
7797 }
7798
7799 //================================================================================
7800 /*!
7801  * \brief Returns a point used to check orientation of _simplices
7802  */
7803 //================================================================================
7804
7805 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7806 {
7807   size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7808
7809   if ( !eos || eos->_sWOL.IsNull() )
7810     return _pos[ i ];
7811
7812   if ( eos->SWOLType() == TopAbs_EDGE )
7813   {
7814     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7815   }
7816   //else //  TopAbs_FACE
7817
7818   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7819 }
7820
7821 //================================================================================
7822 /*!
7823  * \brief Returns size and direction of the last segment
7824  */
7825 //================================================================================
7826
7827 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7828 {
7829   // find two non-coincident positions
7830   gp_XYZ orig = _pos.back();
7831   gp_XYZ vec;
7832   int iPrev = _pos.size() - 2;
7833   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7834   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7835   while ( iPrev >= 0 )
7836   {
7837     vec = orig - _pos[iPrev];
7838     if ( vec.SquareModulus() > tol*tol )
7839       break;
7840     else
7841       iPrev--;
7842   }
7843
7844   // make gp_Ax1
7845   gp_Ax1 segDir;
7846   if ( iPrev < 0 )
7847   {
7848     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7849     segDir.SetDirection( _normal );
7850     segLen = 0;
7851   }
7852   else
7853   {
7854     gp_Pnt pPrev = _pos[ iPrev ];
7855     if ( !eos._sWOL.IsNull() )
7856     {
7857       TopLoc_Location loc;
7858       if ( eos.SWOLType() == TopAbs_EDGE )
7859       {
7860         double f,l;
7861         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7862         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7863       }
7864       else
7865       {
7866         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7867         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7868       }
7869       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7870     }
7871     segDir.SetLocation( pPrev );
7872     segDir.SetDirection( vec );
7873     segLen = vec.Modulus();
7874   }
7875
7876   return segDir;
7877 }
7878
7879 //================================================================================
7880 /*!
7881  * \brief Return the last (or \a which) position of the target node on a FACE. 
7882  *  \param [in] F - the FACE this _LayerEdge is inflated along
7883  *  \param [in] which - index of position
7884  *  \return gp_XY - result UV
7885  */
7886 //================================================================================
7887
7888 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
7889 {
7890   if ( F.IsSame( eos._sWOL )) // F is my FACE
7891     return gp_XY( _pos.back().X(), _pos.back().Y() );
7892
7893   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7894     return gp_XY( 1e100, 1e100 );
7895
7896   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7897   double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
7898   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7899   if ( !C2d.IsNull() && f <= u && u <= l )
7900     return C2d->Value( u ).XY();
7901
7902   return gp_XY( 1e100, 1e100 );
7903 }
7904
7905 //================================================================================
7906 /*!
7907  * \brief Test intersection of the last segment with a given triangle
7908  *   using Moller-Trumbore algorithm
7909  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7910  */
7911 //================================================================================
7912
7913 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7914                                const gp_XYZ& vert0,
7915                                const gp_XYZ& vert1,
7916                                const gp_XYZ& vert2,
7917                                double&       t,
7918                                const double& EPSILON) const
7919 {
7920   const gp_Pnt& orig = lastSegment.Location();
7921   const gp_Dir& dir  = lastSegment.Direction();
7922
7923   /* calculate distance from vert0 to ray origin */
7924   //gp_XYZ tvec = orig.XYZ() - vert0;
7925
7926   //if ( tvec * dir > EPSILON )
7927     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7928     //return false;
7929
7930   gp_XYZ edge1 = vert1 - vert0;
7931   gp_XYZ edge2 = vert2 - vert0;
7932
7933   /* begin calculating determinant - also used to calculate U parameter */
7934   gp_XYZ pvec = dir.XYZ() ^ edge2;
7935
7936   /* if determinant is near zero, ray lies in plane of triangle */
7937   double det = edge1 * pvec;
7938
7939   const double ANGL_EPSILON = 1e-12;
7940   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7941     return false;
7942
7943   /* calculate distance from vert0 to ray origin */
7944   gp_XYZ tvec = orig.XYZ() - vert0;
7945
7946   /* calculate U parameter and test bounds */
7947   double u = ( tvec * pvec ) / det;
7948   //if (u < 0.0 || u > 1.0)
7949   if ( u < -EPSILON || u > 1.0 + EPSILON )
7950     return false;
7951
7952   /* prepare to test V parameter */
7953   gp_XYZ qvec = tvec ^ edge1;
7954
7955   /* calculate V parameter and test bounds */
7956   double v = (dir.XYZ() * qvec) / det;
7957   //if ( v < 0.0 || u + v > 1.0 )
7958   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7959     return false;
7960
7961   /* calculate t, ray intersects triangle */
7962   t = (edge2 * qvec) / det;
7963
7964   //return true;
7965   return t > 0.;
7966 }
7967
7968 //================================================================================
7969 /*!
7970  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7971  *        neighbor _LayerEdge's by it's own inflation vector.
7972  *  \param [in] eov - EOS of the VERTEX
7973  *  \param [in] eos - EOS of the FACE
7974  *  \param [in] step - inflation step
7975  *  \param [in,out] badSmooEdges - tangled _LayerEdge's
7976  */
7977 //================================================================================
7978
7979 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7980                                    const _EdgesOnShape*    eos,
7981                                    const int               step,
7982                                    vector< _LayerEdge* > & badSmooEdges )
7983 {
7984   // check if any of _neibors is in badSmooEdges
7985   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7986                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7987     return;
7988
7989   // get all edges to move
7990
7991   set< _LayerEdge* > edges;
7992
7993   // find a distance between _LayerEdge on VERTEX and its neighbors
7994   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7995   double dist2 = 0;
7996   for ( size_t i = 0; i < _neibors.size(); ++i )
7997   {
7998     _LayerEdge* nEdge = _neibors[i];
7999     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8000     {
8001       edges.insert( nEdge );
8002       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8003     }
8004   }
8005   // add _LayerEdge's close to curPosV
8006   size_t nbE;
8007   do {
8008     nbE = edges.size();
8009     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8010     {
8011       _LayerEdge* edgeF = *e;
8012       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8013       {
8014         _LayerEdge* nEdge = edgeF->_neibors[i];
8015         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8016              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8017           edges.insert( nEdge );
8018       }
8019     }
8020   }
8021   while ( nbE < edges.size() );
8022
8023   // move the target node of the got edges
8024
8025   gp_XYZ prevPosV = PrevPos();
8026   if ( eov->SWOLType() == TopAbs_EDGE )
8027   {
8028     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8029     prevPosV = curve.Value( prevPosV.X() ).XYZ();
8030   }
8031   else if ( eov->SWOLType() == TopAbs_FACE )
8032   {
8033     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8034     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8035   }
8036
8037   SMDS_FacePosition* fPos;
8038   //double r = 1. - Min( 0.9, step / 10. );
8039   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8040   {
8041     _LayerEdge*       edgeF = *e;
8042     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
8043     const gp_XYZ    newPosF = curPosV + prevVF;
8044     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8045     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8046     edgeF->_pos.back() = newPosF;
8047     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8048
8049     // set _curvature to make edgeF updated by putOnOffsetSurface()
8050     if ( !edgeF->_curvature )
8051       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
8052       {
8053         edgeF->_curvature = new _Curvature;
8054         edgeF->_curvature->_r = 0;
8055         edgeF->_curvature->_k = 0;
8056         edgeF->_curvature->_h2lenRatio = 0;
8057         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8058       }
8059   }
8060   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8061   //                      SMESH_TNodeXYZ( _nodes[0]    ));
8062   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8063   // {
8064   //   _LayerEdge*      edgeF = *e;
8065   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8066   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8067   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8068   //   edgeF->_pos.back() = newPosF;
8069   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8070   // }
8071
8072   // smooth _LayerEdge's around moved nodes
8073   //size_t nbBadBefore = badSmooEdges.size();
8074   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8075   {
8076     _LayerEdge* edgeF = *e;
8077     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8078       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8079         //&& !edges.count( edgeF->_neibors[j] ))
8080       {
8081         _LayerEdge* edgeFN = edgeF->_neibors[j];
8082         edgeFN->Unset( SMOOTHED );
8083         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8084         // if ( nbBad > 0 )
8085         // {
8086         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8087         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8088         //   int        nbBadAfter = edgeFN->_simplices.size();
8089         //   double vol;
8090         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8091         //   {
8092         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8093         //   }
8094         //   if ( nbBadAfter <= nbBad )
8095         //   {
8096         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8097         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8098         //     edgeF->_pos.back() = newPosF;
8099         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8100         //     nbBad = nbBadAfter;
8101         //   }
8102         // }
8103         if ( nbBad > 0 )
8104           badSmooEdges.push_back( edgeFN );
8105       }
8106   }
8107     // move a bit not smoothed around moved nodes
8108   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8109   //   {
8110   //   _LayerEdge*      edgeF = badSmooEdges[i];
8111   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8112   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8113   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8114   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8115   //   edgeF->_pos.back() = newPosF;
8116   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8117   // }
8118 }
8119
8120 //================================================================================
8121 /*!
8122  * \brief Perform smooth of _LayerEdge's based on EDGE's
8123  *  \retval bool - true if node has been moved
8124  */
8125 //================================================================================
8126
8127 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8128                               const TopoDS_Face&             F,
8129                               SMESH_MesherHelper&            helper)
8130 {
8131   ASSERT( IsOnEdge() );
8132
8133   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8134   SMESH_TNodeXYZ oldPos( tgtNode );
8135   double dist01, distNewOld;
8136   
8137   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8138   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8139   dist01 = p0.Distance( _2neibors->tgtNode(1) );
8140
8141   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8142   double lenDelta = 0;
8143   if ( _curvature )
8144   {
8145     //lenDelta = _curvature->lenDelta( _len );
8146     lenDelta = _curvature->lenDeltaByDist( dist01 );
8147     newPos.ChangeCoord() += _normal * lenDelta;
8148   }
8149
8150   distNewOld = newPos.Distance( oldPos );
8151
8152   if ( F.IsNull() )
8153   {
8154     if ( _2neibors->_plnNorm )
8155     {
8156       // put newPos on the plane defined by source node and _plnNorm
8157       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8158       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8159       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8160     }
8161     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8162     _pos.back() = newPos.XYZ();
8163   }
8164   else
8165   {
8166     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8167     gp_XY uv( Precision::Infinite(), 0 );
8168     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8169     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8170
8171     newPos = surface->Value( uv );
8172     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8173   }
8174
8175   // commented for IPAL0052478
8176   // if ( _curvature && lenDelta < 0 )
8177   // {
8178   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8179   //   _len -= prevPos.Distance( oldPos );
8180   //   _len += prevPos.Distance( newPos );
8181   // }
8182   bool moved = distNewOld > dist01/50;
8183   //if ( moved )
8184   dumpMove( tgtNode ); // debug
8185
8186   return moved;
8187 }
8188
8189 //================================================================================
8190 /*!
8191  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8192  */
8193 //================================================================================
8194
8195 void _LayerEdge::SmoothWoCheck()
8196 {
8197   if ( Is( DIFFICULT ))
8198     return;
8199
8200   bool moved = Is( SMOOTHED );
8201   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
8202     moved = _neibors[i]->Is( SMOOTHED );
8203   if ( !moved )
8204     return;
8205
8206   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8207
8208   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8209   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8210   _pos.back() = newPos;
8211
8212   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8213 }
8214
8215 //================================================================================
8216 /*!
8217  * \brief Checks validity of _neibors on EDGEs and VERTEXes
8218  */
8219 //================================================================================
8220
8221 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8222 {
8223   if ( ! Is( NEAR_BOUNDARY ))
8224     return 0;
8225
8226   int nbBad = 0;
8227   double vol;
8228   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8229   {
8230     _LayerEdge* eN = _neibors[iN];
8231     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8232       continue;
8233     if ( needSmooth )
8234       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8235                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8236                        eN->_pos.size() != _pos.size() );
8237
8238     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8239     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8240     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8241       if ( eN->_nodes.size() > 1 &&
8242            eN->_simplices[i].Includes( _nodes.back() ) &&
8243            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8244       {
8245         ++nbBad;
8246         if ( badNeibors )
8247         {
8248           badNeibors->push_back( eN );
8249           debugMsg("Bad boundary simplex ( "
8250                    << " "<< eN->_nodes[0]->GetID()
8251                    << " "<< eN->_nodes.back()->GetID()
8252                    << " "<< eN->_simplices[i]._nPrev->GetID()
8253                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8254         }
8255         else
8256         {
8257           break;
8258         }
8259       }
8260   }
8261   return nbBad;
8262 }
8263
8264 //================================================================================
8265 /*!
8266  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8267  *  \retval int - nb of bad simplices around this _LayerEdge
8268  */
8269 //================================================================================
8270
8271 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8272 {
8273   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8274     return 0; // shape of simplices not changed
8275   if ( _simplices.size() < 2 )
8276     return 0; // _LayerEdge inflated along EDGE or FACE
8277
8278   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8279     findBest = true;
8280
8281   const gp_XYZ& curPos  = _pos.back();
8282   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8283
8284   // quality metrics (orientation) of tetras around _tgtNode
8285   int nbOkBefore = 0;
8286   double vol, minVolBefore = 1e100;
8287   for ( size_t i = 0; i < _simplices.size(); ++i )
8288   {
8289     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8290     minVolBefore = Min( minVolBefore, vol );
8291   }
8292   int nbBad = _simplices.size() - nbOkBefore;
8293
8294   bool bndNeedSmooth = false;
8295   if ( nbBad == 0 )
8296     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8297   if ( nbBad > 0 )
8298     Set( DISTORTED );
8299
8300   // evaluate min angle
8301   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8302   {
8303     size_t nbGoodAngles = _simplices.size();
8304     double angle;
8305     for ( size_t i = 0; i < _simplices.size(); ++i )
8306     {
8307       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8308         --nbGoodAngles;
8309     }
8310     if ( nbGoodAngles == _simplices.size() )
8311     {
8312       Unset( MOVED );
8313       return 0;
8314     }
8315   }
8316   if ( Is( ON_CONCAVE_FACE ))
8317     findBest = true;
8318
8319   if ( step % 2 == 0 )
8320     findBest = false;
8321
8322   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8323   {
8324     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8325       _smooFunction = _funs[ FUN_CENTROIDAL ];
8326     else
8327       _smooFunction = _funs[ FUN_LAPLACIAN ];
8328   }
8329
8330   // compute new position for the last _pos using different _funs
8331   gp_XYZ newPos;
8332   bool moved = false;
8333   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8334   {
8335     if ( iFun < 0 )
8336       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8337     else if ( _funs[ iFun ] == _smooFunction )
8338       continue; // _smooFunction again
8339     else if ( step > 1 )
8340       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8341     else
8342       break; // let "easy" functions improve elements around distorted ones
8343
8344     if ( _curvature )
8345     {
8346       double delta  = _curvature->lenDelta( _len );
8347       if ( delta > 0 )
8348         newPos += _normal * delta;
8349       else
8350       {
8351         double segLen = _normal * ( newPos - prevPos );
8352         if ( segLen + delta > 0 )
8353           newPos += _normal * delta;
8354       }
8355       // double segLenChange = _normal * ( curPos - newPos );
8356       // newPos += 0.5 * _normal * segLenChange;
8357     }
8358
8359     int nbOkAfter = 0;
8360     double minVolAfter = 1e100;
8361     for ( size_t i = 0; i < _simplices.size(); ++i )
8362     {
8363       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8364       minVolAfter = Min( minVolAfter, vol );
8365     }
8366     // get worse?
8367     if ( nbOkAfter < nbOkBefore )
8368       continue;
8369
8370     if (( findBest ) &&
8371         ( nbOkAfter == nbOkBefore ) &&
8372         ( minVolAfter <= minVolBefore ))
8373       continue;
8374
8375     nbBad        = _simplices.size() - nbOkAfter;
8376     minVolBefore = minVolAfter;
8377     nbOkBefore   = nbOkAfter;
8378     moved        = true;
8379
8380     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8381     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8382     _pos.back() = newPos;
8383
8384     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8385                   << (nbBad ? " --BAD" : ""));
8386
8387     if ( iFun > -1 )
8388     {
8389       continue; // look for a better function
8390     }
8391
8392     if ( !findBest )
8393       break;
8394
8395   } // loop on smoothing functions
8396
8397   if ( moved ) // notify _neibors
8398   {
8399     Set( SMOOTHED );
8400     for ( size_t i = 0; i < _neibors.size(); ++i )
8401       if ( !_neibors[i]->Is( MOVED ))
8402       {
8403         _neibors[i]->Set( MOVED );
8404         toSmooth.push_back( _neibors[i] );
8405       }
8406   }
8407
8408   return nbBad;
8409 }
8410
8411 //================================================================================
8412 /*!
8413  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8414  *  \retval int - nb of bad simplices around this _LayerEdge
8415  */
8416 //================================================================================
8417
8418 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8419 {
8420   if ( !_smooFunction )
8421     return 0; // _LayerEdge inflated along EDGE or FACE
8422   if ( Is( BLOCKED ))
8423     return 0; // not inflated
8424
8425   const gp_XYZ& curPos  = _pos.back();
8426   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8427
8428   // quality metrics (orientation) of tetras around _tgtNode
8429   int nbOkBefore = 0;
8430   double vol, minVolBefore = 1e100;
8431   for ( size_t i = 0; i < _simplices.size(); ++i )
8432   {
8433     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8434     minVolBefore = Min( minVolBefore, vol );
8435   }
8436   int nbBad = _simplices.size() - nbOkBefore;
8437
8438   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8439   {
8440     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8441       _smooFunction = _funs[ FUN_LAPLACIAN ];
8442     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8443       _smooFunction = _funs[ FUN_CENTROIDAL ];
8444   }
8445
8446   // compute new position for the last _pos using different _funs
8447   gp_XYZ newPos;
8448   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8449   {
8450     if ( iFun < 0 )
8451       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8452     else if ( _funs[ iFun ] == _smooFunction )
8453       continue; // _smooFunction again
8454     else if ( step > 1 )
8455       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8456     else
8457       break; // let "easy" functions improve elements around distorted ones
8458
8459     if ( _curvature )
8460     {
8461       double delta  = _curvature->lenDelta( _len );
8462       if ( delta > 0 )
8463         newPos += _normal * delta;
8464       else
8465       {
8466         double segLen = _normal * ( newPos - prevPos );
8467         if ( segLen + delta > 0 )
8468           newPos += _normal * delta;
8469       }
8470       // double segLenChange = _normal * ( curPos - newPos );
8471       // newPos += 0.5 * _normal * segLenChange;
8472     }
8473
8474     int nbOkAfter = 0;
8475     double minVolAfter = 1e100;
8476     for ( size_t i = 0; i < _simplices.size(); ++i )
8477     {
8478       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8479       minVolAfter = Min( minVolAfter, vol );
8480     }
8481     // get worse?
8482     if ( nbOkAfter < nbOkBefore )
8483       continue;
8484     if (( isConcaveFace || findBest ) &&
8485         ( nbOkAfter == nbOkBefore ) &&
8486         ( minVolAfter <= minVolBefore )
8487         )
8488       continue;
8489
8490     nbBad        = _simplices.size() - nbOkAfter;
8491     minVolBefore = minVolAfter;
8492     nbOkBefore   = nbOkAfter;
8493
8494     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8495     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8496     _pos.back() = newPos;
8497
8498     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8499                   << ( nbBad ? "--BAD" : ""));
8500
8501     // commented for IPAL0052478
8502     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8503     // _len += prevPos.Distance(newPos);
8504
8505     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8506     {
8507       //_smooFunction = _funs[ iFun ];
8508       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8509       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8510       // << " minVol: " << minVolAfter
8511       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8512       // << endl;
8513       continue; // look for a better function
8514     }
8515
8516     if ( !findBest )
8517       break;
8518
8519   } // loop on smoothing functions
8520
8521   return nbBad;
8522 }
8523
8524 //================================================================================
8525 /*!
8526  * \brief Chooses a smoothing technic giving a position most close to an initial one.
8527  *        For a correct result, _simplices must contain nodes lying on geometry.
8528  */
8529 //================================================================================
8530
8531 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8532                                      const TNode2Edge&     n2eMap)
8533 {
8534   if ( _smooFunction ) return;
8535
8536   // use smoothNefPolygon() near concaveVertices
8537   if ( !concaveVertices.empty() )
8538   {
8539     _smooFunction = _funs[ FUN_CENTROIDAL ];
8540
8541     Set( ON_CONCAVE_FACE );
8542
8543     for ( size_t i = 0; i < _simplices.size(); ++i )
8544     {
8545       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8546       {
8547         _smooFunction = _funs[ FUN_NEFPOLY ];
8548
8549         // set FUN_CENTROIDAL to neighbor edges
8550         for ( i = 0; i < _neibors.size(); ++i )
8551         {
8552           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8553           {
8554             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8555           }
8556         }
8557         return;
8558       }
8559     }
8560
8561     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8562     // // where the nodes are smoothed too far along a sphere thus creating
8563     // // inverted _simplices
8564     // double dist[theNbSmooFuns];
8565     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8566     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8567
8568     // double minDist = Precision::Infinite();
8569     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8570     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8571     // {
8572     //   gp_Pnt newP = (this->*_funs[i])();
8573     //   dist[i] = p.SquareDistance( newP );
8574     //   if ( dist[i]*coef[i] < minDist )
8575     //   {
8576     //     _smooFunction = _funs[i];
8577     //     minDist = dist[i]*coef[i];
8578     //   }
8579     // }
8580   }
8581   else
8582   {
8583     _smooFunction = _funs[ FUN_LAPLACIAN ];
8584   }
8585   // int minDim = 3;
8586   // for ( size_t i = 0; i < _simplices.size(); ++i )
8587   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8588   // if ( minDim == 0 )
8589   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8590   // else if ( minDim == 1 )
8591   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8592
8593
8594   // int iMin;
8595   // for ( int i = 0; i < FUN_NB; ++i )
8596   // {
8597   //   //cout << dist[i] << " ";
8598   //   if ( _smooFunction == _funs[i] ) {
8599   //     iMin = i;
8600   //     //debugMsg( fNames[i] );
8601   //     break;
8602   //   }
8603   // }
8604   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8605 }
8606
8607 //================================================================================
8608 /*!
8609  * \brief Returns a name of _SmooFunction
8610  */
8611 //================================================================================
8612
8613 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8614 {
8615   if ( !fun )
8616     fun = _smooFunction;
8617   for ( int i = 0; i < theNbSmooFuns; ++i )
8618     if ( fun == _funs[i] )
8619       return i;
8620
8621   return theNbSmooFuns;
8622 }
8623
8624 //================================================================================
8625 /*!
8626  * \brief Computes a new node position using Laplacian smoothing
8627  */
8628 //================================================================================
8629
8630 gp_XYZ _LayerEdge::smoothLaplacian()
8631 {
8632   gp_XYZ newPos (0,0,0);
8633   for ( size_t i = 0; i < _simplices.size(); ++i )
8634     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8635   newPos /= _simplices.size();
8636
8637   return newPos;
8638 }
8639
8640 //================================================================================
8641 /*!
8642  * \brief Computes a new node position using angular-based smoothing
8643  */
8644 //================================================================================
8645
8646 gp_XYZ _LayerEdge::smoothAngular()
8647 {
8648   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8649   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8650   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8651
8652   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8653   gp_XYZ pN( 0,0,0 );
8654   for ( size_t i = 0; i < _simplices.size(); ++i )
8655   {
8656     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8657     edgeDir.push_back( p - pPrev );
8658     edgeSize.push_back( edgeDir.back().Magnitude() );
8659     if ( edgeSize.back() < numeric_limits<double>::min() )
8660     {
8661       edgeDir.pop_back();
8662       edgeSize.pop_back();
8663     }
8664     else
8665     {
8666       edgeDir.back() /= edgeSize.back();
8667       points.push_back( p );
8668       pN += p;
8669     }
8670     pPrev = p;
8671   }
8672   edgeDir.push_back ( edgeDir[0] );
8673   edgeSize.push_back( edgeSize[0] );
8674   pN /= points.size();
8675
8676   gp_XYZ newPos(0,0,0);
8677   double sumSize = 0;
8678   for ( size_t i = 0; i < points.size(); ++i )
8679   {
8680     gp_Vec toN    = pN - points[i];
8681     double toNLen = toN.Magnitude();
8682     if ( toNLen < numeric_limits<double>::min() )
8683     {
8684       newPos += pN;
8685       continue;
8686     }
8687     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8688     double bisecLen = bisec.SquareMagnitude();
8689     if ( bisecLen < numeric_limits<double>::min() )
8690     {
8691       gp_Vec norm = edgeDir[i] ^ toN;
8692       bisec = norm ^ edgeDir[i];
8693       bisecLen = bisec.SquareMagnitude();
8694     }
8695     bisecLen = Sqrt( bisecLen );
8696     bisec /= bisecLen;
8697
8698 #if 1
8699     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8700     sumSize += bisecLen;
8701 #else
8702     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8703     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8704 #endif
8705     newPos += pNew;
8706   }
8707   newPos /= sumSize;
8708
8709   // project newPos to an average plane
8710
8711   gp_XYZ norm(0,0,0); // plane normal
8712   points.push_back( points[0] );
8713   for ( size_t i = 1; i < points.size(); ++i )
8714   {
8715     gp_XYZ vec1 = points[ i-1 ] - pN;
8716     gp_XYZ vec2 = points[ i   ] - pN;
8717     gp_XYZ cross = vec1 ^ vec2;
8718     try {
8719       cross.Normalize();
8720       if ( cross * norm < numeric_limits<double>::min() )
8721         norm += cross.Reversed();
8722       else
8723         norm += cross;
8724     }
8725     catch (Standard_Failure) { // if |cross| == 0.
8726     }
8727   }
8728   gp_XYZ vec = newPos - pN;
8729   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8730   newPos     = newPos - r * norm;
8731
8732   return newPos;
8733 }
8734
8735 //================================================================================
8736 /*!
8737  * \brief Computes a new node position using weigthed node positions
8738  */
8739 //================================================================================
8740
8741 gp_XYZ _LayerEdge::smoothLengthWeighted()
8742 {
8743   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8744   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8745
8746   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8747   for ( size_t i = 0; i < _simplices.size(); ++i )
8748   {
8749     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8750     edgeSize.push_back( ( p - pPrev ).Modulus() );
8751     if ( edgeSize.back() < numeric_limits<double>::min() )
8752     {
8753       edgeSize.pop_back();
8754     }
8755     else
8756     {
8757       points.push_back( p );
8758     }
8759     pPrev = p;
8760   }
8761   edgeSize.push_back( edgeSize[0] );
8762
8763   gp_XYZ newPos(0,0,0);
8764   double sumSize = 0;
8765   for ( size_t i = 0; i < points.size(); ++i )
8766   {
8767     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8768     sumSize += edgeSize[i] + edgeSize[i+1];
8769   }
8770   newPos /= sumSize;
8771   return newPos;
8772 }
8773
8774 //================================================================================
8775 /*!
8776  * \brief Computes a new node position using angular-based smoothing
8777  */
8778 //================================================================================
8779
8780 gp_XYZ _LayerEdge::smoothCentroidal()
8781 {
8782   gp_XYZ newPos(0,0,0);
8783   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8784   double sumSize = 0;
8785   for ( size_t i = 0; i < _simplices.size(); ++i )
8786   {
8787     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8788     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8789     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8790     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8791
8792     sumSize += size;
8793     newPos += gc * size;
8794   }
8795   newPos /= sumSize;
8796
8797   return newPos;
8798 }
8799
8800 //================================================================================
8801 /*!
8802  * \brief Computes a new node position located inside a Nef polygon
8803  */
8804 //================================================================================
8805
8806 gp_XYZ _LayerEdge::smoothNefPolygon()
8807 #ifdef OLD_NEF_POLYGON
8808 {
8809   gp_XYZ newPos(0,0,0);
8810
8811   // get a plane to search a solution on
8812
8813   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8814   size_t i;
8815   const double tol = numeric_limits<double>::min();
8816   gp_XYZ center(0,0,0);
8817   for ( i = 0; i < _simplices.size(); ++i )
8818   {
8819     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8820                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8821     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8822   }
8823   vecs.back() = vecs[0];
8824   center /= _simplices.size();
8825
8826   gp_XYZ zAxis(0,0,0);
8827   for ( i = 0; i < _simplices.size(); ++i )
8828     zAxis += vecs[i] ^ vecs[i+1];
8829
8830   gp_XYZ yAxis;
8831   for ( i = 0; i < _simplices.size(); ++i )
8832   {
8833     yAxis = vecs[i];
8834     if ( yAxis.SquareModulus() > tol )
8835       break;
8836   }
8837   gp_XYZ xAxis = yAxis ^ zAxis;
8838   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8839   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8840   //                             p0.Distance( _simplices[2]._nPrev ));
8841   // gp_XYZ center = smoothLaplacian();
8842   // gp_XYZ xAxis, yAxis, zAxis;
8843   // for ( i = 0; i < _simplices.size(); ++i )
8844   // {
8845   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8846   //   if ( xAxis.SquareModulus() > tol*tol )
8847   //     break;
8848   // }
8849   // for ( i = 1; i < _simplices.size(); ++i )
8850   // {
8851   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8852   //   zAxis = xAxis ^ yAxis;
8853   //   if ( zAxis.SquareModulus() > tol*tol )
8854   //     break;
8855   // }
8856   // if ( i == _simplices.size() ) return newPos;
8857
8858   yAxis = zAxis ^ xAxis;
8859   xAxis /= xAxis.Modulus();
8860   yAxis /= yAxis.Modulus();
8861
8862   // get half-planes of _simplices
8863
8864   vector< _halfPlane > halfPlns( _simplices.size() );
8865   int nbHP = 0;
8866   for ( size_t i = 0; i < _simplices.size(); ++i )
8867   {
8868     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8869     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8870     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8871     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8872     gp_XY  vec12 = p2 - p1;
8873     double dist12 = vec12.Modulus();
8874     if ( dist12 < tol )
8875       continue;
8876     vec12 /= dist12;
8877     halfPlns[ nbHP ]._pos = p1;
8878     halfPlns[ nbHP ]._dir = vec12;
8879     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8880     ++nbHP;
8881   }
8882
8883   // intersect boundaries of half-planes, define state of intersection points
8884   // in relation to all half-planes and calculate internal point of a 2D polygon
8885
8886   double sumLen = 0;
8887   gp_XY newPos2D (0,0);
8888
8889   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8890   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8891   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8892
8893   vector< vector< TIntPntState > > allIntPnts( nbHP );
8894   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8895   {
8896     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8897     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8898
8899     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8900     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8901
8902     int nbNotOut = 0;
8903     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8904
8905     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8906     {
8907       if ( iHP1 == iHP2 ) continue;
8908
8909       TIntPntState & ips1 = intPnts1[ iHP2 ];
8910       if ( ips1.second == UNDEF )
8911       {
8912         // find an intersection point of boundaries of iHP1 and iHP2
8913
8914         if ( iHP2 == iPrev ) // intersection with neighbors is known
8915           ips1.first = halfPlns[ iHP1 ]._pos;
8916         else if ( iHP2 == iNext )
8917           ips1.first = halfPlns[ iHP2 ]._pos;
8918         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8919           ips1.second = NO_INT;
8920
8921         // classify the found intersection point
8922         if ( ips1.second != NO_INT )
8923         {
8924           ips1.second = NOT_OUT;
8925           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8926             if ( i != iHP1 && i != iHP2 &&
8927                  halfPlns[ i ].IsOut( ips1.first, tol ))
8928               ips1.second = IS_OUT;
8929         }
8930         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8931         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8932         TIntPntState & ips2 = intPnts2[ iHP1 ];
8933         ips2 = ips1;
8934       }
8935       if ( ips1.second == NOT_OUT )
8936       {
8937         ++nbNotOut;
8938         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8939       }
8940     }
8941
8942     // find a NOT_OUT segment of boundary which is located between
8943     // two NOT_OUT int points
8944
8945     if ( nbNotOut < 2 )
8946       continue; // no such a segment
8947
8948     if ( nbNotOut > 2 )
8949     {
8950       // sort points along the boundary
8951       map< double, TIntPntState* > ipsByParam;
8952       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8953       {
8954         TIntPntState & ips1 = intPnts1[ iHP2 ];
8955         if ( ips1.second != NO_INT )
8956         {
8957           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8958           double param = op * halfPlns[ iHP1 ]._dir;
8959           ipsByParam.insert( make_pair( param, & ips1 ));
8960         }
8961       }
8962       // look for two neighboring NOT_OUT points
8963       nbNotOut = 0;
8964       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8965       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8966       {
8967         TIntPntState & ips1 = *(u2ips->second);
8968         if ( ips1.second == NOT_OUT )
8969           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8970         else if ( nbNotOut >= 2 )
8971           break;
8972         else
8973           nbNotOut = 0;
8974       }
8975     }
8976
8977     if ( nbNotOut >= 2 )
8978     {
8979       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8980       sumLen += len;
8981
8982       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8983     }
8984   }
8985
8986   if ( sumLen > 0 )
8987   {
8988     newPos2D /= sumLen;
8989     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8990   }
8991   else
8992   {
8993     newPos = center;
8994   }
8995
8996   return newPos;
8997 }
8998 #else // OLD_NEF_POLYGON
8999 { ////////////////////////////////// NEW
9000   gp_XYZ newPos(0,0,0);
9001
9002   // get a plane to search a solution on
9003
9004   size_t i;
9005   gp_XYZ center(0,0,0);
9006   for ( i = 0; i < _simplices.size(); ++i )
9007     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9008   center /= _simplices.size();
9009
9010   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9011   for ( i = 0; i < _simplices.size(); ++i )
9012     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9013   vecs.back() = vecs[0];
9014
9015   const double tol = numeric_limits<double>::min();
9016   gp_XYZ zAxis(0,0,0);
9017   for ( i = 0; i < _simplices.size(); ++i )
9018   {
9019     gp_XYZ cross = vecs[i] ^ vecs[i+1];
9020     try {
9021       cross.Normalize();
9022       if ( cross * zAxis < tol )
9023         zAxis += cross.Reversed();
9024       else
9025         zAxis += cross;
9026     }
9027     catch (Standard_Failure) { // if |cross| == 0.
9028     }
9029   }
9030
9031   gp_XYZ yAxis;
9032   for ( i = 0; i < _simplices.size(); ++i )
9033   {
9034     yAxis = vecs[i];
9035     if ( yAxis.SquareModulus() > tol )
9036       break;
9037   }
9038   gp_XYZ xAxis = yAxis ^ zAxis;
9039   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9040   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9041   //                             p0.Distance( _simplices[2]._nPrev ));
9042   // gp_XYZ center = smoothLaplacian();
9043   // gp_XYZ xAxis, yAxis, zAxis;
9044   // for ( i = 0; i < _simplices.size(); ++i )
9045   // {
9046   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9047   //   if ( xAxis.SquareModulus() > tol*tol )
9048   //     break;
9049   // }
9050   // for ( i = 1; i < _simplices.size(); ++i )
9051   // {
9052   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9053   //   zAxis = xAxis ^ yAxis;
9054   //   if ( zAxis.SquareModulus() > tol*tol )
9055   //     break;
9056   // }
9057   // if ( i == _simplices.size() ) return newPos;
9058
9059   yAxis = zAxis ^ xAxis;
9060   xAxis /= xAxis.Modulus();
9061   yAxis /= yAxis.Modulus();
9062
9063   // get half-planes of _simplices
9064
9065   vector< _halfPlane > halfPlns( _simplices.size() );
9066   int nbHP = 0;
9067   for ( size_t i = 0; i < _simplices.size(); ++i )
9068   {
9069     const gp_XYZ& OP1 = vecs[ i   ];
9070     const gp_XYZ& OP2 = vecs[ i+1 ];
9071     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9072     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9073     gp_XY  vec12 = p2 - p1;
9074     double dist12 = vec12.Modulus();
9075     if ( dist12 < tol )
9076       continue;
9077     vec12 /= dist12;
9078     halfPlns[ nbHP ]._pos = p1;
9079     halfPlns[ nbHP ]._dir = vec12;
9080     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9081     ++nbHP;
9082   }
9083
9084   // intersect boundaries of half-planes, define state of intersection points
9085   // in relation to all half-planes and calculate internal point of a 2D polygon
9086
9087   double sumLen = 0;
9088   gp_XY newPos2D (0,0);
9089
9090   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9091   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9092   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9093
9094   vector< vector< TIntPntState > > allIntPnts( nbHP );
9095   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9096   {
9097     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9098     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9099
9100     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9101     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9102
9103     int nbNotOut = 0;
9104     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9105
9106     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9107     {
9108       if ( iHP1 == iHP2 ) continue;
9109
9110       TIntPntState & ips1 = intPnts1[ iHP2 ];
9111       if ( ips1.second == UNDEF )
9112       {
9113         // find an intersection point of boundaries of iHP1 and iHP2
9114
9115         if ( iHP2 == iPrev ) // intersection with neighbors is known
9116           ips1.first = halfPlns[ iHP1 ]._pos;
9117         else if ( iHP2 == iNext )
9118           ips1.first = halfPlns[ iHP2 ]._pos;
9119         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9120           ips1.second = NO_INT;
9121
9122         // classify the found intersection point
9123         if ( ips1.second != NO_INT )
9124         {
9125           ips1.second = NOT_OUT;
9126           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9127             if ( i != iHP1 && i != iHP2 &&
9128                  halfPlns[ i ].IsOut( ips1.first, tol ))
9129               ips1.second = IS_OUT;
9130         }
9131         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9132         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9133         TIntPntState & ips2 = intPnts2[ iHP1 ];
9134         ips2 = ips1;
9135       }
9136       if ( ips1.second == NOT_OUT )
9137       {
9138         ++nbNotOut;
9139         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9140       }
9141     }
9142
9143     // find a NOT_OUT segment of boundary which is located between
9144     // two NOT_OUT int points
9145
9146     if ( nbNotOut < 2 )
9147       continue; // no such a segment
9148
9149     if ( nbNotOut > 2 )
9150     {
9151       // sort points along the boundary
9152       map< double, TIntPntState* > ipsByParam;
9153       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9154       {
9155         TIntPntState & ips1 = intPnts1[ iHP2 ];
9156         if ( ips1.second != NO_INT )
9157         {
9158           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9159           double param = op * halfPlns[ iHP1 ]._dir;
9160           ipsByParam.insert( make_pair( param, & ips1 ));
9161         }
9162       }
9163       // look for two neighboring NOT_OUT points
9164       nbNotOut = 0;
9165       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9166       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9167       {
9168         TIntPntState & ips1 = *(u2ips->second);
9169         if ( ips1.second == NOT_OUT )
9170           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9171         else if ( nbNotOut >= 2 )
9172           break;
9173         else
9174           nbNotOut = 0;
9175       }
9176     }
9177
9178     if ( nbNotOut >= 2 )
9179     {
9180       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9181       sumLen += len;
9182
9183       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9184     }
9185   }
9186
9187   if ( sumLen > 0 )
9188   {
9189     newPos2D /= sumLen;
9190     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9191   }
9192   else
9193   {
9194     newPos = center;
9195   }
9196
9197   return newPos;
9198 }
9199 #endif // OLD_NEF_POLYGON
9200
9201 //================================================================================
9202 /*!
9203  * \brief Add a new segment to _LayerEdge during inflation
9204  */
9205 //================================================================================
9206
9207 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9208 {
9209   if ( Is( BLOCKED ))
9210     return;
9211
9212   if ( len > _maxLen )
9213   {
9214     len = _maxLen;
9215     Block( eos.GetData() );
9216   }
9217   const double lenDelta = len - _len;
9218   if ( lenDelta < len * 1e-3  )
9219   {
9220     Block( eos.GetData() );
9221     return;
9222   }
9223
9224   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9225   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9226   gp_XYZ newXYZ;
9227   if ( eos._hyp.IsOffsetMethod() )
9228   {
9229     newXYZ = oldXYZ;
9230     gp_Vec faceNorm;
9231     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9232     while ( faceIt->more() )
9233     {
9234       const SMDS_MeshElement* face = faceIt->next();
9235       if ( !eos.GetNormal( face, faceNorm ))
9236         continue;
9237
9238       // translate plane of a face
9239       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9240
9241       // find point of intersection of the face plane located at baryCenter
9242       // and _normal located at newXYZ
9243       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9244       double dot =  ( faceNorm.XYZ() * _normal );
9245       if ( dot < std::numeric_limits<double>::min() )
9246         dot = lenDelta * 1e-3;
9247       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9248       newXYZ += step * _normal;
9249     }
9250     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9251   }
9252   else
9253   {
9254     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9255   }
9256
9257   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9258   _pos.push_back( newXYZ );
9259
9260   if ( !eos._sWOL.IsNull() )
9261   {
9262     double distXYZ[4];
9263     bool uvOK = false;
9264     if ( eos.SWOLType() == TopAbs_EDGE )
9265     {
9266       double u = Precision::Infinite(); // to force projection w/o distance check
9267       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9268                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9269       _pos.back().SetCoord( u, 0, 0 );
9270       if ( _nodes.size() > 1 && uvOK )
9271       {
9272         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9273         pos->SetUParameter( u );
9274       }
9275     }
9276     else //  TopAbs_FACE
9277     {
9278       gp_XY uv( Precision::Infinite(), 0 );
9279       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9280                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9281       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9282       if ( _nodes.size() > 1 && uvOK )
9283       {
9284         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9285         pos->SetUParameter( uv.X() );
9286         pos->SetVParameter( uv.Y() );
9287       }
9288     }
9289     if ( uvOK )
9290     {
9291       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9292     }
9293     else
9294     {
9295       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9296       _pos.pop_back();
9297       Block( eos.GetData() );
9298       return;
9299     }
9300   }
9301
9302   _len = len;
9303
9304   // notify _neibors
9305   if ( eos.ShapeType() != TopAbs_FACE )
9306   {
9307     for ( size_t i = 0; i < _neibors.size(); ++i )
9308       //if (  _len > _neibors[i]->GetSmooLen() )
9309         _neibors[i]->Set( MOVED );
9310
9311     Set( MOVED );
9312   }
9313   dumpMove( n ); //debug
9314 }
9315
9316 //================================================================================
9317 /*!
9318  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9319  */
9320 //================================================================================
9321
9322 void _LayerEdge::Block( _SolidData& data )
9323 {
9324   //if ( Is( BLOCKED )) return;
9325   Set( BLOCKED );
9326
9327   SMESH_Comment msg( "#BLOCK shape=");
9328   msg << data.GetShapeEdges( this )->_shapeID
9329       << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9330   dumpCmd( msg + " -- BEGIN")
9331
9332   _maxLen = _len;
9333   std::queue<_LayerEdge*> queue;
9334   queue.push( this );
9335
9336   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9337   while ( !queue.empty() )
9338   {
9339     _LayerEdge* edge = queue.front(); queue.pop();
9340     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9341     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9342     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9343     {
9344       _LayerEdge* neibor = edge->_neibors[iN];
9345       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9346         continue;
9347       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9348       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9349       double minDist = pSrc.SquareDistance( pSrcN );
9350       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9351       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9352       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9353       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9354       //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9355       {
9356         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9357         // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9358         //                   neibor->_lenFactor / edge->_lenFactor );
9359       }
9360       if ( neibor->_maxLen > newMaxLen )
9361       {
9362         neibor->_maxLen = newMaxLen;
9363         if ( neibor->_maxLen < neibor->_len )
9364         {
9365           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9366           while ( neibor->_len > neibor->_maxLen &&
9367                   neibor->NbSteps() > 1 )
9368             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9369           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9370           //neibor->Block( data );
9371         }
9372         queue.push( neibor );
9373       }
9374     }
9375   }
9376   dumpCmd( msg + " -- END")
9377 }
9378
9379 //================================================================================
9380 /*!
9381  * \brief Remove last inflation step
9382  */
9383 //================================================================================
9384
9385 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9386 {
9387   if ( _pos.size() > curStep && _nodes.size() > 1 )
9388   {
9389     _pos.resize( curStep );
9390
9391     gp_Pnt      nXYZ = _pos.back();
9392     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9393     SMESH_TNodeXYZ curXYZ( n );
9394     if ( !eos._sWOL.IsNull() )
9395     {
9396       TopLoc_Location loc;
9397       if ( eos.SWOLType() == TopAbs_EDGE )
9398       {
9399         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9400         pos->SetUParameter( nXYZ.X() );
9401         double f,l;
9402         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9403         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9404       }
9405       else
9406       {
9407         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9408         pos->SetUParameter( nXYZ.X() );
9409         pos->SetVParameter( nXYZ.Y() );
9410         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9411         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9412       }
9413     }
9414     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9415     dumpMove( n );
9416
9417     if ( restoreLength )
9418     {
9419       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9420     }
9421   }
9422 }
9423
9424 //================================================================================
9425 /*!
9426  * \brief Return index of a _pos distant from _normal
9427  */
9428 //================================================================================
9429
9430 int _LayerEdge::GetSmoothedPos( const double tol )
9431 {
9432   int iSmoothed = 0;
9433   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9434   {
9435     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9436     if ( normDist > tol * tol )
9437       iSmoothed = i;
9438   }
9439   return iSmoothed;
9440 }
9441
9442 //================================================================================
9443 /*!
9444  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9445  */
9446 //================================================================================
9447
9448 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9449 {
9450   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9451     return;
9452
9453   // find the 1st smoothed _pos
9454   int iSmoothed = GetSmoothedPos( tol );
9455   if ( !iSmoothed ) return;
9456
9457   //if ( 1 || Is( DISTORTED ))
9458   {
9459     gp_XYZ normal = _normal;
9460     if ( Is( NORMAL_UPDATED ))
9461       for ( size_t i = 1; i < _pos.size(); ++i )
9462       {
9463         normal = _pos[i] - _pos[0];
9464         double size = normal.Modulus();
9465         if ( size > RealSmall() )
9466         {
9467           normal /= size;
9468           break;
9469         }
9470       }
9471     const double r = 0.2;
9472     for ( int iter = 0; iter < 50; ++iter )
9473     {
9474       double minDot = 1;
9475       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9476       {
9477         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9478         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9479         _pos[i] = newPos;
9480         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9481         double newLen = ( 1-r ) * midLen + r * segLen[i];
9482         const_cast< double& >( segLen[i] ) = newLen;
9483         // check angle between normal and (_pos[i+1], _pos[i] )
9484         gp_XYZ posDir = _pos[i+1] - _pos[i];
9485         double size   = posDir.SquareModulus();
9486         if ( size > RealSmall() )
9487           minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9488       }
9489       if ( minDot > 0.5 * 0.5 )
9490         break;
9491     }
9492   }
9493   // else
9494   // {
9495   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
9496   //   {
9497   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
9498   //       continue;
9499
9500   //     double     wgt = segLen[i] / segLen.back();
9501   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9502   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
9503   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
9504   //     _pos[i] = newPos;
9505   //   }
9506   // }
9507 }
9508
9509 //================================================================================
9510 /*!
9511  * \brief Print flags
9512  */
9513 //================================================================================
9514
9515 std::string _LayerEdge::DumpFlags() const
9516 {
9517   SMESH_Comment dump;
9518   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9519     if ( _flags & flag )
9520     {
9521       EFlags f = (EFlags) flag;
9522       switch ( f ) {
9523       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
9524       case MOVED:           dump << "MOVED";           break;
9525       case SMOOTHED:        dump << "SMOOTHED";        break;
9526       case DIFFICULT:       dump << "DIFFICULT";       break;
9527       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9528       case BLOCKED:         dump << "BLOCKED";         break;
9529       case INTERSECTED:     dump << "INTERSECTED";     break;
9530       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
9531       case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9532       case MARKED:          dump << "MARKED";          break;
9533       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
9534       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
9535       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
9536       case DISTORTED:       dump << "DISTORTED";       break;
9537       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
9538       case SHRUNK:          dump << "SHRUNK";          break;
9539       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
9540       }
9541       dump << " ";
9542     }
9543   cout << dump << endl;
9544   return dump;
9545 }
9546
9547 //================================================================================
9548 /*!
9549   case brief:
9550   default:
9551 */
9552 //================================================================================
9553
9554 bool _ViscousBuilder::refine(_SolidData& data)
9555 {
9556   SMESH_MesherHelper& helper = data.GetHelper();
9557   helper.SetElementsOnShape(false);
9558
9559   Handle(Geom_Curve) curve;
9560   Handle(ShapeAnalysis_Surface) surface;
9561   TopoDS_Edge geomEdge;
9562   TopoDS_Face geomFace;
9563   TopLoc_Location loc;
9564   double f,l, u = 0;
9565   gp_XY uv;
9566   vector< gp_XYZ > pos3D;
9567   bool isOnEdge, isTooConvexFace = false;
9568   TGeomID prevBaseId = -1;
9569   TNode2Edge* n2eMap = 0;
9570   TNode2Edge::iterator n2e;
9571
9572   // Create intermediate nodes on each _LayerEdge
9573
9574   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9575   {
9576     _EdgesOnShape& eos = data._edgesOnShape[iS];
9577     if ( eos._edges.empty() ) continue;
9578
9579     if ( eos._edges[0]->_nodes.size() < 2 )
9580       continue; // on _noShrinkShapes
9581
9582     // get data of a shrink shape
9583     isOnEdge = false;
9584     geomEdge.Nullify(); geomFace.Nullify();
9585     curve.Nullify(); surface.Nullify();
9586     if ( !eos._sWOL.IsNull() )
9587     {
9588       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9589       if ( isOnEdge )
9590       {
9591         geomEdge = TopoDS::Edge( eos._sWOL );
9592         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9593       }
9594       else
9595       {
9596         geomFace = TopoDS::Face( eos._sWOL );
9597         surface  = helper.GetSurface( geomFace );
9598       }
9599     }
9600     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9601     {
9602       geomFace = TopoDS::Face( eos._shape );
9603       surface  = helper.GetSurface( geomFace );
9604       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9605       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9606       {
9607         eos._eosC1[ i ]->_toSmooth = true;
9608         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9609           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9610       }
9611       isTooConvexFace = false;
9612       if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
9613         isTooConvexFace = cf->_isTooCurved;
9614     }
9615
9616     vector< double > segLen;
9617     for ( size_t i = 0; i < eos._edges.size(); ++i )
9618     {
9619       _LayerEdge& edge = *eos._edges[i];
9620       if ( edge._pos.size() < 2 )
9621         continue;
9622
9623       // get accumulated length of segments
9624       segLen.resize( edge._pos.size() );
9625       segLen[0] = 0.0;
9626       if ( eos._sWOL.IsNull() )
9627       {
9628         bool useNormal = true;
9629         bool    usePos = false;
9630         bool  smoothed = false;
9631         double   preci = 0.1 * edge._len;
9632         if ( eos._toSmooth && edge._pos.size() > 2 )
9633         {
9634           smoothed = edge.GetSmoothedPos( preci );
9635         }
9636         if ( smoothed )
9637         {
9638           if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
9639           {
9640             useNormal = usePos = false;
9641             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9642             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9643             {
9644               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9645               if ( surface->Gap() < 2. * edge._len )
9646                 segLen[j] = surface->Gap();
9647               else
9648                 useNormal = true;
9649             }
9650           }
9651         }
9652         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9653         {
9654 #ifndef __NODES_AT_POS
9655           useNormal = usePos = false;
9656           edge._pos[1] = edge._pos.back();
9657           edge._pos.resize( 2 );
9658           segLen.resize( 2 );
9659           segLen[ 1 ] = edge._len;
9660 #endif
9661         }
9662         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9663         {
9664           useNormal = usePos = false;
9665           _LayerEdge tmpEdge; // get original _normal
9666           tmpEdge._nodes.push_back( edge._nodes[0] );
9667           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9668             usePos = true;
9669           else
9670             for ( size_t j = 1; j < edge._pos.size(); ++j )
9671               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9672         }
9673         if ( useNormal )
9674         {
9675           for ( size_t j = 1; j < edge._pos.size(); ++j )
9676             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9677         }
9678         if ( usePos )
9679         {
9680           for ( size_t j = 1; j < edge._pos.size(); ++j )
9681             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9682         }
9683         else
9684         {
9685           bool swapped = ( edge._pos.size() > 2 );
9686           while ( swapped )
9687           {
9688             swapped = false;
9689             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9690               if ( segLen[j] > segLen.back() )
9691               {
9692                 segLen.erase( segLen.begin() + j );
9693                 edge._pos.erase( edge._pos.begin() + j );
9694                 --j;
9695               }
9696               else if ( segLen[j] < segLen[j-1] )
9697               {
9698                 std::swap( segLen[j], segLen[j-1] );
9699                 std::swap( edge._pos[j], edge._pos[j-1] );
9700                 swapped = true;
9701               }
9702           }
9703         }
9704         // smooth a path formed by edge._pos
9705 #ifndef __NODES_AT_POS
9706         if (( smoothed ) /*&&
9707             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9708           edge.SmoothPos( segLen, preci );
9709 #endif
9710       }
9711       else if ( eos._isRegularSWOL ) // usual SWOL
9712       {
9713         for ( size_t j = 1; j < edge._pos.size(); ++j )
9714           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9715       }
9716       else if ( !surface.IsNull() ) // SWOL surface with singularities
9717       {
9718         pos3D.resize( edge._pos.size() );
9719         for ( size_t j = 0; j < edge._pos.size(); ++j )
9720           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9721
9722         for ( size_t j = 1; j < edge._pos.size(); ++j )
9723           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9724       }
9725
9726       // allocate memory for new nodes if it is not yet refined
9727       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9728       if ( edge._nodes.size() == 2 )
9729       {
9730 #ifdef __NODES_AT_POS
9731         int nbNodes = edge._pos.size();
9732 #else
9733         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9734 #endif
9735         edge._nodes.resize( nbNodes, 0 );
9736         edge._nodes[1] = 0;
9737         edge._nodes.back() = tgtNode;
9738       }
9739       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9740       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9741       if ( baseShapeId != prevBaseId )
9742       {
9743         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9744         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9745         prevBaseId = baseShapeId;
9746       }
9747       _LayerEdge* edgeOnSameNode = 0;
9748       bool        useExistingPos = false;
9749       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9750       {
9751         edgeOnSameNode = n2e->second;
9752         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9753         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9754         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9755         if ( isOnEdge )
9756         {
9757           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9758           epos->SetUParameter( otherTgtPos.X() );
9759         }
9760         else
9761         {
9762           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9763           fpos->SetUParameter( otherTgtPos.X() );
9764           fpos->SetVParameter( otherTgtPos.Y() );
9765         }
9766       }
9767       // calculate height of the first layer
9768       double h0;
9769       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9770       const double f = eos._hyp.GetStretchFactor();
9771       const int    N = eos._hyp.GetNumberLayers();
9772       const double fPowN = pow( f, N );
9773       if ( fPowN - 1 <= numeric_limits<double>::min() )
9774         h0 = T / N;
9775       else
9776         h0 = T * ( f - 1 )/( fPowN - 1 );
9777
9778       const double zeroLen = std::numeric_limits<double>::min();
9779
9780       // create intermediate nodes
9781       double hSum = 0, hi = h0/f;
9782       size_t iSeg = 1;
9783       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9784       {
9785         // compute an intermediate position
9786         hi *= f;
9787         hSum += hi;
9788         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9789           ++iSeg;
9790         int iPrevSeg = iSeg-1;
9791         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9792           --iPrevSeg;
9793         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9794         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9795 #ifdef __NODES_AT_POS
9796         pos = edge._pos[ iStep ];
9797 #endif
9798         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9799         if ( !eos._sWOL.IsNull() )
9800         {
9801           // compute XYZ by parameters <pos>
9802           if ( isOnEdge )
9803           {
9804             u = pos.X();
9805             if ( !node )
9806               pos = curve->Value( u ).Transformed(loc);
9807           }
9808           else if ( eos._isRegularSWOL )
9809           {
9810             uv.SetCoord( pos.X(), pos.Y() );
9811             if ( !node )
9812               pos = surface->Value( pos.X(), pos.Y() );
9813           }
9814           else
9815           {
9816             uv.SetCoord( pos.X(), pos.Y() );
9817             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9818             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9819             if ( !node )
9820               pos = surface->Value( uv );
9821           }
9822         }
9823         // create or update the node
9824         if ( !node )
9825         {
9826           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9827           if ( !eos._sWOL.IsNull() )
9828           {
9829             if ( isOnEdge )
9830               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9831             else
9832               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9833           }
9834           else
9835           {
9836             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9837           }
9838         }
9839         else
9840         {
9841           if ( !eos._sWOL.IsNull() )
9842           {
9843             // make average pos from new and current parameters
9844             if ( isOnEdge )
9845             {
9846               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9847               if ( useExistingPos )
9848                 u = helper.GetNodeU( geomEdge, node );
9849               pos = curve->Value( u ).Transformed(loc);
9850
9851               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9852               epos->SetUParameter( u );
9853             }
9854             else
9855             {
9856               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9857               if ( useExistingPos )
9858                 uv = helper.GetNodeUV( geomFace, node );
9859               pos = surface->Value( uv );
9860
9861               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9862               fpos->SetUParameter( uv.X() );
9863               fpos->SetVParameter( uv.Y() );
9864             }
9865           }
9866           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9867         }
9868       } // loop on edge._nodes
9869
9870       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9871       {
9872         if ( isOnEdge )
9873           edge._pos.back().SetCoord( u, 0,0);
9874         else
9875           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9876
9877         if ( edgeOnSameNode )
9878           edgeOnSameNode->_pos.back() = edge._pos.back();
9879       }
9880
9881     } // loop on eos._edges to create nodes
9882
9883
9884     if ( !getMeshDS()->IsEmbeddedMode() )
9885       // Log node movement
9886       for ( size_t i = 0; i < eos._edges.size(); ++i )
9887       {
9888         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9889         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9890       }
9891   }
9892
9893
9894   // Create volumes
9895
9896   helper.SetElementsOnShape(true);
9897
9898   vector< vector<const SMDS_MeshNode*>* > nnVec;
9899   set< vector<const SMDS_MeshNode*>* >    nnSet;
9900   set< int >                       degenEdgeInd;
9901   vector<const SMDS_MeshElement*>     degenVols;
9902
9903   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9904   for ( ; exp.More(); exp.Next() )
9905   {
9906     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9907     if ( data._ignoreFaceIds.count( faceID ))
9908       continue;
9909     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9910     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9911     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9912     while ( fIt->more() )
9913     {
9914       const SMDS_MeshElement* face = fIt->next();
9915       const int            nbNodes = face->NbCornerNodes();
9916       nnVec.resize( nbNodes );
9917       nnSet.clear();
9918       degenEdgeInd.clear();
9919       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9920       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9921       for ( int iN = 0; iN < nbNodes; ++iN )
9922       {
9923         const SMDS_MeshNode* n = nIt->next();
9924         _LayerEdge*       edge = data._n2eMap[ n ];
9925         const int i = isReversedFace ? nbNodes-1-iN : iN;
9926         nnVec[ i ] = & edge->_nodes;
9927         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9928         minZ = std::min( minZ, nnVec[ i ]->size() );
9929
9930         if ( helper.HasDegeneratedEdges() )
9931           nnSet.insert( nnVec[ i ]);
9932       }
9933
9934       if ( maxZ == 0 )
9935         continue;
9936       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9937         continue;
9938
9939       switch ( nbNodes )
9940       {
9941       case 3: // TRIA
9942       {
9943         // PENTA
9944         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9945           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9946                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9947
9948         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9949         {
9950           for ( int iN = 0; iN < nbNodes; ++iN )
9951             if ( nnVec[ iN ]->size() < iZ+1 )
9952               degenEdgeInd.insert( iN );
9953
9954           if ( degenEdgeInd.size() == 1 )  // PYRAM
9955           {
9956             int i2 = *degenEdgeInd.begin();
9957             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9958             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9959             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9960                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9961           }
9962           else  // TETRA
9963           {
9964             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9965             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9966                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9967                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9968                               (*nnVec[ i3 ])[ iZ ]);
9969           }
9970         }
9971         break; // TRIA
9972       }
9973       case 4: // QUAD
9974       {
9975         // HEX
9976         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9977           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9978                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9979                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9980                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9981
9982         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9983         {
9984           for ( int iN = 0; iN < nbNodes; ++iN )
9985             if ( nnVec[ iN ]->size() < iZ+1 )
9986               degenEdgeInd.insert( iN );
9987
9988           switch ( degenEdgeInd.size() )
9989           {
9990           case 2: // PENTA
9991           {
9992             int i2 = *degenEdgeInd.begin();
9993             int i3 = *degenEdgeInd.rbegin();
9994             bool ok = ( i3 - i2 == 1 );
9995             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9996             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9997             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9998
9999             const SMDS_MeshElement* vol =
10000               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10001                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10002             if ( !ok && vol )
10003               degenVols.push_back( vol );
10004           }
10005           break;
10006
10007           default: // degen HEX
10008           {
10009             const SMDS_MeshElement* vol =
10010               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10011                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10012                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10013                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10014                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
10015                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
10016                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
10017                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
10018             degenVols.push_back( vol );
10019           }
10020           }
10021         }
10022         break; // HEX
10023       }
10024       default:
10025         return error("Not supported type of element", data._index);
10026
10027       } // switch ( nbNodes )
10028     } // while ( fIt->more() )
10029   } // loop on FACEs
10030
10031   if ( !degenVols.empty() )
10032   {
10033     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10034     if ( !err || err->IsOK() )
10035     {
10036       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
10037                                          "Bad quality volumes created" ));
10038       err->myBadElements.insert( err->myBadElements.end(),
10039                                  degenVols.begin(),degenVols.end() );
10040     }
10041   }
10042
10043   return true;
10044 }
10045
10046 //================================================================================
10047 /*!
10048  * \brief Shrink 2D mesh on faces to let space for inflated layers
10049  */
10050 //================================================================================
10051
10052 bool _ViscousBuilder::shrink(_SolidData& theData)
10053 {
10054   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10055   // _LayerEdge's inflated along FACE or EDGE)
10056   map< TGeomID, list< _SolidData* > > f2sdMap;
10057   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10058   {
10059     _SolidData& data = _sdVec[i];
10060     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10061     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10062       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
10063       {
10064         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10065
10066         // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
10067         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10068         // by StdMeshers_QuadToTriaAdaptor
10069         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10070         {
10071           SMESH_ProxyMesh::SubMesh* proxySub =
10072             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10073           if ( proxySub->NbElements() == 0 )
10074           {
10075             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10076             while ( fIt->more() )
10077             {
10078               const SMDS_MeshElement* f = fIt->next();
10079               // as a result 3D algo will use elements from proxySub and not from smDS
10080               proxySub->AddElement( f );
10081               f->setIsMarked( true );
10082
10083               // Mark nodes on the FACE to discriminate them from nodes
10084               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10085               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10086               {
10087                 const SMDS_MeshNode* n = f->GetNode( iN );
10088                 if ( n->GetPosition()->GetDim() == 2 )
10089                   n->setIsMarked( true );
10090               }
10091             }
10092           }
10093         }
10094       }
10095   }
10096
10097   SMESH_MesherHelper helper( *_mesh );
10098   helper.ToFixNodeParameters( true );
10099
10100   // EDGEs to shrink
10101   map< TGeomID, _Shrinker1D > e2shrMap;
10102   vector< _EdgesOnShape* > subEOS;
10103   vector< _LayerEdge* > lEdges;
10104
10105   // loop on FACEs to srink mesh on
10106   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10107   for ( ; f2sd != f2sdMap.end(); ++f2sd )
10108   {
10109     list< _SolidData* > & dataList = f2sd->second;
10110     if ( dataList.front()->_n2eMap.empty() ||
10111          dataList.back() ->_n2eMap.empty() )
10112       continue; // not yet computed
10113     if ( dataList.front() != &theData &&
10114          dataList.back()  != &theData )
10115       continue;
10116
10117     _SolidData&      data = *dataList.front();
10118     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
10119     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10120     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
10121     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10122
10123     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10124
10125     _shrinkedFaces.Add( F );
10126     helper.SetSubShape( F );
10127
10128     // ===========================
10129     // Prepare data for shrinking
10130     // ===========================
10131
10132     // Collect nodes to smooth (they are marked at the beginning of this method)
10133     vector < const SMDS_MeshNode* > smoothNodes;
10134     {
10135       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
10136       while ( nIt->more() )
10137       {
10138         const SMDS_MeshNode* n = nIt->next();
10139         if ( n->isMarked() )
10140           smoothNodes.push_back( n );
10141       }
10142     }
10143     // Find out face orientation
10144     double refSign = 1;
10145     const set<TGeomID> ignoreShapes;
10146     bool isOkUV;
10147     if ( !smoothNodes.empty() )
10148     {
10149       vector<_Simplex> simplices;
10150       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
10151       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
10152       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
10153       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
10154       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
10155         refSign = -1;
10156     }
10157
10158     // Find _LayerEdge's inflated along F
10159     subEOS.clear();
10160     lEdges.clear();
10161     {
10162       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
10163                                                                 /*complexFirst=*/true); //!!!
10164       while ( subIt->more() )
10165       {
10166         const TGeomID subID = subIt->next()->GetId();
10167         if ( data._noShrinkShapes.count( subID ))
10168           continue;
10169         _EdgesOnShape* eos = data.GetShapeEdges( subID );
10170         if ( !eos || eos->_sWOL.IsNull() )
10171           if ( data2 ) // check in adjacent SOLID
10172           {
10173             eos = data2->GetShapeEdges( subID );
10174             if ( !eos || eos->_sWOL.IsNull() )
10175               continue;
10176           }
10177         subEOS.push_back( eos );
10178
10179         for ( size_t i = 0; i < eos->_edges.size(); ++i )
10180         {
10181           lEdges.push_back( eos->_edges[ i ] );
10182           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
10183         }
10184       }
10185     }
10186
10187     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
10188     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10189     while ( fIt->more() )
10190       if ( const SMDS_MeshElement* f = fIt->next() )
10191         dumpChangeNodes( f );
10192     dumpFunctionEnd();
10193
10194     // Replace source nodes by target nodes in mesh faces to shrink
10195     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
10196     const SMDS_MeshNode* nodes[20];
10197     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10198     {
10199       _EdgesOnShape& eos = * subEOS[ iS ];
10200       for ( size_t i = 0; i < eos._edges.size(); ++i )
10201       {
10202         _LayerEdge& edge = *eos._edges[i];
10203         const SMDS_MeshNode* srcNode = edge._nodes[0];
10204         const SMDS_MeshNode* tgtNode = edge._nodes.back();
10205         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
10206         while ( fIt->more() )
10207         {
10208           const SMDS_MeshElement* f = fIt->next();
10209           if ( !smDS->Contains( f ) || !f->isMarked() )
10210             continue;
10211           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
10212           for ( int iN = 0; nIt->more(); ++iN )
10213           {
10214             const SMDS_MeshNode* n = nIt->next();
10215             nodes[iN] = ( n == srcNode ? tgtNode : n );
10216           }
10217           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
10218           dumpChangeNodes( f );
10219         }
10220       }
10221     }
10222     dumpFunctionEnd();
10223
10224     // find out if a FACE is concave
10225     const bool isConcaveFace = isConcave( F, helper );
10226
10227     // Create _SmoothNode's on face F
10228     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
10229     {
10230       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
10231       const bool sortSimplices = isConcaveFace;
10232       for ( size_t i = 0; i < smoothNodes.size(); ++i )
10233       {
10234         const SMDS_MeshNode* n = smoothNodes[i];
10235         nodesToSmooth[ i ]._node = n;
10236         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
10237         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
10238         // fix up incorrect uv of nodes on the FACE
10239         helper.GetNodeUV( F, n, 0, &isOkUV);
10240         dumpMove( n );
10241       }
10242       dumpFunctionEnd();
10243     }
10244     //if ( nodesToSmooth.empty() ) continue;
10245
10246     // Find EDGE's to shrink and set simpices to LayerEdge's
10247     set< _Shrinker1D* > eShri1D;
10248     {
10249       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10250       {
10251         _EdgesOnShape& eos = * subEOS[ iS ];
10252         if ( eos.SWOLType() == TopAbs_EDGE )
10253         {
10254           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
10255           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
10256           eShri1D.insert( & srinker );
10257           srinker.AddEdge( eos._edges[0], eos, helper );
10258           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
10259           // restore params of nodes on EGDE if the EDGE has been already
10260           // srinked while srinking other FACE
10261           srinker.RestoreParams();
10262         }
10263         for ( size_t i = 0; i < eos._edges.size(); ++i )
10264         {
10265           _LayerEdge& edge = * eos._edges[i];
10266           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
10267
10268           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
10269           // not-marked nodes are those added by refine()
10270           edge._nodes.back()->setIsMarked( true );
10271         }
10272       }
10273     }
10274
10275     bool toFixTria = false; // to improve quality of trias by diagonal swap
10276     if ( isConcaveFace )
10277     {
10278       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
10279       if ( hasTria != hasQuad ) {
10280         toFixTria = hasTria;
10281       }
10282       else {
10283         set<int> nbNodesSet;
10284         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10285         while ( fIt->more() && nbNodesSet.size() < 2 )
10286           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
10287         toFixTria = ( *nbNodesSet.begin() == 3 );
10288       }
10289     }
10290
10291     // ==================
10292     // Perform shrinking
10293     // ==================
10294
10295     bool shrinked = true;
10296     int nbBad, shriStep=0, smooStep=0;
10297     _SmoothNode::SmoothType smoothType
10298       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
10299     SMESH_Comment errMsg;
10300     while ( shrinked )
10301     {
10302       shriStep++;
10303       // Move boundary nodes (actually just set new UV)
10304       // -----------------------------------------------
10305       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
10306       shrinked = false;
10307       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10308       {
10309         _EdgesOnShape& eos = * subEOS[ iS ];
10310         for ( size_t i = 0; i < eos._edges.size(); ++i )
10311         {
10312           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10313         }
10314       }
10315       dumpFunctionEnd();
10316
10317       // Move nodes on EDGE's
10318       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10319       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10320       for ( ; shr != eShri1D.end(); ++shr )
10321         (*shr)->Compute( /*set3D=*/false, helper );
10322
10323       // Smoothing in 2D
10324       // -----------------
10325       int nbNoImpSteps = 0;
10326       bool       moved = true;
10327       nbBad = 1;
10328       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10329       {
10330         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10331
10332         int oldBadNb = nbBad;
10333         nbBad = 0;
10334         moved = false;
10335         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10336         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10337         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10338         {
10339           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10340                                             smooTy, /*set3D=*/isConcaveFace);
10341         }
10342         if ( nbBad < oldBadNb )
10343           nbNoImpSteps = 0;
10344         else
10345           nbNoImpSteps++;
10346
10347         dumpFunctionEnd();
10348       }
10349
10350       errMsg.clear();
10351       if ( nbBad > 0 )
10352         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10353       if ( shriStep > 200 )
10354         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10355       if ( !errMsg.empty() )
10356         break;
10357
10358       // Fix narrow triangles by swapping diagonals
10359       // ---------------------------------------
10360       if ( toFixTria )
10361       {
10362         set<const SMDS_MeshNode*> usedNodes;
10363         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10364
10365         // update working data
10366         set<const SMDS_MeshNode*>::iterator n;
10367         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10368         {
10369           n = usedNodes.find( nodesToSmooth[ i ]._node );
10370           if ( n != usedNodes.end())
10371           {
10372             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10373                                     nodesToSmooth[ i ]._simplices,
10374                                     ignoreShapes, NULL,
10375                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10376             usedNodes.erase( n );
10377           }
10378         }
10379         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10380         {
10381           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10382           if ( n != usedNodes.end())
10383           {
10384             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10385                                     lEdges[i]->_simplices,
10386                                     ignoreShapes );
10387             usedNodes.erase( n );
10388           }
10389         }
10390       }
10391       // TODO: check effect of this additional smooth
10392       // additional laplacian smooth to increase allowed shrink step
10393       // for ( int st = 1; st; --st )
10394       // {
10395       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10396       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10397       //   {
10398       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10399       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
10400       //   }
10401       // }
10402
10403     } // while ( shrinked )
10404
10405     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10406     {
10407       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10408
10409       // remove faces
10410       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10411       {
10412         vector< const SMDS_MeshElement* > facesToRm;
10413         if ( psm )
10414         {
10415           facesToRm.reserve( psm->NbElements() );
10416           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10417             facesToRm.push_back( ite->next() );
10418
10419           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10420             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10421               psm->Clear();
10422         }
10423         for ( size_t i = 0; i < facesToRm.size(); ++i )
10424           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10425       }
10426       // remove nodes
10427       {
10428         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10429         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10430           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10431             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10432                                 subEOS[iS]->_edges[i]->_nodes.end() );
10433         }
10434         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10435         while ( itn->more() ) {
10436           const SMDS_MeshNode* n = itn->next();
10437           if ( !nodesToKeep.count( n ))
10438             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10439         }
10440       }
10441       // restore position and UV of target nodes
10442       gp_Pnt p;
10443       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10444         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10445         {
10446           _LayerEdge*       edge = subEOS[iS]->_edges[i];
10447           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10448           if ( edge->_pos.empty() ||
10449                edge->Is( _LayerEdge::SHRUNK )) continue;
10450           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10451           {
10452             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10453             pos->SetUParameter( edge->_pos[0].X() );
10454             pos->SetVParameter( edge->_pos[0].Y() );
10455             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10456           }
10457           else
10458           {
10459             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10460             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10461             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10462           }
10463           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10464           dumpMove( tgtNode );
10465         }
10466       // shrink EDGE sub-meshes and set proxy sub-meshes
10467       UVPtStructVec uvPtVec;
10468       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10469       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10470       {
10471         _Shrinker1D* shr = (*shrIt);
10472         shr->Compute( /*set3D=*/true, helper );
10473
10474         // set proxy mesh of EDGEs w/o layers
10475         map< double, const SMDS_MeshNode* > nodes;
10476         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10477         // remove refinement nodes
10478         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10479         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10480         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10481         if ( u2n->second == sn0 || u2n->second == sn1 )
10482         {
10483           while ( u2n->second != tn0 && u2n->second != tn1 )
10484             ++u2n;
10485           nodes.erase( nodes.begin(), u2n );
10486         }
10487         u2n = --nodes.end();
10488         if ( u2n->second == sn0 || u2n->second == sn1 )
10489         {
10490           while ( u2n->second != tn0 && u2n->second != tn1 )
10491             --u2n;
10492           nodes.erase( ++u2n, nodes.end() );
10493         }
10494         // set proxy sub-mesh
10495         uvPtVec.resize( nodes.size() );
10496         u2n = nodes.begin();
10497         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10498         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10499         {
10500           uvPtVec[ i ].node = u2n->second;
10501           uvPtVec[ i ].param = u2n->first;
10502           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10503         }
10504         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10505         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10506       }
10507
10508       // set proxy mesh of EDGEs with layers
10509       vector< _LayerEdge* > edges;
10510       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10511       {
10512         _EdgesOnShape& eos = * subEOS[ iS ];
10513         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10514
10515         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10516         data.SortOnEdge( E, eos._edges );
10517
10518         edges.clear();
10519         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10520           if ( !eov->_edges.empty() )
10521             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10522
10523         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10524
10525         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10526           if ( !eov->_edges.empty() )
10527             edges.push_back( eov->_edges[0] ); // on last VERTEX
10528
10529         uvPtVec.resize( edges.size() );
10530         for ( size_t i = 0; i < edges.size(); ++i )
10531         {
10532           uvPtVec[ i ].node = edges[i]->_nodes.back();
10533           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10534           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10535         }
10536         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10537         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10538         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10539       }
10540       // temporary clear the FACE sub-mesh from faces made by refine()
10541       vector< const SMDS_MeshElement* > elems;
10542       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10543       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10544         elems.push_back( ite->next() );
10545       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10546         elems.push_back( ite->next() );
10547       smDS->Clear();
10548
10549       // compute the mesh on the FACE
10550       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10551       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10552
10553       // re-fill proxy sub-meshes of the FACE
10554       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10555         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10556           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10557             psm->AddElement( ite->next() );
10558
10559       // re-fill smDS
10560       for ( size_t i = 0; i < elems.size(); ++i )
10561         smDS->AddElement( elems[i] );
10562
10563       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10564         return error( errMsg );
10565
10566     } // end of re-meshing in case of failed smoothing
10567     else
10568     {
10569       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10570       bool isStructuredFixed = false;
10571       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10572         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10573       if ( !isStructuredFixed )
10574       {
10575         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10576           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10577
10578         for ( int st = 3; st; --st )
10579         {
10580           switch( st ) {
10581           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10582           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10583           case 3: smoothType = _SmoothNode::ANGULAR; break;
10584           }
10585           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10586           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10587           {
10588             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10589                                      smoothType,/*set3D=*/st==1 );
10590           }
10591           dumpFunctionEnd();
10592         }
10593       }
10594       if ( !getMeshDS()->IsEmbeddedMode() )
10595         // Log node movement
10596         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10597         {
10598           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10599           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10600         }
10601     }
10602
10603     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10604     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10605     if ( data2 )
10606       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
10607
10608   } // loop on FACES to srink mesh on
10609
10610
10611   // Replace source nodes by target nodes in shrinked mesh edges
10612
10613   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10614   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10615     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10616
10617   return true;
10618 }
10619
10620 //================================================================================
10621 /*!
10622  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10623  */
10624 //================================================================================
10625
10626 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10627                                            _EdgesOnShape&         eos,
10628                                            SMESH_MesherHelper&    helper,
10629                                            const SMESHDS_SubMesh* faceSubMesh)
10630 {
10631   const SMDS_MeshNode* srcNode = edge._nodes[0];
10632   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10633
10634   if ( eos.SWOLType() == TopAbs_FACE )
10635   {
10636     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10637     {
10638       edge._pos.clear();
10639       edge.Set( _LayerEdge::SHRUNK );
10640       return srcNode == tgtNode;
10641     }
10642     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10643     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10644     gp_Vec2d uvDir( srcUV, tgtUV );
10645     double uvLen = uvDir.Magnitude();
10646     uvDir /= uvLen;
10647     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10648     edge._len = uvLen;
10649
10650     //edge._pos.resize(1);
10651     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10652
10653     // set UV of source node to target node
10654     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10655     pos->SetUParameter( srcUV.X() );
10656     pos->SetVParameter( srcUV.Y() );
10657   }
10658   else // _sWOL is TopAbs_EDGE
10659   {
10660     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10661     {
10662       edge._pos.clear();
10663       edge.Set( _LayerEdge::SHRUNK );
10664       return srcNode == tgtNode;
10665     }
10666     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10667     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10668     if ( !edgeSM || edgeSM->NbElements() == 0 )
10669       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10670
10671     const SMDS_MeshNode* n2 = 0;
10672     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10673     while ( eIt->more() && !n2 )
10674     {
10675       const SMDS_MeshElement* e = eIt->next();
10676       if ( !edgeSM->Contains(e)) continue;
10677       n2 = e->GetNode( 0 );
10678       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10679     }
10680     if ( !n2 )
10681       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10682
10683     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10684     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10685     double u2   = helper.GetNodeU( E, n2,      srcNode );
10686
10687     //edge._pos.clear();
10688
10689     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10690     {
10691       // tgtNode is located so that it does not make faces with wrong orientation
10692       edge.Set( _LayerEdge::SHRUNK );
10693       return true;
10694     }
10695     //edge._pos.resize(1);
10696     edge._pos[0].SetCoord( U_TGT, uTgt );
10697     edge._pos[0].SetCoord( U_SRC, uSrc );
10698     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10699
10700     edge._simplices.resize( 1 );
10701     edge._simplices[0]._nPrev = n2;
10702
10703     // set U of source node to the target node
10704     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10705     pos->SetUParameter( uSrc );
10706   }
10707   return true;
10708 }
10709
10710 //================================================================================
10711 /*!
10712  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10713  */
10714 //================================================================================
10715
10716 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10717 {
10718   if ( edge._nodes.size() == 1 )
10719   {
10720     edge._pos.clear();
10721     edge._len = 0;
10722
10723     const SMDS_MeshNode* srcNode = edge._nodes[0];
10724     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10725     if ( S.IsNull() ) return;
10726
10727     gp_Pnt p;
10728
10729     switch ( S.ShapeType() )
10730     {
10731     case TopAbs_EDGE:
10732     {
10733       double f,l;
10734       TopLoc_Location loc;
10735       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10736       if ( curve.IsNull() ) return;
10737       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10738       p = curve->Value( ePos->GetUParameter() );
10739       break;
10740     }
10741     case TopAbs_VERTEX:
10742     {
10743       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10744       break;
10745     }
10746     default: return;
10747     }
10748     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10749     dumpMove( srcNode );
10750   }
10751 }
10752
10753 //================================================================================
10754 /*!
10755  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10756  */
10757 //================================================================================
10758
10759 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10760                                   SMESH_MesherHelper&         helper,
10761                                   const bool                  is2D,
10762                                   const int                   step,
10763                                   set<const SMDS_MeshNode*> * involvedNodes)
10764 {
10765   SMESH::Controls::AspectRatio qualifier;
10766   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10767   const double maxAspectRatio = is2D ? 4. : 2;
10768   _NodeCoordHelper xyz( F, helper, is2D );
10769
10770   // find bad triangles
10771
10772   vector< const SMDS_MeshElement* > badTrias;
10773   vector< double >                  badAspects;
10774   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10775   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10776   while ( fIt->more() )
10777   {
10778     const SMDS_MeshElement * f = fIt->next();
10779     if ( f->NbCornerNodes() != 3 ) continue;
10780     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10781     double aspect = qualifier.GetValue( points );
10782     if ( aspect > maxAspectRatio )
10783     {
10784       badTrias.push_back( f );
10785       badAspects.push_back( aspect );
10786     }
10787   }
10788   if ( step == 1 )
10789   {
10790     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10791     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10792     while ( fIt->more() )
10793     {
10794       const SMDS_MeshElement * f = fIt->next();
10795       if ( f->NbCornerNodes() == 3 )
10796         dumpChangeNodes( f );
10797     }
10798     dumpFunctionEnd();
10799   }
10800   if ( badTrias.empty() )
10801     return;
10802
10803   // find couples of faces to swap diagonal
10804
10805   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10806   vector< T2Trias > triaCouples; 
10807
10808   TIDSortedElemSet involvedFaces, emptySet;
10809   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10810   {
10811     T2Trias trias    [3];
10812     double  aspRatio [3];
10813     int i1, i2, i3;
10814
10815     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10816       continue;
10817     for ( int iP = 0; iP < 3; ++iP )
10818       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10819
10820     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10821     int bestCouple = -1;
10822     for ( int iSide = 0; iSide < 3; ++iSide )
10823     {
10824       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10825       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10826       trias [iSide].first  = badTrias[iTia];
10827       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10828                                                              & i1, & i2 );
10829       if (( ! trias[iSide].second ) ||
10830           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10831           ( ! sm->Contains( trias[iSide].second )))
10832         continue;
10833
10834       // aspect ratio of an adjacent tria
10835       for ( int iP = 0; iP < 3; ++iP )
10836         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10837       double aspectInit = qualifier.GetValue( points2 );
10838
10839       // arrange nodes as after diag-swaping
10840       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10841         i3 = helper.WrapIndex( i1-1, 3 );
10842       else
10843         i3 = helper.WrapIndex( i1+1, 3 );
10844       points1 = points;
10845       points1( 1+ iSide ) = points2( 1+ i3 );
10846       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10847
10848       // aspect ratio after diag-swaping
10849       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10850       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10851         continue;
10852
10853       // prevent inversion of a triangle
10854       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10855       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10856       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10857         continue;
10858
10859       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10860         bestCouple = iSide;
10861     }
10862
10863     if ( bestCouple >= 0 )
10864     {
10865       triaCouples.push_back( trias[bestCouple] );
10866       involvedFaces.insert ( trias[bestCouple].second );
10867     }
10868     else
10869     {
10870       involvedFaces.erase( badTrias[iTia] );
10871     }
10872   }
10873   if ( triaCouples.empty() )
10874     return;
10875
10876   // swap diagonals
10877
10878   SMESH_MeshEditor editor( helper.GetMesh() );
10879   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10880   for ( size_t i = 0; i < triaCouples.size(); ++i )
10881   {
10882     dumpChangeNodes( triaCouples[i].first );
10883     dumpChangeNodes( triaCouples[i].second );
10884     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10885   }
10886
10887   if ( involvedNodes )
10888     for ( size_t i = 0; i < triaCouples.size(); ++i )
10889     {
10890       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10891                              triaCouples[i].first->end_nodes() );
10892       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10893                              triaCouples[i].second->end_nodes() );
10894     }
10895
10896   // just for debug dump resulting triangles
10897   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10898   for ( size_t i = 0; i < triaCouples.size(); ++i )
10899   {
10900     dumpChangeNodes( triaCouples[i].first );
10901     dumpChangeNodes( triaCouples[i].second );
10902   }
10903 }
10904
10905 //================================================================================
10906 /*!
10907  * \brief Move target node to it's final position on the FACE during shrinking
10908  */
10909 //================================================================================
10910
10911 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10912                                  const TopoDS_Face&    F,
10913                                  _EdgesOnShape&        eos,
10914                                  SMESH_MesherHelper&   helper )
10915 {
10916   if ( Is( SHRUNK ))
10917     return false; // already at the target position
10918
10919   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10920
10921   if ( eos.SWOLType() == TopAbs_FACE )
10922   {
10923     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10924     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10925     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10926     const double uvLen = tgtUV.Distance( curUV );
10927     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10928
10929     // Select shrinking step such that not to make faces with wrong orientation.
10930     double stepSize = 1e100;
10931     for ( size_t i = 0; i < _simplices.size(); ++i )
10932     {
10933       if ( !_simplices[i]._nPrev->isMarked() ||
10934            !_simplices[i]._nNext->isMarked() )
10935         continue; // simplex of quadrangle created by addBoundaryElements()
10936
10937       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10938       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10939       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10940       gp_XY dirN = uvN2 - uvN1;
10941       double det = uvDir.Crossed( dirN );
10942       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10943       gp_XY dirN2Cur = curUV - uvN1;
10944       double step = dirN.Crossed( dirN2Cur ) / det;
10945       if ( step > 0 )
10946         stepSize = Min( step, stepSize );
10947     }
10948     gp_Pnt2d newUV;
10949     if ( uvLen <= stepSize )
10950     {
10951       newUV = tgtUV;
10952       Set( SHRUNK );
10953       //_pos.clear();
10954     }
10955     else if ( stepSize > 0 )
10956     {
10957       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10958     }
10959     else
10960     {
10961       return true;
10962     }
10963     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10964     pos->SetUParameter( newUV.X() );
10965     pos->SetVParameter( newUV.Y() );
10966
10967 #ifdef __myDEBUG
10968     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10969     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10970     dumpMove( tgtNode );
10971 #endif
10972   }
10973   else // _sWOL is TopAbs_EDGE
10974   {
10975     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10976     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10977     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10978
10979     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10980     const double uSrc   = _pos[0].Coord( U_SRC );
10981     const double lenTgt = _pos[0].Coord( LEN_TGT );
10982
10983     double newU = _pos[0].Coord( U_TGT );
10984     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10985     {
10986       Set( _LayerEdge::SHRUNK );
10987       //_pos.clear();
10988     }
10989     else
10990     {
10991       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10992     }
10993     tgtPos->SetUParameter( newU );
10994 #ifdef __myDEBUG
10995     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10996     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10997     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10998     dumpMove( tgtNode );
10999 #endif
11000   }
11001
11002   return true;
11003 }
11004
11005 //================================================================================
11006 /*!
11007  * \brief Perform smooth on the FACE
11008  *  \retval bool - true if the node has been moved
11009  */
11010 //================================================================================
11011
11012 bool _SmoothNode::Smooth(int&                  nbBad,
11013                          Handle(Geom_Surface)& surface,
11014                          SMESH_MesherHelper&   helper,
11015                          const double          refSign,
11016                          SmoothType            how,
11017                          bool                  set3D)
11018 {
11019   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11020
11021   // get uv of surrounding nodes
11022   vector<gp_XY> uv( _simplices.size() );
11023   for ( size_t i = 0; i < _simplices.size(); ++i )
11024     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11025
11026   // compute new UV for the node
11027   gp_XY newPos (0,0);
11028   if ( how == TFI && _simplices.size() == 4 )
11029   {
11030     gp_XY corners[4];
11031     for ( size_t i = 0; i < _simplices.size(); ++i )
11032       if ( _simplices[i]._nOpp )
11033         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11034       else
11035         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11036
11037     newPos = helper.calcTFI ( 0.5, 0.5,
11038                               corners[0], corners[1], corners[2], corners[3],
11039                               uv[1], uv[2], uv[3], uv[0] );
11040   }
11041   else if ( how == ANGULAR )
11042   {
11043     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11044   }
11045   else if ( how == CENTROIDAL && _simplices.size() > 3 )
11046   {
11047     // average centers of diagonals wieghted with their reciprocal lengths
11048     if ( _simplices.size() == 4 )
11049     {
11050       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11051       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11052       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11053     }
11054     else
11055     {
11056       double sumWeight = 0;
11057       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11058       for ( int i = 0; i < nb; ++i )
11059       {
11060         int iFrom = i + 2;
11061         int iTo   = i + _simplices.size() - 1;
11062         for ( int j = iFrom; j < iTo; ++j )
11063         {
11064           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11065           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11066           sumWeight += w;
11067           newPos += w * ( uv[i]+uv[i2] );
11068         }
11069       }
11070       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11071     }
11072   }
11073   else
11074   {
11075     // Laplacian smooth
11076     for ( size_t i = 0; i < _simplices.size(); ++i )
11077       newPos += uv[i];
11078     newPos /= _simplices.size();
11079   }
11080
11081   // count quality metrics (orientation) of triangles around the node
11082   int nbOkBefore = 0;
11083   gp_XY tgtUV = helper.GetNodeUV( face, _node );
11084   for ( size_t i = 0; i < _simplices.size(); ++i )
11085     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11086
11087   int nbOkAfter = 0;
11088   for ( size_t i = 0; i < _simplices.size(); ++i )
11089     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11090
11091   if ( nbOkAfter < nbOkBefore )
11092   {
11093     nbBad += _simplices.size() - nbOkBefore;
11094     return false;
11095   }
11096
11097   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
11098   pos->SetUParameter( newPos.X() );
11099   pos->SetVParameter( newPos.Y() );
11100
11101 #ifdef __myDEBUG
11102   set3D = true;
11103 #endif
11104   if ( set3D )
11105   {
11106     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
11107     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
11108     dumpMove( _node );
11109   }
11110
11111   nbBad += _simplices.size() - nbOkAfter;
11112   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
11113 }
11114
11115 //================================================================================
11116 /*!
11117  * \brief Computes new UV using angle based smoothing technic
11118  */
11119 //================================================================================
11120
11121 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
11122                                      const gp_XY&   uvToFix,
11123                                      const double   refSign)
11124 {
11125   uv.push_back( uv.front() );
11126
11127   vector< gp_XY >  edgeDir ( uv.size() );
11128   vector< double > edgeSize( uv.size() );
11129   for ( size_t i = 1; i < edgeDir.size(); ++i )
11130   {
11131     edgeDir [i-1] = uv[i] - uv[i-1];
11132     edgeSize[i-1] = edgeDir[i-1].Modulus();
11133     if ( edgeSize[i-1] < numeric_limits<double>::min() )
11134       edgeDir[i-1].SetX( 100 );
11135     else
11136       edgeDir[i-1] /= edgeSize[i-1] * refSign;
11137   }
11138   edgeDir.back()  = edgeDir.front();
11139   edgeSize.back() = edgeSize.front();
11140
11141   gp_XY  newPos(0,0);
11142   //int    nbEdges = 0;
11143   double sumSize = 0;
11144   for ( size_t i = 1; i < edgeDir.size(); ++i )
11145   {
11146     if ( edgeDir[i-1].X() > 1. ) continue;
11147     int i1 = i-1;
11148     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
11149     if ( i == edgeDir.size() ) break;
11150     gp_XY p = uv[i];
11151     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
11152     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
11153     gp_XY bisec = norm1 + norm2;
11154     double bisecSize = bisec.Modulus();
11155     if ( bisecSize < numeric_limits<double>::min() )
11156     {
11157       bisec = -edgeDir[i1] + edgeDir[i];
11158       bisecSize = bisec.Modulus();
11159     }
11160     bisec /= bisecSize;
11161
11162     gp_XY  dirToN  = uvToFix - p;
11163     double distToN = dirToN.Modulus();
11164     if ( bisec * dirToN < 0 )
11165       distToN = -distToN;
11166
11167     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
11168     //++nbEdges;
11169     sumSize += edgeSize[i1] + edgeSize[i];
11170   }
11171   newPos /= /*nbEdges * */sumSize;
11172   return newPos;
11173 }
11174
11175 //================================================================================
11176 /*!
11177  * \brief Delete _SolidData
11178  */
11179 //================================================================================
11180
11181 _SolidData::~_SolidData()
11182 {
11183   TNode2Edge::iterator n2e = _n2eMap.begin();
11184   for ( ; n2e != _n2eMap.end(); ++n2e )
11185   {
11186     _LayerEdge* & e = n2e->second;
11187     if ( e )
11188     {
11189       delete e->_curvature;
11190       if ( e->_2neibors )
11191         delete e->_2neibors->_plnNorm;
11192       delete e->_2neibors;
11193     }
11194     delete e;
11195     e = 0;
11196   }
11197   _n2eMap.clear();
11198
11199   delete _helper;
11200   _helper = 0;
11201 }
11202
11203 //================================================================================
11204 /*!
11205  * \brief Keep a _LayerEdge inflated along the EDGE
11206  */
11207 //================================================================================
11208
11209 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
11210                            _EdgesOnShape&      eos,
11211                            SMESH_MesherHelper& helper )
11212 {
11213   // init
11214   if ( _nodes.empty() )
11215   {
11216     _edges[0] = _edges[1] = 0;
11217     _done = false;
11218   }
11219   // check _LayerEdge
11220   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
11221     return;
11222   if ( eos.SWOLType() != TopAbs_EDGE )
11223     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11224   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
11225     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
11226
11227   // store _LayerEdge
11228   _geomEdge = TopoDS::Edge( eos._sWOL );
11229   double f,l;
11230   BRep_Tool::Range( _geomEdge, f,l );
11231   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
11232   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
11233
11234   // Update _nodes
11235
11236   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
11237   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
11238
11239   if ( _nodes.empty() )
11240   {
11241     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
11242     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
11243       return;
11244     TopLoc_Location loc;
11245     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
11246     GeomAdaptor_Curve aCurve(C, f,l);
11247     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
11248
11249     int nbExpectNodes = eSubMesh->NbNodes();
11250     _initU  .reserve( nbExpectNodes );
11251     _normPar.reserve( nbExpectNodes );
11252     _nodes  .reserve( nbExpectNodes );
11253     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
11254     while ( nIt->more() )
11255     {
11256       const SMDS_MeshNode* node = nIt->next();
11257
11258       // skip refinement nodes
11259       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
11260            node == tgtNode0 || node == tgtNode1 )
11261         continue;
11262       bool hasMarkedFace = false;
11263       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
11264       while ( fIt->more() && !hasMarkedFace )
11265         hasMarkedFace = fIt->next()->isMarked();
11266       if ( !hasMarkedFace )
11267         continue;
11268
11269       _nodes.push_back( node );
11270       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
11271       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
11272       _normPar.push_back(  len / totLen );
11273     }
11274   }
11275   else
11276   {
11277     // remove target node of the _LayerEdge from _nodes
11278     size_t nbFound = 0;
11279     for ( size_t i = 0; i < _nodes.size(); ++i )
11280       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
11281         _nodes[i] = 0, nbFound++;
11282     if ( nbFound == _nodes.size() )
11283       _nodes.clear();
11284   }
11285 }
11286
11287 //================================================================================
11288 /*!
11289  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
11290  */
11291 //================================================================================
11292
11293 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
11294 {
11295   if ( _done || _nodes.empty())
11296     return;
11297   const _LayerEdge* e = _edges[0];
11298   if ( !e ) e = _edges[1];
11299   if ( !e ) return;
11300
11301   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
11302             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
11303
11304   double f,l;
11305   if ( set3D || _done )
11306   {
11307     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
11308     GeomAdaptor_Curve aCurve(C, f,l);
11309
11310     if ( _edges[0] )
11311       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11312     if ( _edges[1] )
11313       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11314     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
11315
11316     for ( size_t i = 0; i < _nodes.size(); ++i )
11317     {
11318       if ( !_nodes[i] ) continue;
11319       double len = totLen * _normPar[i];
11320       GCPnts_AbscissaPoint discret( aCurve, len, f );
11321       if ( !discret.IsDone() )
11322         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11323       double u = discret.Parameter();
11324       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11325       pos->SetUParameter( u );
11326       gp_Pnt p = C->Value( u );
11327       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11328     }
11329   }
11330   else
11331   {
11332     BRep_Tool::Range( _geomEdge, f,l );
11333     if ( _edges[0] )
11334       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11335     if ( _edges[1] )
11336       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11337     
11338     for ( size_t i = 0; i < _nodes.size(); ++i )
11339     {
11340       if ( !_nodes[i] ) continue;
11341       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11342       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11343       pos->SetUParameter( u );
11344     }
11345   }
11346 }
11347
11348 //================================================================================
11349 /*!
11350  * \brief Restore initial parameters of nodes on EDGE
11351  */
11352 //================================================================================
11353
11354 void _Shrinker1D::RestoreParams()
11355 {
11356   if ( _done )
11357     for ( size_t i = 0; i < _nodes.size(); ++i )
11358     {
11359       if ( !_nodes[i] ) continue;
11360       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11361       pos->SetUParameter( _initU[i] );
11362     }
11363   _done = false;
11364 }
11365
11366 //================================================================================
11367 /*!
11368  * \brief Replace source nodes by target nodes in shrinked mesh edges
11369  */
11370 //================================================================================
11371
11372 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11373 {
11374   const SMDS_MeshNode* nodes[3];
11375   for ( int i = 0; i < 2; ++i )
11376   {
11377     if ( !_edges[i] ) continue;
11378
11379     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11380     if ( !eSubMesh ) return;
11381     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11382     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11383     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11384     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11385     while ( eIt->more() )
11386     {
11387       const SMDS_MeshElement* e = eIt->next();
11388       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11389           continue;
11390       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11391       for ( int iN = 0; iN < e->NbNodes(); ++iN )
11392       {
11393         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11394         nodes[iN] = ( n == srcNode ? tgtNode : n );
11395       }
11396       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11397     }
11398   }
11399 }
11400
11401 //================================================================================
11402 /*!
11403  * \brief Creates 2D and 1D elements on boundaries of new prisms
11404  */
11405 //================================================================================
11406
11407 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11408 {
11409   SMESH_MesherHelper helper( *_mesh );
11410
11411   vector< const SMDS_MeshNode* > faceNodes;
11412
11413   //for ( size_t i = 0; i < _sdVec.size(); ++i )
11414   {
11415     //_SolidData& data = _sdVec[i];
11416     TopTools_IndexedMapOfShape geomEdges;
11417     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11418     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11419     {
11420       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11421       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
11422       if ( data._noShrinkShapes.count( edgeID ))
11423         continue;
11424
11425       // Get _LayerEdge's based on E
11426
11427       map< double, const SMDS_MeshNode* > u2nodes;
11428       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11429         continue;
11430
11431       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11432       TNode2Edge & n2eMap = data._n2eMap;
11433       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11434       {
11435         //check if 2D elements are needed on E
11436         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11437         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11438         ledges.push_back( n2e->second );
11439         u2n++;
11440         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11441           continue; // no layers on E
11442         ledges.push_back( n2eMap[ u2n->second ]);
11443
11444         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11445         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11446         int nbSharedPyram = 0;
11447         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11448         while ( vIt->more() )
11449         {
11450           const SMDS_MeshElement* v = vIt->next();
11451           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11452         }
11453         if ( nbSharedPyram > 1 )
11454           continue; // not free border of the pyramid
11455
11456         faceNodes.clear();
11457         faceNodes.push_back( ledges[0]->_nodes[0] );
11458         faceNodes.push_back( ledges[1]->_nodes[0] );
11459         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11460         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11461
11462         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11463           continue; // faces already created
11464       }
11465       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11466         ledges.push_back( n2eMap[ u2n->second ]);
11467
11468       // Find out orientation and type of face to create
11469
11470       bool reverse = false, isOnFace;
11471       TopoDS_Shape F;
11472
11473       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
11474       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11475       {
11476         F = e2f->second.Oriented( TopAbs_FORWARD );
11477         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11478         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11479           reverse = !reverse, F.Reverse();
11480         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11481           reverse = !reverse;
11482       }
11483       else if ( !data._ignoreFaceIds.count( e2f->first ))
11484       {
11485         // find FACE with layers sharing E
11486         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11487         if ( fIt->more() )
11488           F = *( fIt->next() );
11489       }
11490       // Find the sub-mesh to add new faces
11491       SMESHDS_SubMesh* sm = 0;
11492       if ( isOnFace )
11493         sm = getMeshDS()->MeshElements( F );
11494       else
11495         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11496       if ( !sm )
11497         return error("error in addBoundaryElements()", data._index);
11498
11499       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
11500       // faces for 3D meshing (PAL23414)
11501       SMESHDS_SubMesh* adjSM = 0;
11502       if ( isOnFace )
11503       {
11504         const TGeomID   faceID = sm->GetID();
11505         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
11506         while ( const TopoDS_Shape* solid = soIt->next() )
11507           if ( !solid->IsSame( data._solid ))
11508           {
11509             size_t iData = _solids.FindIndex( *solid ) - 1;
11510             if ( iData < _sdVec.size() &&
11511                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
11512                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
11513             {
11514               SMESH_ProxyMesh::SubMesh* proxySub =
11515                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
11516               if ( proxySub && proxySub->NbElements() > 0 )
11517                 adjSM = proxySub;
11518             }
11519           }
11520       }
11521
11522       // Make faces
11523       const int dj1 = reverse ? 0 : 1;
11524       const int dj2 = reverse ? 1 : 0;
11525       vector< const SMDS_MeshElement*> ff; // new faces row
11526       SMESHDS_Mesh* m = getMeshDS();
11527       for ( size_t j = 1; j < ledges.size(); ++j )
11528       {
11529         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11530         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11531         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
11532         if ( nn1.size() == nn2.size() )
11533         {
11534           if ( isOnFace )
11535             for ( size_t z = 1; z < nn1.size(); ++z )
11536               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11537           else
11538             for ( size_t z = 1; z < nn1.size(); ++z )
11539               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11540         }
11541         else if ( nn1.size() == 1 )
11542         {
11543           if ( isOnFace )
11544             for ( size_t z = 1; z < nn2.size(); ++z )
11545               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11546           else
11547             for ( size_t z = 1; z < nn2.size(); ++z )
11548               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11549         }
11550         else
11551         {
11552           if ( isOnFace )
11553             for ( size_t z = 1; z < nn1.size(); ++z )
11554               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11555           else
11556             for ( size_t z = 1; z < nn1.size(); ++z )
11557               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11558         }
11559
11560         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
11561         {
11562           for ( size_t z = 0; z < ff.size(); ++z )
11563             if ( ff[ z ])
11564               adjSM->AddElement( ff[ z ]);
11565           ff.clear();
11566         }
11567       }
11568
11569       // Make edges
11570       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11571       {
11572         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11573         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11574         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11575         {
11576           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11577           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
11578             continue;
11579           helper.SetSubShape( eos->_sWOL );
11580           helper.SetElementsOnShape( true );
11581           for ( size_t z = 1; z < nn.size(); ++z )
11582             helper.AddEdge( nn[z-1], nn[z] );
11583         }
11584       }
11585
11586     } // loop on EDGE's
11587   } // loop on _SolidData's
11588
11589   return true;
11590 }