Salome HOME
Fix regressions caused by the preceding commit
[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 achived 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 this->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                   MARKED          = 0x0000100, // local usage
437                   MULTI_NORMAL    = 0x0000200, // a normal is invisible by some of surrounding faces
438                   NEAR_BOUNDARY   = 0x0000400, // is near FACE boundary forcing smooth
439                   SMOOTHED_C1     = 0x0000800, // is on _eosC1
440                   DISTORTED       = 0x0001000, // was bad before smoothing
441                   RISKY_SWOL      = 0x0002000, // SWOL is parallel to a source FACE
442                   SHRUNK          = 0x0004000, // target node reached a tgt position while shrink()
443                   UNUSED_FLAG     = 0x0100000
444     };
445     bool Is   ( int flag ) const { return _flags & flag; }
446     void Set  ( int flag ) { _flags |= flag; }
447     void Unset( int flag ) { _flags &= ~flag; }
448
449     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
450     bool SetNewLength2d( Handle(Geom_Surface)& surface,
451                          const TopoDS_Face&    F,
452                          _EdgesOnShape&        eos,
453                          SMESH_MesherHelper&   helper );
454     void SetDataByNeighbors( const SMDS_MeshNode* n1,
455                              const SMDS_MeshNode* n2,
456                              const _EdgesOnShape& eos,
457                              SMESH_MesherHelper&  helper);
458     void Block( _SolidData& data );
459     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
460     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
461                             const TNode2Edge&     n2eMap);
462     void SmoothPos( const vector< double >& segLen, const double tol );
463     int  GetSmoothedPos( const double tol );
464     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
465     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
466     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
467     void SmoothWoCheck();
468     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
469                       const TopoDS_Face&             F,
470                       SMESH_MesherHelper&            helper);
471     void MoveNearConcaVer( const _EdgesOnShape*    eov,
472                            const _EdgesOnShape*    eos,
473                            const int               step,
474                            vector< _LayerEdge* > & badSmooEdges);
475     bool FindIntersection( SMESH_ElementSearcher&   searcher,
476                            double &                 distance,
477                            const double&            epsilon,
478                            _EdgesOnShape&           eos,
479                            const SMDS_MeshElement** face = 0);
480     bool SegTriaInter( const gp_Ax1&        lastSegment,
481                        const gp_XYZ&        p0,
482                        const gp_XYZ&        p1,
483                        const gp_XYZ&        p2,
484                        double&              dist,
485                        const double&        epsilon) const;
486     bool SegTriaInter( const gp_Ax1&        lastSegment,
487                        const SMDS_MeshNode* n0,
488                        const SMDS_MeshNode* n1,
489                        const SMDS_MeshNode* n2,
490                        double&              dist,
491                        const double&        epsilon) const
492     { return SegTriaInter( lastSegment,
493                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
494                            dist, epsilon );
495     }
496     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
497     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
498     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
499     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
500     bool   IsOnEdge() const { return _2neibors; }
501     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
502     void   SetCosin( double cosin );
503     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
504     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
505     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
506     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
507       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
508     }
509     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
510
511     gp_XYZ smoothLaplacian();
512     gp_XYZ smoothAngular();
513     gp_XYZ smoothLengthWeighted();
514     gp_XYZ smoothCentroidal();
515     gp_XYZ smoothNefPolygon();
516
517     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
518     static const int theNbSmooFuns = FUN_NB;
519     static PSmooFun _funs[theNbSmooFuns];
520     static const char* _funNames[theNbSmooFuns+1];
521     int smooFunID( PSmooFun fun=0) const;
522   };
523   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
524                                                             &_LayerEdge::smoothLengthWeighted,
525                                                             &_LayerEdge::smoothCentroidal,
526                                                             &_LayerEdge::smoothNefPolygon,
527                                                             &_LayerEdge::smoothAngular };
528   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
529                                                          "LengthWeighted",
530                                                          "Centroidal",
531                                                          "NefPolygon",
532                                                          "Angular",
533                                                          "None"};
534   struct _LayerEdgeCmp
535   {
536     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
537     {
538       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
539       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
540     }
541   };
542   //--------------------------------------------------------------------------------
543   /*!
544    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
545    */
546   struct _halfPlane
547   {
548     gp_XY _pos, _dir, _inNorm;
549     bool IsOut( const gp_XY p, const double tol ) const
550     {
551       return _inNorm * ( p - _pos ) < -tol;
552     }
553     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
554     {
555       //const double eps = 1e-10;
556       double D = _dir.Crossed( hp._dir );
557       if ( fabs(D) < std::numeric_limits<double>::min())
558         return false;
559       gp_XY vec21 = _pos - hp._pos; 
560       double u = hp._dir.Crossed( vec21 ) / D; 
561       intPnt = _pos + _dir * u;
562       return true;
563     }
564   };
565   //--------------------------------------------------------------------------------
566   /*!
567    * Structure used to smooth a _LayerEdge based on an EDGE.
568    */
569   struct _2NearEdges
570   {
571     double               _wgt  [2]; // weights of _nodes
572     _LayerEdge*          _edges[2];
573
574      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
575     gp_XYZ*              _plnNorm;
576
577     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
578     const SMDS_MeshNode* tgtNode(bool is2nd) {
579       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
580     }
581     const SMDS_MeshNode* srcNode(bool is2nd) {
582       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
583     }
584     void reverse() {
585       std::swap( _wgt  [0], _wgt  [1] );
586       std::swap( _edges[0], _edges[1] );
587     }
588     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
589       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
590     }
591     bool include( const _LayerEdge* e ) {
592       return ( _edges[0] == e || _edges[1] == e );
593     }
594   };
595
596
597   //--------------------------------------------------------------------------------
598   /*!
599    * \brief Layers parameters got by averaging several hypotheses
600    */
601   struct AverageHyp
602   {
603     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
604       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
605     {
606       Add( hyp );
607     }
608     void Add( const StdMeshers_ViscousLayers* hyp )
609     {
610       if ( hyp )
611       {
612         _nbHyps++;
613         _nbLayers       = hyp->GetNumberLayers();
614         //_thickness     += hyp->GetTotalThickness();
615         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
616         _stretchFactor += hyp->GetStretchFactor();
617         _method         = hyp->GetMethod();
618       }
619     }
620     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
621     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
622     int    GetNumberLayers()   const { return _nbLayers; }
623     int    GetMethod()         const { return _method; }
624
625     bool   UseSurfaceNormal()  const
626     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
627     bool   ToSmooth()          const
628     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
629     bool   IsOffsetMethod()    const
630     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
631
632   private:
633     int     _nbLayers, _nbHyps, _method;
634     double  _thickness, _stretchFactor;
635   };
636
637   //--------------------------------------------------------------------------------
638   /*!
639    * \brief _LayerEdge's on a shape and other shape data
640    */
641   struct _EdgesOnShape
642   {
643     vector< _LayerEdge* > _edges;
644
645     TopoDS_Shape          _shape;
646     TGeomID               _shapeID;
647     SMESH_subMesh *       _subMesh;
648     // face or edge w/o layer along or near which _edges are inflated
649     TopoDS_Shape          _sWOL;
650     bool                  _isRegularSWOL; // w/o singularities
651     // averaged StdMeshers_ViscousLayers parameters
652     AverageHyp            _hyp;
653     bool                  _toSmooth;
654     _Smoother1D*          _edgeSmoother;
655     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
656     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
657
658     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
659     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
660
661     Handle(ShapeAnalysis_Surface) _offsetSurf;
662     _LayerEdge*                   _edgeForOffset;
663
664     _SolidData*            _data; // parent SOLID
665
666     TopAbs_ShapeEnum ShapeType() const
667     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
668     TopAbs_ShapeEnum SWOLType() const
669     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
670     bool             HasC1( const _EdgesOnShape* other ) const
671     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
672     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
673     _SolidData&      GetData() const { return *_data; }
674
675     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
676   };
677
678   //--------------------------------------------------------------------------------
679   /*!
680    * \brief Convex FACE whose radius of curvature is less than the thickness of 
681    *        layers. It is used to detect distortion of prisms based on a convex
682    *        FACE and to update normals to enable further increasing the thickness
683    */
684   struct _ConvexFace
685   {
686     TopoDS_Face                     _face;
687
688     // edges whose _simplices are used to detect prism distortion
689     vector< _LayerEdge* >           _simplexTestEdges;
690
691     // map a sub-shape to _SolidData::_edgesOnShape
692     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
693
694     bool                            _normalsFixed;
695
696     bool GetCenterOfCurvature( _LayerEdge*         ledge,
697                                BRepLProp_SLProps&  surfProp,
698                                SMESH_MesherHelper& helper,
699                                gp_Pnt &            center ) const;
700     bool CheckPrisms() const;
701   };
702
703   //--------------------------------------------------------------------------------
704   /*!
705    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
706    *        at inflation up to the full thickness. A detected collision
707    *        is fixed in updateNormals()
708    */
709   struct _CollisionEdges
710   {
711     _LayerEdge*           _edge;
712     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
713     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
714     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
715   };
716
717   //--------------------------------------------------------------------------------
718   /*!
719    * \brief Data of a SOLID
720    */
721   struct _SolidData
722   {
723     typedef const StdMeshers_ViscousLayers* THyp;
724     TopoDS_Shape                    _solid;
725     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
726     TGeomID                         _index; // SOLID id
727     _MeshOfSolid*                   _proxyMesh;
728     list< THyp >                    _hyps;
729     list< TopoDS_Shape >            _hypShapes;
730     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
731     set< TGeomID >                  _reversedFaceIds;
732     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
733
734     double                          _stepSize, _stepSizeCoeff, _geomSize;
735     const SMDS_MeshNode*            _stepSizeNodes[2];
736
737     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
738
739     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
740     map< TGeomID, TNode2Edge* >     _s2neMap;
741     // _LayerEdge's with underlying shapes
742     vector< _EdgesOnShape >         _edgesOnShape;
743
744     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
745     //        layers and a FACE w/o layers
746     // value: the shape (FACE or EDGE) to shrink mesh on.
747     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
748     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
749
750     // Convex FACEs whose radius of curvature is less than the thickness of layers
751     map< TGeomID, _ConvexFace >      _convexFaces;
752
753     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
754     // the adjacent SOLID
755     set< TGeomID >                   _noShrinkShapes;
756
757     int                              _nbShapesToSmooth;
758
759     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
760
761     vector< _CollisionEdges >        _collisionEdges;
762     set< TGeomID >                   _concaveFaces;
763
764     double                           _maxThickness; // of all _hyps
765     double                           _minThickness; // of all _hyps
766
767     double                           _epsilon; // precision for SegTriaInter()
768
769     SMESH_MesherHelper*              _helper;
770
771     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
772                _MeshOfSolid*       m=0)
773       :_solid(s), _proxyMesh(m), _helper(0) {}
774     ~_SolidData();
775
776     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
777     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
778
779     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
780       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
781       return id2face == _convexFaces.end() ? 0 : & id2face->second;
782     }
783     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
784     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
785     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
786     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
787
788     SMESH_MesherHelper& GetHelper() const { return *_helper; }
789
790     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
791       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
792         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
793           _edgesOnShape[i]._edges[j]->Unset( flag );
794     }
795     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
796                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
797
798     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
799   };
800   //--------------------------------------------------------------------------------
801   /*!
802    * \brief Offset plane used in getNormalByOffset()
803    */
804   struct _OffsetPlane
805   {
806     gp_Pln _plane;
807     int    _faceIndex;
808     int    _faceIndexNext[2];
809     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
810     bool   _isLineOK[2];
811     _OffsetPlane() {
812       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
813     }
814     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
815                                     const TopoDS_Edge&   E,
816                                     const TopoDS_Vertex& V );
817     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
818     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
819   };
820   //--------------------------------------------------------------------------------
821   /*!
822    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
823    */
824   struct _CentralCurveOnEdge
825   {
826     bool                  _isDegenerated;
827     vector< gp_Pnt >      _curvaCenters;
828     vector< _LayerEdge* > _ledges;
829     vector< gp_XYZ >      _normals; // new normal for each of _ledges
830     vector< double >      _segLength2;
831
832     TopoDS_Edge           _edge;
833     TopoDS_Face           _adjFace;
834     bool                  _adjFaceToSmooth;
835
836     void Append( const gp_Pnt& center, _LayerEdge* ledge )
837     {
838       if ( _curvaCenters.size() > 0 )
839         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
840       _curvaCenters.push_back( center );
841       _ledges.push_back( ledge );
842       _normals.push_back( ledge->_normal );
843     }
844     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
845     void SetShapes( const TopoDS_Edge&  edge,
846                     const _ConvexFace&  convFace,
847                     _SolidData&         data,
848                     SMESH_MesherHelper& helper);
849   };
850   //--------------------------------------------------------------------------------
851   /*!
852    * \brief Data of node on a shrinked FACE
853    */
854   struct _SmoothNode
855   {
856     const SMDS_MeshNode*         _node;
857     vector<_Simplex>             _simplices; // for quality check
858
859     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
860
861     bool Smooth(int&                  badNb,
862                 Handle(Geom_Surface)& surface,
863                 SMESH_MesherHelper&   helper,
864                 const double          refSign,
865                 SmoothType            how,
866                 bool                  set3D);
867
868     gp_XY computeAngularPos(vector<gp_XY>& uv,
869                             const gp_XY&   uvToFix,
870                             const double   refSign );
871   };
872   //--------------------------------------------------------------------------------
873   /*!
874    * \brief Builder of viscous layers
875    */
876   class _ViscousBuilder
877   {
878   public:
879     _ViscousBuilder();
880     // does it's job
881     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
882                                   const TopoDS_Shape& shape);
883     // check validity of hypotheses
884     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
885                                            const TopoDS_Shape& shape );
886
887     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
888     void RestoreListeners();
889
890     // computes SMESH_ProxyMesh::SubMesh::_n2n;
891     bool MakeN2NMap( _MeshOfSolid* pm );
892
893   private:
894
895     bool findSolidsWithLayers();
896     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
897     bool findFacesWithLayers(const bool onlyWith=false);
898     void getIgnoreFaces(const TopoDS_Shape&             solid,
899                         const StdMeshers_ViscousLayers* hyp,
900                         const TopoDS_Shape&             hypShape,
901                         set<TGeomID>&                   ignoreFaces);
902     bool makeLayer(_SolidData& data);
903     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
904     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
905                       SMESH_MesherHelper& helper, _SolidData& data);
906     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
907                          const TopoDS_Face&   face,
908                          SMESH_MesherHelper&  helper,
909                          bool&                isOK,
910                          bool                 shiftInside=false);
911     bool getFaceNormalAtSingularity(const gp_XY&        uv,
912                                     const TopoDS_Face&  face,
913                                     SMESH_MesherHelper& helper,
914                                     gp_Dir&             normal );
915     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
916     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
917                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
918                               int                              nbFaces,
919                               bool                             lastNoOffset = false);
920     bool findNeiborsOnEdge(const _LayerEdge*     edge,
921                            const SMDS_MeshNode*& n1,
922                            const SMDS_MeshNode*& n2,
923                            _EdgesOnShape&        eos,
924                            _SolidData&           data);
925     void findSimplexTestEdges( _SolidData&                    data,
926                                vector< vector<_LayerEdge*> >& edgesByGeom);
927     void computeGeomSize( _SolidData& data );
928     bool findShapesToSmooth( _SolidData& data);
929     void limitStepSizeByCurvature( _SolidData&  data );
930     void limitStepSize( _SolidData&             data,
931                         const SMDS_MeshElement* face,
932                         const _LayerEdge*       maxCosinEdge );
933     void limitStepSize( _SolidData& data, const double minSize);
934     bool inflate(_SolidData& data);
935     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
936     int  invalidateBadSmooth( _SolidData&               data,
937                               SMESH_MesherHelper&       helper,
938                               vector< _LayerEdge* >&    badSmooEdges,
939                               vector< _EdgesOnShape* >& eosC1,
940                               const int                 infStep );
941     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
942     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
943                              vector< _EdgesOnShape* >& eosC1,
944                              int smooStep=0, bool moveAll=false );
945     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
946     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
947     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
948                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
949                                  SMESH_MesherHelper& helper );
950     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
951     bool updateNormalsOfConvexFaces( _SolidData&         data,
952                                      SMESH_MesherHelper& helper,
953                                      int                 stepNb );
954     void updateNormalsOfC1Vertices( _SolidData& data );
955     bool updateNormalsOfSmoothed( _SolidData&         data,
956                                   SMESH_MesherHelper& helper,
957                                   const int           nbSteps,
958                                   const double        stepSize );
959     bool isNewNormalOk( _SolidData&   data,
960                         _LayerEdge&   edge,
961                         const gp_XYZ& newNormal);
962     bool refine(_SolidData& data);
963     bool shrink(_SolidData& data);
964     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
965                               SMESH_MesherHelper& helper,
966                               const SMESHDS_SubMesh* faceSubMesh );
967     void restoreNoShrink( _LayerEdge& edge ) const;
968     void fixBadFaces(const TopoDS_Face&          F,
969                      SMESH_MesherHelper&         helper,
970                      const bool                  is2D,
971                      const int                   step,
972                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
973     bool addBoundaryElements(_SolidData& data);
974
975     bool error( const string& text, int solidID=-1 );
976     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
977
978     // debug
979     void makeGroupOfLE();
980
981     SMESH_Mesh*                _mesh;
982     SMESH_ComputeErrorPtr      _error;
983
984     vector<                    _SolidData >  _sdVec;
985     TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
986     TopTools_MapOfShape        _shrinkedFaces;
987
988     int                        _tmpFaceID;
989   };
990   //--------------------------------------------------------------------------------
991   /*!
992    * \brief Shrinker of nodes on the EDGE
993    */
994   class _Shrinker1D
995   {
996     TopoDS_Edge                   _geomEdge;
997     vector<double>                _initU;
998     vector<double>                _normPar;
999     vector<const SMDS_MeshNode*>  _nodes;
1000     const _LayerEdge*             _edges[2];
1001     bool                          _done;
1002   public:
1003     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1004     void Compute(bool set3D, SMESH_MesherHelper& helper);
1005     void RestoreParams();
1006     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1007     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1008     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1009     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1010     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1011     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1012   };
1013   //--------------------------------------------------------------------------------
1014   /*!
1015    * \brief Smoother of _LayerEdge's on EDGE.
1016    */
1017   struct _Smoother1D
1018   {
1019     struct OffPnt // point of the offsetted EDGE
1020     {
1021       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1022       double      _len;    // length reached at previous inflation step
1023       double      _param;  // on EDGE
1024       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1025       gp_XYZ      _edgeDir;// EDGE tangent at _param
1026       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1027     };
1028     vector< OffPnt >   _offPoints;
1029     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1030     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1031     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1032     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1033     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1034     _EdgesOnShape&     _eos;
1035     double             _curveLen; // length of the EDGE
1036
1037     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1038                                               _EdgesOnShape&      eos,
1039                                               SMESH_MesherHelper& helper);
1040
1041     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1042                  _EdgesOnShape&     eos )
1043       : _anaCurve( curveForSmooth ), _eos( eos )
1044     {
1045     }
1046     bool Perform(_SolidData&                    data,
1047                  Handle(ShapeAnalysis_Surface)& surface,
1048                  const TopoDS_Face&             F,
1049                  SMESH_MesherHelper&            helper )
1050     {
1051       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1052         prepare( data );
1053
1054       if ( isAnalytic() )
1055         return smoothAnalyticEdge( data, surface, F, helper );
1056       else
1057         return smoothComplexEdge ( data, surface, F, helper );
1058     }
1059     void prepare(_SolidData& data );
1060
1061     bool smoothAnalyticEdge( _SolidData&                    data,
1062                              Handle(ShapeAnalysis_Surface)& surface,
1063                              const TopoDS_Face&             F,
1064                              SMESH_MesherHelper&            helper);
1065
1066     bool smoothComplexEdge( _SolidData&                    data,
1067                             Handle(ShapeAnalysis_Surface)& surface,
1068                             const TopoDS_Face&             F,
1069                             SMESH_MesherHelper&            helper);
1070
1071     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1072                             const gp_XYZ&  edgeDir);
1073
1074     _LayerEdge* getLEdgeOnV( bool is2nd )
1075     {
1076       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1077     }
1078     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1079   };
1080   //--------------------------------------------------------------------------------
1081   /*!
1082    * \brief Class of temporary mesh face.
1083    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1084    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1085    */
1086   struct _TmpMeshFace : public SMDS_MeshElement
1087   {
1088     vector<const SMDS_MeshNode* > _nn;
1089     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1090                   int id, int faceID=-1, int idInFace=-1):
1091       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1092     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1093     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1094     virtual vtkIdType GetVtkType() const                      { return -1; }
1095     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1096     virtual SMDSAbs_GeometryType GetGeomType() const
1097     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1098     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1099     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1100   };
1101   //--------------------------------------------------------------------------------
1102   /*!
1103    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1104    */
1105   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1106   {
1107     _LayerEdge *_le1, *_le2;
1108     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1109       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1110     {
1111       _nn[0]=_le1->_nodes[0];
1112       _nn[1]=_le1->_nodes.back();
1113       _nn[2]=_le2->_nodes.back();
1114       _nn[3]=_le2->_nodes[0];
1115     }
1116     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1117     {
1118       SMESH_TNodeXYZ p0s( _nn[0] );
1119       SMESH_TNodeXYZ p0t( _nn[1] );
1120       SMESH_TNodeXYZ p1t( _nn[2] );
1121       SMESH_TNodeXYZ p1s( _nn[3] );
1122       gp_XYZ  v0 = p0t - p0s;
1123       gp_XYZ  v1 = p1t - p1s;
1124       gp_XYZ v01 = p1s - p0s;
1125       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1126       gp_XYZ   d = v01 ^ n;
1127       d.Normalize();
1128       return d;
1129     }
1130     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1131     {
1132       _nn[0]=le1->_nodes[0];
1133       _nn[1]=le1->_nodes.back();
1134       _nn[2]=le2->_nodes.back();
1135       _nn[3]=le2->_nodes[0];
1136       return GetDir();
1137     }
1138   };
1139   //--------------------------------------------------------------------------------
1140   /*!
1141    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1142    * \warning Location of a surface is ignored
1143    */
1144   struct _NodeCoordHelper
1145   {
1146     SMESH_MesherHelper&        _helper;
1147     const TopoDS_Face&         _face;
1148     Handle(Geom_Surface)       _surface;
1149     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1150
1151     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1152       : _helper( helper ), _face( F )
1153     {
1154       if ( is2D )
1155       {
1156         TopLoc_Location loc;
1157         _surface = BRep_Tool::Surface( _face, loc );
1158       }
1159       if ( _surface.IsNull() )
1160         _fun = & _NodeCoordHelper::direct;
1161       else
1162         _fun = & _NodeCoordHelper::byUV;
1163     }
1164     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1165
1166   private:
1167     gp_XYZ direct(const SMDS_MeshNode* n) const
1168     {
1169       return SMESH_TNodeXYZ( n );
1170     }
1171     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1172     {
1173       gp_XY uv = _helper.GetNodeUV( _face, n );
1174       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1175     }
1176   };
1177
1178   //================================================================================
1179   /*!
1180    * \brief Check angle between vectors 
1181    */
1182   //================================================================================
1183
1184   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1185   {
1186     double dot = v1 * v2; // cos * |v1| * |v2|
1187     double l1  = v1.SquareMagnitude();
1188     double l2  = v2.SquareMagnitude();
1189     return (( dot * cos >= 0 ) && 
1190             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1191   }
1192
1193 } // namespace VISCOUS_3D
1194
1195
1196
1197 //================================================================================
1198 // StdMeshers_ViscousLayers hypothesis
1199 //
1200 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1201   :SMESH_Hypothesis(hypId, studyId, gen),
1202    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1203    _method( SURF_OFFSET_SMOOTH )
1204 {
1205   _name = StdMeshers_ViscousLayers::GetHypType();
1206   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1207 } // --------------------------------------------------------------------------------
1208 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1209 {
1210   if ( faceIds != _shapeIds )
1211     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1212   if ( _isToIgnoreShapes != toIgnore )
1213     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1214 } // --------------------------------------------------------------------------------
1215 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1216 {
1217   if ( thickness != _thickness )
1218     _thickness = thickness, NotifySubMeshesHypothesisModification();
1219 } // --------------------------------------------------------------------------------
1220 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1221 {
1222   if ( _nbLayers != nb )
1223     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1224 } // --------------------------------------------------------------------------------
1225 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1226 {
1227   if ( _stretchFactor != factor )
1228     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1229 } // --------------------------------------------------------------------------------
1230 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1231 {
1232   if ( _method != method )
1233     _method = method, NotifySubMeshesHypothesisModification();
1234 } // --------------------------------------------------------------------------------
1235 SMESH_ProxyMesh::Ptr
1236 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1237                                   const TopoDS_Shape& theShape,
1238                                   const bool          toMakeN2NMap) const
1239 {
1240   using namespace VISCOUS_3D;
1241   _ViscousBuilder builder;
1242   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1243   if ( err && !err->IsOK() )
1244     return SMESH_ProxyMesh::Ptr();
1245
1246   vector<SMESH_ProxyMesh::Ptr> components;
1247   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1248   for ( ; exp.More(); exp.Next() )
1249   {
1250     if ( _MeshOfSolid* pm =
1251          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1252     {
1253       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1254         if ( !builder.MakeN2NMap( pm ))
1255           return SMESH_ProxyMesh::Ptr();
1256       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1257       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1258
1259       if ( pm->_warning && !pm->_warning->IsOK() )
1260       {
1261         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1262         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1263         if ( !smError || smError->IsOK() )
1264           smError = pm->_warning;
1265       }
1266     }
1267     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1268   }
1269   switch ( components.size() )
1270   {
1271   case 0: break;
1272
1273   case 1: return components[0];
1274
1275   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1276   }
1277   return SMESH_ProxyMesh::Ptr();
1278 } // --------------------------------------------------------------------------------
1279 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1280 {
1281   save << " " << _nbLayers
1282        << " " << _thickness
1283        << " " << _stretchFactor
1284        << " " << _shapeIds.size();
1285   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1286     save << " " << _shapeIds[i];
1287   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1288   save << " " << _method;
1289   return save;
1290 } // --------------------------------------------------------------------------------
1291 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1292 {
1293   int nbFaces, faceID, shapeToTreat, method;
1294   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1295   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1296     _shapeIds.push_back( faceID );
1297   if ( load >> shapeToTreat ) {
1298     _isToIgnoreShapes = !shapeToTreat;
1299     if ( load >> method )
1300       _method = (ExtrusionMethod) method;
1301   }
1302   else {
1303     _isToIgnoreShapes = true; // old behavior
1304   }
1305   return load;
1306 } // --------------------------------------------------------------------------------
1307 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1308                                                    const TopoDS_Shape& theShape)
1309 {
1310   // TODO
1311   return false;
1312 } // --------------------------------------------------------------------------------
1313 SMESH_ComputeErrorPtr
1314 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1315                                           const TopoDS_Shape&                  theShape,
1316                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1317 {
1318   VISCOUS_3D::_ViscousBuilder builder;
1319   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1320   if ( err && !err->IsOK() )
1321     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1322   else
1323     theStatus = SMESH_Hypothesis::HYP_OK;
1324
1325   return err;
1326 }
1327 // --------------------------------------------------------------------------------
1328 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1329 {
1330   bool isIn =
1331     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1332   return IsToIgnoreShapes() ? !isIn : isIn;
1333 }
1334 // END StdMeshers_ViscousLayers hypothesis
1335 //================================================================================
1336
1337 namespace VISCOUS_3D
1338 {
1339   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1340   {
1341     gp_Vec dir;
1342     double f,l;
1343     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1344     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1345     gp_Pnt p = BRep_Tool::Pnt( fromV );
1346     double distF = p.SquareDistance( c->Value( f ));
1347     double distL = p.SquareDistance( c->Value( l ));
1348     c->D1(( distF < distL ? f : l), p, dir );
1349     if ( distL < distF ) dir.Reverse();
1350     return dir.XYZ();
1351   }
1352   //--------------------------------------------------------------------------------
1353   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1354                      SMESH_MesherHelper& helper)
1355   {
1356     gp_Vec dir;
1357     double f,l; gp_Pnt p;
1358     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1359     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1360     double u = helper.GetNodeU( E, atNode );
1361     c->D1( u, p, dir );
1362     return dir.XYZ();
1363   }
1364   //--------------------------------------------------------------------------------
1365   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1366                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1367                      double* cosin=0);
1368   //--------------------------------------------------------------------------------
1369   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1370                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1371   {
1372     double f,l;
1373     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1374     if ( c.IsNull() )
1375     {
1376       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1377       return getFaceDir( F, v, node, helper, ok );
1378     }
1379     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1380     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1381     gp_Pnt p; gp_Vec du, dv, norm;
1382     surface->D1( uv.X(),uv.Y(), p, du,dv );
1383     norm = du ^ dv;
1384
1385     double u = helper.GetNodeU( fromE, node, 0, &ok );
1386     c->D1( u, p, du );
1387     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1388     if ( o == TopAbs_REVERSED )
1389       du.Reverse();
1390
1391     gp_Vec dir = norm ^ du;
1392
1393     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1394          helper.IsClosedEdge( fromE ))
1395     {
1396       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1397       else                        c->D1( f, p, dv );
1398       if ( o == TopAbs_REVERSED )
1399         dv.Reverse();
1400       gp_Vec dir2 = norm ^ dv;
1401       dir = dir.Normalized() + dir2.Normalized();
1402     }
1403     return dir.XYZ();
1404   }
1405   //--------------------------------------------------------------------------------
1406   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1407                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1408                      bool& ok, double* cosin)
1409   {
1410     TopoDS_Face faceFrw = F;
1411     faceFrw.Orientation( TopAbs_FORWARD );
1412     //double f,l; TopLoc_Location loc;
1413     TopoDS_Edge edges[2]; // sharing a vertex
1414     size_t nbEdges = 0;
1415     {
1416       TopoDS_Vertex VV[2];
1417       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1418       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1419       {
1420         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1421         if ( SMESH_Algo::isDegenerated( e )) continue;
1422         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1423         if ( VV[1].IsSame( fromV )) {
1424           nbEdges += edges[ 0 ].IsNull();
1425           edges[ 0 ] = e;
1426         }
1427         else if ( VV[0].IsSame( fromV )) {
1428           nbEdges += edges[ 1 ].IsNull();
1429           edges[ 1 ] = e;
1430         }
1431       }
1432     }
1433     gp_XYZ dir(0,0,0), edgeDir[2];
1434     if ( nbEdges == 2 )
1435     {
1436       // get dirs of edges going fromV
1437       ok = true;
1438       for ( size_t i = 0; i < nbEdges && ok; ++i )
1439       {
1440         edgeDir[i] = getEdgeDir( edges[i], fromV );
1441         double size2 = edgeDir[i].SquareModulus();
1442         if (( ok = size2 > numeric_limits<double>::min() ))
1443           edgeDir[i] /= sqrt( size2 );
1444       }
1445       if ( !ok ) return dir;
1446
1447       // get angle between the 2 edges
1448       gp_Vec faceNormal;
1449       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1450       if ( Abs( angle ) < 5 * M_PI/180 )
1451       {
1452         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1453       }
1454       else
1455       {
1456         dir = edgeDir[0] + edgeDir[1];
1457         if ( angle < 0 )
1458           dir.Reverse();
1459       }
1460       if ( cosin ) {
1461         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1462         *cosin = Cos( angle );
1463       }
1464     }
1465     else if ( nbEdges == 1 )
1466     {
1467       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1468       if ( cosin ) *cosin = 1.;
1469     }
1470     else
1471     {
1472       ok = false;
1473     }
1474
1475     return dir;
1476   }
1477
1478   //================================================================================
1479   /*!
1480    * \brief Finds concave VERTEXes of a FACE
1481    */
1482   //================================================================================
1483
1484   bool getConcaveVertices( const TopoDS_Face&  F,
1485                            SMESH_MesherHelper& helper,
1486                            set< TGeomID >*     vertices = 0)
1487   {
1488     // check angles at VERTEXes
1489     TError error;
1490     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1491     for ( size_t iW = 0; iW < wires.size(); ++iW )
1492     {
1493       const int nbEdges = wires[iW]->NbEdges();
1494       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1495         continue;
1496       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1497       {
1498         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1499         int iE2 = ( iE1 + 1 ) % nbEdges;
1500         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1501           iE2 = ( iE2 + 1 ) % nbEdges;
1502         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1503         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1504                                         wires[iW]->Edge( iE2 ), F, V );
1505         if ( angle < -5. * M_PI / 180. )
1506         {
1507           if ( !vertices )
1508             return true;
1509           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1510         }
1511       }
1512     }
1513     return vertices ? !vertices->empty() : false;
1514   }
1515
1516   //================================================================================
1517   /*!
1518    * \brief Returns true if a FACE is bound by a concave EDGE
1519    */
1520   //================================================================================
1521
1522   bool isConcave( const TopoDS_Face&  F,
1523                   SMESH_MesherHelper& helper,
1524                   set< TGeomID >*     vertices = 0 )
1525   {
1526     bool isConcv = false;
1527     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1528     //   return true;
1529     gp_Vec2d drv1, drv2;
1530     gp_Pnt2d p;
1531     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1532     for ( ; eExp.More(); eExp.Next() )
1533     {
1534       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1535       if ( SMESH_Algo::isDegenerated( E )) continue;
1536       // check if 2D curve is concave
1537       BRepAdaptor_Curve2d curve( E, F );
1538       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1539       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1540       curve.Intervals( intervals, GeomAbs_C2 );
1541       bool isConvex = true;
1542       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1543       {
1544         double u1 = intervals( i );
1545         double u2 = intervals( i+1 );
1546         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1547         double cross = drv1 ^ drv2;
1548         if ( E.Orientation() == TopAbs_REVERSED )
1549           cross = -cross;
1550         isConvex = ( cross > -1e-9 ); // 0.1 );
1551       }
1552       if ( !isConvex )
1553       {
1554         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1555         isConcv = true;
1556         if ( vertices )
1557           break;
1558         else
1559           return true;
1560       }
1561     }
1562
1563     // check angles at VERTEXes
1564     if ( getConcaveVertices( F, helper, vertices ))
1565       isConcv = true;
1566
1567     return isConcv;
1568   }
1569
1570   //================================================================================
1571   /*!
1572    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1573    *  \param [in] face - the mesh face to treat
1574    *  \param [in] nodeOnEdge - a node on the EDGE
1575    *  \param [out] faceSize - the computed distance
1576    *  \return bool - true if faceSize computed
1577    */
1578   //================================================================================
1579
1580   bool getDistFromEdge( const SMDS_MeshElement* face,
1581                         const SMDS_MeshNode*    nodeOnEdge,
1582                         double &                faceSize )
1583   {
1584     faceSize = Precision::Infinite();
1585     bool done = false;
1586
1587     int nbN  = face->NbCornerNodes();
1588     int iOnE = face->GetNodeIndex( nodeOnEdge );
1589     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1590                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1591     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1592                                       face->GetNode( iNext[1] ) };
1593     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1594     double segLen = -1.;
1595     // look for two neighbor not in-FACE nodes of face
1596     for ( int i = 0; i < 2; ++i )
1597     {
1598       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1599            nNext[i]->GetID() < nodeOnEdge->GetID() )
1600       {
1601         // look for an in-FACE node
1602         for ( int iN = 0; iN < nbN; ++iN )
1603         {
1604           if ( iN == iOnE || iN == iNext[i] )
1605             continue;
1606           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1607           gp_XYZ v = pInFace - segEnd;
1608           if ( segLen < 0 )
1609           {
1610             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1611             segLen = segVec.Modulus();
1612           }
1613           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1614           faceSize = Min( faceSize, distToSeg );
1615           done = true;
1616         }
1617         segLen = -1;
1618       }
1619     }
1620     return done;
1621   }
1622   //================================================================================
1623   /*!
1624    * \brief Return direction of axis or revolution of a surface
1625    */
1626   //================================================================================
1627
1628   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1629                           gp_Dir &                 axis )
1630   {
1631     switch ( surface.GetType() ) {
1632     case GeomAbs_Cone:
1633     {
1634       gp_Cone cone = surface.Cone();
1635       axis = cone.Axis().Direction();
1636       break;
1637     }
1638     case GeomAbs_Sphere:
1639     {
1640       gp_Sphere sphere = surface.Sphere();
1641       axis = sphere.Position().Direction();
1642       break;
1643     }
1644     case GeomAbs_SurfaceOfRevolution:
1645     {
1646       axis = surface.AxeOfRevolution().Direction();
1647       break;
1648     }
1649     //case GeomAbs_SurfaceOfExtrusion:
1650     case GeomAbs_OffsetSurface:
1651     {
1652       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1653       return getRovolutionAxis( base->Surface(), axis );
1654     }
1655     default: return false;
1656     }
1657     return true;
1658   }
1659
1660   //--------------------------------------------------------------------------------
1661   // DEBUG. Dump intermediate node positions into a python script
1662   // HOWTO use: run python commands written in a console to see
1663   //  construction steps of viscous layers
1664 #ifdef __myDEBUG
1665   ofstream* py;
1666   int       theNbPyFunc;
1667   struct PyDump {
1668     PyDump(SMESH_Mesh& m) {
1669       int tag = 3 + m.GetId();
1670       const char* fname = "/tmp/viscous.py";
1671       cout << "execfile('"<<fname<<"')"<<endl;
1672       py = new ofstream(fname);
1673       *py << "import SMESH" << endl
1674           << "from salome.smesh import smeshBuilder" << endl
1675           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1676           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1677           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1678       theNbPyFunc = 0;
1679     }
1680     void Finish() {
1681       if (py) {
1682         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1683           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1684         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1685           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1686       }
1687       delete py; py=0;
1688     }
1689     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1690   };
1691 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1692 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1693 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1694 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1695   void _dumpFunction(const string& fun, int ln)
1696   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1697   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1698   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1699                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1700   void _dumpCmd(const string& txt, int ln)
1701   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1702   void dumpFunctionEnd()
1703   { if (py) *py<< "  return"<< endl; }
1704   void dumpChangeNodes( const SMDS_MeshElement* f )
1705   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1706       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1707       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1708 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1709
1710 #else
1711
1712   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1713 #define dumpFunction(f) f
1714 #define dumpMove(n)
1715 #define dumpMoveComm(n,txt)
1716 #define dumpCmd(txt)
1717 #define dumpFunctionEnd()
1718 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1719 #define debugMsg( txt ) {}
1720
1721 #endif
1722 }
1723
1724 using namespace VISCOUS_3D;
1725
1726 //================================================================================
1727 /*!
1728  * \brief Constructor of _ViscousBuilder
1729  */
1730 //================================================================================
1731
1732 _ViscousBuilder::_ViscousBuilder()
1733 {
1734   _error = SMESH_ComputeError::New(COMPERR_OK);
1735   _tmpFaceID = 0;
1736 }
1737
1738 //================================================================================
1739 /*!
1740  * \brief Stores error description and returns false
1741  */
1742 //================================================================================
1743
1744 bool _ViscousBuilder::error(const string& text, int solidId )
1745 {
1746   const string prefix = string("Viscous layers builder: ");
1747   _error->myName    = COMPERR_ALGO_FAILED;
1748   _error->myComment = prefix + text;
1749   if ( _mesh )
1750   {
1751     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1752     if ( !sm && !_sdVec.empty() )
1753       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1754     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1755     {
1756       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1757       if ( smError && smError->myAlgo )
1758         _error->myAlgo = smError->myAlgo;
1759       smError = _error;
1760       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1761     }
1762     // set KO to all solids
1763     for ( size_t i = 0; i < _sdVec.size(); ++i )
1764     {
1765       if ( _sdVec[i]._index == solidId )
1766         continue;
1767       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1768       if ( !sm->IsEmpty() )
1769         continue;
1770       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1771       if ( !smError || smError->IsOK() )
1772       {
1773         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1774         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1775       }
1776     }
1777   }
1778   makeGroupOfLE(); // debug
1779
1780   return false;
1781 }
1782
1783 //================================================================================
1784 /*!
1785  * \brief At study restoration, restore event listeners used to clear an inferior
1786  *  dim sub-mesh modified by viscous layers
1787  */
1788 //================================================================================
1789
1790 void _ViscousBuilder::RestoreListeners()
1791 {
1792   // TODO
1793 }
1794
1795 //================================================================================
1796 /*!
1797  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1798  */
1799 //================================================================================
1800
1801 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1802 {
1803   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1804   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1805   for ( ; fExp.More(); fExp.Next() )
1806   {
1807     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1808     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1809
1810     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1811       continue;
1812     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1813       continue;
1814
1815     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1816       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1817
1818     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1819     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1820     while( prxIt->more() )
1821     {
1822       const SMDS_MeshElement* fSrc = srcIt->next();
1823       const SMDS_MeshElement* fPrx = prxIt->next();
1824       if ( fSrc->NbNodes() != fPrx->NbNodes())
1825         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1826       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1827         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1828     }
1829   }
1830   pm->_n2nMapComputed = true;
1831   return true;
1832 }
1833
1834 //================================================================================
1835 /*!
1836  * \brief Does its job
1837  */
1838 //================================================================================
1839
1840 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1841                                                const TopoDS_Shape& theShape)
1842 {
1843   _mesh = & theMesh;
1844
1845   // check if proxy mesh already computed
1846   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1847   if ( !exp.More() )
1848     return error("No SOLID's in theShape"), _error;
1849
1850   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1851     return SMESH_ComputeErrorPtr(); // everything already computed
1852
1853   PyDump debugDump( theMesh );
1854
1855   // TODO: ignore already computed SOLIDs 
1856   if ( !findSolidsWithLayers())
1857     return _error;
1858
1859   if ( !findFacesWithLayers() )
1860     return _error;
1861
1862   for ( size_t i = 0; i < _sdVec.size(); ++i )
1863   {
1864     size_t iSD = 0;
1865     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1866       if ( _sdVec[iSD]._before.IsEmpty() &&
1867            _sdVec[iSD]._n2eMap.empty() )
1868         break;
1869
1870     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1871       return _error;
1872
1873     if ( _sdVec[iSD]._n2eMap.size() == 0 )
1874       continue;
1875     
1876     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
1877       return _error;
1878
1879     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
1880       return _error;
1881
1882     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
1883       return _error;
1884
1885     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1886
1887     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1888     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1889       _sdVec[iSD]._before.Remove( solid );
1890   }
1891
1892   makeGroupOfLE(); // debug
1893   debugDump.Finish();
1894
1895   return _error;
1896 }
1897
1898 //================================================================================
1899 /*!
1900  * \brief Check validity of hypotheses
1901  */
1902 //================================================================================
1903
1904 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1905                                                         const TopoDS_Shape& shape )
1906 {
1907   _mesh = & mesh;
1908
1909   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1910     return SMESH_ComputeErrorPtr(); // everything already computed
1911
1912
1913   findSolidsWithLayers();
1914   bool ok = findFacesWithLayers( true );
1915
1916   // remove _MeshOfSolid's of _SolidData's
1917   for ( size_t i = 0; i < _sdVec.size(); ++i )
1918     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1919
1920   if ( !ok )
1921     return _error;
1922
1923   return SMESH_ComputeErrorPtr();
1924 }
1925
1926 //================================================================================
1927 /*!
1928  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1929  */
1930 //================================================================================
1931
1932 bool _ViscousBuilder::findSolidsWithLayers()
1933 {
1934   // get all solids
1935   TopTools_IndexedMapOfShape allSolids;
1936   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1937   _sdVec.reserve( allSolids.Extent());
1938
1939   SMESH_HypoFilter filter;
1940   for ( int i = 1; i <= allSolids.Extent(); ++i )
1941   {
1942     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1943     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1944     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1945       continue; // solid is already meshed
1946     SMESH_Algo* algo = sm->GetAlgo();
1947     if ( !algo ) continue;
1948     // TODO: check if algo is hidden
1949     const list <const SMESHDS_Hypothesis *> & allHyps =
1950       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1951     _SolidData* soData = 0;
1952     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1953     const StdMeshers_ViscousLayers* viscHyp = 0;
1954     for ( ; hyp != allHyps.end(); ++hyp )
1955       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1956       {
1957         TopoDS_Shape hypShape;
1958         filter.Init( filter.Is( viscHyp ));
1959         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1960
1961         if ( !soData )
1962         {
1963           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1964                                                                     allSolids(i),
1965                                                                     /*toCreate=*/true);
1966           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1967           soData = & _sdVec.back();
1968           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1969           soData->_helper = new SMESH_MesherHelper( *_mesh );
1970           soData->_helper->SetSubShape( allSolids(i) );
1971           _solids.Add( allSolids(i) );
1972         }
1973         soData->_hyps.push_back( viscHyp );
1974         soData->_hypShapes.push_back( hypShape );
1975       }
1976   }
1977   if ( _sdVec.empty() )
1978     return error
1979       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1980
1981   return true;
1982 }
1983
1984 //================================================================================
1985 /*!
1986  * \brief Set a _SolidData to be computed before another
1987  */
1988 //================================================================================
1989
1990 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
1991 {
1992   // check possibility to set this order; get all solids before solidBefore
1993   TopTools_IndexedMapOfShape allSolidsBefore;
1994   allSolidsBefore.Add( solidBefore._solid );
1995   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
1996   {
1997     int iSD = _solids.FindIndex( allSolidsBefore(i) );
1998     if ( iSD )
1999     {
2000       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2001       for ( ; soIt.More(); soIt.Next() )
2002         allSolidsBefore.Add( soIt.Value() );
2003     }
2004   }
2005   if ( allSolidsBefore.Contains( solidAfter._solid ))
2006     return false;
2007
2008   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2009     solidAfter._before.Add( allSolidsBefore(i) );
2010
2011   return true;
2012 }
2013
2014 //================================================================================
2015 /*!
2016  * \brief
2017  */
2018 //================================================================================
2019
2020 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2021 {
2022   SMESH_MesherHelper helper( *_mesh );
2023   TopExp_Explorer exp;
2024
2025   // collect all faces-to-ignore defined by hyp
2026   for ( size_t i = 0; i < _sdVec.size(); ++i )
2027   {
2028     // get faces-to-ignore defined by each hyp
2029     typedef const StdMeshers_ViscousLayers* THyp;
2030     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2031     list< TFacesOfHyp > ignoreFacesOfHyps;
2032     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2033     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2034     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2035     {
2036       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2037       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2038     }
2039
2040     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2041     const int nbHyps = _sdVec[i]._hyps.size();
2042     if ( nbHyps > 1 )
2043     {
2044       // check if two hypotheses define different parameters for the same FACE
2045       list< TFacesOfHyp >::iterator igFacesOfHyp;
2046       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2047       {
2048         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2049         THyp hyp = 0;
2050         igFacesOfHyp = ignoreFacesOfHyps.begin();
2051         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2052           if ( ! igFacesOfHyp->first.count( faceID ))
2053           {
2054             if ( hyp )
2055               return error(SMESH_Comment("Several hypotheses define "
2056                                          "Viscous Layers on the face #") << faceID );
2057             hyp = igFacesOfHyp->second;
2058           }
2059         if ( hyp )
2060           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2061         else
2062           _sdVec[i]._ignoreFaceIds.insert( faceID );
2063       }
2064
2065       // check if two hypotheses define different number of viscous layers for
2066       // adjacent faces of a solid
2067       set< int > nbLayersSet;
2068       igFacesOfHyp = ignoreFacesOfHyps.begin();
2069       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2070       {
2071         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2072       }
2073       if ( nbLayersSet.size() > 1 )
2074       {
2075         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2076         {
2077           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2078           THyp hyp1 = 0, hyp2 = 0;
2079           while( const TopoDS_Shape* face = fIt->next() )
2080           {
2081             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2082             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2083             if ( f2h != _sdVec[i]._face2hyp.end() )
2084             {
2085               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2086             }
2087           }
2088           if ( hyp1 && hyp2 &&
2089                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2090           {
2091             return error("Two hypotheses define different number of "
2092                          "viscous layers on adjacent faces");
2093           }
2094         }
2095       }
2096     } // if ( nbHyps > 1 )
2097     else
2098     {
2099       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2100     }
2101   } // loop on _sdVec
2102
2103   if ( onlyWith ) // is called to check hypotheses compatibility only
2104     return true;
2105
2106   // fill _SolidData::_reversedFaceIds
2107   for ( size_t i = 0; i < _sdVec.size(); ++i )
2108   {
2109     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2110     for ( ; exp.More(); exp.Next() )
2111     {
2112       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2113       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2114       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2115           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2116           helper.IsReversedSubMesh( face ))
2117       {
2118         _sdVec[i]._reversedFaceIds.insert( faceID );
2119       }
2120     }
2121   }
2122
2123   // Find faces to shrink mesh on (solution 2 in issue 0020832);
2124   TopTools_IndexedMapOfShape shapes;
2125   std::string structAlgoName = "Hexa_3D";
2126   for ( size_t i = 0; i < _sdVec.size(); ++i )
2127   {
2128     shapes.Clear();
2129     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2130     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2131     {
2132       const TopoDS_Shape& edge = shapes(iE);
2133       // find 2 faces sharing an edge
2134       TopoDS_Shape FF[2];
2135       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2136       while ( fIt->more())
2137       {
2138         const TopoDS_Shape* f = fIt->next();
2139         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2140           FF[ int( !FF[0].IsNull()) ] = *f;
2141       }
2142       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2143       // check presence of layers on them
2144       int ignore[2];
2145       for ( int j = 0; j < 2; ++j )
2146         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2147       if ( ignore[0] == ignore[1] )
2148         continue; // nothing interesting
2149       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2150       // check presence of layers on fWOL within an adjacent SOLID
2151       bool collision = false;
2152       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2153       while ( const TopoDS_Shape* solid = sIt->next() )
2154         if ( !solid->IsSame( _sdVec[i]._solid ))
2155         {
2156           int iSolid = _solids.FindIndex( *solid );
2157           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
2158           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2159           {
2160             // check if solid's mesh is unstructured and then try to set it
2161             // to be computed after the i-th solid
2162             SMESH_Algo*  algo = _mesh->GetSubMesh( *solid )->GetAlgo();
2163             bool isStructured = ( algo->GetName() == structAlgoName );
2164             if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid-1 ] ))
2165               collision = true; // don't shrink fWOL
2166             break;
2167           }
2168         }
2169       // add edge to maps
2170       if ( !fWOL.IsNull())
2171       {
2172         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2173         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2174         if ( collision )
2175         {
2176           // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2177           // on the edge but shrink won't be performed
2178           _sdVec[i]._noShrinkShapes.insert( edgeInd );
2179           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2180             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2181         }
2182       }
2183     }
2184   }
2185   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2186   // the algo of the SOLID sharing the FACE does not support it
2187   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2188   for ( size_t i = 0; i < _sdVec.size(); ++i )
2189   {
2190     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2191     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2192     {
2193       const TopoDS_Shape& fWOL = e2f->second;
2194       const TGeomID     edgeID = e2f->first;
2195       bool notShrinkFace = false;
2196       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2197       while ( soIt->more() )
2198       {
2199         const TopoDS_Shape* solid = soIt->next();
2200         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2201         SMESH_Algo* algo = _mesh->GetSubMesh( *solid )->GetAlgo();
2202         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2203         notShrinkFace = true;
2204         size_t iSolid = 0;
2205         for ( ; iSolid < _sdVec.size(); ++iSolid )
2206         {
2207           if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2208             if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2209               notShrinkFace = false;
2210             break;
2211           }
2212         }
2213         if ( notShrinkFace )
2214         {
2215           _sdVec[i]._noShrinkShapes.insert( edgeID );
2216
2217           // add VERTEXes of the edge in _noShrinkShapes
2218           TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2219           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2220             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2221
2222           // check if there is a collision with to-shrink-from EDGEs in iSolid
2223           if ( iSolid == _sdVec.size() )
2224             continue; // no VL in the solid
2225           shapes.Clear();
2226           TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2227           for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2228           {
2229             const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2230             const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2231             if ( eID == edgeID ||
2232                  !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2233                  _sdVec[i]._noShrinkShapes.count( eID ))
2234               continue;
2235             for ( int is1st = 0; is1st < 2; ++is1st )
2236             {
2237               TopoDS_Vertex V = helper.IthVertex( is1st, E );
2238               if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2239               {
2240                 // _sdVec[i]._noShrinkShapes.insert( eID );
2241                 // V = helper.IthVertex( !is1st, E );
2242                 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2243                 //iE = 0; // re-start the loop on EDGEs of fWOL
2244                 return error("No way to make a conformal mesh with "
2245                              "the given set of faces with layers", _sdVec[i]._index);
2246               }
2247             }
2248           }
2249         }
2250
2251       } // while ( soIt->more() )
2252     } // loop on _sdVec[i]._shrinkShape2Shape
2253   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2254
2255   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2256
2257   for ( size_t i = 0; i < _sdVec.size(); ++i )
2258   {
2259     shapes.Clear();
2260     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2261     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2262     {
2263       const TopoDS_Shape& vertex = shapes(iV);
2264       // find faces WOL sharing the vertex
2265       vector< TopoDS_Shape > facesWOL;
2266       size_t totalNbFaces = 0;
2267       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2268       while ( fIt->more())
2269       {
2270         const TopoDS_Shape* f = fIt->next();
2271         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2272         {
2273           totalNbFaces++;
2274           const int fID = getMeshDS()->ShapeToIndex( *f );
2275           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2276                !_sdVec[i]._noShrinkShapes.count( fID )*/)
2277             facesWOL.push_back( *f );
2278         }
2279       }
2280       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2281         continue; // no layers at this vertex or no WOL
2282       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2283       switch ( facesWOL.size() )
2284       {
2285       case 1:
2286       {
2287         helper.SetSubShape( facesWOL[0] );
2288         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2289         {
2290           TopoDS_Shape seamEdge;
2291           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2292           while ( eIt->more() && seamEdge.IsNull() )
2293           {
2294             const TopoDS_Shape* e = eIt->next();
2295             if ( helper.IsRealSeam( *e ) )
2296               seamEdge = *e;
2297           }
2298           if ( !seamEdge.IsNull() )
2299           {
2300             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2301             break;
2302           }
2303         }
2304         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2305         break;
2306       }
2307       case 2:
2308       {
2309         // find an edge shared by 2 faces
2310         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2311         while ( eIt->more())
2312         {
2313           const TopoDS_Shape* e = eIt->next();
2314           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2315                helper.IsSubShape( *e, facesWOL[1]))
2316           {
2317             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2318           }
2319         }
2320         break;
2321       }
2322       default:
2323         return error("Not yet supported case", _sdVec[i]._index);
2324       }
2325     }
2326   }
2327
2328   // add FACEs of other SOLIDs to _ignoreFaceIds
2329   for ( size_t i = 0; i < _sdVec.size(); ++i )
2330   {
2331     shapes.Clear();
2332     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2333
2334     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2335     {
2336       if ( !shapes.Contains( exp.Current() ))
2337         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2338     }
2339   }
2340
2341   return true;
2342 }
2343
2344 //================================================================================
2345 /*!
2346  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2347  */
2348 //================================================================================
2349
2350 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2351                                      const StdMeshers_ViscousLayers* hyp,
2352                                      const TopoDS_Shape&             hypShape,
2353                                      set<TGeomID>&                   ignoreFaceIds)
2354 {
2355   TopExp_Explorer exp;
2356
2357   vector<TGeomID> ids = hyp->GetBndShapes();
2358   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2359   {
2360     for ( size_t ii = 0; ii < ids.size(); ++ii )
2361     {
2362       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2363       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2364         ignoreFaceIds.insert( ids[ii] );
2365     }
2366   }
2367   else // FACEs with layers are given
2368   {
2369     exp.Init( solid, TopAbs_FACE );
2370     for ( ; exp.More(); exp.Next() )
2371     {
2372       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2373       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2374         ignoreFaceIds.insert( faceInd );
2375     }
2376   }
2377
2378   // ignore internal FACEs if inlets and outlets are specified
2379   if ( hyp->IsToIgnoreShapes() )
2380   {
2381     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2382     TopExp::MapShapesAndAncestors( hypShape,
2383                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2384
2385     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2386     {
2387       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2388       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2389         continue;
2390
2391       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2392       if ( nbSolids > 1 )
2393         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2394     }
2395   }
2396 }
2397
2398 //================================================================================
2399 /*!
2400  * \brief Create the inner surface of the viscous layer and prepare data for infation
2401  */
2402 //================================================================================
2403
2404 bool _ViscousBuilder::makeLayer(_SolidData& data)
2405 {
2406   // get all sub-shapes to make layers on
2407   set<TGeomID> subIds, faceIds;
2408   subIds = data._noShrinkShapes;
2409   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2410   for ( ; exp.More(); exp.Next() )
2411   {
2412     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2413     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2414       faceIds.insert( fSubM->GetId() );
2415   }
2416
2417   // make a map to find new nodes on sub-shapes shared with other SOLID
2418   map< TGeomID, TNode2Edge* >::iterator s2ne;
2419   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2420   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2421   {
2422     TGeomID shapeInd = s2s->first;
2423     for ( size_t i = 0; i < _sdVec.size(); ++i )
2424     {
2425       if ( _sdVec[i]._index == data._index ) continue;
2426       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2427       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2428            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2429       {
2430         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2431         break;
2432       }
2433     }
2434   }
2435
2436   // Create temporary faces and _LayerEdge's
2437
2438   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2439
2440   data._stepSize = Precision::Infinite();
2441   data._stepSizeNodes[0] = 0;
2442
2443   SMESH_MesherHelper helper( *_mesh );
2444   helper.SetSubShape( data._solid );
2445   helper.SetElementsOnShape( true );
2446
2447   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2448   TNode2Edge::iterator n2e2;
2449
2450   // collect _LayerEdge's of shapes they are based on
2451   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2452   const int nbShapes = getMeshDS()->MaxShapeIndex();
2453   edgesByGeom.resize( nbShapes+1 );
2454
2455   // set data of _EdgesOnShape's
2456   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2457   {
2458     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2459     while ( smIt->more() )
2460     {
2461       sm = smIt->next();
2462       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2463            !faceIds.count( sm->GetId() ))
2464         continue;
2465       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2466     }
2467   }
2468   // make _LayerEdge's
2469   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2470   {
2471     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2472     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2473     SMESH_ProxyMesh::SubMesh* proxySub =
2474       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2475
2476     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2477     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2478
2479     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2480     while ( eIt->more() )
2481     {
2482       const SMDS_MeshElement* face = eIt->next();
2483       double          faceMaxCosin = -1;
2484       _LayerEdge*     maxCosinEdge = 0;
2485       int             nbDegenNodes = 0;
2486
2487       newNodes.resize( face->NbCornerNodes() );
2488       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2489       {
2490         const SMDS_MeshNode* n = face->GetNode( i );
2491         const int      shapeID = n->getshapeId();
2492         const bool onDegenShap = helper.IsDegenShape( shapeID );
2493         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2494         if ( onDegenShap )
2495         {
2496           if ( onDegenEdge )
2497           {
2498             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2499             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2500             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2501             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2502               n = vN;
2503               nbDegenNodes++;
2504             }
2505           }
2506           else
2507           {
2508             nbDegenNodes++;
2509           }
2510         }
2511         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2512         if ( !(*n2e).second )
2513         {
2514           // add a _LayerEdge
2515           _LayerEdge* edge = new _LayerEdge();
2516           edge->_nodes.push_back( n );
2517           n2e->second = edge;
2518           edgesByGeom[ shapeID ]._edges.push_back( edge );
2519           const bool noShrink = data._noShrinkShapes.count( shapeID );
2520
2521           SMESH_TNodeXYZ xyz( n );
2522
2523           // set edge data or find already refined _LayerEdge and get data from it
2524           if (( !noShrink                                                     ) &&
2525               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2526               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2527               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2528           {
2529             _LayerEdge* foundEdge = (*n2e2).second;
2530             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2531             foundEdge->_pos.push_back( lastPos );
2532             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2533             const_cast< SMDS_MeshNode* >
2534               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2535           }
2536           else
2537           {
2538             if ( !noShrink )
2539             {
2540               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2541             }
2542             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2543               return false;
2544
2545             if ( edge->_nodes.size() < 2 )
2546               edge->Block( data );
2547               //data._noShrinkShapes.insert( shapeID );
2548           }
2549           dumpMove(edge->_nodes.back());
2550
2551           if ( edge->_cosin > faceMaxCosin )
2552           {
2553             faceMaxCosin = edge->_cosin;
2554             maxCosinEdge = edge;
2555           }
2556         }
2557         newNodes[ i ] = n2e->second->_nodes.back();
2558
2559         if ( onDegenEdge )
2560           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2561       }
2562       if ( newNodes.size() - nbDegenNodes < 2 )
2563         continue;
2564
2565       // create a temporary face
2566       const SMDS_MeshElement* newFace =
2567         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2568       proxySub->AddElement( newFace );
2569
2570       // compute inflation step size by min size of element on a convex surface
2571       if ( faceMaxCosin > theMinSmoothCosin )
2572         limitStepSize( data, face, maxCosinEdge );
2573
2574     } // loop on 2D elements on a FACE
2575   } // loop on FACEs of a SOLID to create _LayerEdge's
2576
2577
2578   // Set _LayerEdge::_neibors
2579   TNode2Edge::iterator n2e;
2580   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2581   {
2582     _EdgesOnShape& eos = data._edgesOnShape[iS];
2583     for ( size_t i = 0; i < eos._edges.size(); ++i )
2584     {
2585       _LayerEdge* edge = eos._edges[i];
2586       TIDSortedNodeSet nearNodes;
2587       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2588       while ( fIt->more() )
2589       {
2590         const SMDS_MeshElement* f = fIt->next();
2591         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2592           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2593       }
2594       nearNodes.erase( edge->_nodes[0] );
2595       edge->_neibors.reserve( nearNodes.size() );
2596       TIDSortedNodeSet::iterator node = nearNodes.begin();
2597       for ( ; node != nearNodes.end(); ++node )
2598         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2599           edge->_neibors.push_back( n2e->second );
2600     }
2601   }
2602
2603   data._epsilon = 1e-7;
2604   if ( data._stepSize < 1. )
2605     data._epsilon *= data._stepSize;
2606
2607   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2608     return false;
2609
2610   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2611   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2612
2613   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2614   const SMDS_MeshNode* nn[2];
2615   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2616   {
2617     _EdgesOnShape& eos = data._edgesOnShape[iS];
2618     for ( size_t i = 0; i < eos._edges.size(); ++i )
2619     {
2620       _LayerEdge* edge = eos._edges[i];
2621       if ( edge->IsOnEdge() )
2622       {
2623         // get neighbor nodes
2624         bool hasData = ( edge->_2neibors->_edges[0] );
2625         if ( hasData ) // _LayerEdge is a copy of another one
2626         {
2627           nn[0] = edge->_2neibors->srcNode(0);
2628           nn[1] = edge->_2neibors->srcNode(1);
2629         }
2630         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2631         {
2632           return false;
2633         }
2634         // set neighbor _LayerEdge's
2635         for ( int j = 0; j < 2; ++j )
2636         {
2637           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2638             return error("_LayerEdge not found by src node", data._index);
2639           edge->_2neibors->_edges[j] = n2e->second;
2640         }
2641         if ( !hasData )
2642           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2643       }
2644
2645       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2646       {
2647         _Simplex& s = edge->_simplices[j];
2648         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2649         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2650       }
2651
2652       // For an _LayerEdge on a degenerated EDGE, copy some data from
2653       // a corresponding _LayerEdge on a VERTEX
2654       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2655       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2656       {
2657         // Generally we should not get here
2658         if ( eos.ShapeType() != TopAbs_EDGE )
2659           continue;
2660         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2661         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2662         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2663           continue;
2664         const _LayerEdge* vEdge = n2e->second;
2665         edge->_normal    = vEdge->_normal;
2666         edge->_lenFactor = vEdge->_lenFactor;
2667         edge->_cosin     = vEdge->_cosin;
2668       }
2669
2670     } // loop on data._edgesOnShape._edges
2671   } // loop on data._edgesOnShape
2672
2673   // fix _LayerEdge::_2neibors on EDGEs to smooth
2674   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2675   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2676   //   if ( !e2c->second.IsNull() )
2677   //   {
2678   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2679   //       data.Sort2NeiborsOnEdge( eos->_edges );
2680   //   }
2681
2682   dumpFunctionEnd();
2683   return true;
2684 }
2685
2686 //================================================================================
2687 /*!
2688  * \brief Compute inflation step size by min size of element on a convex surface
2689  */
2690 //================================================================================
2691
2692 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2693                                      const SMDS_MeshElement* face,
2694                                      const _LayerEdge*       maxCosinEdge )
2695 {
2696   int iN = 0;
2697   double minSize = 10 * data._stepSize;
2698   const int nbNodes = face->NbCornerNodes();
2699   for ( int i = 0; i < nbNodes; ++i )
2700   {
2701     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2702     const SMDS_MeshNode*  curN = face->GetNode( i );
2703     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2704          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2705     {
2706       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2707       if ( dist < minSize )
2708         minSize = dist, iN = i;
2709     }
2710   }
2711   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2712   if ( newStep < data._stepSize )
2713   {
2714     data._stepSize = newStep;
2715     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2716     data._stepSizeNodes[0] = face->GetNode( iN );
2717     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2718   }
2719 }
2720
2721 //================================================================================
2722 /*!
2723  * \brief Compute inflation step size by min size of element on a convex surface
2724  */
2725 //================================================================================
2726
2727 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2728 {
2729   if ( minSize < data._stepSize )
2730   {
2731     data._stepSize = minSize;
2732     if ( data._stepSizeNodes[0] )
2733     {
2734       double dist =
2735         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2736       data._stepSizeCoeff = data._stepSize / dist;
2737     }
2738   }
2739 }
2740
2741 //================================================================================
2742 /*!
2743  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2744  */
2745 //================================================================================
2746
2747 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2748 {
2749   SMESH_MesherHelper helper( *_mesh );
2750
2751   const int nbTestPnt = 5; // on a FACE sub-shape
2752
2753   BRepLProp_SLProps surfProp( 2, 1e-6 );
2754   data._convexFaces.clear();
2755
2756   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2757   {
2758     _EdgesOnShape& eof = data._edgesOnShape[iS];
2759     if ( eof.ShapeType() != TopAbs_FACE ||
2760          data._ignoreFaceIds.count( eof._shapeID ))
2761       continue;
2762
2763     TopoDS_Face        F = TopoDS::Face( eof._shape );
2764     SMESH_subMesh *   sm = eof._subMesh;
2765     const TGeomID faceID = eof._shapeID;
2766
2767     BRepAdaptor_Surface surface( F, false );
2768     surfProp.SetSurface( surface );
2769
2770     bool isTooCurved = false;
2771
2772     _ConvexFace cnvFace;
2773     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2774     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2775     while ( smIt->more() )
2776     {
2777       sm = smIt->next();
2778       const TGeomID subID = sm->GetId();
2779       // find _LayerEdge's of a sub-shape
2780       _EdgesOnShape* eos;
2781       if (( eos = data.GetShapeEdges( subID )))
2782         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2783       else
2784         continue;
2785       // check concavity and curvature and limit data._stepSize
2786       const double minCurvature =
2787         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2788       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2789       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2790       {
2791         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2792         surfProp.SetParameters( uv.X(), uv.Y() );
2793         if ( !surfProp.IsCurvatureDefined() )
2794           continue;
2795         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2796         {
2797           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2798           isTooCurved = true;
2799         }
2800         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2801         {
2802           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2803           isTooCurved = true;
2804         }
2805       }
2806     } // loop on sub-shapes of the FACE
2807
2808     if ( !isTooCurved ) continue;
2809
2810     _ConvexFace & convFace =
2811       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2812
2813     convFace._face = F;
2814     convFace._normalsFixed = false;
2815
2816     // skip a closed surface (data._convexFaces is useful anyway)
2817     bool isClosedF = false;
2818     helper.SetSubShape( F );
2819     if ( helper.HasRealSeam() )
2820     {
2821       // in the closed surface there must be a closed EDGE
2822       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2823         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2824     }
2825     if ( isClosedF )
2826     {
2827       // limit _LayerEdge::_maxLen on the FACE
2828       const double minCurvature =
2829         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2830       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2831       if ( id2eos != cnvFace._subIdToEOS.end() )
2832       {
2833         _EdgesOnShape& eos = * id2eos->second;
2834         for ( size_t i = 0; i < eos._edges.size(); ++i )
2835         {
2836           _LayerEdge* ledge = eos._edges[ i ];
2837           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2838           surfProp.SetParameters( uv.X(), uv.Y() );
2839           if ( !surfProp.IsCurvatureDefined() )
2840             continue;
2841
2842           if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2843             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2844
2845           if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2846             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2847         }
2848       }
2849       continue;
2850     }
2851
2852     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2853     // prism distortion.
2854     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2855     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2856     {
2857       // there are _LayerEdge's on the FACE it-self;
2858       // select _LayerEdge's near EDGEs
2859       _EdgesOnShape& eos = * id2eos->second;
2860       for ( size_t i = 0; i < eos._edges.size(); ++i )
2861       {
2862         _LayerEdge* ledge = eos._edges[ i ];
2863         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2864           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2865           {
2866             convFace._simplexTestEdges.push_back( ledge );
2867             break;
2868           }
2869       }
2870     }
2871     else
2872     {
2873       // where there are no _LayerEdge's on a _ConvexFace,
2874       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2875       // so that collision of viscous internal faces is not detected by check of
2876       // intersection of _LayerEdge's with the viscous internal faces.
2877
2878       set< const SMDS_MeshNode* > usedNodes;
2879
2880       // look for _LayerEdge's with null _sWOL
2881       id2eos = convFace._subIdToEOS.begin();
2882       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2883       {
2884         _EdgesOnShape& eos = * id2eos->second;
2885         if ( !eos._sWOL.IsNull() )
2886           continue;
2887         for ( size_t i = 0; i < eos._edges.size(); ++i )
2888         {
2889           _LayerEdge* ledge = eos._edges[ i ];
2890           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2891           if ( !usedNodes.insert( srcNode ).second ) continue;
2892
2893           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2894           {
2895             usedNodes.insert( ledge->_simplices[i]._nPrev );
2896             usedNodes.insert( ledge->_simplices[i]._nNext );
2897           }
2898           convFace._simplexTestEdges.push_back( ledge );
2899         }
2900       }
2901     }
2902   } // loop on FACEs of data._solid
2903 }
2904
2905 //================================================================================
2906 /*!
2907  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2908  */
2909 //================================================================================
2910
2911 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2912 {
2913   // define allowed thickness
2914   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2915
2916   data._maxThickness = 0;
2917   data._minThickness = 1e100;
2918   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2919   for ( ; hyp != data._hyps.end(); ++hyp )
2920   {
2921     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2922     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2923   }
2924   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2925
2926   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2927   // boundry inclined to the shape at a sharp angle
2928
2929   //list< TGeomID > shapesToSmooth;
2930   TopTools_MapOfShape edgesOfSmooFaces;
2931
2932   SMESH_MesherHelper helper( *_mesh );
2933   bool ok = true;
2934
2935   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2936   data._nbShapesToSmooth = 0;
2937
2938   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2939   {
2940     _EdgesOnShape& eos = edgesByGeom[iS];
2941     eos._toSmooth = false;
2942     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2943       continue;
2944
2945     double tgtThick = eos._hyp.GetTotalThickness();
2946     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2947     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2948     {
2949       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2950       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2951       if ( eE.empty() ) continue;
2952
2953       double faceSize;
2954       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2955         if ( eE[i]->_cosin > theMinSmoothCosin )
2956         {
2957           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2958           while ( fIt->more() && !eos._toSmooth )
2959           {
2960             const SMDS_MeshElement* face = fIt->next();
2961             if ( face->getshapeId() == eos._shapeID &&
2962                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2963             {
2964               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2965             }
2966           }
2967         }
2968     }
2969     if ( eos._toSmooth )
2970     {
2971       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2972         edgesOfSmooFaces.Add( eExp.Current() );
2973
2974       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2975     }
2976     data._nbShapesToSmooth += eos._toSmooth;
2977
2978   }  // check FACEs
2979
2980   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2981   {
2982     _EdgesOnShape& eos = edgesByGeom[iS];
2983     eos._edgeSmoother = NULL;
2984     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2985     if ( !eos._hyp.ToSmooth() ) continue;
2986
2987     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2988     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2989       continue;
2990
2991     double tgtThick = eos._hyp.GetTotalThickness();
2992     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2993     {
2994       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2995       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2996       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
2997       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2998       double angle    = eDir.Angle( eV[0]->_normal );
2999       double cosin    = Cos( angle );
3000       double cosinAbs = Abs( cosin );
3001       if ( cosinAbs > theMinSmoothCosin )
3002       {
3003         // always smooth analytic EDGEs
3004         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3005         eos._toSmooth = ! curve.IsNull();
3006
3007         // compare tgtThick with the length of an end segment
3008         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3009         while ( eIt->more() && !eos._toSmooth )
3010         {
3011           const SMDS_MeshElement* endSeg = eIt->next();
3012           if ( endSeg->getshapeId() == (int) iS )
3013           {
3014             double segLen =
3015               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3016             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3017           }
3018         }
3019         if ( eos._toSmooth )
3020         {
3021           eos._edgeSmoother = new _Smoother1D( curve, eos );
3022
3023           for ( size_t i = 0; i < eos._edges.size(); ++i )
3024             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3025         }
3026       }
3027     }
3028     data._nbShapesToSmooth += eos._toSmooth;
3029
3030   } // check EDGEs
3031
3032   // Reset _cosin if no smooth is allowed by the user
3033   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3034   {
3035     _EdgesOnShape& eos = edgesByGeom[iS];
3036     if ( eos._edges.empty() ) continue;
3037
3038     if ( !eos._hyp.ToSmooth() )
3039       for ( size_t i = 0; i < eos._edges.size(); ++i )
3040         eos._edges[i]->SetCosin( 0 );
3041   }
3042
3043
3044   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3045
3046   TopTools_MapOfShape c1VV;
3047
3048   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3049   {
3050     _EdgesOnShape& eos = edgesByGeom[iS];
3051     if ( eos._edges.empty() ||
3052          eos.ShapeType() != TopAbs_FACE ||
3053          !eos._toSmooth )
3054       continue;
3055
3056     // check EDGEs of a FACE
3057     TopTools_MapOfShape checkedEE, allVV;
3058     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3059     while ( !smQueue.empty() )
3060     {
3061       SMESH_subMesh* sm = smQueue.front();
3062       smQueue.pop_front();
3063       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3064       while ( smIt->more() )
3065       {
3066         sm = smIt->next();
3067         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3068           allVV.Add( sm->GetSubShape() );
3069         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3070              !checkedEE.Add( sm->GetSubShape() ))
3071           continue;
3072
3073         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3074         vector<_LayerEdge*>& eE = eoe->_edges;
3075         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3076           continue;
3077
3078         bool isC1 = true; // check continuity along an EDGE
3079         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3080           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3081         if ( !isC1 )
3082           continue;
3083
3084         // check that mesh faces are C1 as well
3085         {
3086           gp_XYZ norm1, norm2;
3087           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3088           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3089           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3090             continue;
3091           while ( fIt->more() && isC1 )
3092             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3093                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3094           if ( !isC1 )
3095             continue;
3096         }
3097
3098         // add the EDGE and an adjacent FACE to _eosC1
3099         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3100         while ( const TopoDS_Shape* face = fIt->next() )
3101         {
3102           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3103           if ( !eof ) continue; // other solid
3104           if ( !eos.HasC1( eoe ))
3105           {
3106             eos._eosC1.push_back( eoe );
3107             eoe->_toSmooth = false;
3108             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3109           }
3110           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3111           {
3112             eos._eosC1.push_back( eof );
3113             eof->_toSmooth = false;
3114             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3115             smQueue.push_back( eof->_subMesh );
3116           }
3117         }
3118       }
3119     }
3120     if ( eos._eosC1.empty() )
3121       continue;
3122
3123     // check VERTEXes of C1 FACEs
3124     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3125     for ( ; vIt.More(); vIt.Next() )
3126     {
3127       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3128       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3129         continue;
3130
3131       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3132       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3133       while ( const TopoDS_Shape* face = fIt->next() )
3134       {
3135         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3136         if ( !eof ) continue; // other solid
3137         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3138         if ( !isC1 )
3139           break;
3140       }
3141       if ( isC1 )
3142       {
3143         eos._eosC1.push_back( eov );
3144         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3145         c1VV.Add( eov->_shape );
3146       }
3147     }
3148
3149   } // fill _eosC1 of FACEs
3150
3151
3152   // Find C1 EDGEs
3153
3154   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3155
3156   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3157   {
3158     _EdgesOnShape& eov = edgesByGeom[iS];
3159     if ( eov._edges.empty() ||
3160          eov.ShapeType() != TopAbs_VERTEX ||
3161          c1VV.Contains( eov._shape ))
3162       continue;
3163     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3164
3165     // get directions of surrounding EDGEs
3166     dirOfEdges.clear();
3167     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3168     while ( const TopoDS_Shape* e = fIt->next() )
3169     {
3170       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3171       if ( !eoe ) continue; // other solid
3172       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3173       if ( !Precision::IsInfinite( eDir.X() ))
3174         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3175     }
3176
3177     // find EDGEs with C1 directions
3178     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3179       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3180         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3181         {
3182           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3183           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3184           if ( isC1 )
3185           {
3186             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3187             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3188             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3189             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3190             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3191             dirOfEdges[i].first = 0;
3192             dirOfEdges[j].first = 0;
3193           }
3194         }
3195   } // fill _eosC1 of VERTEXes
3196
3197
3198
3199   return ok;
3200 }
3201
3202 //================================================================================
3203 /*!
3204  * \brief initialize data of _EdgesOnShape
3205  */
3206 //================================================================================
3207
3208 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3209                                     SMESH_subMesh* sm,
3210                                     _SolidData&    data )
3211 {
3212   if ( !eos._shape.IsNull() ||
3213        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3214     return;
3215
3216   SMESH_MesherHelper helper( *_mesh );
3217
3218   eos._subMesh = sm;
3219   eos._shapeID = sm->GetId();
3220   eos._shape   = sm->GetSubShape();
3221   if ( eos.ShapeType() == TopAbs_FACE )
3222     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3223   eos._toSmooth = false;
3224   eos._data = &data;
3225
3226   // set _SWOL
3227   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3228     data._shrinkShape2Shape.find( eos._shapeID );
3229   if ( s2s != data._shrinkShape2Shape.end() )
3230     eos._sWOL = s2s->second;
3231
3232   eos._isRegularSWOL = true;
3233   if ( eos.SWOLType() == TopAbs_FACE )
3234   {
3235     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3236     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3237     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3238   }
3239
3240   // set _hyp
3241   if ( data._hyps.size() == 1 )
3242   {
3243     eos._hyp = data._hyps.back();
3244   }
3245   else
3246   {
3247     // compute average StdMeshers_ViscousLayers parameters
3248     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3249     if ( eos.ShapeType() == TopAbs_FACE )
3250     {
3251       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3252         eos._hyp = f2hyp->second;
3253     }
3254     else
3255     {
3256       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3257       while ( const TopoDS_Shape* face = fIt->next() )
3258       {
3259         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3260         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3261           eos._hyp.Add( f2hyp->second );
3262       }
3263     }
3264   }
3265
3266   // set _faceNormals
3267   if ( ! eos._hyp.UseSurfaceNormal() )
3268   {
3269     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3270     {
3271       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3272       eos._faceNormals.resize( smDS->NbElements() );
3273
3274       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3275       for ( int iF = 0; eIt->more(); ++iF )
3276       {
3277         const SMDS_MeshElement* face = eIt->next();
3278         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3279           eos._faceNormals[iF].SetCoord( 0,0,0 );
3280       }
3281
3282       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3283         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3284           eos._faceNormals[iF].Reverse();
3285     }
3286     else // find EOS of adjacent FACEs
3287     {
3288       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3289       while ( const TopoDS_Shape* face = fIt->next() )
3290       {
3291         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3292         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3293         if ( eos._faceEOS.back()->_shape.IsNull() )
3294           // avoid using uninitialised _shapeID in GetNormal()
3295           eos._faceEOS.back()->_shapeID = faceID;
3296       }
3297     }
3298   }
3299 }
3300
3301 //================================================================================
3302 /*!
3303  * \brief Returns normal of a face
3304  */
3305 //================================================================================
3306
3307 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3308 {
3309   bool ok = false;
3310   const _EdgesOnShape* eos = 0;
3311
3312   if ( face->getshapeId() == _shapeID )
3313   {
3314     eos = this;
3315   }
3316   else
3317   {
3318     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3319       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3320         eos = _faceEOS[ iF ];
3321   }
3322
3323   if (( eos ) &&
3324       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3325   {
3326     norm = eos->_faceNormals[ face->getIdInShape() ];
3327   }
3328   else if ( !eos )
3329   {
3330     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3331               << " on _shape #" << _shapeID );
3332   }
3333   return ok;
3334 }
3335
3336
3337 //================================================================================
3338 /*!
3339  * \brief Set data of _LayerEdge needed for smoothing
3340  */
3341 //================================================================================
3342
3343 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3344                                   _EdgesOnShape&      eos,
3345                                   SMESH_MesherHelper& helper,
3346                                   _SolidData&         data)
3347 {
3348   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3349
3350   edge._len       = 0;
3351   edge._maxLen    = Precision::Infinite();
3352   edge._minAngle  = 0;
3353   edge._2neibors  = 0;
3354   edge._curvature = 0;
3355   edge._flags     = 0;
3356
3357   // --------------------------
3358   // Compute _normal and _cosin
3359   // --------------------------
3360
3361   edge._cosin     = 0;
3362   edge._lenFactor = 1.;
3363   edge._normal.SetCoord(0,0,0);
3364   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3365
3366   int totalNbFaces = 0;
3367   TopoDS_Face F;
3368   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3369   gp_Vec geomNorm;
3370   bool normOK = true;
3371
3372   const bool onShrinkShape = !eos._sWOL.IsNull();
3373   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3374                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3375
3376   // get geom FACEs the node lies on
3377   //if ( useGeometry )
3378   {
3379     set<TGeomID> faceIds;
3380     if  ( eos.ShapeType() == TopAbs_FACE )
3381     {
3382       faceIds.insert( eos._shapeID );
3383     }
3384     else
3385     {
3386       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3387       while ( fIt->more() )
3388         faceIds.insert( fIt->next()->getshapeId() );
3389     }
3390     set<TGeomID>::iterator id = faceIds.begin();
3391     for ( ; id != faceIds.end(); ++id )
3392     {
3393       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3394       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3395         continue;
3396       F = TopoDS::Face( s );
3397       face2Norm[ totalNbFaces ].first = F;
3398       totalNbFaces++;
3399     }
3400   }
3401
3402   // find _normal
3403   if ( useGeometry )
3404   {
3405     bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3406                       eos.SWOLType()  == TopAbs_FACE  &&
3407                       totalNbFaces > 1 );
3408
3409     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3410     {
3411       if ( eos.SWOLType() == TopAbs_EDGE )
3412       {
3413         // inflate from VERTEX along EDGE
3414         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3415       }
3416       else if ( eos.ShapeType() == TopAbs_VERTEX )
3417       {
3418         // inflate from VERTEX along FACE
3419         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3420                                    node, helper, normOK, &edge._cosin);
3421       }
3422       else
3423       {
3424         // inflate from EDGE along FACE
3425         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3426                                    node, helper, normOK);
3427       }
3428     }
3429     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3430     {
3431       if ( fromVonF )
3432         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3433
3434       int nbOkNorms = 0;
3435       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3436       {
3437         F = face2Norm[ iF ].first;
3438         geomNorm = getFaceNormal( node, F, helper, normOK );
3439         if ( !normOK ) continue;
3440         nbOkNorms++;
3441
3442         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3443           geomNorm.Reverse();
3444         face2Norm[ iF ].second = geomNorm.XYZ();
3445         edge._normal += geomNorm.XYZ();
3446       }
3447       if ( nbOkNorms == 0 )
3448         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3449
3450       if ( totalNbFaces >= 3 )
3451       {
3452         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3453       }
3454
3455       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3456       {
3457         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3458         edge._normal.SetCoord( 0,0,0 );
3459         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3460         {
3461           const TopoDS_Face& F = face2Norm[iF].first;
3462           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3463           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3464             geomNorm.Reverse();
3465           if ( normOK )
3466             face2Norm[ iF ].second = geomNorm.XYZ();
3467           edge._normal += face2Norm[ iF ].second;
3468         }
3469       }
3470     }
3471   }
3472   else // !useGeometry - get _normal using surrounding mesh faces
3473   {
3474     edge._normal = getWeigthedNormal( &edge );
3475
3476     // set<TGeomID> faceIds;
3477     //
3478     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3479     // while ( fIt->more() )
3480     // {
3481     //   const SMDS_MeshElement* face = fIt->next();
3482     //   if ( eos.GetNormal( face, geomNorm ))
3483     //   {
3484     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3485     //       continue; // use only one mesh face on FACE
3486     //     edge._normal += geomNorm.XYZ();
3487     //     totalNbFaces++;
3488     //   }
3489     // }
3490   }
3491
3492   // compute _cosin
3493   //if ( eos._hyp.UseSurfaceNormal() )
3494   {
3495     switch ( eos.ShapeType() )
3496     {
3497     case TopAbs_FACE: {
3498       edge._cosin = 0;
3499       break;
3500     }
3501     case TopAbs_EDGE: {
3502       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3503       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3504       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3505       edge._cosin      = Cos( angle );
3506       break;
3507     }
3508     case TopAbs_VERTEX: {
3509       //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3510       {
3511         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3512         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3513         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3514         edge._cosin      = Cos( angle );
3515         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3516           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3517           {
3518             F = face2Norm[ iF ].first;
3519             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3520             if ( normOK ) {
3521               double angle = inFaceDir.Angle( edge._normal );
3522               double cosin = Cos( angle );
3523               if ( Abs( cosin ) > Abs( edge._cosin ))
3524                 edge._cosin = cosin;
3525             }
3526           }
3527       }
3528       break;
3529     }
3530     default:
3531       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3532     }
3533   }
3534
3535   double normSize = edge._normal.SquareModulus();
3536   if ( normSize < numeric_limits<double>::min() )
3537     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3538
3539   edge._normal /= sqrt( normSize );
3540
3541   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3542   {
3543     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3544     edge._nodes.resize( 1 );
3545     edge._normal.SetCoord( 0,0,0 );
3546     edge._maxLen = 0;
3547   }
3548
3549   // Set the rest data
3550   // --------------------
3551
3552   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3553
3554   if ( onShrinkShape )
3555   {
3556     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3557     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3558       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3559
3560     // set initial position which is parameters on _sWOL in this case
3561     if ( eos.SWOLType() == TopAbs_EDGE )
3562     {
3563       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3564       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3565       if ( edge._nodes.size() > 1 )
3566         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3567     }
3568     else // eos.SWOLType() == TopAbs_FACE
3569     {
3570       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3571       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3572       if ( edge._nodes.size() > 1 )
3573         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3574     }
3575
3576     if ( edge._nodes.size() > 1 )
3577     {
3578       // check if an angle between a FACE with layers and SWOL is sharp,
3579       // else the edge should not inflate
3580       F.Nullify();
3581       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3582         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3583           F = face2Norm[iF].first;
3584       if ( !F.IsNull())
3585       {
3586         geomNorm = getFaceNormal( node, F, helper, normOK );
3587         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3588           geomNorm.Reverse(); // inside the SOLID
3589         if ( geomNorm * edge._normal < -0.001 )
3590         {
3591           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3592           edge._nodes.resize( 1 );
3593         }
3594         else if ( edge._lenFactor > 3 )
3595         {
3596           edge._lenFactor = 2;
3597           edge.Set( _LayerEdge::RISKY_SWOL );
3598         }
3599       }
3600     }
3601   }
3602   else
3603   {
3604     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3605
3606     if ( eos.ShapeType() == TopAbs_FACE )
3607     {
3608       double angle;
3609       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3610       {
3611         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3612         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3613       }
3614     }
3615   }
3616
3617   // Set neighbor nodes for a _LayerEdge based on EDGE
3618
3619   if ( eos.ShapeType() == TopAbs_EDGE /*||
3620        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3621   {
3622     edge._2neibors = new _2NearEdges;
3623     // target nodes instead of source ones will be set later
3624   }
3625
3626   return true;
3627 }
3628
3629 //================================================================================
3630 /*!
3631  * \brief Return normal to a FACE at a node
3632  *  \param [in] n - node
3633  *  \param [in] face - FACE
3634  *  \param [in] helper - helper
3635  *  \param [out] isOK - true or false
3636  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3637  *  \return gp_XYZ - normal
3638  */
3639 //================================================================================
3640
3641 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3642                                       const TopoDS_Face&   face,
3643                                       SMESH_MesherHelper&  helper,
3644                                       bool&                isOK,
3645                                       bool                 shiftInside)
3646 {
3647   gp_XY uv;
3648   if ( shiftInside )
3649   {
3650     // get a shifted position
3651     gp_Pnt p = SMESH_TNodeXYZ( node );
3652     gp_XYZ shift( 0,0,0 );
3653     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3654     switch ( S.ShapeType() ) {
3655     case TopAbs_VERTEX:
3656     {
3657       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3658       break;
3659     }
3660     case TopAbs_EDGE:
3661     {
3662       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3663       break;
3664     }
3665     default:
3666       isOK = false;
3667     }
3668     if ( isOK )
3669       shift.Normalize();
3670     p.Translate( shift * 1e-5 );
3671
3672     TopLoc_Location loc;
3673     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3674
3675     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3676     
3677     projector.Perform( p );
3678     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3679     {
3680       isOK = false;
3681       return p.XYZ();
3682     }
3683     Quantity_Parameter U,V;
3684     projector.LowerDistanceParameters(U,V);
3685     uv.SetCoord( U,V );
3686   }
3687   else
3688   {
3689     uv = helper.GetNodeUV( face, node, 0, &isOK );
3690   }
3691
3692   gp_Dir normal;
3693   isOK = false;
3694
3695   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3696
3697   if ( !shiftInside &&
3698        helper.IsDegenShape( node->getshapeId() ) &&
3699        getFaceNormalAtSingularity( uv, face, helper, normal ))
3700   {
3701     isOK = true;
3702     return normal.XYZ();
3703   }
3704
3705   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3706   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3707
3708   if ( pointKind == IMPOSSIBLE &&
3709        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3710   {
3711     // probably NormEstim() failed due to a too high tolerance
3712     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3713     isOK = ( pointKind < IMPOSSIBLE );
3714   }
3715   if ( pointKind < IMPOSSIBLE )
3716   {
3717     if ( pointKind != REGULAR &&
3718          !shiftInside &&
3719          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3720     {
3721       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3722       if ( normShift * normal.XYZ() < 0. )
3723         normal = normShift;
3724     }
3725     isOK = true;
3726   }
3727
3728   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3729   {
3730     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3731
3732     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3733     while ( fIt->more() )
3734     {
3735       const SMDS_MeshElement* f = fIt->next();
3736       if ( f->getshapeId() == faceID )
3737       {
3738         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3739         if ( isOK )
3740         {
3741           TopoDS_Face ff = face;
3742           ff.Orientation( TopAbs_FORWARD );
3743           if ( helper.IsReversedSubMesh( ff ))
3744             normal.Reverse();
3745           break;
3746         }
3747       }
3748     }
3749   }
3750   return normal.XYZ();
3751 }
3752
3753 //================================================================================
3754 /*!
3755  * \brief Try to get normal at a singularity of a surface basing on it's nature
3756  */
3757 //================================================================================
3758
3759 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3760                                                   const TopoDS_Face&  face,
3761                                                   SMESH_MesherHelper& helper,
3762                                                   gp_Dir&             normal )
3763 {
3764   BRepAdaptor_Surface surface( face );
3765   gp_Dir axis;
3766   if ( !getRovolutionAxis( surface, axis ))
3767     return false;
3768
3769   double f,l, d, du, dv;
3770   f = surface.FirstUParameter();
3771   l = surface.LastUParameter();
3772   d = ( uv.X() - f ) / ( l - f );
3773   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3774   f = surface.FirstVParameter();
3775   l = surface.LastVParameter();
3776   d = ( uv.Y() - f ) / ( l - f );
3777   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3778
3779   gp_Dir refDir;
3780   gp_Pnt2d testUV = uv;
3781   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3782   double tol = 1e-5;
3783   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3784   for ( int iLoop = 0; true ; ++iLoop )
3785   {
3786     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3787     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3788       break;
3789     if ( iLoop > 20 )
3790       return false;
3791     tol /= 10.;
3792   }
3793
3794   if ( axis * refDir < 0. )
3795     axis.Reverse();
3796
3797   normal = axis;
3798
3799   return true;
3800 }
3801
3802 //================================================================================
3803 /*!
3804  * \brief Return a normal at a node weighted with angles taken by faces
3805  */
3806 //================================================================================
3807
3808 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3809 {
3810   const SMDS_MeshNode* n = edge->_nodes[0];
3811
3812   gp_XYZ resNorm(0,0,0);
3813   SMESH_TNodeXYZ p0( n ), pP, pN;
3814   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3815   {
3816     pP.Set( edge->_simplices[i]._nPrev );
3817     pN.Set( edge->_simplices[i]._nNext );
3818     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3819     double l0P = v0P.SquareMagnitude();
3820     double l0N = v0N.SquareMagnitude();
3821     double lPN = vPN.SquareMagnitude();
3822     if ( l0P < std::numeric_limits<double>::min() ||
3823          l0N < std::numeric_limits<double>::min() ||
3824          lPN < std::numeric_limits<double>::min() )
3825       continue;
3826     double lNorm = norm.SquareMagnitude();
3827     double  sin2 = lNorm / l0P / l0N;
3828     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3829
3830     double weight = sin2 * angle / lPN;
3831     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3832   }
3833
3834   return resNorm;
3835 }
3836
3837 //================================================================================
3838 /*!
3839  * \brief Return a normal at a node by getting a common point of offset planes
3840  *        defined by the FACE normals
3841  */
3842 //================================================================================
3843
3844 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3845                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3846                                            int                              nbFaces,
3847                                            bool                             lastNoOffset)
3848 {
3849   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3850
3851   gp_XYZ resNorm(0,0,0);
3852   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3853   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3854   {
3855     for ( int i = 0; i < nbFaces; ++i )
3856       resNorm += f2Normal[i].second;
3857     return resNorm;
3858   }
3859
3860   // prepare _OffsetPlane's
3861   vector< _OffsetPlane > pln( nbFaces );
3862   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3863   {
3864     pln[i]._faceIndex = i;
3865     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3866   }
3867   if ( lastNoOffset )
3868   {
3869     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3870     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3871   }
3872
3873   // intersect neighboring OffsetPlane's
3874   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3875   while ( const TopoDS_Shape* edge = edgeIt->next() )
3876   {
3877     int f1 = -1, f2 = -1;
3878     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3879       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3880         (( f1 < 0 ) ? f1 : f2 ) = i;
3881
3882     if ( f2 >= 0 )
3883       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3884   }
3885
3886   // get a common point
3887   gp_XYZ commonPnt( 0, 0, 0 );
3888   int nbPoints = 0;
3889   bool isPointFound;
3890   for ( int i = 0; i < nbFaces; ++i )
3891   {
3892     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3893     nbPoints  += isPointFound;
3894   }
3895   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3896   if ( nbPoints == 0 )
3897     return wgtNorm;
3898
3899   commonPnt /= nbPoints;
3900   resNorm = commonPnt - p0;
3901   if ( lastNoOffset )
3902     return resNorm;
3903
3904   // choose the best among resNorm and wgtNorm
3905   resNorm.Normalize();
3906   wgtNorm.Normalize();
3907   double resMinDot = std::numeric_limits<double>::max();
3908   double wgtMinDot = std::numeric_limits<double>::max();
3909   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3910   {
3911     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3912     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3913   }
3914
3915   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3916   {
3917     edge->Set( _LayerEdge::MULTI_NORMAL );
3918   }
3919
3920   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3921 }
3922
3923 //================================================================================
3924 /*!
3925  * \brief Compute line of intersection of 2 planes
3926  */
3927 //================================================================================
3928
3929 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3930                                             const TopoDS_Edge&   E,
3931                                             const TopoDS_Vertex& V )
3932 {
3933   int iNext = bool( _faceIndexNext[0] >= 0 );
3934   _faceIndexNext[ iNext ] = pln._faceIndex;
3935
3936   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3937   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3938
3939   gp_XYZ lineDir = n1 ^ n2;
3940
3941   double x = Abs( lineDir.X() );
3942   double y = Abs( lineDir.Y() );
3943   double z = Abs( lineDir.Z() );
3944
3945   int cooMax; // max coordinate
3946   if (x > y) {
3947     if (x > z) cooMax = 1;
3948     else       cooMax = 3;
3949   }
3950   else {
3951     if (y > z) cooMax = 2;
3952     else       cooMax = 3;
3953   }
3954
3955   gp_Pnt linePos;
3956   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3957   {
3958     // parallel planes - intersection is an offset of the common EDGE
3959     gp_Pnt p = BRep_Tool::Pnt( V );
3960     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3961     lineDir  = getEdgeDir( E, V );
3962   }
3963   else
3964   {
3965     // the constants in the 2 plane equations
3966     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3967     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3968
3969     switch ( cooMax ) {
3970     case 1:
3971       linePos.SetX(  0 );
3972       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3973       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3974       break;
3975     case 2:
3976       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3977       linePos.SetY(  0 );
3978       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3979       break;
3980     case 3:
3981       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3982       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3983       linePos.SetZ(  0 );
3984     }
3985   }
3986   gp_Lin& line = _lines[ iNext ];
3987   line.SetDirection( lineDir );
3988   line.SetLocation ( linePos );
3989
3990   _isLineOK[ iNext ] = true;
3991
3992
3993   iNext = bool( pln._faceIndexNext[0] >= 0 );
3994   pln._lines        [ iNext ] = line;
3995   pln._faceIndexNext[ iNext ] = this->_faceIndex;
3996   pln._isLineOK     [ iNext ] = true;
3997 }
3998
3999 //================================================================================
4000 /*!
4001  * \brief Computes intersection point of two _lines
4002  */
4003 //================================================================================
4004
4005 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4006                                     const TopoDS_Vertex & V) const
4007 {
4008   gp_XYZ p( 0,0,0 );
4009   isFound = false;
4010
4011   if ( NbLines() == 2 )
4012   {
4013     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4014     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4015     if ( Abs( dot01 ) > 0.05 )
4016     {
4017       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4018       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4019       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4020       isFound = true;
4021     }
4022     else
4023     {
4024       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4025       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4026       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4027       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4028       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4029       isFound = true;
4030     }
4031   }
4032
4033   return p;
4034 }
4035
4036 //================================================================================
4037 /*!
4038  * \brief Find 2 neigbor nodes of a node on EDGE
4039  */
4040 //================================================================================
4041
4042 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4043                                         const SMDS_MeshNode*& n1,
4044                                         const SMDS_MeshNode*& n2,
4045                                         _EdgesOnShape&        eos,
4046                                         _SolidData&           data)
4047 {
4048   const SMDS_MeshNode* node = edge->_nodes[0];
4049   const int        shapeInd = eos._shapeID;
4050   SMESHDS_SubMesh*   edgeSM = 0;
4051   if ( eos.ShapeType() == TopAbs_EDGE )
4052   {
4053     edgeSM = eos._subMesh->GetSubMeshDS();
4054     if ( !edgeSM || edgeSM->NbElements() == 0 )
4055       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4056   }
4057   int iN = 0;
4058   n2 = 0;
4059   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4060   while ( eIt->more() && !n2 )
4061   {
4062     const SMDS_MeshElement* e = eIt->next();
4063     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4064     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4065     if ( edgeSM )
4066     {
4067       if (!edgeSM->Contains(e)) continue;
4068     }
4069     else
4070     {
4071       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4072       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4073     }
4074     ( iN++ ? n2 : n1 ) = nNeibor;
4075   }
4076   if ( !n2 )
4077     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4078   return true;
4079 }
4080
4081 //================================================================================
4082 /*!
4083  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4084  */
4085 //================================================================================
4086
4087 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4088                                      const SMDS_MeshNode* n2,
4089                                      const _EdgesOnShape& eos,
4090                                      SMESH_MesherHelper&  helper)
4091 {
4092   if ( eos.ShapeType() != TopAbs_EDGE )
4093     return;
4094
4095   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4096   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4097   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4098
4099   // Set _curvature
4100
4101   double      sumLen = vec1.Modulus() + vec2.Modulus();
4102   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4103   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4104   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4105   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4106   if ( _curvature ) delete _curvature;
4107   _curvature = _Curvature::New( avgNormProj, avgLen );
4108   // if ( _curvature )
4109   //   debugMsg( _nodes[0]->GetID()
4110   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4111   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4112   //             << _curvature->lenDelta(0) );
4113
4114   // Set _plnNorm
4115
4116   if ( eos._sWOL.IsNull() )
4117   {
4118     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4119     // if ( SMESH_Algo::isDegenerated( E ))
4120     //   return;
4121     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4122     gp_XYZ plnNorm = dirE ^ _normal;
4123     double proj0   = plnNorm * vec1;
4124     double proj1   = plnNorm * vec2;
4125     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4126     {
4127       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4128       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4129     }
4130   }
4131 }
4132
4133 //================================================================================
4134 /*!
4135  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4136  * this and other _LayerEdge's are inflated along a FACE or an EDGE
4137  */
4138 //================================================================================
4139
4140 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4141                          _EdgesOnShape&      eos,
4142                          SMESH_MesherHelper& helper )
4143 {
4144   _nodes     = other._nodes;
4145   _normal    = other._normal;
4146   _len       = 0;
4147   _lenFactor = other._lenFactor;
4148   _cosin     = other._cosin;
4149   _2neibors  = other._2neibors;
4150   _curvature = 0; std::swap( _curvature, other._curvature );
4151   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4152
4153   gp_XYZ lastPos( 0,0,0 );
4154   if ( eos.SWOLType() == TopAbs_EDGE )
4155   {
4156     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4157     _pos.push_back( gp_XYZ( u, 0, 0));
4158
4159     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4160     lastPos.SetX( u );
4161   }
4162   else // TopAbs_FACE
4163   {
4164     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4165     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4166
4167     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4168     lastPos.SetX( uv.X() );
4169     lastPos.SetY( uv.Y() );
4170   }
4171   return lastPos;
4172 }
4173
4174 //================================================================================
4175 /*!
4176  * \brief Set _cosin and _lenFactor
4177  */
4178 //================================================================================
4179
4180 void _LayerEdge::SetCosin( double cosin )
4181 {
4182   _cosin = cosin;
4183   cosin = Abs( _cosin );
4184   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4185   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4186 }
4187
4188 //================================================================================
4189 /*!
4190  * \brief Check if another _LayerEdge is a neighbor on EDGE
4191  */
4192 //================================================================================
4193
4194 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4195 {
4196   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4197           ( edge->_2neibors && edge->_2neibors->include( this )));
4198 }
4199
4200 //================================================================================
4201 /*!
4202  * \brief Fills a vector<_Simplex > 
4203  */
4204 //================================================================================
4205
4206 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4207                              vector<_Simplex>&    simplices,
4208                              const set<TGeomID>&  ingnoreShapes,
4209                              const _SolidData*    dataToCheckOri,
4210                              const bool           toSort)
4211 {
4212   simplices.clear();
4213   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4214   while ( fIt->more() )
4215   {
4216     const SMDS_MeshElement* f = fIt->next();
4217     const TGeomID    shapeInd = f->getshapeId();
4218     if ( ingnoreShapes.count( shapeInd )) continue;
4219     const int nbNodes = f->NbCornerNodes();
4220     const int  srcInd = f->GetNodeIndex( node );
4221     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4222     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4223     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4224     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4225       std::swap( nPrev, nNext );
4226     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4227   }
4228
4229   if ( toSort )
4230     SortSimplices( simplices );
4231 }
4232
4233 //================================================================================
4234 /*!
4235  * \brief Set neighbor simplices side by side
4236  */
4237 //================================================================================
4238
4239 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4240 {
4241   vector<_Simplex> sortedSimplices( simplices.size() );
4242   sortedSimplices[0] = simplices[0];
4243   size_t nbFound = 0;
4244   for ( size_t i = 1; i < simplices.size(); ++i )
4245   {
4246     for ( size_t j = 1; j < simplices.size(); ++j )
4247       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4248       {
4249         sortedSimplices[i] = simplices[j];
4250         nbFound++;
4251         break;
4252       }
4253   }
4254   if ( nbFound == simplices.size() - 1 )
4255     simplices.swap( sortedSimplices );
4256 }
4257
4258 //================================================================================
4259 /*!
4260  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4261  */
4262 //================================================================================
4263
4264 void _ViscousBuilder::makeGroupOfLE()
4265 {
4266 #ifdef _DEBUG_
4267   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4268   {
4269     if ( _sdVec[i]._n2eMap.empty() ) continue;
4270
4271     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4272     TNode2Edge::iterator n2e;
4273     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4274     {
4275       _LayerEdge* le = n2e->second;
4276       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4277       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4278       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4279       if ( le ) {
4280         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4281                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4282       }
4283     }
4284     dumpFunctionEnd();
4285
4286     dumpFunction( SMESH_Comment("makeNormals") << i );
4287     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4288     {
4289       _LayerEdge* edge = n2e->second;
4290       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4291       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4292       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4293               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4294     }
4295     dumpFunctionEnd();
4296
4297     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4298     dumpCmd( "faceId1 = mesh.NbElements()" );
4299     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4300     for ( ; fExp.More(); fExp.Next() )
4301     {
4302       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4303       {
4304         if ( sm->NbElements() == 0 ) continue;
4305         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4306         while ( fIt->more())
4307         {
4308           const SMDS_MeshElement* e = fIt->next();
4309           SMESH_Comment cmd("mesh.AddFace([");
4310           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4311             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4312           dumpCmd( cmd );
4313         }
4314       }
4315     }
4316     dumpCmd( "faceId2 = mesh.NbElements()" );
4317     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4318              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4319              << "'%s-%s' % (faceId1+1, faceId2))");
4320     dumpFunctionEnd();
4321   }
4322 #endif
4323 }
4324
4325 //================================================================================
4326 /*!
4327  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4328  */
4329 //================================================================================
4330
4331 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4332 {
4333   data._geomSize = Precision::Infinite();
4334   double intersecDist;
4335   const SMDS_MeshElement* face;
4336   SMESH_MesherHelper helper( *_mesh );
4337
4338   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4339     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4340                                            data._proxyMesh->GetFaces( data._solid )));
4341
4342   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4343   {
4344     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4345     if ( eos._edges.empty() )
4346       continue;
4347     // get neighbor faces intersection with which should not be considered since
4348     // collisions are avoided by means of smoothing
4349     set< TGeomID > neighborFaces;
4350     if ( eos._hyp.ToSmooth() )
4351     {
4352       SMESH_subMeshIteratorPtr subIt =
4353         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4354       while ( subIt->more() )
4355       {
4356         SMESH_subMesh* sm = subIt->next();
4357         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4358         while ( const TopoDS_Shape* face = fIt->next() )
4359           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4360       }
4361     }
4362     // find intersections
4363     double thinkness = eos._hyp.GetTotalThickness();
4364     for ( size_t i = 0; i < eos._edges.size(); ++i )
4365     {
4366       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4367       eos._edges[i]->_maxLen = thinkness;
4368       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4369       if ( intersecDist > 0 && face )
4370       {
4371         data._geomSize = Min( data._geomSize, intersecDist );
4372         if ( !neighborFaces.count( face->getshapeId() ))
4373           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4374       }
4375     }
4376   }
4377 }
4378
4379 //================================================================================
4380 /*!
4381  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4382  */
4383 //================================================================================
4384
4385 bool _ViscousBuilder::inflate(_SolidData& data)
4386 {
4387   SMESH_MesherHelper helper( *_mesh );
4388
4389   // Limit inflation step size by geometry size found by itersecting
4390   // normals of _LayerEdge's with mesh faces
4391   if ( data._stepSize > 0.3 * data._geomSize )
4392     limitStepSize( data, 0.3 * data._geomSize );
4393
4394   const double tgtThick = data._maxThickness;
4395   if ( data._stepSize > data._minThickness )
4396     limitStepSize( data, data._minThickness );
4397
4398   if ( data._stepSize < 1. )
4399     data._epsilon = data._stepSize * 1e-7;
4400
4401   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4402
4403   findCollisionEdges( data, helper );
4404
4405   limitMaxLenByCurvature( data, helper );
4406
4407   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4408   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4409     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4410          data._edgesOnShape[i]._edges.size() > 0 &&
4411          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4412     {
4413       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4414       data._edgesOnShape[i]._edges[0]->Block( data );
4415     }
4416
4417   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4418
4419   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4420   int nbSteps = 0, nbRepeats = 0;
4421   while ( avgThick < 0.99 )
4422   {
4423     // new target length
4424     double prevThick = curThick;
4425     curThick += data._stepSize;
4426     if ( curThick > tgtThick )
4427     {
4428       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4429       nbRepeats++;
4430     }
4431
4432     double stepSize = curThick - prevThick;
4433     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4434
4435     // Elongate _LayerEdge's
4436     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4437     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4438     {
4439       _EdgesOnShape& eos = data._edgesOnShape[iS];
4440       if ( eos._edges.empty() ) continue;
4441
4442       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4443       for ( size_t i = 0; i < eos._edges.size(); ++i )
4444       {
4445         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4446       }
4447     }
4448     dumpFunctionEnd();
4449
4450     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4451       return false;
4452
4453     // Improve and check quality
4454     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4455     {
4456       if ( nbSteps > 0 )
4457       {
4458 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4459         debugMsg("NOT INVALIDATED STEP!");
4460         return error("Smoothing failed", data._index);
4461 #endif
4462         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4463         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4464         {
4465           _EdgesOnShape& eos = data._edgesOnShape[iS];
4466           for ( size_t i = 0; i < eos._edges.size(); ++i )
4467             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4468         }
4469         dumpFunctionEnd();
4470       }
4471       break; // no more inflating possible
4472     }
4473     nbSteps++;
4474
4475     // Evaluate achieved thickness
4476     avgThick = 0;
4477     int nbActiveEdges = 0;
4478     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4479     {
4480       _EdgesOnShape& eos = data._edgesOnShape[iS];
4481       if ( eos._edges.empty() ) continue;
4482
4483       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4484       for ( size_t i = 0; i < eos._edges.size(); ++i )
4485       {
4486         avgThick      += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4487         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4488       }
4489     }
4490     avgThick /= data._n2eMap.size();
4491     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4492
4493 #ifdef BLOCK_INFLATION
4494     if ( nbActiveEdges == 0 )
4495     {
4496       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4497       break;
4498     }
4499 #else
4500     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4501     {
4502       debugMsg( "-- Stop inflation since "
4503                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4504                 << tgtThick * avgThick << " ) * " << safeFactor );
4505       break;
4506     }
4507 #endif
4508     // new step size
4509     limitStepSize( data, 0.25 * distToIntersection );
4510     if ( data._stepSizeNodes[0] )
4511       data._stepSize = data._stepSizeCoeff *
4512         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4513
4514   } // while ( avgThick < 0.99 )
4515
4516   if ( nbSteps == 0 )
4517     return error("failed at the very first inflation step", data._index);
4518
4519   if ( avgThick < 0.99 )
4520   {
4521     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4522     {
4523       data._proxyMesh->_warning.reset
4524         ( new SMESH_ComputeError (COMPERR_WARNING,
4525                                   SMESH_Comment("Thickness ") << tgtThick <<
4526                                   " of viscous layers not reached,"
4527                                   " average reached thickness is " << avgThick*tgtThick));
4528     }
4529   }
4530
4531   // Restore position of src nodes moved by inflation on _noShrinkShapes
4532   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4533   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4534   {
4535     _EdgesOnShape& eos = data._edgesOnShape[iS];
4536     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4537       for ( size_t i = 0; i < eos._edges.size(); ++i )
4538       {
4539         restoreNoShrink( *eos._edges[ i ] );
4540       }
4541   }
4542   dumpFunctionEnd();
4543
4544   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4545 }
4546
4547 //================================================================================
4548 /*!
4549  * \brief Improve quality of layer inner surface and check intersection
4550  */
4551 //================================================================================
4552
4553 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4554                                      const int   infStep,
4555                                      double &    distToIntersection)
4556 {
4557   if ( data._nbShapesToSmooth == 0 )
4558     return true; // no shapes needing smoothing
4559
4560   bool moved, improved;
4561   double vol;
4562   vector< _LayerEdge* >    movedEdges, badEdges;
4563   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4564   vector< bool >           isConcaveFace;
4565
4566   SMESH_MesherHelper helper(*_mesh);
4567   Handle(ShapeAnalysis_Surface) surface;
4568   TopoDS_Face F;
4569
4570   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4571   {
4572     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4573
4574     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4575     {
4576       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4577       if ( !eos._toSmooth ||
4578            eos.ShapeType() != shapeType ||
4579            eos._edges.empty() )
4580         continue;
4581
4582       // already smoothed?
4583       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4584       // if ( !toSmooth ) continue;
4585
4586       if ( !eos._hyp.ToSmooth() )
4587       {
4588         // smooth disabled by the user; check validy only
4589         if ( !isFace ) continue;
4590         badEdges.clear();
4591         for ( size_t i = 0; i < eos._edges.size(); ++i )
4592         {
4593           _LayerEdge* edge = eos._edges[i];
4594           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4595             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4596             {
4597               // debugMsg( "-- Stop inflation. Bad simplex ("
4598               //           << " "<< edge->_nodes[0]->GetID()
4599               //           << " "<< edge->_nodes.back()->GetID()
4600               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4601               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4602               // return false;
4603               badEdges.push_back( edge );
4604             }
4605         }
4606         if ( !badEdges.empty() )
4607         {
4608           eosC1.resize(1);
4609           eosC1[0] = &eos;
4610           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4611           if ( nbBad > 0 )
4612             return false;
4613         }
4614         continue; // goto the next EDGE or FACE
4615       }
4616
4617       // prepare data
4618       if ( eos.SWOLType() == TopAbs_FACE )
4619       {
4620         if ( !F.IsSame( eos._sWOL )) {
4621           F = TopoDS::Face( eos._sWOL );
4622           helper.SetSubShape( F );
4623           surface = helper.GetSurface( F );
4624         }
4625       }
4626       else
4627       {
4628         F.Nullify(); surface.Nullify();
4629       }
4630       const TGeomID sInd = eos._shapeID;
4631
4632       // perform smoothing
4633
4634       if ( eos.ShapeType() == TopAbs_EDGE )
4635       {
4636         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4637
4638         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4639         {
4640           // smooth on EDGE's (normally we should not get here)
4641           int step = 0;
4642           do {
4643             moved = false;
4644             for ( size_t i = 0; i < eos._edges.size(); ++i )
4645             {
4646               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4647             }
4648             dumpCmd( SMESH_Comment("# end step ")<<step);
4649           }
4650           while ( moved && step++ < 5 );
4651         }
4652         dumpFunctionEnd();
4653       }
4654
4655       else // smooth on FACE
4656       {
4657         eosC1.clear();
4658         eosC1.push_back( & eos );
4659         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4660
4661         movedEdges.clear();
4662         isConcaveFace.resize( eosC1.size() );
4663         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4664         {
4665           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4666           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4667           for ( size_t i = 0; i < edges.size(); ++i )
4668             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4669                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4670               movedEdges.push_back( edges[i] );
4671
4672           makeOffsetSurface( *eosC1[ iEOS ], helper );
4673         }
4674
4675         int step = 0, stepLimit = 5, nbBad = 0;
4676         while (( ++step <= stepLimit ) || improved )
4677         {
4678           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4679                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4680           int oldBadNb = nbBad;
4681           badEdges.clear();
4682
4683 #ifdef INCREMENTAL_SMOOTH
4684           bool findBest = false; // ( step == stepLimit );
4685           for ( size_t i = 0; i < movedEdges.size(); ++i )
4686           {
4687             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4688             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4689               badEdges.push_back( movedEdges[i] );
4690           }
4691 #else
4692           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4693           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4694           {
4695             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4696             for ( size_t i = 0; i < edges.size(); ++i )
4697             {
4698               edges[i]->Unset( _LayerEdge::SMOOTHED );
4699               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4700                 badEdges.push_back( eos._edges[i] );
4701             }
4702           }
4703 #endif
4704           nbBad = badEdges.size();
4705
4706           if ( nbBad > 0 )
4707             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4708
4709           if ( !badEdges.empty() && step >= stepLimit / 2 )
4710           {
4711             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4712               stepLimit = 9;
4713
4714             // resolve hard smoothing situation around concave VERTEXes
4715             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4716             {
4717               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4718               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4719                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4720                                                          step, badEdges );
4721             }
4722             // look for the best smooth of _LayerEdge's neighboring badEdges
4723             nbBad = 0;
4724             for ( size_t i = 0; i < badEdges.size(); ++i )
4725             {
4726               _LayerEdge* ledge = badEdges[i];
4727               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4728               {
4729                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4730                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4731               }
4732               ledge->Unset( _LayerEdge::SMOOTHED );
4733               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4734             }
4735             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4736           }
4737
4738           if ( nbBad == oldBadNb  &&
4739                nbBad > 0 &&
4740                step < stepLimit ) // smooth w/o chech of validity
4741           {
4742             dumpFunctionEnd();
4743             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4744                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4745             for ( size_t i = 0; i < movedEdges.size(); ++i )
4746             {
4747               movedEdges[i]->SmoothWoCheck();
4748             }
4749             if ( stepLimit < 9 )
4750               stepLimit++;
4751           }
4752
4753           improved = ( nbBad < oldBadNb );
4754
4755           dumpFunctionEnd();
4756
4757           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4758             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4759             {
4760               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4761             }
4762
4763         } // smoothing steps
4764
4765         // project -- to prevent intersections or fix bad simplices
4766         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4767         {
4768           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4769             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4770         }
4771
4772         //if ( !badEdges.empty() )
4773         {
4774           badEdges.clear();
4775           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4776           {
4777             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4778             {
4779               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4780
4781               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4782               edge->CheckNeiborsOnBoundary( & badEdges );
4783               if (( nbBad > 0 ) ||
4784                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4785               {
4786                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4787                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4788                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4789                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4790                   {
4791                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4792                              << " "<< tgtXYZ._node->GetID()
4793                              << " "<< edge->_simplices[j]._nPrev->GetID()
4794                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4795                     badEdges.push_back( edge );
4796                     break;
4797                   }
4798               }
4799             }
4800           }
4801
4802           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4803           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4804
4805           if ( nbBad > 0 )
4806             return false;
4807         }
4808
4809       } // // smooth on FACE's
4810     } // loop on shapes
4811   } // smooth on [ EDGEs, FACEs ]
4812
4813   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4814   eosC1.resize(1);
4815   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4816   {
4817     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4818     if ( eos.ShapeType() == TopAbs_FACE ||
4819          eos._edges.empty() ||
4820          !eos._sWOL.IsNull() )
4821       continue;
4822
4823     badEdges.clear();
4824     for ( size_t i = 0; i < eos._edges.size(); ++i )
4825     {
4826       _LayerEdge*      edge = eos._edges[i];
4827       if ( edge->_nodes.size() < 2 ) continue;
4828       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4829       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4830       //const gp_XYZ& prevXYZ = edge->PrevPos();
4831       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4832         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4833         {
4834           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4835                    << " "<< tgtXYZ._node->GetID()
4836                    << " "<< edge->_simplices[j]._nPrev->GetID()
4837                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4838           badEdges.push_back( edge );
4839           break;
4840         }
4841     }
4842
4843     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4844     eosC1[0] = &eos;
4845     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4846     if ( nbBad > 0 )
4847       return false;
4848   }
4849
4850
4851   // Check if the last segments of _LayerEdge intersects 2D elements;
4852   // checked elements are either temporary faces or faces on surfaces w/o the layers
4853
4854   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4855     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4856                                            data._proxyMesh->GetFaces( data._solid )) );
4857
4858 #ifdef BLOCK_INFLATION
4859   const bool toBlockInfaltion = true;
4860 #else
4861   const bool toBlockInfaltion = false;
4862 #endif
4863   distToIntersection = Precision::Infinite();
4864   double dist;
4865   const SMDS_MeshElement* intFace = 0;
4866   const SMDS_MeshElement* closestFace = 0;
4867   _LayerEdge* le = 0;
4868   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4869   {
4870     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4871     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4872       continue;
4873     for ( size_t i = 0; i < eos._edges.size(); ++i )
4874     {
4875       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4876            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4877         continue;
4878       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4879       {
4880         return false;
4881         // commented due to "Illegal hash-positionPosition" error in NETGEN
4882         // on Debian60 on viscous_layers_01/B2 case
4883         // Collision; try to deflate _LayerEdge's causing it
4884         // badEdges.clear();
4885         // badEdges.push_back( eos._edges[i] );
4886         // eosC1[0] = & eos;
4887         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4888         // if ( nbBad > 0 )
4889         //   return false;
4890
4891         // badEdges.clear();
4892         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4893         // {
4894         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4895         //   {
4896         //     const SMDS_MeshElement* srcFace =
4897         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4898         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4899         //     while ( nIt->more() )
4900         //     {
4901         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4902         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4903         //       if ( n2e != data._n2eMap.end() )
4904         //         badEdges.push_back( n2e->second );
4905         //     }
4906         //     eosC1[0] = eof;
4907         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4908         //     if ( nbBad > 0 )
4909         //       return false;
4910         //   }
4911         // }
4912         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4913         //   return false;
4914         // else
4915         //   continue;
4916       }
4917       if ( !intFace )
4918       {
4919         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4920         debugMsg( msg );
4921         continue;
4922       }
4923
4924       const bool isShorterDist = ( distToIntersection > dist );
4925       if ( toBlockInfaltion || isShorterDist )
4926       {
4927         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4928         // lying on this _ConvexFace
4929         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4930           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4931             continue;
4932
4933         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4934         // ( avoid limiting the thickness on the case of issue 22576)
4935         if ( intFace->getshapeId() == eos._shapeID  )
4936           continue;
4937
4938         // ignore intersection with intFace of an adjacent FACE
4939         if ( dist > 0 )
4940         {
4941           bool toIgnore = false;
4942           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4943           {
4944             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4945             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4946             {
4947               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4948               for ( ; !toIgnore && edge.More(); edge.Next() )
4949                 // is adjacent - has a common EDGE
4950                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4951
4952               if ( toIgnore ) // check angle between normals
4953               {
4954                 gp_XYZ normal;
4955                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4956                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4957               }
4958             }
4959           }
4960           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4961           {
4962             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4963             {
4964               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4965               toIgnore = ( nInd >= 0 );
4966             }
4967           }
4968           if ( toIgnore )
4969             continue;
4970         }
4971
4972         // intersection not ignored
4973
4974         if ( toBlockInfaltion &&
4975              dist < ( eos._edges[i]->_len * theThickToIntersection ))
4976         {
4977           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4978           eos._edges[i]->Block( data );                  // not to inflate
4979
4980           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4981           {
4982             // block _LayerEdge's, on top of which intFace is
4983             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4984             {
4985               const SMDS_MeshElement* srcFace =
4986                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4987               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4988               while ( nIt->more() )
4989               {
4990                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4991                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4992                 if ( n2e != data._n2eMap.end() )
4993                   n2e->second->Block( data );
4994               }
4995             }
4996           }
4997         }
4998
4999         if ( isShorterDist )
5000         {
5001           distToIntersection = dist;
5002           le = eos._edges[i];
5003           closestFace = intFace;
5004         }
5005
5006       } // if ( toBlockInfaltion || isShorterDist )
5007     } // loop on eos._edges
5008   } // loop on data._edgesOnShape
5009
5010   if ( closestFace && le )
5011   {
5012 #ifdef __myDEBUG
5013     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5014     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5015          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5016          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5017          << ") distance = " << distToIntersection<< endl;
5018 #endif
5019   }
5020
5021   return true;
5022 }
5023
5024 //================================================================================
5025 /*!
5026  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5027  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5028  *  \return int - resulting nb of bad _LayerEdge's
5029  */
5030 //================================================================================
5031
5032 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5033                                           SMESH_MesherHelper&       helper,
5034                                           vector< _LayerEdge* >&    badSmooEdges,
5035                                           vector< _EdgesOnShape* >& eosC1,
5036                                           const int                 infStep )
5037 {
5038   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5039
5040   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5041
5042   enum {
5043     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5044     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5045     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5046   };
5047   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5048
5049   double vol;
5050   bool haveInvalidated = true;
5051   while ( haveInvalidated )
5052   {
5053     haveInvalidated = false;
5054     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5055     {
5056       _LayerEdge*   edge = badSmooEdges[i];
5057       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5058       edge->Set( ADDED );
5059       bool invalidated = false;
5060       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5061       {
5062         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5063         edge->Block( data );
5064         edge->Set( INVALIDATED );
5065         edge->Unset( TO_INVALIDATE );
5066         invalidated = true;
5067         haveInvalidated = true;
5068       }
5069
5070       // look for _LayerEdge's of bad _simplices
5071       int nbBad = 0;
5072       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5073       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5074       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5075       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5076       {
5077         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5078             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5079           continue;
5080
5081         bool isBad = true;
5082         _LayerEdge* ee[2] = { 0,0 };
5083         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5084           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5085             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5086
5087         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5088         while ( maxNbSteps > edge->NbSteps() && isBad )
5089         {
5090           --maxNbSteps;
5091           for ( int iE = 0; iE < 2; ++iE )
5092           {
5093             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5094                  ee[ iE ]->NbSteps() > 1 )
5095             {
5096               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5097               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5098               ee[ iE ]->Block( data );
5099               ee[ iE ]->Set( INVALIDATED );
5100               haveInvalidated = true;
5101             }
5102           }
5103           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5104               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5105             isBad = false;
5106         }
5107         nbBad += isBad;
5108         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5109         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5110         ee[0]->Set( ADDED );
5111         ee[1]->Set( ADDED );
5112         if ( isBad )
5113         {
5114           ee[0]->Set( TO_INVALIDATE );
5115           ee[1]->Set( TO_INVALIDATE );
5116         }
5117       }
5118
5119       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5120       {
5121         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5122         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5123         edge->Block( data );
5124         edge->Set( INVALIDATED );
5125         edge->Unset( TO_INVALIDATE );
5126         haveInvalidated = true;
5127       }
5128     } // loop on badSmooEdges
5129   } // while ( haveInvalidated )
5130
5131   // re-smooth on analytical EDGEs
5132   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5133   {
5134     _LayerEdge* edge = badSmooEdges[i];
5135     if ( !edge->Is( INVALIDATED )) continue;
5136
5137     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5138     if ( eos->ShapeType() == TopAbs_VERTEX )
5139     {
5140       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5141       while ( const TopoDS_Shape* e = eIt->next() )
5142         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5143           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5144           {
5145             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5146             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5147             //   F       = TopoDS::Face( eoe->_sWOL );
5148             //   surface = helper.GetSurface( F );
5149             // }
5150             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5151             eoe->_edgeSmoother->_anaCurve.Nullify();
5152           }
5153     }
5154   }
5155
5156
5157   // check result of invalidation
5158
5159   int nbBad = 0;
5160   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5161   {
5162     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5163     {
5164       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5165       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5166       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5167       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5168       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5169         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5170         {
5171           ++nbBad;
5172           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5173                    << " "<< tgtXYZ._node->GetID()
5174                    << " "<< edge->_simplices[j]._nPrev->GetID()
5175                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5176         }
5177     }
5178   }
5179   dumpFunctionEnd();
5180
5181   return nbBad;
5182 }
5183
5184 //================================================================================
5185 /*!
5186  * \brief Create an offset surface
5187  */
5188 //================================================================================
5189
5190 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5191 {
5192   if ( eos._offsetSurf.IsNull() ||
5193        eos._edgeForOffset == 0 ||
5194        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5195     return;
5196
5197   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5198
5199   // find offset
5200   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5201   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5202   double offset = baseSurface->Gap();
5203
5204   eos._offsetSurf.Nullify();
5205
5206   try
5207   {
5208     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5209     if ( !offsetMaker.IsDone() ) return;
5210
5211     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5212     if ( !fExp.More() ) return;
5213
5214     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5215     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5216     if ( surf.IsNull() ) return;
5217
5218     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5219   }
5220   catch ( Standard_Failure )
5221   {
5222   }
5223 }
5224
5225 //================================================================================
5226 /*!
5227  * \brief Put nodes of a curved FACE to its offset surface
5228  */
5229 //================================================================================
5230
5231 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5232                                           int                       infStep,
5233                                           vector< _EdgesOnShape* >& eosC1,
5234                                           int                       smooStep,
5235                                           bool                      moveAll )
5236 {
5237   _EdgesOnShape * eof = & eos;
5238   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5239   {
5240     eof = 0;
5241     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5242     {
5243       if ( eosC1[i]->_offsetSurf.IsNull() ||
5244            eosC1[i]->ShapeType() != TopAbs_FACE ||
5245            eosC1[i]->_edgeForOffset == 0 ||
5246            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5247         continue;
5248       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5249         eof = eosC1[i];
5250     }
5251   }
5252   if ( !eof ||
5253        eof->_offsetSurf.IsNull() ||
5254        eof->ShapeType() != TopAbs_FACE ||
5255        eof->_edgeForOffset == 0 ||
5256        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5257     return;
5258
5259   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5260   for ( size_t i = 0; i < eos._edges.size(); ++i )
5261   {
5262     _LayerEdge* edge = eos._edges[i];
5263     edge->Unset( _LayerEdge::MARKED );
5264     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5265       continue;
5266     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5267         continue;
5268
5269     int nbBlockedAround = 0;
5270     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5271       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5272     if ( nbBlockedAround > 1 )
5273       continue;
5274
5275     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5276     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5277     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5278     edge->_curvature->_uv = uv;
5279     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5280
5281     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5282     gp_XYZ prevP = edge->PrevCheckPos();
5283     bool      ok = true;
5284     if ( !moveAll )
5285       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5286       {
5287         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5288       }
5289     if ( ok )
5290     {
5291       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5292       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5293       edge->_pos.back() = newP;
5294
5295       edge->Set( _LayerEdge::MARKED );
5296     }
5297   }
5298
5299 #ifdef _DEBUG_
5300   // dumpMove() for debug
5301   size_t i = 0;
5302   for ( ; i < eos._edges.size(); ++i )
5303     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5304       break;
5305   if ( i < eos._edges.size() )
5306   {
5307     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5308                  << "_InfStep" << infStep << "_" << smooStep );
5309     for ( ; i < eos._edges.size(); ++i )
5310     {
5311       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5312         dumpMove( eos._edges[i]->_nodes.back() );
5313     }
5314     dumpFunctionEnd();
5315   }
5316 #endif
5317 }
5318
5319 //================================================================================
5320 /*!
5321  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5322  *        _LayerEdge's to be in a consequent order
5323  */
5324 //================================================================================
5325
5326 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5327                                                 _EdgesOnShape&      eos,
5328                                                 SMESH_MesherHelper& helper)
5329 {
5330   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5331
5332   TopLoc_Location loc; double f,l;
5333
5334   Handle(Geom_Line)   line;
5335   Handle(Geom_Circle) circle;
5336   bool isLine, isCirc;
5337   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5338   {
5339     // check if the EDGE is a line
5340     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5341     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5342       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5343
5344     line   = Handle(Geom_Line)::DownCast( curve );
5345     circle = Handle(Geom_Circle)::DownCast( curve );
5346     isLine = (!line.IsNull());
5347     isCirc = (!circle.IsNull());
5348
5349     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5350     {
5351       isLine = SMESH_Algo::IsStraight( E );
5352
5353       if ( isLine )
5354         line = new Geom_Line( gp::OX() ); // only type does matter
5355     }
5356     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5357     {
5358       // TODO
5359     }
5360   }
5361   else //////////////////////////////////////////////////////////////////////// 2D case
5362   {
5363     if ( !eos._isRegularSWOL ) // 23190
5364       return NULL;
5365
5366     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5367
5368     // check if the EDGE is a line
5369     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5370     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5371       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5372
5373     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5374     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5375     isLine = (!line2d.IsNull());
5376     isCirc = (!circle2d.IsNull());
5377
5378     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5379     {
5380       Bnd_B2d bndBox;
5381       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5382       while ( nIt->more() )
5383         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5384       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5385
5386       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5387       for ( int i = 0; i < 2 && !isLine; ++i )
5388         isLine = ( size.Coord( i+1 ) <= lineTol );
5389     }
5390     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5391     {
5392       // TODO
5393     }
5394     if ( isLine )
5395     {
5396       line = new Geom_Line( gp::OX() ); // only type does matter
5397     }
5398     else if ( isCirc )
5399     {
5400       gp_Pnt2d p = circle2d->Location();
5401       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5402       circle = new Geom_Circle( ax, 1.); // only center position does matter
5403     }
5404   }
5405
5406   if ( isLine )
5407     return line;
5408   if ( isCirc )
5409     return circle;
5410
5411   return Handle(Geom_Curve)();
5412 }
5413
5414 //================================================================================
5415 /*!
5416  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5417  */
5418 //================================================================================
5419
5420 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5421                                       Handle(ShapeAnalysis_Surface)& surface,
5422                                       const TopoDS_Face&             F,
5423                                       SMESH_MesherHelper&            helper)
5424 {
5425   if ( !isAnalytic() ) return false;
5426
5427   const size_t iFrom = 0, iTo = _eos._edges.size();
5428
5429   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5430   {
5431     if ( F.IsNull() ) // 3D
5432     {
5433       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5434       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5435       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5436       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5437       gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5438       _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5439       _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5440       bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5441                          vLE0->Is( _LayerEdge::BLOCKED ) ||
5442                          vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5443                          vLE1->Is( _LayerEdge::BLOCKED ));
5444       for ( size_t i = iFrom; i < iTo; ++i )
5445       {
5446         _LayerEdge*       edge = _eos._edges[i];
5447         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5448         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5449
5450         if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5451         {
5452           gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5453           double  shift = ( lineDir * ( newPos - pSrc0 ) -
5454                             lineDir * ( curPos - pSrc0 ));
5455           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5456         }
5457         if ( edge->Is( _LayerEdge::BLOCKED ))
5458         {
5459           SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5460           double curThick = pSrc.SquareDistance( tgtNode );
5461           double newThink = ( pSrc - newPos ).SquareModulus();
5462           if ( newThink > curThick )
5463             continue;
5464         }
5465         edge->_pos.back() = newPos;
5466         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5467         dumpMove( tgtNode );
5468       }
5469     }
5470     else // 2D
5471     {
5472       _LayerEdge* e0 = getLEdgeOnV( 0 );
5473       _LayerEdge* e1 = getLEdgeOnV( 1 );
5474       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5475       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5476       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5477       {
5478         int iPeriodic = helper.GetPeriodicIndex();
5479         if ( iPeriodic == 1 || iPeriodic == 2 )
5480         {
5481           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5482           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5483             std::swap( uv0, uv1 );
5484         }
5485       }
5486       const gp_XY rangeUV = uv1 - uv0;
5487       for ( size_t i = iFrom; i < iTo; ++i )
5488       {
5489         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5490         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5491         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5492
5493         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5494         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5495         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5496         dumpMove( tgtNode );
5497
5498         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5499         pos->SetUParameter( newUV.X() );
5500         pos->SetVParameter( newUV.Y() );
5501       }
5502     }
5503     return true;
5504   }
5505
5506   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5507   {
5508     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5509     gp_Pnt center3D = circle->Location();
5510
5511     if ( F.IsNull() ) // 3D
5512     {
5513       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5514         return true; // closed EDGE - nothing to do
5515
5516       // circle is a real curve of EDGE
5517       gp_Circ circ = circle->Circ();
5518
5519       // new center is shifted along its axis
5520       const gp_Dir& axis = circ.Axis().Direction();
5521       _LayerEdge*     e0 = getLEdgeOnV(0);
5522       _LayerEdge*     e1 = getLEdgeOnV(1);
5523       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5524       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5525       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5526       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5527       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5528
5529       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5530
5531       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5532       gp_Circ newCirc( newAxis, newRadius );
5533       gp_Vec  vecC1  ( newCenter, p1 );
5534
5535       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5536       if ( uLast < 0 )
5537         uLast += 2 * M_PI;
5538       
5539       for ( size_t i = iFrom; i < iTo; ++i )
5540       {
5541         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5542         double u = uLast * _leParams[i];
5543         gp_Pnt p = ElCLib::Value( u, newCirc );
5544         _eos._edges[i]->_pos.back() = p.XYZ();
5545
5546         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5547         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5548         dumpMove( tgtNode );
5549       }
5550       return true;
5551     }
5552     else // 2D
5553     {
5554       const gp_XY center( center3D.X(), center3D.Y() );
5555
5556       _LayerEdge* e0 = getLEdgeOnV(0);
5557       _LayerEdge* eM = _eos._edges[ 0 ];
5558       _LayerEdge* e1 = getLEdgeOnV(1);
5559       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5560       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5561       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5562       gp_Vec2d vec0( center, uv0 );
5563       gp_Vec2d vecM( center, uvM );
5564       gp_Vec2d vec1( center, uv1 );
5565       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5566       double uMidl = vec0.Angle( vecM );
5567       if ( uLast * uMidl <= 0. )
5568         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5569       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5570
5571       gp_Ax2d   axis( center, vec0 );
5572       gp_Circ2d circ( axis, radius );
5573       for ( size_t i = iFrom; i < iTo; ++i )
5574       {
5575         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5576         double    newU = uLast * _leParams[i];
5577         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5578         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5579
5580         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5581         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5582         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5583         dumpMove( tgtNode );
5584
5585         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5586         pos->SetUParameter( newUV.X() );
5587         pos->SetVParameter( newUV.Y() );
5588       }
5589     }
5590     return true;
5591   }
5592
5593   return false;
5594 }
5595
5596 //================================================================================
5597 /*!
5598  * \brief smooth _LayerEdge's on a an EDGE
5599  */
5600 //================================================================================
5601
5602 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5603                                      Handle(ShapeAnalysis_Surface)& surface,
5604                                      const TopoDS_Face&             F,
5605                                      SMESH_MesherHelper&            helper)
5606 {
5607   if ( _offPoints.empty() )
5608     return false;
5609
5610   // move _offPoints along normals of _LayerEdge's
5611
5612   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5613   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5614     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5615   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5616     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5617   _leOnV[0]._len = e[0]->_len;
5618   _leOnV[1]._len = e[1]->_len;
5619   for ( size_t i = 0; i < _offPoints.size(); i++ )
5620   {
5621     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5622     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5623     const double w0 = _offPoints[i]._2edges._wgt[0];
5624     const double w1 = _offPoints[i]._2edges._wgt[1];
5625     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5626     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5627     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5628     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5629          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5630       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5631
5632     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5633     _offPoints[i]._len  = avgLen;
5634   }
5635
5636   double fTol = 0;
5637   if ( !surface.IsNull() ) // project _offPoints to the FACE
5638   {
5639     fTol = 100 * BRep_Tool::Tolerance( F );
5640     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5641
5642     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5643     //if ( surface->Gap() < 0.5 * segLen )
5644       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5645
5646     for ( size_t i = 1; i < _offPoints.size(); ++i )
5647     {
5648       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5649       //if ( surface->Gap() < 0.5 * segLen )
5650         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5651     }
5652   }
5653
5654   // project tgt nodes of extreme _LayerEdge's to the offset segments
5655
5656   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5657   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5658
5659   gp_Pnt pExtreme[2], pProj[2];
5660   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5661   {
5662     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5663     int  i = _iSeg[ is2nd ];
5664     int di = is2nd ? -1 : +1;
5665     bool projected = false;
5666     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5667     int nbWorse = 0;
5668     do {
5669       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5670       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5671       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5672       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5673       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5674       if ( dist < distMin || projected )
5675       {
5676         _iSeg[ is2nd ] = i;
5677         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5678         distMin = dist;
5679       }
5680       else if ( dist > distPrev )
5681       {
5682         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5683           break;
5684       }
5685       distPrev = dist;
5686       i += di;
5687     }
5688     while ( !projected &&
5689             i >= 0 && i+1 < (int)_offPoints.size() );
5690
5691     if ( !projected )
5692     {
5693       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5694       {
5695         _iSeg[0] = 0;
5696         _iSeg[1] = _offPoints.size()-2;
5697         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5698         return false;
5699       }
5700     }
5701   }
5702   if ( _iSeg[0] > _iSeg[1] )
5703   {
5704     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5705     return false;
5706   }
5707
5708   // adjust length of extreme LE (test viscous_layers_01/B7)
5709   gp_Vec vDiv0( pExtreme[0], pProj[0] );
5710   gp_Vec vDiv1( pExtreme[1], pProj[1] );
5711   double d0 = vDiv0.Magnitude();
5712   double d1 = vDiv1.Magnitude();
5713   if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5714   else                                   e[0]->_len -= d0;
5715   if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5716   else                                   e[1]->_len -= d1;
5717
5718   // compute normalized length of the offset segments located between the projections
5719
5720   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5721   vector< double > len( nbSeg + 1 );
5722   len[ iSeg++ ] = 0;
5723   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5724   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5725   {
5726     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5727   }
5728   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5729
5730   // d0 *= e[0]->_lenFactor;
5731   // d1 *= e[1]->_lenFactor;
5732   double fullLen = len.back() - d0 - d1;
5733   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5734     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5735
5736   // temporary replace extreme _offPoints by pExtreme
5737   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5738                    _offPoints[ _iSeg[1]+1 ]._xyz };
5739   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5740   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5741
5742   // distribute tgt nodes of _LayerEdge's between the projections
5743
5744   iSeg = 0;
5745   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5746   {
5747     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5748     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5749       iSeg++;
5750     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5751     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5752                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5753
5754     if ( surface.IsNull() )
5755     {
5756       _eos._edges[i]->_pos.back() = p;
5757     }
5758     else // project a new node position to a FACE
5759     {
5760       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5761       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5762
5763       p = surface->Value( uv2 ).XYZ();
5764       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5765     }
5766     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5767     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5768     dumpMove( tgtNode );
5769   }
5770
5771   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5772   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5773
5774   return true;
5775 }
5776
5777 //================================================================================
5778 /*!
5779  * \brief Prepare for smoothing
5780  */
5781 //================================================================================
5782
5783 void _Smoother1D::prepare(_SolidData& data)
5784 {
5785   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5786   _curveLen = SMESH_Algo::EdgeLength( E );
5787
5788   // sort _LayerEdge's by position on the EDGE
5789   data.SortOnEdge( E, _eos._edges );
5790
5791   // compute normalized param of _eos._edges on EDGE
5792   _leParams.resize( _eos._edges.size() + 1 );
5793   {
5794     double curLen;
5795     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5796     _leParams[0] = 0;
5797     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5798     {
5799       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5800       curLen         = p.Distance( pPrev );
5801       _leParams[i+1] = _leParams[i] + curLen;
5802       pPrev          = p;
5803     }
5804     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5805     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5806       _leParams[i] = _leParams[i+1] / fullLen;
5807   }
5808
5809   if ( isAnalytic() )
5810     return;
5811
5812   // divide E to have offset segments with low deflection
5813   BRepAdaptor_Curve c3dAdaptor( E );
5814   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5815   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5816   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5817   if ( discret.NbPoints() <= 2 )
5818   {
5819     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5820     return;
5821   }
5822
5823   const double u0 = c3dAdaptor.FirstParameter();
5824   gp_Pnt p; gp_Vec tangent;
5825   _offPoints.resize( discret.NbPoints() );
5826   for ( size_t i = 0; i < _offPoints.size(); i++ )
5827   {
5828     double u = discret.Parameter( i+1 );
5829     c3dAdaptor.D1( u, p, tangent );
5830     _offPoints[i]._xyz     = p.XYZ();
5831     _offPoints[i]._edgeDir = tangent.XYZ();
5832     _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5833   }
5834
5835   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5836
5837   // set _2edges
5838   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5839   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5840   _2NearEdges tmp2edges;
5841   tmp2edges._edges[1] = _eos._edges[0];
5842   _leOnV[0]._2neibors = & tmp2edges;
5843   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5844   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5845   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5846   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5847   {
5848     // find _LayerEdge's located before and after an offset point
5849     // (_eos._edges[ iLE ] is next after ePrev)
5850     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5851       ePrev = _eos._edges[ iLE++ ];
5852     eNext = ePrev->_2neibors->_edges[1];
5853
5854     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5855     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5856     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5857     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5858   }
5859
5860   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5861   for ( size_t i = 0; i < _offPoints.size(); i++ )
5862     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5863       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5864     else break;
5865   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5866     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5867       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5868     else break;
5869
5870   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5871
5872   int iLBO = _offPoints.size() - 2; // last but one
5873
5874   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5875   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5876
5877   _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5878   _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5879   _leOnV[ 0 ]._len = 0;
5880   _leOnV[ 1 ]._len = 0;
5881   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5882   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5883
5884   _iSeg[0] = 0;
5885   _iSeg[1] = _offPoints.size()-2;
5886
5887   // initialize OffPnt::_len
5888   for ( size_t i = 0; i < _offPoints.size(); ++i )
5889     _offPoints[i]._len = 0;
5890
5891   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5892   {
5893     _leOnV[0]._len = leOnV[0]->_len;
5894     _leOnV[1]._len = leOnV[1]->_len;
5895     for ( size_t i = 0; i < _offPoints.size(); i++ )
5896     {
5897       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5898       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5899       const double w0 = _offPoints[i]._2edges._wgt[0];
5900       const double w1 = _offPoints[i]._2edges._wgt[1];
5901       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5902       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5903                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5904       _offPoints[i]._xyz = avgXYZ;
5905       _offPoints[i]._len = avgLen;
5906     }
5907   }
5908 }
5909
5910 //================================================================================
5911 /*!
5912  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5913  */
5914 //================================================================================
5915
5916 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5917                                      const gp_XYZ&  edgeDir)
5918 {
5919   gp_XYZ cross = normal ^ edgeDir;
5920   gp_XYZ  norm = edgeDir ^ cross;
5921   double  size = norm.Modulus();
5922
5923   return norm / size;
5924 }
5925
5926 //================================================================================
5927 /*!
5928  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5929  */
5930 //================================================================================
5931
5932 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5933                              vector< _LayerEdge* >& edges)
5934 {
5935   map< double, _LayerEdge* > u2edge;
5936   for ( size_t i = 0; i < edges.size(); ++i )
5937     u2edge.insert( u2edge.end(),
5938                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5939
5940   ASSERT( u2edge.size() == edges.size() );
5941   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5942   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5943     edges[i] = u2e->second;
5944
5945   Sort2NeiborsOnEdge( edges );
5946 }
5947
5948 //================================================================================
5949 /*!
5950  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5951  */
5952 //================================================================================
5953
5954 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5955 {
5956   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5957
5958   for ( size_t i = 0; i < edges.size()-1; ++i )
5959     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5960       edges[i]->_2neibors->reverse();
5961
5962   const size_t iLast = edges.size() - 1;
5963   if ( edges.size() > 1 &&
5964        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5965     edges[iLast]->_2neibors->reverse();
5966 }
5967
5968 //================================================================================
5969 /*!
5970  * \brief Return _EdgesOnShape* corresponding to the shape
5971  */
5972 //================================================================================
5973
5974 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5975 {
5976   if ( shapeID < (int)_edgesOnShape.size() &&
5977        _edgesOnShape[ shapeID ]._shapeID == shapeID )
5978     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5979
5980   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5981     if ( _edgesOnShape[i]._shapeID == shapeID )
5982       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5983
5984   return 0;
5985 }
5986
5987 //================================================================================
5988 /*!
5989  * \brief Return _EdgesOnShape* corresponding to the shape
5990  */
5991 //================================================================================
5992
5993 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5994 {
5995   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5996   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5997 }
5998
5999 //================================================================================
6000 /*!
6001  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6002  */
6003 //================================================================================
6004
6005 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6006 {
6007   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6008
6009   set< TGeomID > vertices;
6010   TopoDS_Face F;
6011   if ( eos->ShapeType() == TopAbs_FACE )
6012   {
6013     // check FACE concavity and get concave VERTEXes
6014     F = TopoDS::Face( eos->_shape );
6015     if ( isConcave( F, helper, &vertices ))
6016       _concaveFaces.insert( eos->_shapeID );
6017
6018     // set eos._eosConcaVer
6019     eos->_eosConcaVer.clear();
6020     eos->_eosConcaVer.reserve( vertices.size() );
6021     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6022     {
6023       _EdgesOnShape* eov = GetShapeEdges( *v );
6024       if ( eov && eov->_edges.size() == 1 )
6025       {
6026         eos->_eosConcaVer.push_back( eov );
6027         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6028           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6029       }
6030     }
6031
6032     // SetSmooLen() to _LayerEdge's on FACE
6033     for ( size_t i = 0; i < eos->_edges.size(); ++i )
6034     {
6035       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6036     }
6037     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6038     while ( smIt->more() ) // loop on sub-shapes of the FACE
6039     {
6040       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6041       if ( !eoe ) continue;
6042
6043       vector<_LayerEdge*>& eE = eoe->_edges;
6044       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6045       {
6046         if ( eE[iE]->_cosin <= theMinSmoothCosin )
6047           continue;
6048
6049         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6050         while ( segIt->more() )
6051         {
6052           const SMDS_MeshElement* seg = segIt->next();
6053           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6054             continue;
6055           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6056             continue; // not to check a seg twice
6057           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6058           {
6059             _LayerEdge* eN = eE[iE]->_neibors[iN];
6060             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6061               continue;
6062             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6063             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6064             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6065             eN->Set( _LayerEdge::NEAR_BOUNDARY );
6066           }
6067         }
6068       }
6069     }
6070   } // if ( eos->ShapeType() == TopAbs_FACE )
6071
6072   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6073   {
6074     eos->_edges[i]->_smooFunction = 0;
6075     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6076   }
6077   bool isCurved = false;
6078   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6079   {
6080     _LayerEdge* edge = eos->_edges[i];
6081
6082     // get simplices sorted
6083     _Simplex::SortSimplices( edge->_simplices );
6084
6085     // smoothing function
6086     edge->ChooseSmooFunction( vertices, _n2eMap );
6087
6088     // set _curvature
6089     double avgNormProj = 0, avgLen = 0;
6090     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6091     {
6092       _Simplex& s = edge->_simplices[iS];
6093
6094       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6095       avgNormProj += edge->_normal * vec;
6096       avgLen      += vec.Modulus();
6097       if ( substituteSrcNodes )
6098       {
6099         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6100         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6101       }
6102     }
6103     avgNormProj /= edge->_simplices.size();
6104     avgLen      /= edge->_simplices.size();
6105     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6106     {
6107       isCurved = true;
6108       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6109       if ( !fPos )
6110         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6111           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6112       if ( fPos )
6113         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6114     }
6115   }
6116
6117   // prepare for putOnOffsetSurface()
6118   if (( eos->ShapeType() == TopAbs_FACE ) &&
6119       ( isCurved || !eos->_eosConcaVer.empty() ))
6120   {
6121     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6122     eos->_edgeForOffset = 0;
6123
6124     double maxCosin = -1;
6125     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6126     {
6127       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6128       if ( !eoe || eoe->_edges.empty() ) continue;
6129
6130       vector<_LayerEdge*>& eE = eoe->_edges;
6131       _LayerEdge* e = eE[ eE.size() / 2 ];
6132       if ( e->_cosin > maxCosin )
6133       {
6134         eos->_edgeForOffset = e;
6135         maxCosin = e->_cosin;
6136       }
6137     }
6138   }
6139 }
6140
6141 //================================================================================
6142 /*!
6143  * \brief Add faces for smoothing
6144  */
6145 //================================================================================
6146
6147 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6148                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6149 {
6150   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6151   for ( ; eos != eosToSmooth.end(); ++eos )
6152   {
6153     if ( !*eos || (*eos)->_toSmooth ) continue;
6154
6155     (*eos)->_toSmooth = true;
6156
6157     if ( (*eos)->ShapeType() == TopAbs_FACE )
6158     {
6159       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6160       (*eos)->_toSmooth = true;
6161     }
6162   }
6163
6164   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6165   if ( edgesNoAnaSmooth )
6166     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6167     {
6168       if ( (*eos)->_edgeSmoother )
6169         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6170     }
6171 }
6172
6173 //================================================================================
6174 /*!
6175  * \brief Limit _LayerEdge::_maxLen according to local curvature
6176  */
6177 //================================================================================
6178
6179 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6180 {
6181   // find intersection of neighbor _LayerEdge's to limit _maxLen
6182   // according to local curvature (IPAL52648)
6183
6184   // This method must be called after findCollisionEdges() where _LayerEdge's
6185   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6186
6187   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6188   {
6189     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6190     if ( eosI._edges.empty() ) continue;
6191     if ( !eosI._hyp.ToSmooth() )
6192     {
6193       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6194       {
6195         _LayerEdge* eI = eosI._edges[i];
6196         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6197         {
6198           _LayerEdge* eN = eI->_neibors[iN];
6199           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6200           {
6201             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6202             limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6203           }
6204         }
6205       }
6206     }
6207     else if ( eosI.ShapeType() == TopAbs_EDGE )
6208     {
6209       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6210       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6211
6212       _LayerEdge* e0 = eosI._edges[0];
6213       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6214       {
6215         _LayerEdge* eI = eosI._edges[i];
6216         limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6217         e0 = eI;
6218       }
6219     }
6220   }
6221 }
6222
6223 //================================================================================
6224 /*!
6225  * \brief Limit _LayerEdge::_maxLen according to local curvature
6226  */
6227 //================================================================================
6228
6229 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*         e1,
6230                                               _LayerEdge*         e2,
6231                                               _EdgesOnShape&      eos1,
6232                                               _EdgesOnShape&      eos2,
6233                                               SMESH_MesherHelper& helper )
6234 {
6235   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6236   double norSize = plnNorm.SquareModulus();
6237   if ( norSize < std::numeric_limits<double>::min() )
6238     return; // parallel normals
6239
6240   // find closest points of skew _LayerEdge's
6241   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6242   gp_XYZ dir12 = src2 - src1;
6243   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6244   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6245   double  dot1 = perp2 * e1->_normal;
6246   double  dot2 = perp1 * e2->_normal;
6247   double    u1 =   ( perp2 * dir12 ) / dot1;
6248   double    u2 = - ( perp1 * dir12 ) / dot2;
6249   if ( u1 > 0 && u2 > 0 )
6250   {
6251     double ovl = ( u1 * e1->_normal * dir12 -
6252                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6253     if ( ovl > theSmoothThickToElemSizeRatio )
6254     {    
6255       e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6256       e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6257     }
6258   }
6259 }
6260
6261 //================================================================================
6262 /*!
6263  * \brief Fill data._collisionEdges
6264  */
6265 //================================================================================
6266
6267 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6268 {
6269   data._collisionEdges.clear();
6270
6271   // set the full thickness of the layers to LEs
6272   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6273   {
6274     _EdgesOnShape& eos = data._edgesOnShape[iS];
6275     if ( eos._edges.empty() ) continue;
6276     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6277
6278     for ( size_t i = 0; i < eos._edges.size(); ++i )
6279     {
6280       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6281       double maxLen = eos._edges[i]->_maxLen;
6282       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6283       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6284       eos._edges[i]->_maxLen = maxLen;
6285     }
6286   }
6287
6288   // make temporary quadrangles got by extrusion of
6289   // mesh edges along _LayerEdge._normal's
6290
6291   vector< const SMDS_MeshElement* > tmpFaces;
6292
6293   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6294   {
6295     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6296     if ( eos.ShapeType() != TopAbs_EDGE )
6297       continue;
6298     if ( eos._edges.empty() )
6299     {
6300       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6301       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6302       while ( smIt->more() )
6303         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6304           if ( eov->_edges.size() == 1 )
6305             edge[ bool( edge[0]) ] = eov->_edges[0];
6306
6307       if ( edge[1] )
6308       {
6309         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6310         tmpFaces.push_back( f );
6311       }
6312     }
6313     for ( size_t i = 0; i < eos._edges.size(); ++i )
6314     {
6315       _LayerEdge* edge = eos._edges[i];
6316       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6317       {
6318         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6319         if ( src2->GetPosition()->GetDim() > 0 &&
6320              src2->GetID() < edge->_nodes[0]->GetID() )
6321           continue; // avoid using same segment twice
6322
6323         // a _LayerEdge containg tgt2
6324         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6325
6326         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6327         tmpFaces.push_back( f );
6328       }
6329     }
6330   }
6331
6332   // Find _LayerEdge's intersecting tmpFaces.
6333
6334   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6335                                                             tmpFaces.end()));
6336   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6337     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6338
6339   double dist1, dist2, segLen, eps = 0.5;
6340   _CollisionEdges collEdges;
6341   vector< const SMDS_MeshElement* > suspectFaces;
6342   const double angle45 = Cos( 45. * M_PI / 180. );
6343
6344   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6345   {
6346     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6347     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6348       continue;
6349     // find sub-shapes whose VL can influence VL on eos
6350     set< TGeomID > neighborShapes;
6351     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6352     while ( const TopoDS_Shape* face = fIt->next() )
6353     {
6354       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6355       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6356       {
6357         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6358         while ( subIt->more() )
6359           neighborShapes.insert( subIt->next()->GetId() );
6360       }
6361     }
6362     if ( eos.ShapeType() == TopAbs_VERTEX )
6363     {
6364       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6365       while ( const TopoDS_Shape* edge = eIt->next() )
6366         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6367     }
6368     // find intersecting _LayerEdge's
6369     for ( size_t i = 0; i < eos._edges.size(); ++i )
6370     {
6371       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6372       _LayerEdge*   edge = eos._edges[i];
6373       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6374       segLen *= 1.2;
6375
6376       gp_Vec eSegDir0, eSegDir1;
6377       if ( edge->IsOnEdge() )
6378       {
6379         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6380         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6381         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6382       }
6383       suspectFaces.clear();
6384       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6385                                      SMDSAbs_Face, suspectFaces );
6386       collEdges._intEdges.clear();
6387       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6388       {
6389         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6390         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6391         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6392         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6393         if ( edge->IsOnEdge() ) {
6394           if ( edge->_2neibors->include( f->_le1 ) ||
6395                edge->_2neibors->include( f->_le2 )) continue;
6396         }
6397         else {
6398           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6399               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6400         }
6401         dist1 = dist2 = Precision::Infinite();
6402         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6403           dist1 = Precision::Infinite();
6404         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6405           dist2 = Precision::Infinite();
6406         if (( dist1 > segLen ) && ( dist2 > segLen ))
6407           continue;
6408
6409         if ( edge->IsOnEdge() )
6410         {
6411           // skip perpendicular EDGEs
6412           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6413           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6414                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6415                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6416                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6417           if ( !isParallel )
6418             continue;
6419         }
6420
6421         // either limit inflation of edges or remember them for updating _normal
6422         // double dot = edge->_normal * f->GetDir();
6423         // if ( dot > 0.1 )
6424         {
6425           collEdges._intEdges.push_back( f->_le1 );
6426           collEdges._intEdges.push_back( f->_le2 );
6427         }
6428         // else
6429         // {
6430         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6431         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6432         // }
6433       }
6434
6435       if ( !collEdges._intEdges.empty() )
6436       {
6437         collEdges._edge = edge;
6438         data._collisionEdges.push_back( collEdges );
6439       }
6440     }
6441   }
6442
6443   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6444     delete tmpFaces[i];
6445
6446   // restore the zero thickness
6447   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6448   {
6449     _EdgesOnShape& eos = data._edgesOnShape[iS];
6450     if ( eos._edges.empty() ) continue;
6451     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6452
6453     for ( size_t i = 0; i < eos._edges.size(); ++i )
6454     {
6455       eos._edges[i]->InvalidateStep( 1, eos );
6456       eos._edges[i]->_len = 0;
6457     }
6458   }
6459 }
6460
6461 //================================================================================
6462 /*!
6463  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6464  * _LayerEdge's on neighbor EDGE's
6465  */
6466 //================================================================================
6467
6468 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6469                                      SMESH_MesherHelper& helper,
6470                                      int                 stepNb,
6471                                      double              stepSize)
6472 {
6473   updateNormalsOfC1Vertices( data );
6474
6475   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6476     return false;
6477
6478   // map to store new _normal and _cosin for each intersected edge
6479   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6480   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6481   _LayerEdge zeroEdge;
6482   zeroEdge._normal.SetCoord( 0,0,0 );
6483   zeroEdge._maxLen = Precision::Infinite();
6484   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6485
6486   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6487
6488   double segLen, dist1, dist2, dist;
6489   vector< pair< _LayerEdge*, double > > intEdgesDist;
6490   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6491
6492   for ( int iter = 0; iter < 5; ++iter )
6493   {
6494     edge2newEdge.clear();
6495
6496     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6497     {
6498       _CollisionEdges& ce = data._collisionEdges[iE];
6499       _LayerEdge*   edge1 = ce._edge;
6500       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6501       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6502       if ( !eos1 ) continue;
6503
6504       // detect intersections
6505       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6506       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6507       double     eps = 0.5;
6508       intEdgesDist.clear();
6509       double minIntDist = Precision::Infinite();
6510       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6511       {
6512         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6513              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6514              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6515           continue;
6516         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6517         double fact = ( 1.1 + dot * dot );
6518         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6519         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6520         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6521         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6522         dist1 = dist2 = Precision::Infinite();
6523         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
6524              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6525           continue;
6526         dist = dist1;
6527         if ( dist > testLen || dist <= 0 )
6528         {
6529           dist = dist2;
6530           if ( dist > testLen || dist <= 0 )
6531             continue;
6532         }
6533         // choose a closest edge
6534         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6535         double d1 = intP.SquareDistance( pSrc0 );
6536         double d2 = intP.SquareDistance( pSrc1 );
6537         int iClose = i + ( d2 < d1 );
6538         _LayerEdge* edge2 = ce._intEdges[iClose];
6539         edge2->Unset( _LayerEdge::MARKED );
6540
6541         // choose a closest edge among neighbors
6542         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6543         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6544         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6545         {
6546           _LayerEdge * edgeJ = intEdgesDist[j].first;
6547           if ( edge2->IsNeiborOnEdge( edgeJ ))
6548           {
6549             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6550             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6551           }
6552         }
6553         intEdgesDist.push_back( make_pair( edge2, dist ));
6554         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6555         // {
6556         //   iClose = i + !( d2 < d1 );
6557         //   intEdges.push_back( ce._intEdges[iClose] );
6558         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6559         // }
6560         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6561       }
6562
6563       //ce._edge = 0;
6564
6565       // compute new _normals
6566       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6567       {
6568         _LayerEdge* edge2    = intEdgesDist[i].first;
6569         double       distWgt = edge1->_len / intEdgesDist[i].second;
6570         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6571         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
6572         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6573         edge2->Set( _LayerEdge::MARKED );
6574
6575         // get a new normal
6576         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6577
6578         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6579         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6580         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6581         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6582         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6583         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6584         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6585         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6586         newNormal.Normalize();
6587
6588         // get new cosin
6589         double newCos;
6590         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6591         if ( cos1 < theMinSmoothCosin )
6592         {
6593           newCos = cos2 * sgn1;
6594         }
6595         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6596         {
6597           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6598         }
6599         else
6600         {
6601           newCos = edge1->_cosin;
6602         }
6603
6604         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6605         e2neIt->second._normal += distWgt * newNormal;
6606         e2neIt->second._cosin   = newCos;
6607         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6608         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6609           e2neIt->second._normal += dir2;
6610         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6611         e2neIt->second._normal += distWgt * newNormal;
6612         e2neIt->second._cosin   = edge2->_cosin;
6613         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6614           e2neIt->second._normal += dir1;
6615       }
6616     }
6617
6618     if ( edge2newEdge.empty() )
6619       break; //return true;
6620
6621     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6622
6623     // Update data of edges depending on a new _normal
6624
6625     data.UnmarkEdges();
6626     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6627     {
6628       _LayerEdge*    edge = e2neIt->first;
6629       if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6630       _LayerEdge& newEdge = e2neIt->second;
6631       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6632
6633       // Check if a new _normal is OK:
6634       newEdge._normal.Normalize();
6635       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6636       {
6637         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6638         {
6639           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6640           edge->_maxLen = newEdge._maxLen;
6641           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6642         }
6643         continue; // the new _normal is bad
6644       }
6645       // the new _normal is OK
6646
6647       // find shapes that need smoothing due to change of _normal
6648       if ( edge->_cosin   < theMinSmoothCosin &&
6649            newEdge._cosin > theMinSmoothCosin )
6650       {
6651         if ( eos->_sWOL.IsNull() )
6652         {
6653           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6654           while ( fIt->more() )
6655             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6656         }
6657         else // edge inflates along a FACE
6658         {
6659           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6660           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6661           while ( const TopoDS_Shape* E = eIt->next() )
6662           {
6663             if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6664               continue;
6665             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6666             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6667             if ( angle < M_PI / 2 )
6668               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6669           }
6670         }
6671       }
6672
6673       double len = edge->_len;
6674       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6675       edge->SetNormal( newEdge._normal );
6676       edge->SetCosin( newEdge._cosin );
6677       edge->SetNewLength( len, *eos, helper );
6678       edge->Set( _LayerEdge::MARKED );
6679       edge->Set( _LayerEdge::NORMAL_UPDATED );
6680       edgesNoAnaSmooth.insert( eos );
6681     }
6682
6683     // Update normals and other dependent data of not intersecting _LayerEdge's
6684     // neighboring the intersecting ones
6685
6686     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6687     {
6688       _LayerEdge*   edge1 = e2neIt->first;
6689       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6690       if ( !edge1->Is( _LayerEdge::MARKED ))
6691         continue;
6692
6693       if ( edge1->IsOnEdge() )
6694       {
6695         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6696         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6697         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6698       }
6699
6700       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6701         continue;
6702       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6703       {
6704         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6705         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6706           continue; // j-th neighbor is also intersected
6707         _LayerEdge* prevEdge = edge1;
6708         const int nbSteps = 10;
6709         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6710         {
6711           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6712                neighbor->Is( _LayerEdge::MARKED ))
6713             break;
6714           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6715           if ( !eos ) continue;
6716           _LayerEdge* nextEdge = neighbor;
6717           if ( neighbor->_2neibors )
6718           {
6719             int iNext = 0;
6720             nextEdge = neighbor->_2neibors->_edges[iNext];
6721             if ( nextEdge == prevEdge )
6722               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6723           }
6724           double r = double(step-1)/nbSteps/(iter+1);
6725           if ( !nextEdge->_2neibors )
6726             r = Min( r, 0.5 );
6727
6728           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6729           newNorm.Normalize();
6730           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6731             break;
6732
6733           double len = neighbor->_len;
6734           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6735           neighbor->SetNormal( newNorm );
6736           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6737           if ( neighbor->_2neibors )
6738             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6739           neighbor->SetNewLength( len, *eos, helper );
6740           neighbor->Set( _LayerEdge::MARKED );
6741           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6742           edgesNoAnaSmooth.insert( eos );
6743
6744           if ( !neighbor->_2neibors )
6745             break; // neighbor is on VERTEX
6746
6747           // goto the next neighbor
6748           prevEdge = neighbor;
6749           neighbor = nextEdge;
6750         }
6751       }
6752     }
6753     dumpFunctionEnd();
6754   } // iterations
6755
6756   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6757
6758   return true;
6759 }
6760
6761 //================================================================================
6762 /*!
6763  * \brief Check if a new normal is OK
6764  */
6765 //================================================================================
6766
6767 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6768                                      _LayerEdge&   edge,
6769                                      const gp_XYZ& newNormal)
6770 {
6771   // check a min angle between the newNormal and surrounding faces
6772   vector<_Simplex> simplices;
6773   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6774   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6775   double newMinDot = 1, curMinDot = 1;
6776   for ( size_t i = 0; i < simplices.size(); ++i )
6777   {
6778     n1.Set( simplices[i]._nPrev );
6779     n2.Set( simplices[i]._nNext );
6780     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6781     double normLen2 = normFace.SquareModulus();
6782     if ( normLen2 < std::numeric_limits<double>::min() )
6783       continue;
6784     normFace /= Sqrt( normLen2 );
6785     newMinDot = Min( newNormal    * normFace, newMinDot );
6786     curMinDot = Min( edge._normal * normFace, curMinDot );
6787   }
6788   bool ok = true;
6789   if ( newMinDot < 0.5 )
6790   {
6791     ok = ( newMinDot >= curMinDot * 0.9 );
6792     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6793     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6794     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6795   }
6796
6797   return ok;
6798 }
6799
6800 //================================================================================
6801 /*!
6802  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6803  */
6804 //================================================================================
6805
6806 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6807                                                SMESH_MesherHelper& helper,
6808                                                const int           nbSteps,
6809                                                const double        stepSize )
6810 {
6811   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6812     return true; // no shapes needing smoothing
6813
6814   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6815   {
6816     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6817     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6818          !eos._hyp.ToSmooth() ||
6819          eos.ShapeType() != TopAbs_FACE ||
6820          eos._edges.empty() )
6821       continue;
6822
6823     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6824     if ( !toSmooth ) continue;
6825
6826     for ( size_t i = 0; i < eos._edges.size(); ++i )
6827     {
6828       _LayerEdge* edge = eos._edges[i];
6829       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6830         continue;
6831       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6832         continue;
6833
6834       const gp_XYZ& pPrev = edge->PrevPos();
6835       const gp_XYZ& pLast = edge->_pos.back();
6836       gp_XYZ      stepVec = pLast - pPrev;
6837       double realStepSize = stepVec.Modulus();
6838       if ( realStepSize < numeric_limits<double>::min() )
6839         continue;
6840
6841       edge->_lenFactor = realStepSize / stepSize;
6842       edge->_normal    = stepVec / realStepSize;
6843       edge->Set( _LayerEdge::NORMAL_UPDATED );
6844     }
6845   }
6846
6847   return true;
6848 }
6849
6850 //================================================================================
6851 /*!
6852  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6853  */
6854 //================================================================================
6855
6856 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6857 {
6858   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6859   {
6860     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6861     if ( eov._eosC1.empty() ||
6862          eov.ShapeType() != TopAbs_VERTEX ||
6863          eov._edges.empty() )
6864       continue;
6865
6866     gp_XYZ newNorm   = eov._edges[0]->_normal;
6867     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6868     bool normChanged = false;
6869
6870     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6871     {
6872       _EdgesOnShape*   eoe = eov._eosC1[i];
6873       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6874       const double    eLen = SMESH_Algo::EdgeLength( e );
6875       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6876       if ( oppV.IsSame( eov._shape ))
6877         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6878       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6879       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6880       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6881
6882       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6883       if ( curThickOpp + curThick < eLen )
6884         continue;
6885
6886       double wgt = 2. * curThick / eLen;
6887       newNorm += wgt * eovOpp->_edges[0]->_normal;
6888       normChanged = true;
6889     }
6890     if ( normChanged )
6891     {
6892       eov._edges[0]->SetNormal( newNorm.Normalized() );
6893       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6894     }
6895   }
6896 }
6897
6898 //================================================================================
6899 /*!
6900  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6901  */
6902 //================================================================================
6903
6904 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6905                                                   SMESH_MesherHelper& helper,
6906                                                   int                 stepNb )
6907 {
6908   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6909   bool isOK;
6910
6911   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6912   for ( ; id2face != data._convexFaces.end(); ++id2face )
6913   {
6914     _ConvexFace & convFace = (*id2face).second;
6915     if ( convFace._normalsFixed )
6916       continue; // already fixed
6917     if ( convFace.CheckPrisms() )
6918       continue; // nothing to fix
6919
6920     convFace._normalsFixed = true;
6921
6922     BRepAdaptor_Surface surface ( convFace._face, false );
6923     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6924
6925     // check if the convex FACE is of spherical shape
6926
6927     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6928     Bnd_B3d nodesBox;
6929     gp_Pnt  center;
6930
6931     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6932     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6933     {
6934       _EdgesOnShape& eos = *(id2eos->second);
6935       if ( eos.ShapeType() == TopAbs_VERTEX )
6936       {
6937         _LayerEdge* ledge = eos._edges[ 0 ];
6938         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6939           centersBox.Add( center );
6940       }
6941       for ( size_t i = 0; i < eos._edges.size(); ++i )
6942         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6943     }
6944     if ( centersBox.IsVoid() )
6945     {
6946       debugMsg( "Error: centersBox.IsVoid()" );
6947       return false;
6948     }
6949     const bool isSpherical =
6950       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6951
6952     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6953     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6954
6955     if ( isSpherical )
6956     {
6957       // set _LayerEdge::_normal as average of all normals
6958
6959       // WARNING: different density of nodes on EDGEs is not taken into account that
6960       // can lead to an improper new normal
6961
6962       gp_XYZ avgNormal( 0,0,0 );
6963       nbEdges = 0;
6964       id2eos = convFace._subIdToEOS.begin();
6965       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6966       {
6967         _EdgesOnShape& eos = *(id2eos->second);
6968         // set data of _CentralCurveOnEdge
6969         if ( eos.ShapeType() == TopAbs_EDGE )
6970         {
6971           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6972           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6973           if ( !eos._sWOL.IsNull() )
6974             ceCurve._adjFace.Nullify();
6975           else
6976             ceCurve._ledges.insert( ceCurve._ledges.end(),
6977                                     eos._edges.begin(), eos._edges.end());
6978         }
6979         // summarize normals
6980         for ( size_t i = 0; i < eos._edges.size(); ++i )
6981           avgNormal += eos._edges[ i ]->_normal;
6982       }
6983       double normSize = avgNormal.SquareModulus();
6984       if ( normSize < 1e-200 )
6985       {
6986         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6987         return false;
6988       }
6989       avgNormal /= Sqrt( normSize );
6990
6991       // compute new _LayerEdge::_cosin on EDGEs
6992       double avgCosin = 0;
6993       int     nbCosin = 0;
6994       gp_Vec inFaceDir;
6995       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6996       {
6997         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6998         if ( ceCurve._adjFace.IsNull() )
6999           continue;
7000         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7001         {
7002           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7003           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7004           if ( isOK )
7005           {
7006             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7007             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7008             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7009             nbCosin++;
7010           }
7011         }
7012       }
7013       if ( nbCosin > 0 )
7014         avgCosin /= nbCosin;
7015
7016       // set _LayerEdge::_normal = avgNormal
7017       id2eos = convFace._subIdToEOS.begin();
7018       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7019       {
7020         _EdgesOnShape& eos = *(id2eos->second);
7021         if ( eos.ShapeType() != TopAbs_EDGE )
7022           for ( size_t i = 0; i < eos._edges.size(); ++i )
7023             eos._edges[ i ]->_cosin = avgCosin;
7024
7025         for ( size_t i = 0; i < eos._edges.size(); ++i )
7026         {
7027           eos._edges[ i ]->SetNormal( avgNormal );
7028           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7029         }
7030       }
7031     }
7032     else // if ( isSpherical )
7033     {
7034       // We suppose that centers of curvature at all points of the FACE
7035       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7036       // having a common center of curvature we define the same new normal
7037       // as a sum of normals of _LayerEdge's on EDGEs among them.
7038
7039       // get all centers of curvature for each EDGE
7040
7041       helper.SetSubShape( convFace._face );
7042       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7043
7044       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7045       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7046       {
7047         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7048
7049         // set adjacent FACE
7050         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7051
7052         // get _LayerEdge's of the EDGE
7053         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7054         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7055         if ( !eos || eos->_edges.empty() )
7056         {
7057           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7058           for ( int iV = 0; iV < 2; ++iV )
7059           {
7060             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7061             TGeomID     vID = meshDS->ShapeToIndex( v );
7062             eos = data.GetShapeEdges( vID );
7063             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7064           }
7065           edgeLEdge    = &vertexLEdges[0];
7066           edgeLEdgeEnd = edgeLEdge + 2;
7067
7068           centerCurves[ iE ]._adjFace.Nullify();
7069         }
7070         else
7071         {
7072           if ( ! eos->_toSmooth )
7073             data.SortOnEdge( edge, eos->_edges );
7074           edgeLEdge    = &eos->_edges[ 0 ];
7075           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7076           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7077           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7078
7079           if ( ! eos->_sWOL.IsNull() )
7080             centerCurves[ iE ]._adjFace.Nullify();
7081         }
7082
7083         // Get curvature centers
7084
7085         centersBox.Clear();
7086
7087         if ( edgeLEdge[0]->IsOnEdge() &&
7088              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7089         { // 1st VERTEX
7090           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7091           centersBox.Add( center );
7092         }
7093         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7094           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7095           { // EDGE or VERTEXes
7096             centerCurves[ iE ].Append( center, *edgeLEdge );
7097             centersBox.Add( center );
7098           }
7099         if ( edgeLEdge[-1]->IsOnEdge() &&
7100              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7101         { // 2nd VERTEX
7102           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7103           centersBox.Add( center );
7104         }
7105         centerCurves[ iE ]._isDegenerated =
7106           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7107
7108       } // loop on EDGES of convFace._face to set up data of centerCurves
7109
7110       // Compute new normals for _LayerEdge's on EDGEs
7111
7112       double avgCosin = 0;
7113       int     nbCosin = 0;
7114       gp_Vec inFaceDir;
7115       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7116       {
7117         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7118         if ( ceCurve._isDegenerated )
7119           continue;
7120         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7121         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7122         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7123         {
7124           isOK = false;
7125           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7126           {
7127             if ( iE1 != iE2 )
7128               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7129           }
7130           if ( isOK && !ceCurve._adjFace.IsNull() )
7131           {
7132             // compute new _LayerEdge::_cosin
7133             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7134             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7135             if ( isOK )
7136             {
7137               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7138               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7139               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7140               nbCosin++;
7141             }
7142           }
7143         }
7144       }
7145       // set new normals to _LayerEdge's of NOT degenerated central curves
7146       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7147       {
7148         if ( centerCurves[ iE ]._isDegenerated )
7149           continue;
7150         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7151         {
7152           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7153           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7154         }
7155       }
7156       // set new normals to _LayerEdge's of     degenerated central curves
7157       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7158       {
7159         if ( !centerCurves[ iE ]._isDegenerated ||
7160              centerCurves[ iE ]._ledges.size() < 3 )
7161           continue;
7162         // new normal is an average of new normals at VERTEXes that
7163         // was computed on non-degenerated _CentralCurveOnEdge's
7164         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7165                            centerCurves[ iE ]._ledges.back ()->_normal );
7166         double sz = newNorm.Modulus();
7167         if ( sz < 1e-200 )
7168           continue;
7169         newNorm /= sz;
7170         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7171                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7172         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7173         {
7174           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7175           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7176           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7177         }
7178       }
7179
7180       // Find new normals for _LayerEdge's based on FACE
7181
7182       if ( nbCosin > 0 )
7183         avgCosin /= nbCosin;
7184       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7185       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7186       if ( id2eos != convFace._subIdToEOS.end() )
7187       {
7188         int iE = 0;
7189         gp_XYZ newNorm;
7190         _EdgesOnShape& eos = * ( id2eos->second );
7191         for ( size_t i = 0; i < eos._edges.size(); ++i )
7192         {
7193           _LayerEdge* ledge = eos._edges[ i ];
7194           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7195             continue;
7196           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7197           {
7198             iE = iE % centerCurves.size();
7199             if ( centerCurves[ iE ]._isDegenerated )
7200               continue;
7201             newNorm.SetCoord( 0,0,0 );
7202             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7203             {
7204               ledge->SetNormal( newNorm );
7205               ledge->_cosin  = avgCosin;
7206               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7207               break;
7208             }
7209           }
7210         }
7211       }
7212
7213     } // not a quasi-spherical FACE
7214
7215     // Update _LayerEdge's data according to a new normal
7216
7217     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7218                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7219
7220     id2eos = convFace._subIdToEOS.begin();
7221     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7222     {
7223       _EdgesOnShape& eos = * ( id2eos->second );
7224       for ( size_t i = 0; i < eos._edges.size(); ++i )
7225       {
7226         _LayerEdge* & ledge = eos._edges[ i ];
7227         double len = ledge->_len;
7228         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7229         ledge->SetCosin( ledge->_cosin );
7230         ledge->SetNewLength( len, eos, helper );
7231       }
7232       if ( eos.ShapeType() != TopAbs_FACE )
7233         for ( size_t i = 0; i < eos._edges.size(); ++i )
7234         {
7235           _LayerEdge* ledge = eos._edges[ i ];
7236           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7237           {
7238             _LayerEdge* neibor = ledge->_neibors[iN];
7239             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7240             {
7241               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7242               neibor->Set( _LayerEdge::MOVED );
7243               neibor->SetSmooLen( neibor->_len );
7244             }
7245           }
7246         }
7247     } // loop on sub-shapes of convFace._face
7248
7249     // Find FACEs adjacent to convFace._face that got necessity to smooth
7250     // as a result of normals modification
7251
7252     set< _EdgesOnShape* > adjFacesToSmooth;
7253     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7254     {
7255       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7256            centerCurves[ iE ]._adjFaceToSmooth )
7257         continue;
7258       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7259       {
7260         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7261         {
7262           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7263           break;
7264         }
7265       }
7266     }
7267     data.AddShapesToSmooth( adjFacesToSmooth );
7268
7269     dumpFunctionEnd();
7270
7271
7272   } // loop on data._convexFaces
7273
7274   return true;
7275 }
7276
7277 //================================================================================
7278 /*!
7279  * \brief Finds a center of curvature of a surface at a _LayerEdge
7280  */
7281 //================================================================================
7282
7283 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7284                                         BRepLProp_SLProps&  surfProp,
7285                                         SMESH_MesherHelper& helper,
7286                                         gp_Pnt &            center ) const
7287 {
7288   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7289   surfProp.SetParameters( uv.X(), uv.Y() );
7290   if ( !surfProp.IsCurvatureDefined() )
7291     return false;
7292
7293   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7294   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7295   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7296   if ( surfCurvatureMin > surfCurvatureMax )
7297     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7298   else
7299     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7300
7301   return true;
7302 }
7303
7304 //================================================================================
7305 /*!
7306  * \brief Check that prisms are not distorted
7307  */
7308 //================================================================================
7309
7310 bool _ConvexFace::CheckPrisms() const
7311 {
7312   double vol = 0;
7313   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7314   {
7315     const _LayerEdge* edge = _simplexTestEdges[i];
7316     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7317     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7318       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7319       {
7320         debugMsg( "Bad simplex of _simplexTestEdges ("
7321                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7322                   << " "<< edge->_simplices[j]._nPrev->GetID()
7323                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7324         return false;
7325       }
7326   }
7327   return true;
7328 }
7329
7330 //================================================================================
7331 /*!
7332  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7333  *        stored in this _CentralCurveOnEdge.
7334  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7335  *  \param [in,out] newNormal - current normal at this point, to be redefined
7336  *  \return bool - true if succeeded.
7337  */
7338 //================================================================================
7339
7340 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7341 {
7342   if ( this->_isDegenerated )
7343     return false;
7344
7345   // find two centers the given one lies between
7346
7347   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7348   {
7349     double sl2 = 1.001 * _segLength2[ i ];
7350
7351     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7352     if ( d1 > sl2 )
7353       continue;
7354     
7355     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7356     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7357       continue;
7358
7359     d1 = Sqrt( d1 );
7360     d2 = Sqrt( d2 );
7361     double r = d1 / ( d1 + d2 );
7362     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7363                    (      r ) * _ledges[ i+1 ]->_normal );
7364     norm.Normalize();
7365
7366     newNormal += norm;
7367     double sz = newNormal.Modulus();
7368     if ( sz < 1e-200 )
7369       break;
7370     newNormal /= sz;
7371     return true;
7372   }
7373   return false;
7374 }
7375
7376 //================================================================================
7377 /*!
7378  * \brief Set shape members
7379  */
7380 //================================================================================
7381
7382 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7383                                      const _ConvexFace&  convFace,
7384                                      _SolidData&         data,
7385                                      SMESH_MesherHelper& helper)
7386 {
7387   _edge = edge;
7388
7389   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7390   while ( const TopoDS_Shape* F = fIt->next())
7391     if ( !convFace._face.IsSame( *F ))
7392     {
7393       _adjFace = TopoDS::Face( *F );
7394       _adjFaceToSmooth = false;
7395       // _adjFace already in a smoothing queue ?
7396       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7397         _adjFaceToSmooth = eos->_toSmooth;
7398       break;
7399     }
7400 }
7401
7402 //================================================================================
7403 /*!
7404  * \brief Looks for intersection of it's last segment with faces
7405  *  \param distance - returns shortest distance from the last node to intersection
7406  */
7407 //================================================================================
7408
7409 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7410                                    double &                 distance,
7411                                    const double&            epsilon,
7412                                    _EdgesOnShape&           eos,
7413                                    const SMDS_MeshElement** intFace)
7414 {
7415   vector< const SMDS_MeshElement* > suspectFaces;
7416   double segLen;
7417   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7418   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7419
7420   bool segmentIntersected = false;
7421   distance = Precision::Infinite();
7422   int iFace = -1; // intersected face
7423   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7424   {
7425     const SMDS_MeshElement* face = suspectFaces[j];
7426     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7427          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7428       continue; // face sharing _LayerEdge node
7429     const int nbNodes = face->NbCornerNodes();
7430     bool intFound = false;
7431     double dist;
7432     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7433     if ( nbNodes == 3 )
7434     {
7435       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7436     }
7437     else
7438     {
7439       const SMDS_MeshNode* tria[3];
7440       tria[0] = *nIt++;
7441       tria[1] = *nIt++;
7442       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7443       {
7444         tria[2] = *nIt++;
7445         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7446         tria[1] = tria[2];
7447       }
7448     }
7449     if ( intFound )
7450     {
7451       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7452         segmentIntersected = true;
7453       if ( distance > dist )
7454         distance = dist, iFace = j;
7455     }
7456   }
7457   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7458
7459   distance -= segLen;
7460
7461   if ( segmentIntersected )
7462   {
7463 #ifdef __myDEBUG
7464     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7465     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7466     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7467          << ", intersection with face ("
7468          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7469          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7470          << ") distance = " << distance << endl;
7471 #endif
7472   }
7473
7474   return segmentIntersected;
7475 }
7476
7477 //================================================================================
7478 /*!
7479  * \brief Returns a point used to check orientation of _simplices
7480  */
7481 //================================================================================
7482
7483 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7484 {
7485   size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7486
7487   if ( !eos || eos->_sWOL.IsNull() )
7488     return _pos[ i ];
7489
7490   if ( eos->SWOLType() == TopAbs_EDGE )
7491   {
7492     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7493   }
7494   //else //  TopAbs_FACE
7495
7496   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7497 }
7498
7499 //================================================================================
7500 /*!
7501  * \brief Returns size and direction of the last segment
7502  */
7503 //================================================================================
7504
7505 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7506 {
7507   // find two non-coincident positions
7508   gp_XYZ orig = _pos.back();
7509   gp_XYZ vec;
7510   int iPrev = _pos.size() - 2;
7511   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7512   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7513   while ( iPrev >= 0 )
7514   {
7515     vec = orig - _pos[iPrev];
7516     if ( vec.SquareModulus() > tol*tol )
7517       break;
7518     else
7519       iPrev--;
7520   }
7521
7522   // make gp_Ax1
7523   gp_Ax1 segDir;
7524   if ( iPrev < 0 )
7525   {
7526     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7527     segDir.SetDirection( _normal );
7528     segLen = 0;
7529   }
7530   else
7531   {
7532     gp_Pnt pPrev = _pos[ iPrev ];
7533     if ( !eos._sWOL.IsNull() )
7534     {
7535       TopLoc_Location loc;
7536       if ( eos.SWOLType() == TopAbs_EDGE )
7537       {
7538         double f,l;
7539         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7540         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7541       }
7542       else
7543       {
7544         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7545         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7546       }
7547       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7548     }
7549     segDir.SetLocation( pPrev );
7550     segDir.SetDirection( vec );
7551     segLen = vec.Modulus();
7552   }
7553
7554   return segDir;
7555 }
7556
7557 //================================================================================
7558 /*!
7559  * \brief Return the last position of the target node on a FACE. 
7560  *  \param [in] F - the FACE this _LayerEdge is inflated along
7561  *  \return gp_XY - result UV
7562  */
7563 //================================================================================
7564
7565 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7566 {
7567   if ( F.IsSame( eos._sWOL )) // F is my FACE
7568     return gp_XY( _pos.back().X(), _pos.back().Y() );
7569
7570   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7571     return gp_XY( 1e100, 1e100 );
7572
7573   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7574   double f, l, u = _pos.back().X();
7575   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7576   if ( !C2d.IsNull() && f <= u && u <= l )
7577     return C2d->Value( u ).XY();
7578
7579   return gp_XY( 1e100, 1e100 );
7580 }
7581
7582 //================================================================================
7583 /*!
7584  * \brief Test intersection of the last segment with a given triangle
7585  *   using Moller-Trumbore algorithm
7586  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7587  */
7588 //================================================================================
7589
7590 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7591                                const gp_XYZ& vert0,
7592                                const gp_XYZ& vert1,
7593                                const gp_XYZ& vert2,
7594                                double&       t,
7595                                const double& EPSILON) const
7596 {
7597   const gp_Pnt& orig = lastSegment.Location();
7598   const gp_Dir& dir  = lastSegment.Direction();
7599
7600   /* calculate distance from vert0 to ray origin */
7601   //gp_XYZ tvec = orig.XYZ() - vert0;
7602
7603   //if ( tvec * dir > EPSILON )
7604     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7605     //return false;
7606
7607   gp_XYZ edge1 = vert1 - vert0;
7608   gp_XYZ edge2 = vert2 - vert0;
7609
7610   /* begin calculating determinant - also used to calculate U parameter */
7611   gp_XYZ pvec = dir.XYZ() ^ edge2;
7612
7613   /* if determinant is near zero, ray lies in plane of triangle */
7614   double det = edge1 * pvec;
7615
7616   const double ANGL_EPSILON = 1e-12;
7617   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7618     return false;
7619
7620   /* calculate distance from vert0 to ray origin */
7621   gp_XYZ tvec = orig.XYZ() - vert0;
7622
7623   /* calculate U parameter and test bounds */
7624   double u = ( tvec * pvec ) / det;
7625   //if (u < 0.0 || u > 1.0)
7626   if ( u < -EPSILON || u > 1.0 + EPSILON )
7627     return false;
7628
7629   /* prepare to test V parameter */
7630   gp_XYZ qvec = tvec ^ edge1;
7631
7632   /* calculate V parameter and test bounds */
7633   double v = (dir.XYZ() * qvec) / det;
7634   //if ( v < 0.0 || u + v > 1.0 )
7635   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7636     return false;
7637
7638   /* calculate t, ray intersects triangle */
7639   t = (edge2 * qvec) / det;
7640
7641   //return true;
7642   return t > 0.;
7643 }
7644
7645 //================================================================================
7646 /*!
7647  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7648  *        neighbor _LayerEdge's by it's own inflation vector.
7649  *  \param [in] eov - EOS of the VERTEX
7650  *  \param [in] eos - EOS of the FACE
7651  *  \param [in] step - inflation step
7652  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7653  */
7654 //================================================================================
7655
7656 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7657                                    const _EdgesOnShape*    eos,
7658                                    const int               step,
7659                                    vector< _LayerEdge* > & badSmooEdges )
7660 {
7661   // check if any of _neibors is in badSmooEdges
7662   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7663                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7664     return;
7665
7666   // get all edges to move
7667
7668   set< _LayerEdge* > edges;
7669
7670   // find a distance between _LayerEdge on VERTEX and its neighbors
7671   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7672   double dist2 = 0;
7673   for ( size_t i = 0; i < _neibors.size(); ++i )
7674   {
7675     _LayerEdge* nEdge = _neibors[i];
7676     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7677     {
7678       edges.insert( nEdge );
7679       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7680     }
7681   }
7682   // add _LayerEdge's close to curPosV
7683   size_t nbE;
7684   do {
7685     nbE = edges.size();
7686     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7687     {
7688       _LayerEdge* edgeF = *e;
7689       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7690       {
7691         _LayerEdge* nEdge = edgeF->_neibors[i];
7692         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7693              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7694           edges.insert( nEdge );
7695       }
7696     }
7697   }
7698   while ( nbE < edges.size() );
7699
7700   // move the target node of the got edges
7701
7702   gp_XYZ prevPosV = PrevPos();
7703   if ( eov->SWOLType() == TopAbs_EDGE )
7704   {
7705     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7706     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7707   }
7708   else if ( eov->SWOLType() == TopAbs_FACE )
7709   {
7710     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7711     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7712   }
7713
7714   SMDS_FacePosition* fPos;
7715   //double r = 1. - Min( 0.9, step / 10. );
7716   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7717   {
7718     _LayerEdge*       edgeF = *e;
7719     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7720     const gp_XYZ    newPosF = curPosV + prevVF;
7721     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7722     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7723     edgeF->_pos.back() = newPosF;
7724     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7725
7726     // set _curvature to make edgeF updated by putOnOffsetSurface()
7727     if ( !edgeF->_curvature )
7728       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7729       {
7730         edgeF->_curvature = new _Curvature;
7731         edgeF->_curvature->_r = 0;
7732         edgeF->_curvature->_k = 0;
7733         edgeF->_curvature->_h2lenRatio = 0;
7734         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7735       }
7736   }
7737   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7738   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7739   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7740   // {
7741   //   _LayerEdge*      edgeF = *e;
7742   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7743   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7744   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7745   //   edgeF->_pos.back() = newPosF;
7746   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7747   // }
7748
7749   // smooth _LayerEdge's around moved nodes
7750   //size_t nbBadBefore = badSmooEdges.size();
7751   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7752   {
7753     _LayerEdge* edgeF = *e;
7754     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7755       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7756         //&& !edges.count( edgeF->_neibors[j] ))
7757       {
7758         _LayerEdge* edgeFN = edgeF->_neibors[j];
7759         edgeFN->Unset( SMOOTHED );
7760         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7761         // if ( nbBad > 0 )
7762         // {
7763         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7764         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7765         //   int        nbBadAfter = edgeFN->_simplices.size();
7766         //   double vol;
7767         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7768         //   {
7769         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7770         //   }
7771         //   if ( nbBadAfter <= nbBad )
7772         //   {
7773         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7774         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7775         //     edgeF->_pos.back() = newPosF;
7776         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7777         //     nbBad = nbBadAfter;
7778         //   }
7779         // }
7780         if ( nbBad > 0 )
7781           badSmooEdges.push_back( edgeFN );
7782       }
7783   }
7784     // move a bit not smoothed around moved nodes
7785   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7786   //   {
7787   //   _LayerEdge*      edgeF = badSmooEdges[i];
7788   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7789   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7790   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7791   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7792   //   edgeF->_pos.back() = newPosF;
7793   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7794   // }
7795 }
7796
7797 //================================================================================
7798 /*!
7799  * \brief Perform smooth of _LayerEdge's based on EDGE's
7800  *  \retval bool - true if node has been moved
7801  */
7802 //================================================================================
7803
7804 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7805                               const TopoDS_Face&             F,
7806                               SMESH_MesherHelper&            helper)
7807 {
7808   ASSERT( IsOnEdge() );
7809
7810   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7811   SMESH_TNodeXYZ oldPos( tgtNode );
7812   double dist01, distNewOld;
7813   
7814   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7815   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7816   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7817
7818   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7819   double lenDelta = 0;
7820   if ( _curvature )
7821   {
7822     //lenDelta = _curvature->lenDelta( _len );
7823     lenDelta = _curvature->lenDeltaByDist( dist01 );
7824     newPos.ChangeCoord() += _normal * lenDelta;
7825   }
7826
7827   distNewOld = newPos.Distance( oldPos );
7828
7829   if ( F.IsNull() )
7830   {
7831     if ( _2neibors->_plnNorm )
7832     {
7833       // put newPos on the plane defined by source node and _plnNorm
7834       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7835       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7836       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7837     }
7838     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7839     _pos.back() = newPos.XYZ();
7840   }
7841   else
7842   {
7843     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7844     gp_XY uv( Precision::Infinite(), 0 );
7845     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7846     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7847
7848     newPos = surface->Value( uv );
7849     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7850   }
7851
7852   // commented for IPAL0052478
7853   // if ( _curvature && lenDelta < 0 )
7854   // {
7855   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7856   //   _len -= prevPos.Distance( oldPos );
7857   //   _len += prevPos.Distance( newPos );
7858   // }
7859   bool moved = distNewOld > dist01/50;
7860   //if ( moved )
7861   dumpMove( tgtNode ); // debug
7862
7863   return moved;
7864 }
7865
7866 //================================================================================
7867 /*!
7868  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7869  */
7870 //================================================================================
7871
7872 void _LayerEdge::SmoothWoCheck()
7873 {
7874   if ( Is( DIFFICULT ))
7875     return;
7876
7877   bool moved = Is( SMOOTHED );
7878   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7879     moved = _neibors[i]->Is( SMOOTHED );
7880   if ( !moved )
7881     return;
7882
7883   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7884
7885   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7886   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7887   _pos.back() = newPos;
7888
7889   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7890 }
7891
7892 //================================================================================
7893 /*!
7894  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7895  */
7896 //================================================================================
7897
7898 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7899 {
7900   if ( ! Is( NEAR_BOUNDARY ))
7901     return 0;
7902
7903   int nbBad = 0;
7904   double vol;
7905   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7906   {
7907     _LayerEdge* eN = _neibors[iN];
7908     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7909       continue;
7910     if ( needSmooth )
7911       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7912                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7913                        eN->_pos.size() != _pos.size() );
7914
7915     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7916     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7917     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7918       if ( eN->_nodes.size() > 1 &&
7919            eN->_simplices[i].Includes( _nodes.back() ) &&
7920            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7921       {
7922         ++nbBad;
7923         if ( badNeibors )
7924         {
7925           badNeibors->push_back( eN );
7926           debugMsg("Bad boundary simplex ( "
7927                    << " "<< eN->_nodes[0]->GetID()
7928                    << " "<< eN->_nodes.back()->GetID()
7929                    << " "<< eN->_simplices[i]._nPrev->GetID()
7930                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7931         }
7932         else
7933         {
7934           break;
7935         }
7936       }
7937   }
7938   return nbBad;
7939 }
7940
7941 //================================================================================
7942 /*!
7943  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7944  *  \retval int - nb of bad simplices around this _LayerEdge
7945  */
7946 //================================================================================
7947
7948 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7949 {
7950   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7951     return 0; // shape of simplices not changed
7952   if ( _simplices.size() < 2 )
7953     return 0; // _LayerEdge inflated along EDGE or FACE
7954
7955   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7956     findBest = true;
7957
7958   const gp_XYZ& curPos  = _pos.back();
7959   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7960
7961   // quality metrics (orientation) of tetras around _tgtNode
7962   int nbOkBefore = 0;
7963   double vol, minVolBefore = 1e100;
7964   for ( size_t i = 0; i < _simplices.size(); ++i )
7965   {
7966     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7967     minVolBefore = Min( minVolBefore, vol );
7968   }
7969   int nbBad = _simplices.size() - nbOkBefore;
7970
7971   bool bndNeedSmooth = false;
7972   if ( nbBad == 0 )
7973     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7974   if ( nbBad > 0 )
7975     Set( DISTORTED );
7976
7977   // evaluate min angle
7978   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7979   {
7980     size_t nbGoodAngles = _simplices.size();
7981     double angle;
7982     for ( size_t i = 0; i < _simplices.size(); ++i )
7983     {
7984       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7985         --nbGoodAngles;
7986     }
7987     if ( nbGoodAngles == _simplices.size() )
7988     {
7989       Unset( MOVED );
7990       return 0;
7991     }
7992   }
7993   if ( Is( ON_CONCAVE_FACE ))
7994     findBest = true;
7995
7996   if ( step % 2 == 0 )
7997     findBest = false;
7998
7999   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8000   {
8001     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8002       _smooFunction = _funs[ FUN_CENTROIDAL ];
8003     else
8004       _smooFunction = _funs[ FUN_LAPLACIAN ];
8005   }
8006
8007   // compute new position for the last _pos using different _funs
8008   gp_XYZ newPos;
8009   bool moved = false;
8010   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8011   {
8012     if ( iFun < 0 )
8013       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8014     else if ( _funs[ iFun ] == _smooFunction )
8015       continue; // _smooFunction again
8016     else if ( step > 1 )
8017       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8018     else
8019       break; // let "easy" functions improve elements around distorted ones
8020
8021     if ( _curvature )
8022     {
8023       double delta  = _curvature->lenDelta( _len );
8024       if ( delta > 0 )
8025         newPos += _normal * delta;
8026       else
8027       {
8028         double segLen = _normal * ( newPos - prevPos );
8029         if ( segLen + delta > 0 )
8030           newPos += _normal * delta;
8031       }
8032       // double segLenChange = _normal * ( curPos - newPos );
8033       // newPos += 0.5 * _normal * segLenChange;
8034     }
8035
8036     int nbOkAfter = 0;
8037     double minVolAfter = 1e100;
8038     for ( size_t i = 0; i < _simplices.size(); ++i )
8039     {
8040       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8041       minVolAfter = Min( minVolAfter, vol );
8042     }
8043     // get worse?
8044     if ( nbOkAfter < nbOkBefore )
8045       continue;
8046
8047     if (( findBest ) &&
8048         ( nbOkAfter == nbOkBefore ) &&
8049         ( minVolAfter <= minVolBefore ))
8050       continue;
8051
8052     nbBad        = _simplices.size() - nbOkAfter;
8053     minVolBefore = minVolAfter;
8054     nbOkBefore   = nbOkAfter;
8055     moved        = true;
8056
8057     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8058     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8059     _pos.back() = newPos;
8060
8061     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8062                   << (nbBad ? " --BAD" : ""));
8063
8064     if ( iFun > -1 )
8065     {
8066       continue; // look for a better function
8067     }
8068
8069     if ( !findBest )
8070       break;
8071
8072   } // loop on smoothing functions
8073
8074   if ( moved ) // notify _neibors
8075   {
8076     Set( SMOOTHED );
8077     for ( size_t i = 0; i < _neibors.size(); ++i )
8078       if ( !_neibors[i]->Is( MOVED ))
8079       {
8080         _neibors[i]->Set( MOVED );
8081         toSmooth.push_back( _neibors[i] );
8082       }
8083   }
8084
8085   return nbBad;
8086 }
8087
8088 //================================================================================
8089 /*!
8090  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8091  *  \retval int - nb of bad simplices around this _LayerEdge
8092  */
8093 //================================================================================
8094
8095 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8096 {
8097   if ( !_smooFunction )
8098     return 0; // _LayerEdge inflated along EDGE or FACE
8099   if ( Is( BLOCKED ))
8100     return 0; // not inflated
8101
8102   const gp_XYZ& curPos  = _pos.back();
8103   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8104
8105   // quality metrics (orientation) of tetras around _tgtNode
8106   int nbOkBefore = 0;
8107   double vol, minVolBefore = 1e100;
8108   for ( size_t i = 0; i < _simplices.size(); ++i )
8109   {
8110     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8111     minVolBefore = Min( minVolBefore, vol );
8112   }
8113   int nbBad = _simplices.size() - nbOkBefore;
8114
8115   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8116   {
8117     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8118       _smooFunction = _funs[ FUN_LAPLACIAN ];
8119     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8120       _smooFunction = _funs[ FUN_CENTROIDAL ];
8121   }
8122
8123   // compute new position for the last _pos using different _funs
8124   gp_XYZ newPos;
8125   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8126   {
8127     if ( iFun < 0 )
8128       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8129     else if ( _funs[ iFun ] == _smooFunction )
8130       continue; // _smooFunction again
8131     else if ( step > 1 )
8132       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8133     else
8134       break; // let "easy" functions improve elements around distorted ones
8135
8136     if ( _curvature )
8137     {
8138       double delta  = _curvature->lenDelta( _len );
8139       if ( delta > 0 )
8140         newPos += _normal * delta;
8141       else
8142       {
8143         double segLen = _normal * ( newPos - prevPos );
8144         if ( segLen + delta > 0 )
8145           newPos += _normal * delta;
8146       }
8147       // double segLenChange = _normal * ( curPos - newPos );
8148       // newPos += 0.5 * _normal * segLenChange;
8149     }
8150
8151     int nbOkAfter = 0;
8152     double minVolAfter = 1e100;
8153     for ( size_t i = 0; i < _simplices.size(); ++i )
8154     {
8155       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8156       minVolAfter = Min( minVolAfter, vol );
8157     }
8158     // get worse?
8159     if ( nbOkAfter < nbOkBefore )
8160       continue;
8161     if (( isConcaveFace || findBest ) &&
8162         ( nbOkAfter == nbOkBefore ) &&
8163         ( minVolAfter <= minVolBefore )
8164         )
8165       continue;
8166
8167     nbBad        = _simplices.size() - nbOkAfter;
8168     minVolBefore = minVolAfter;
8169     nbOkBefore   = nbOkAfter;
8170
8171     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8172     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8173     _pos.back() = newPos;
8174
8175     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8176                   << ( nbBad ? "--BAD" : ""));
8177
8178     // commented for IPAL0052478
8179     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8180     // _len += prevPos.Distance(newPos);
8181
8182     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8183     {
8184       //_smooFunction = _funs[ iFun ];
8185       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8186       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8187       // << " minVol: " << minVolAfter
8188       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8189       // << endl;
8190       continue; // look for a better function
8191     }
8192
8193     if ( !findBest )
8194       break;
8195
8196   } // loop on smoothing functions
8197
8198   return nbBad;
8199 }
8200
8201 //================================================================================
8202 /*!
8203  * \brief Chooses a smoothing technic giving a position most close to an initial one.
8204  *        For a correct result, _simplices must contain nodes lying on geometry.
8205  */
8206 //================================================================================
8207
8208 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8209                                      const TNode2Edge&     n2eMap)
8210 {
8211   if ( _smooFunction ) return;
8212
8213   // use smoothNefPolygon() near concaveVertices
8214   if ( !concaveVertices.empty() )
8215   {
8216     _smooFunction = _funs[ FUN_CENTROIDAL ];
8217
8218     Set( ON_CONCAVE_FACE );
8219
8220     for ( size_t i = 0; i < _simplices.size(); ++i )
8221     {
8222       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8223       {
8224         _smooFunction = _funs[ FUN_NEFPOLY ];
8225
8226         // set FUN_CENTROIDAL to neighbor edges
8227         for ( i = 0; i < _neibors.size(); ++i )
8228         {
8229           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8230           {
8231             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8232           }
8233         }
8234         return;
8235       }
8236     }
8237
8238     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8239     // // where the nodes are smoothed too far along a sphere thus creating
8240     // // inverted _simplices
8241     // double dist[theNbSmooFuns];
8242     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8243     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8244
8245     // double minDist = Precision::Infinite();
8246     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8247     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8248     // {
8249     //   gp_Pnt newP = (this->*_funs[i])();
8250     //   dist[i] = p.SquareDistance( newP );
8251     //   if ( dist[i]*coef[i] < minDist )
8252     //   {
8253     //     _smooFunction = _funs[i];
8254     //     minDist = dist[i]*coef[i];
8255     //   }
8256     // }
8257   }
8258   else
8259   {
8260     _smooFunction = _funs[ FUN_LAPLACIAN ];
8261   }
8262   // int minDim = 3;
8263   // for ( size_t i = 0; i < _simplices.size(); ++i )
8264   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8265   // if ( minDim == 0 )
8266   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8267   // else if ( minDim == 1 )
8268   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8269
8270
8271   // int iMin;
8272   // for ( int i = 0; i < FUN_NB; ++i )
8273   // {
8274   //   //cout << dist[i] << " ";
8275   //   if ( _smooFunction == _funs[i] ) {
8276   //     iMin = i;
8277   //     //debugMsg( fNames[i] );
8278   //     break;
8279   //   }
8280   // }
8281   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8282 }
8283
8284 //================================================================================
8285 /*!
8286  * \brief Returns a name of _SmooFunction
8287  */
8288 //================================================================================
8289
8290 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8291 {
8292   if ( !fun )
8293     fun = _smooFunction;
8294   for ( int i = 0; i < theNbSmooFuns; ++i )
8295     if ( fun == _funs[i] )
8296       return i;
8297
8298   return theNbSmooFuns;
8299 }
8300
8301 //================================================================================
8302 /*!
8303  * \brief Computes a new node position using Laplacian smoothing
8304  */
8305 //================================================================================
8306
8307 gp_XYZ _LayerEdge::smoothLaplacian()
8308 {
8309   gp_XYZ newPos (0,0,0);
8310   for ( size_t i = 0; i < _simplices.size(); ++i )
8311     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8312   newPos /= _simplices.size();
8313
8314   return newPos;
8315 }
8316
8317 //================================================================================
8318 /*!
8319  * \brief Computes a new node position using angular-based smoothing
8320  */
8321 //================================================================================
8322
8323 gp_XYZ _LayerEdge::smoothAngular()
8324 {
8325   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8326   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8327   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8328
8329   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8330   gp_XYZ pN( 0,0,0 );
8331   for ( size_t i = 0; i < _simplices.size(); ++i )
8332   {
8333     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8334     edgeDir.push_back( p - pPrev );
8335     edgeSize.push_back( edgeDir.back().Magnitude() );
8336     if ( edgeSize.back() < numeric_limits<double>::min() )
8337     {
8338       edgeDir.pop_back();
8339       edgeSize.pop_back();
8340     }
8341     else
8342     {
8343       edgeDir.back() /= edgeSize.back();
8344       points.push_back( p );
8345       pN += p;
8346     }
8347     pPrev = p;
8348   }
8349   edgeDir.push_back ( edgeDir[0] );
8350   edgeSize.push_back( edgeSize[0] );
8351   pN /= points.size();
8352
8353   gp_XYZ newPos(0,0,0);
8354   double sumSize = 0;
8355   for ( size_t i = 0; i < points.size(); ++i )
8356   {
8357     gp_Vec toN    = pN - points[i];
8358     double toNLen = toN.Magnitude();
8359     if ( toNLen < numeric_limits<double>::min() )
8360     {
8361       newPos += pN;
8362       continue;
8363     }
8364     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8365     double bisecLen = bisec.SquareMagnitude();
8366     if ( bisecLen < numeric_limits<double>::min() )
8367     {
8368       gp_Vec norm = edgeDir[i] ^ toN;
8369       bisec = norm ^ edgeDir[i];
8370       bisecLen = bisec.SquareMagnitude();
8371     }
8372     bisecLen = Sqrt( bisecLen );
8373     bisec /= bisecLen;
8374
8375 #if 1
8376     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8377     sumSize += bisecLen;
8378 #else
8379     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8380     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8381 #endif
8382     newPos += pNew;
8383   }
8384   newPos /= sumSize;
8385
8386   // project newPos to an average plane
8387
8388   gp_XYZ norm(0,0,0); // plane normal
8389   points.push_back( points[0] );
8390   for ( size_t i = 1; i < points.size(); ++i )
8391   {
8392     gp_XYZ vec1 = points[ i-1 ] - pN;
8393     gp_XYZ vec2 = points[ i   ] - pN;
8394     gp_XYZ cross = vec1 ^ vec2;
8395     try {
8396       cross.Normalize();
8397       if ( cross * norm < numeric_limits<double>::min() )
8398         norm += cross.Reversed();
8399       else
8400         norm += cross;
8401     }
8402     catch (Standard_Failure) { // if |cross| == 0.
8403     }
8404   }
8405   gp_XYZ vec = newPos - pN;
8406   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8407   newPos     = newPos - r * norm;
8408
8409   return newPos;
8410 }
8411
8412 //================================================================================
8413 /*!
8414  * \brief Computes a new node position using weigthed node positions
8415  */
8416 //================================================================================
8417
8418 gp_XYZ _LayerEdge::smoothLengthWeighted()
8419 {
8420   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8421   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8422
8423   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8424   for ( size_t i = 0; i < _simplices.size(); ++i )
8425   {
8426     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8427     edgeSize.push_back( ( p - pPrev ).Modulus() );
8428     if ( edgeSize.back() < numeric_limits<double>::min() )
8429     {
8430       edgeSize.pop_back();
8431     }
8432     else
8433     {
8434       points.push_back( p );
8435     }
8436     pPrev = p;
8437   }
8438   edgeSize.push_back( edgeSize[0] );
8439
8440   gp_XYZ newPos(0,0,0);
8441   double sumSize = 0;
8442   for ( size_t i = 0; i < points.size(); ++i )
8443   {
8444     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8445     sumSize += edgeSize[i] + edgeSize[i+1];
8446   }
8447   newPos /= sumSize;
8448   return newPos;
8449 }
8450
8451 //================================================================================
8452 /*!
8453  * \brief Computes a new node position using angular-based smoothing
8454  */
8455 //================================================================================
8456
8457 gp_XYZ _LayerEdge::smoothCentroidal()
8458 {
8459   gp_XYZ newPos(0,0,0);
8460   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8461   double sumSize = 0;
8462   for ( size_t i = 0; i < _simplices.size(); ++i )
8463   {
8464     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8465     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8466     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8467     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8468
8469     sumSize += size;
8470     newPos += gc * size;
8471   }
8472   newPos /= sumSize;
8473
8474   return newPos;
8475 }
8476
8477 //================================================================================
8478 /*!
8479  * \brief Computes a new node position located inside a Nef polygon
8480  */
8481 //================================================================================
8482
8483 gp_XYZ _LayerEdge::smoothNefPolygon()
8484 #ifdef OLD_NEF_POLYGON
8485 {
8486   gp_XYZ newPos(0,0,0);
8487
8488   // get a plane to seach a solution on
8489
8490   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8491   size_t i;
8492   const double tol = numeric_limits<double>::min();
8493   gp_XYZ center(0,0,0);
8494   for ( i = 0; i < _simplices.size(); ++i )
8495   {
8496     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8497                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8498     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8499   }
8500   vecs.back() = vecs[0];
8501   center /= _simplices.size();
8502
8503   gp_XYZ zAxis(0,0,0);
8504   for ( i = 0; i < _simplices.size(); ++i )
8505     zAxis += vecs[i] ^ vecs[i+1];
8506
8507   gp_XYZ yAxis;
8508   for ( i = 0; i < _simplices.size(); ++i )
8509   {
8510     yAxis = vecs[i];
8511     if ( yAxis.SquareModulus() > tol )
8512       break;
8513   }
8514   gp_XYZ xAxis = yAxis ^ zAxis;
8515   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8516   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8517   //                             p0.Distance( _simplices[2]._nPrev ));
8518   // gp_XYZ center = smoothLaplacian();
8519   // gp_XYZ xAxis, yAxis, zAxis;
8520   // for ( i = 0; i < _simplices.size(); ++i )
8521   // {
8522   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8523   //   if ( xAxis.SquareModulus() > tol*tol )
8524   //     break;
8525   // }
8526   // for ( i = 1; i < _simplices.size(); ++i )
8527   // {
8528   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8529   //   zAxis = xAxis ^ yAxis;
8530   //   if ( zAxis.SquareModulus() > tol*tol )
8531   //     break;
8532   // }
8533   // if ( i == _simplices.size() ) return newPos;
8534
8535   yAxis = zAxis ^ xAxis;
8536   xAxis /= xAxis.Modulus();
8537   yAxis /= yAxis.Modulus();
8538
8539   // get half-planes of _simplices
8540
8541   vector< _halfPlane > halfPlns( _simplices.size() );
8542   int nbHP = 0;
8543   for ( size_t i = 0; i < _simplices.size(); ++i )
8544   {
8545     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8546     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8547     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8548     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8549     gp_XY  vec12 = p2 - p1;
8550     double dist12 = vec12.Modulus();
8551     if ( dist12 < tol )
8552       continue;
8553     vec12 /= dist12;
8554     halfPlns[ nbHP ]._pos = p1;
8555     halfPlns[ nbHP ]._dir = vec12;
8556     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8557     ++nbHP;
8558   }
8559
8560   // intersect boundaries of half-planes, define state of intersection points
8561   // in relation to all half-planes and calculate internal point of a 2D polygon
8562
8563   double sumLen = 0;
8564   gp_XY newPos2D (0,0);
8565
8566   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8567   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8568   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8569
8570   vector< vector< TIntPntState > > allIntPnts( nbHP );
8571   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8572   {
8573     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8574     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8575
8576     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8577     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8578
8579     int nbNotOut = 0;
8580     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8581
8582     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8583     {
8584       if ( iHP1 == iHP2 ) continue;
8585
8586       TIntPntState & ips1 = intPnts1[ iHP2 ];
8587       if ( ips1.second == UNDEF )
8588       {
8589         // find an intersection point of boundaries of iHP1 and iHP2
8590
8591         if ( iHP2 == iPrev ) // intersection with neighbors is known
8592           ips1.first = halfPlns[ iHP1 ]._pos;
8593         else if ( iHP2 == iNext )
8594           ips1.first = halfPlns[ iHP2 ]._pos;
8595         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8596           ips1.second = NO_INT;
8597
8598         // classify the found intersection point
8599         if ( ips1.second != NO_INT )
8600         {
8601           ips1.second = NOT_OUT;
8602           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8603             if ( i != iHP1 && i != iHP2 &&
8604                  halfPlns[ i ].IsOut( ips1.first, tol ))
8605               ips1.second = IS_OUT;
8606         }
8607         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8608         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8609         TIntPntState & ips2 = intPnts2[ iHP1 ];
8610         ips2 = ips1;
8611       }
8612       if ( ips1.second == NOT_OUT )
8613       {
8614         ++nbNotOut;
8615         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8616       }
8617     }
8618
8619     // find a NOT_OUT segment of boundary which is located between
8620     // two NOT_OUT int points
8621
8622     if ( nbNotOut < 2 )
8623       continue; // no such a segment
8624
8625     if ( nbNotOut > 2 )
8626     {
8627       // sort points along the boundary
8628       map< double, TIntPntState* > ipsByParam;
8629       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8630       {
8631         TIntPntState & ips1 = intPnts1[ iHP2 ];
8632         if ( ips1.second != NO_INT )
8633         {
8634           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8635           double param = op * halfPlns[ iHP1 ]._dir;
8636           ipsByParam.insert( make_pair( param, & ips1 ));
8637         }
8638       }
8639       // look for two neighboring NOT_OUT points
8640       nbNotOut = 0;
8641       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8642       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8643       {
8644         TIntPntState & ips1 = *(u2ips->second);
8645         if ( ips1.second == NOT_OUT )
8646           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8647         else if ( nbNotOut >= 2 )
8648           break;
8649         else
8650           nbNotOut = 0;
8651       }
8652     }
8653
8654     if ( nbNotOut >= 2 )
8655     {
8656       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8657       sumLen += len;
8658
8659       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8660     }
8661   }
8662
8663   if ( sumLen > 0 )
8664   {
8665     newPos2D /= sumLen;
8666     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8667   }
8668   else
8669   {
8670     newPos = center;
8671   }
8672
8673   return newPos;
8674 }
8675 #else // OLD_NEF_POLYGON
8676 { ////////////////////////////////// NEW
8677   gp_XYZ newPos(0,0,0);
8678
8679   // get a plane to seach a solution on
8680
8681   size_t i;
8682   gp_XYZ center(0,0,0);
8683   for ( i = 0; i < _simplices.size(); ++i )
8684     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8685   center /= _simplices.size();
8686
8687   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8688   for ( i = 0; i < _simplices.size(); ++i )
8689     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8690   vecs.back() = vecs[0];
8691
8692   const double tol = numeric_limits<double>::min();
8693   gp_XYZ zAxis(0,0,0);
8694   for ( i = 0; i < _simplices.size(); ++i )
8695   {
8696     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8697     try {
8698       cross.Normalize();
8699       if ( cross * zAxis < tol )
8700         zAxis += cross.Reversed();
8701       else
8702         zAxis += cross;
8703     }
8704     catch (Standard_Failure) { // if |cross| == 0.
8705     }
8706   }
8707
8708   gp_XYZ yAxis;
8709   for ( i = 0; i < _simplices.size(); ++i )
8710   {
8711     yAxis = vecs[i];
8712     if ( yAxis.SquareModulus() > tol )
8713       break;
8714   }
8715   gp_XYZ xAxis = yAxis ^ zAxis;
8716   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8717   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8718   //                             p0.Distance( _simplices[2]._nPrev ));
8719   // gp_XYZ center = smoothLaplacian();
8720   // gp_XYZ xAxis, yAxis, zAxis;
8721   // for ( i = 0; i < _simplices.size(); ++i )
8722   // {
8723   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8724   //   if ( xAxis.SquareModulus() > tol*tol )
8725   //     break;
8726   // }
8727   // for ( i = 1; i < _simplices.size(); ++i )
8728   // {
8729   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8730   //   zAxis = xAxis ^ yAxis;
8731   //   if ( zAxis.SquareModulus() > tol*tol )
8732   //     break;
8733   // }
8734   // if ( i == _simplices.size() ) return newPos;
8735
8736   yAxis = zAxis ^ xAxis;
8737   xAxis /= xAxis.Modulus();
8738   yAxis /= yAxis.Modulus();
8739
8740   // get half-planes of _simplices
8741
8742   vector< _halfPlane > halfPlns( _simplices.size() );
8743   int nbHP = 0;
8744   for ( size_t i = 0; i < _simplices.size(); ++i )
8745   {
8746     const gp_XYZ& OP1 = vecs[ i   ];
8747     const gp_XYZ& OP2 = vecs[ i+1 ];
8748     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8749     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8750     gp_XY  vec12 = p2 - p1;
8751     double dist12 = vec12.Modulus();
8752     if ( dist12 < tol )
8753       continue;
8754     vec12 /= dist12;
8755     halfPlns[ nbHP ]._pos = p1;
8756     halfPlns[ nbHP ]._dir = vec12;
8757     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8758     ++nbHP;
8759   }
8760
8761   // intersect boundaries of half-planes, define state of intersection points
8762   // in relation to all half-planes and calculate internal point of a 2D polygon
8763
8764   double sumLen = 0;
8765   gp_XY newPos2D (0,0);
8766
8767   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8768   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8769   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8770
8771   vector< vector< TIntPntState > > allIntPnts( nbHP );
8772   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8773   {
8774     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8775     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8776
8777     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8778     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8779
8780     int nbNotOut = 0;
8781     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8782
8783     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8784     {
8785       if ( iHP1 == iHP2 ) continue;
8786
8787       TIntPntState & ips1 = intPnts1[ iHP2 ];
8788       if ( ips1.second == UNDEF )
8789       {
8790         // find an intersection point of boundaries of iHP1 and iHP2
8791
8792         if ( iHP2 == iPrev ) // intersection with neighbors is known
8793           ips1.first = halfPlns[ iHP1 ]._pos;
8794         else if ( iHP2 == iNext )
8795           ips1.first = halfPlns[ iHP2 ]._pos;
8796         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8797           ips1.second = NO_INT;
8798
8799         // classify the found intersection point
8800         if ( ips1.second != NO_INT )
8801         {
8802           ips1.second = NOT_OUT;
8803           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8804             if ( i != iHP1 && i != iHP2 &&
8805                  halfPlns[ i ].IsOut( ips1.first, tol ))
8806               ips1.second = IS_OUT;
8807         }
8808         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8809         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8810         TIntPntState & ips2 = intPnts2[ iHP1 ];
8811         ips2 = ips1;
8812       }
8813       if ( ips1.second == NOT_OUT )
8814       {
8815         ++nbNotOut;
8816         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8817       }
8818     }
8819
8820     // find a NOT_OUT segment of boundary which is located between
8821     // two NOT_OUT int points
8822
8823     if ( nbNotOut < 2 )
8824       continue; // no such a segment
8825
8826     if ( nbNotOut > 2 )
8827     {
8828       // sort points along the boundary
8829       map< double, TIntPntState* > ipsByParam;
8830       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8831       {
8832         TIntPntState & ips1 = intPnts1[ iHP2 ];
8833         if ( ips1.second != NO_INT )
8834         {
8835           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8836           double param = op * halfPlns[ iHP1 ]._dir;
8837           ipsByParam.insert( make_pair( param, & ips1 ));
8838         }
8839       }
8840       // look for two neighboring NOT_OUT points
8841       nbNotOut = 0;
8842       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8843       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8844       {
8845         TIntPntState & ips1 = *(u2ips->second);
8846         if ( ips1.second == NOT_OUT )
8847           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8848         else if ( nbNotOut >= 2 )
8849           break;
8850         else
8851           nbNotOut = 0;
8852       }
8853     }
8854
8855     if ( nbNotOut >= 2 )
8856     {
8857       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8858       sumLen += len;
8859
8860       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8861     }
8862   }
8863
8864   if ( sumLen > 0 )
8865   {
8866     newPos2D /= sumLen;
8867     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8868   }
8869   else
8870   {
8871     newPos = center;
8872   }
8873
8874   return newPos;
8875 }
8876 #endif // OLD_NEF_POLYGON
8877
8878 //================================================================================
8879 /*!
8880  * \brief Add a new segment to _LayerEdge during inflation
8881  */
8882 //================================================================================
8883
8884 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8885 {
8886   if ( Is( BLOCKED ))
8887     return;
8888
8889   if ( len > _maxLen )
8890   {
8891     len = _maxLen;
8892     Block( eos.GetData() );
8893   }
8894   const double lenDelta = len - _len;
8895   if ( lenDelta < len * 1e-3  )
8896   {
8897     Block( eos.GetData() );
8898     return;
8899   }
8900
8901   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8902   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8903   gp_XYZ newXYZ;
8904   if ( eos._hyp.IsOffsetMethod() )
8905   {
8906     newXYZ = oldXYZ;
8907     gp_Vec faceNorm;
8908     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8909     while ( faceIt->more() )
8910     {
8911       const SMDS_MeshElement* face = faceIt->next();
8912       if ( !eos.GetNormal( face, faceNorm ))
8913         continue;
8914
8915       // translate plane of a face
8916       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8917
8918       // find point of intersection of the face plane located at baryCenter
8919       // and _normal located at newXYZ
8920       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8921       double dot =  ( faceNorm.XYZ() * _normal );
8922       if ( dot < std::numeric_limits<double>::min() )
8923         dot = lenDelta * 1e-3;
8924       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8925       newXYZ += step * _normal;
8926     }
8927     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8928   }
8929   else
8930   {
8931     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8932   }
8933
8934   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8935   _pos.push_back( newXYZ );
8936
8937   if ( !eos._sWOL.IsNull() )
8938   {
8939     double distXYZ[4];
8940     bool uvOK = false;
8941     if ( eos.SWOLType() == TopAbs_EDGE )
8942     {
8943       double u = Precision::Infinite(); // to force projection w/o distance check
8944       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8945                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8946       _pos.back().SetCoord( u, 0, 0 );
8947       if ( _nodes.size() > 1 && uvOK )
8948       {
8949         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8950         pos->SetUParameter( u );
8951       }
8952     }
8953     else //  TopAbs_FACE
8954     {
8955       gp_XY uv( Precision::Infinite(), 0 );
8956       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8957                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8958       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8959       if ( _nodes.size() > 1 && uvOK )
8960       {
8961         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8962         pos->SetUParameter( uv.X() );
8963         pos->SetVParameter( uv.Y() );
8964       }
8965     }
8966     if ( uvOK )
8967     {
8968       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8969     }
8970     else
8971     {
8972       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8973       _pos.pop_back();
8974       Block( eos.GetData() );
8975       return;
8976     }
8977   }
8978
8979   _len = len;
8980
8981   // notify _neibors
8982   if ( eos.ShapeType() != TopAbs_FACE )
8983   {
8984     for ( size_t i = 0; i < _neibors.size(); ++i )
8985       //if (  _len > _neibors[i]->GetSmooLen() )
8986         _neibors[i]->Set( MOVED );
8987
8988     Set( MOVED );
8989   }
8990   dumpMove( n ); //debug
8991 }
8992
8993 //================================================================================
8994 /*!
8995  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8996  */
8997 //================================================================================
8998
8999 void _LayerEdge::Block( _SolidData& data )
9000 {
9001   //if ( Is( BLOCKED )) return;
9002   Set( BLOCKED );
9003
9004   _maxLen = _len;
9005   std::queue<_LayerEdge*> queue;
9006   queue.push( this );
9007
9008   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9009   while ( !queue.empty() )
9010   {
9011     _LayerEdge* edge = queue.front(); queue.pop();
9012     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9013     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9014     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9015     {
9016       _LayerEdge* neibor = edge->_neibors[iN];
9017       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9018         continue;
9019       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9020       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9021       double minDist = pSrc.SquareDistance( pSrcN );
9022       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9023       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9024       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9025       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9026       if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
9027       {
9028         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9029       }
9030       if ( neibor->_maxLen > newMaxLen )
9031       {
9032         neibor->_maxLen = newMaxLen;
9033         if ( neibor->_maxLen < neibor->_len )
9034         {
9035           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9036           while ( neibor->_len > neibor->_maxLen &&
9037                   neibor->NbSteps() > 1 )
9038             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9039           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9040           //neibor->Block( data );
9041         }
9042         queue.push( neibor );
9043       }
9044     }
9045   }
9046 }
9047
9048 //================================================================================
9049 /*!
9050  * \brief Remove last inflation step
9051  */
9052 //================================================================================
9053
9054 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9055 {
9056   if ( _pos.size() > curStep && _nodes.size() > 1 )
9057   {
9058     _pos.resize( curStep );
9059
9060     gp_Pnt      nXYZ = _pos.back();
9061     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9062     SMESH_TNodeXYZ curXYZ( n );
9063     if ( !eos._sWOL.IsNull() )
9064     {
9065       TopLoc_Location loc;
9066       if ( eos.SWOLType() == TopAbs_EDGE )
9067       {
9068         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9069         pos->SetUParameter( nXYZ.X() );
9070         double f,l;
9071         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9072         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9073       }
9074       else
9075       {
9076         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9077         pos->SetUParameter( nXYZ.X() );
9078         pos->SetVParameter( nXYZ.Y() );
9079         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9080         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9081       }
9082     }
9083     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9084     dumpMove( n );
9085
9086     if ( restoreLength )
9087     {
9088       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9089     }
9090   }
9091 }
9092
9093 //================================================================================
9094 /*!
9095  * \brief Return index of a _pos distant from _normal
9096  */
9097 //================================================================================
9098
9099 int _LayerEdge::GetSmoothedPos( const double tol )
9100 {
9101   int iSmoothed = 0;
9102   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9103   {
9104     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9105     if ( normDist > tol * tol )
9106       iSmoothed = i;
9107   }
9108   return iSmoothed;
9109 }
9110
9111 //================================================================================
9112 /*!
9113  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9114  */
9115 //================================================================================
9116
9117 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9118 {
9119   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9120     return;
9121
9122   // find the 1st smoothed _pos
9123   int iSmoothed = GetSmoothedPos( tol );
9124   if ( !iSmoothed ) return;
9125
9126   //if ( 1 || Is( DISTORTED ))
9127   {
9128     gp_XYZ normal = _normal;
9129     if ( Is( NORMAL_UPDATED ))
9130       for ( size_t i = 1; i < _pos.size(); ++i )
9131       {
9132         normal = _pos[i] - _pos[0];
9133         double size = normal.Modulus();
9134         if ( size > RealSmall() )
9135         {
9136           normal /= size;
9137           break;
9138         }
9139       }
9140     const double r = 0.2;
9141     for ( int iter = 0; iter < 50; ++iter )
9142     {
9143       double minDot = 1;
9144       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9145       {
9146         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9147         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9148         _pos[i] = newPos;
9149         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9150         double newLen = ( 1-r ) * midLen + r * segLen[i];
9151         const_cast< double& >( segLen[i] ) = newLen;
9152         // check angle between normal and (_pos[i+1], _pos[i] )
9153         gp_XYZ posDir = _pos[i+1] - _pos[i];
9154         double size   = posDir.SquareModulus();
9155         if ( size > RealSmall() )
9156           minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9157       }
9158       if ( minDot > 0.5 * 0.5 )
9159         break;
9160     }
9161   }
9162   // else
9163   // {
9164   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
9165   //   {
9166   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
9167   //       continue;
9168
9169   //     double     wgt = segLen[i] / segLen.back();
9170   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9171   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
9172   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
9173   //     _pos[i] = newPos;
9174   //   }
9175   // }
9176 }
9177
9178 //================================================================================
9179 /*!
9180  * \brief Create layers of prisms
9181  */
9182 //================================================================================
9183
9184 bool _ViscousBuilder::refine(_SolidData& data)
9185 {
9186   SMESH_MesherHelper& helper = data.GetHelper();
9187   helper.SetElementsOnShape(false);
9188
9189   Handle(Geom_Curve) curve;
9190   Handle(ShapeAnalysis_Surface) surface;
9191   TopoDS_Edge geomEdge;
9192   TopoDS_Face geomFace;
9193   TopLoc_Location loc;
9194   double f,l, u = 0;
9195   gp_XY uv;
9196   vector< gp_XYZ > pos3D;
9197   bool isOnEdge;
9198   TGeomID prevBaseId = -1;
9199   TNode2Edge* n2eMap = 0;
9200   TNode2Edge::iterator n2e;
9201
9202   // Create intermediate nodes on each _LayerEdge
9203
9204   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9205   {
9206     _EdgesOnShape& eos = data._edgesOnShape[iS];
9207     if ( eos._edges.empty() ) continue;
9208
9209     if ( eos._edges[0]->_nodes.size() < 2 )
9210       continue; // on _noShrinkShapes
9211
9212     // get data of a shrink shape
9213     isOnEdge = false;
9214     geomEdge.Nullify(); geomFace.Nullify();
9215     curve.Nullify(); surface.Nullify();
9216     if ( !eos._sWOL.IsNull() )
9217     {
9218       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9219       if ( isOnEdge )
9220       {
9221         geomEdge = TopoDS::Edge( eos._sWOL );
9222         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9223       }
9224       else
9225       {
9226         geomFace = TopoDS::Face( eos._sWOL );
9227         surface  = helper.GetSurface( geomFace );
9228       }
9229     }
9230     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9231     {
9232       geomFace = TopoDS::Face( eos._shape );
9233       surface  = helper.GetSurface( geomFace );
9234       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9235       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9236       {
9237         eos._eosC1[ i ]->_toSmooth = true;
9238         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9239           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9240       }
9241     }
9242
9243     vector< double > segLen;
9244     for ( size_t i = 0; i < eos._edges.size(); ++i )
9245     {
9246       _LayerEdge& edge = *eos._edges[i];
9247       if ( edge._pos.size() < 2 )
9248         continue;
9249
9250       // get accumulated length of segments
9251       segLen.resize( edge._pos.size() );
9252       segLen[0] = 0.0;
9253       if ( eos._sWOL.IsNull() )
9254       {
9255         bool useNormal = true;
9256         bool   usePos  = false;
9257         bool smoothed  = false;
9258         double   preci = 0.1 * edge._len;
9259         if ( eos._toSmooth && edge._pos.size() > 2 )
9260         {
9261           smoothed = edge.GetSmoothedPos( preci );
9262         }
9263         if ( smoothed )
9264         {
9265           if ( !surface.IsNull() &&
9266                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9267           {
9268             useNormal = usePos = false;
9269             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9270             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9271             {
9272               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9273               if ( surface->Gap() < 2. * edge._len )
9274                 segLen[j] = surface->Gap();
9275               else
9276                 useNormal = true;
9277             }
9278           }
9279         }
9280         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9281         {
9282 #ifndef __NODES_AT_POS
9283           useNormal = usePos = false;
9284           edge._pos[1] = edge._pos.back();
9285           edge._pos.resize( 2 );
9286           segLen.resize( 2 );
9287           segLen[ 1 ] = edge._len;
9288 #endif
9289         }
9290         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9291         {
9292           useNormal = usePos = false;
9293           _LayerEdge tmpEdge; // get original _normal
9294           tmpEdge._nodes.push_back( edge._nodes[0] );
9295           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9296             usePos = true;
9297           else
9298             for ( size_t j = 1; j < edge._pos.size(); ++j )
9299               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9300         }
9301         if ( useNormal )
9302         {
9303           for ( size_t j = 1; j < edge._pos.size(); ++j )
9304             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9305         }
9306         if ( usePos )
9307         {
9308           for ( size_t j = 1; j < edge._pos.size(); ++j )
9309             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9310         }
9311         else
9312         {
9313           bool swapped = ( edge._pos.size() > 2 );
9314           while ( swapped )
9315           {
9316             swapped = false;
9317             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9318               if ( segLen[j] > segLen.back() )
9319               {
9320                 segLen.erase( segLen.begin() + j );
9321                 edge._pos.erase( edge._pos.begin() + j );
9322                 --j;
9323               }
9324               else if ( segLen[j] < segLen[j-1] )
9325               {
9326                 std::swap( segLen[j], segLen[j-1] );
9327                 std::swap( edge._pos[j], edge._pos[j-1] );
9328                 swapped = true;
9329               }
9330           }
9331         }
9332         // smooth a path formed by edge._pos
9333 #ifndef __NODES_AT_POS
9334         if (( smoothed ) /*&&
9335             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9336           edge.SmoothPos( segLen, preci );
9337 #endif
9338       }
9339       else if ( eos._isRegularSWOL ) // usual SWOL
9340       {
9341         for ( size_t j = 1; j < edge._pos.size(); ++j )
9342           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9343       }
9344       else if ( !surface.IsNull() ) // SWOL surface with singularities
9345       {
9346         pos3D.resize( edge._pos.size() );
9347         for ( size_t j = 0; j < edge._pos.size(); ++j )
9348           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9349
9350         for ( size_t j = 1; j < edge._pos.size(); ++j )
9351           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9352       }
9353
9354       // allocate memory for new nodes if it is not yet refined
9355       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9356       if ( edge._nodes.size() == 2 )
9357       {
9358 #ifdef __NODES_AT_POS
9359         int nbNodes = edge._pos.size();
9360 #else
9361         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9362 #endif
9363         edge._nodes.resize( nbNodes, 0 );
9364         edge._nodes[1] = 0;
9365         edge._nodes.back() = tgtNode;
9366       }
9367       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9368       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9369       if ( baseShapeId != prevBaseId )
9370       {
9371         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9372         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9373         prevBaseId = baseShapeId;
9374       }
9375       _LayerEdge* edgeOnSameNode = 0;
9376       bool        useExistingPos = false;
9377       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9378       {
9379         edgeOnSameNode = n2e->second;
9380         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9381         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9382         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9383         if ( isOnEdge )
9384         {
9385           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9386           epos->SetUParameter( otherTgtPos.X() );
9387         }
9388         else
9389         {
9390           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9391           fpos->SetUParameter( otherTgtPos.X() );
9392           fpos->SetVParameter( otherTgtPos.Y() );
9393         }
9394       }
9395       // calculate height of the first layer
9396       double h0;
9397       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9398       const double f = eos._hyp.GetStretchFactor();
9399       const int    N = eos._hyp.GetNumberLayers();
9400       const double fPowN = pow( f, N );
9401       if ( fPowN - 1 <= numeric_limits<double>::min() )
9402         h0 = T / N;
9403       else
9404         h0 = T * ( f - 1 )/( fPowN - 1 );
9405
9406       const double zeroLen = std::numeric_limits<double>::min();
9407
9408       // create intermediate nodes
9409       double hSum = 0, hi = h0/f;
9410       size_t iSeg = 1;
9411       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9412       {
9413         // compute an intermediate position
9414         hi *= f;
9415         hSum += hi;
9416         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9417           ++iSeg;
9418         int iPrevSeg = iSeg-1;
9419         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9420           --iPrevSeg;
9421         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9422         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9423 #ifdef __NODES_AT_POS
9424         pos = edge._pos[ iStep ];
9425 #endif
9426         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9427         if ( !eos._sWOL.IsNull() )
9428         {
9429           // compute XYZ by parameters <pos>
9430           if ( isOnEdge )
9431           {
9432             u = pos.X();
9433             if ( !node )
9434               pos = curve->Value( u ).Transformed(loc);
9435           }
9436           else if ( eos._isRegularSWOL )
9437           {
9438             uv.SetCoord( pos.X(), pos.Y() );
9439             if ( !node )
9440               pos = surface->Value( pos.X(), pos.Y() );
9441           }
9442           else
9443           {
9444             uv.SetCoord( pos.X(), pos.Y() );
9445             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9446             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9447             if ( !node )
9448               pos = surface->Value( uv );
9449           }
9450         }
9451         // create or update the node
9452         if ( !node )
9453         {
9454           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9455           if ( !eos._sWOL.IsNull() )
9456           {
9457             if ( isOnEdge )
9458               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9459             else
9460               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9461           }
9462           else
9463           {
9464             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9465           }
9466         }
9467         else
9468         {
9469           if ( !eos._sWOL.IsNull() )
9470           {
9471             // make average pos from new and current parameters
9472             if ( isOnEdge )
9473             {
9474               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9475               if ( useExistingPos )
9476                 u = helper.GetNodeU( geomEdge, node );
9477               pos = curve->Value( u ).Transformed(loc);
9478
9479               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9480               epos->SetUParameter( u );
9481             }
9482             else
9483             {
9484               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9485               if ( useExistingPos )
9486                 uv = helper.GetNodeUV( geomFace, node );
9487               pos = surface->Value( uv );
9488
9489               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9490               fpos->SetUParameter( uv.X() );
9491               fpos->SetVParameter( uv.Y() );
9492             }
9493           }
9494           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9495         }
9496       } // loop on edge._nodes
9497
9498       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9499       {
9500         if ( isOnEdge )
9501           edge._pos.back().SetCoord( u, 0,0);
9502         else
9503           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9504
9505         if ( edgeOnSameNode )
9506           edgeOnSameNode->_pos.back() = edge._pos.back();
9507       }
9508
9509     } // loop on eos._edges to create nodes
9510
9511
9512     if ( !getMeshDS()->IsEmbeddedMode() )
9513       // Log node movement
9514       for ( size_t i = 0; i < eos._edges.size(); ++i )
9515       {
9516         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9517         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9518       }
9519   }
9520
9521
9522   // Create volumes
9523
9524   helper.SetElementsOnShape(true);
9525
9526   vector< vector<const SMDS_MeshNode*>* > nnVec;
9527   set< vector<const SMDS_MeshNode*>* >    nnSet;
9528   set< int >                       degenEdgeInd;
9529   vector<const SMDS_MeshElement*>     degenVols;
9530   vector<int>                       isRiskySWOL;
9531
9532   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9533   for ( ; exp.More(); exp.Next() )
9534   {
9535     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9536     if ( data._ignoreFaceIds.count( faceID ))
9537       continue;
9538     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9539     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9540     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9541     while ( fIt->more() )
9542     {
9543       const SMDS_MeshElement* face = fIt->next();
9544       const int            nbNodes = face->NbCornerNodes();
9545       nnVec.resize( nbNodes );
9546       nnSet.clear();
9547       degenEdgeInd.clear();
9548       isRiskySWOL.resize( nbNodes );
9549       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9550       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9551       for ( int iN = 0; iN < nbNodes; ++iN )
9552       {
9553         const SMDS_MeshNode* n = nIt->next();
9554         _LayerEdge*       edge = data._n2eMap[ n ];
9555         const int i = isReversedFace ? nbNodes-1-iN : iN;
9556         nnVec[ i ] = & edge->_nodes;
9557         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9558         minZ = std::min( minZ, nnVec[ i ]->size() );
9559         //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9560
9561         if ( helper.HasDegeneratedEdges() )
9562           nnSet.insert( nnVec[ i ]);
9563       }
9564
9565       if ( maxZ == 0 )
9566         continue;
9567       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9568         continue;
9569
9570       switch ( nbNodes )
9571       {
9572       case 3: // TRIA
9573       {
9574         // PENTA
9575         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9576           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9577                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9578
9579         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9580         {
9581           for ( int iN = 0; iN < nbNodes; ++iN )
9582             if ( nnVec[ iN ]->size() < iZ+1 )
9583               degenEdgeInd.insert( iN );
9584
9585           if ( degenEdgeInd.size() == 1 )  // PYRAM
9586           {
9587             int i2 = *degenEdgeInd.begin();
9588             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9589             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9590             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9591                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9592           }
9593           else  // TETRA
9594           {
9595             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9596             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9597                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9598                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9599                               (*nnVec[ i3 ])[ iZ ]);
9600           }
9601         }
9602         break; // TRIA
9603       }
9604       case 4: // QUAD
9605       {
9606         // HEX
9607         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9608           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9609                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9610                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9611                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9612
9613         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9614         {
9615           for ( int iN = 0; iN < nbNodes; ++iN )
9616             if ( nnVec[ iN ]->size() < iZ+1 )
9617               degenEdgeInd.insert( iN );
9618
9619           switch ( degenEdgeInd.size() )
9620           {
9621           case 2: // PENTA
9622           {
9623             int i2 = *degenEdgeInd.begin();
9624             int i3 = *degenEdgeInd.rbegin();
9625             bool ok = ( i3 - i2 == 1 );
9626             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9627             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9628             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9629
9630             const SMDS_MeshElement* vol =
9631               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9632                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9633             if ( !ok && vol )
9634               degenVols.push_back( vol );
9635           }
9636           break;
9637
9638           default: // degen HEX
9639           {
9640             const SMDS_MeshElement* vol =
9641               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9642                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9643                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9644                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9645                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9646                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9647                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9648                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9649             degenVols.push_back( vol );
9650           }
9651           }
9652         }
9653         break; // HEX
9654       }
9655       default:
9656         return error("Not supported type of element", data._index);
9657
9658       } // switch ( nbNodes )
9659     } // while ( fIt->more() )
9660   } // loop on FACEs
9661
9662   if ( !degenVols.empty() )
9663   {
9664     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9665     if ( !err || err->IsOK() )
9666     {
9667       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9668                                          "Degenerated volumes created" ));
9669       err->myBadElements.insert( err->myBadElements.end(),
9670                                  degenVols.begin(),degenVols.end() );
9671     }
9672   }
9673
9674   return true;
9675 }
9676
9677 //================================================================================
9678 /*!
9679  * \brief Shrink 2D mesh on faces to let space for inflated layers
9680  */
9681 //================================================================================
9682
9683 bool _ViscousBuilder::shrink(_SolidData& theData)
9684 {
9685   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
9686   // _LayerEdge's inflated along FACE or EDGE)
9687   map< TGeomID, list< _SolidData* > > f2sdMap;
9688   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9689   {
9690     _SolidData& data = _sdVec[i];
9691     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9692     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9693       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
9694       {
9695         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
9696
9697         // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9698         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9699         // by StdMeshers_QuadToTriaAdaptor
9700         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9701         {
9702           SMESH_ProxyMesh::SubMesh* proxySub =
9703             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9704           if ( proxySub->NbElements() == 0 )
9705           {
9706             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9707             while ( fIt->more() )
9708             {
9709               const SMDS_MeshElement* f = fIt->next();
9710               // as a result 3D algo will use elements from proxySub and not from smDS
9711               proxySub->AddElement( f );
9712               f->setIsMarked( true );
9713
9714               // Mark nodes on the FACE to discriminate them from nodes
9715               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
9716               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
9717               {
9718                 const SMDS_MeshNode* n = f->GetNode( iN );
9719                 if ( n->GetPosition()->GetDim() == 2 )
9720                   n->setIsMarked( true );
9721               }
9722             }
9723           }
9724         }
9725       }
9726   }
9727
9728   SMESH_MesherHelper helper( *_mesh );
9729   helper.ToFixNodeParameters( true );
9730
9731   // EDGEs to shrink
9732   map< TGeomID, _Shrinker1D > e2shrMap;
9733   vector< _EdgesOnShape* > subEOS;
9734   vector< _LayerEdge* > lEdges;
9735
9736   // loop on FACEs to srink mesh on
9737   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
9738   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9739   {
9740     list< _SolidData* > & dataList = f2sd->second;
9741     if ( dataList.front()->_n2eMap.empty() ||
9742          dataList.back() ->_n2eMap.empty() )
9743       continue; // not yet computed
9744     if ( dataList.front() != &theData &&
9745          dataList.back()  != &theData )
9746       continue;
9747
9748     _SolidData&      data = *dataList.front();
9749     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9750     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9751     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9752
9753     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
9754
9755     _shrinkedFaces.Add( F );
9756     helper.SetSubShape( F );
9757
9758     // ===========================
9759     // Prepare data for shrinking
9760     // ===========================
9761
9762     // Collect nodes to smooth, they are marked at the beginning of this method
9763     vector < const SMDS_MeshNode* > smoothNodes;
9764     {
9765       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9766       while ( nIt->more() )
9767       {
9768         const SMDS_MeshNode* n = nIt->next();
9769         if ( n->isMarked() )
9770           smoothNodes.push_back( n );
9771       }
9772     }
9773     // Find out face orientation
9774     double refSign = 1;
9775     const set<TGeomID> ignoreShapes;
9776     bool isOkUV;
9777     if ( !smoothNodes.empty() )
9778     {
9779       vector<_Simplex> simplices;
9780       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9781       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
9782       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9783       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9784       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
9785         refSign = -1;
9786     }
9787
9788     // Find _LayerEdge's inflated along F
9789     subEOS.clear();
9790     lEdges.clear();
9791     {
9792       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9793                                                                 /*complexFirst=*/true); //!!!
9794       while ( subIt->more() )
9795       {
9796         const TGeomID subID = subIt->next()->GetId();
9797         if ( data._noShrinkShapes.count( subID ))
9798           continue;
9799         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9800         if ( !eos || eos->_sWOL.IsNull() ) continue;
9801
9802         subEOS.push_back( eos );
9803
9804         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9805         {
9806           lEdges.push_back( eos->_edges[ i ] );
9807           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9808         }
9809       }
9810     }
9811
9812     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9813     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9814     while ( fIt->more() )
9815       if ( const SMDS_MeshElement* f = fIt->next() )
9816         dumpChangeNodes( f );
9817     dumpFunctionEnd();
9818
9819     // Replace source nodes by target nodes in mesh faces to shrink
9820     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9821     const SMDS_MeshNode* nodes[20];
9822     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9823     {
9824       _EdgesOnShape& eos = * subEOS[ iS ];
9825       for ( size_t i = 0; i < eos._edges.size(); ++i )
9826       {
9827         _LayerEdge& edge = *eos._edges[i];
9828         const SMDS_MeshNode* srcNode = edge._nodes[0];
9829         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9830         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9831         while ( fIt->more() )
9832         {
9833           const SMDS_MeshElement* f = fIt->next();
9834           if ( !smDS->Contains( f ) || !f->isMarked() )
9835             continue;
9836           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9837           for ( int iN = 0; nIt->more(); ++iN )
9838           {
9839             const SMDS_MeshNode* n = nIt->next();
9840             nodes[iN] = ( n == srcNode ? tgtNode : n );
9841           }
9842           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9843           dumpChangeNodes( f );
9844         }
9845       }
9846     }
9847     dumpFunctionEnd();
9848
9849     // find out if a FACE is concave
9850     const bool isConcaveFace = isConcave( F, helper );
9851
9852     // Create _SmoothNode's on face F
9853     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9854     {
9855       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9856       const bool sortSimplices = isConcaveFace;
9857       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9858       {
9859         const SMDS_MeshNode* n = smoothNodes[i];
9860         nodesToSmooth[ i ]._node = n;
9861         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9862         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9863         // fix up incorrect uv of nodes on the FACE
9864         helper.GetNodeUV( F, n, 0, &isOkUV);
9865         dumpMove( n );
9866       }
9867       dumpFunctionEnd();
9868     }
9869     //if ( nodesToSmooth.empty() ) continue;
9870
9871     // Find EDGE's to shrink and set simpices to LayerEdge's
9872     set< _Shrinker1D* > eShri1D;
9873     {
9874       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9875       {
9876         _EdgesOnShape& eos = * subEOS[ iS ];
9877         if ( eos.SWOLType() == TopAbs_EDGE )
9878         {
9879           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9880           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9881           eShri1D.insert( & srinker );
9882           srinker.AddEdge( eos._edges[0], eos, helper );
9883           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9884           // restore params of nodes on EGDE if the EDGE has been already
9885           // srinked while srinking other FACE
9886           srinker.RestoreParams();
9887         }
9888         for ( size_t i = 0; i < eos._edges.size(); ++i )
9889         {
9890           _LayerEdge& edge = * eos._edges[i];
9891           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9892
9893           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
9894           // not-marked nodes are those added by refine()
9895           edge._nodes.back()->setIsMarked( true );
9896         }
9897       }
9898     }
9899
9900     bool toFixTria = false; // to improve quality of trias by diagonal swap
9901     if ( isConcaveFace )
9902     {
9903       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9904       if ( hasTria != hasQuad ) {
9905         toFixTria = hasTria;
9906       }
9907       else {
9908         set<int> nbNodesSet;
9909         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9910         while ( fIt->more() && nbNodesSet.size() < 2 )
9911           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9912         toFixTria = ( *nbNodesSet.begin() == 3 );
9913       }
9914     }
9915
9916     // ==================
9917     // Perform shrinking
9918     // ==================
9919
9920     bool shrinked = true;
9921     int nbBad, shriStep=0, smooStep=0;
9922     _SmoothNode::SmoothType smoothType
9923       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9924     SMESH_Comment errMsg;
9925     while ( shrinked )
9926     {
9927       shriStep++;
9928       // Move boundary nodes (actually just set new UV)
9929       // -----------------------------------------------
9930       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9931       shrinked = false;
9932       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9933       {
9934         _EdgesOnShape& eos = * subEOS[ iS ];
9935         for ( size_t i = 0; i < eos._edges.size(); ++i )
9936         {
9937           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9938         }
9939       }
9940       dumpFunctionEnd();
9941
9942       // Move nodes on EDGE's
9943       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9944       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9945       for ( ; shr != eShri1D.end(); ++shr )
9946         (*shr)->Compute( /*set3D=*/false, helper );
9947
9948       // Smoothing in 2D
9949       // -----------------
9950       int nbNoImpSteps = 0;
9951       bool       moved = true;
9952       nbBad = 1;
9953       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9954       {
9955         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9956
9957         int oldBadNb = nbBad;
9958         nbBad = 0;
9959         moved = false;
9960         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9961         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9962         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9963         {
9964           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9965                                             smooTy, /*set3D=*/isConcaveFace);
9966         }
9967         if ( nbBad < oldBadNb )
9968           nbNoImpSteps = 0;
9969         else
9970           nbNoImpSteps++;
9971
9972         dumpFunctionEnd();
9973       }
9974
9975       errMsg.clear();
9976       if ( nbBad > 0 )
9977         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9978       if ( shriStep > 200 )
9979         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9980       if ( !errMsg.empty() )
9981         break;
9982
9983       // Fix narrow triangles by swapping diagonals
9984       // ---------------------------------------
9985       if ( toFixTria )
9986       {
9987         set<const SMDS_MeshNode*> usedNodes;
9988         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9989
9990         // update working data
9991         set<const SMDS_MeshNode*>::iterator n;
9992         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9993         {
9994           n = usedNodes.find( nodesToSmooth[ i ]._node );
9995           if ( n != usedNodes.end())
9996           {
9997             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9998                                     nodesToSmooth[ i ]._simplices,
9999                                     ignoreShapes, NULL,
10000                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10001             usedNodes.erase( n );
10002           }
10003         }
10004         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10005         {
10006           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10007           if ( n != usedNodes.end())
10008           {
10009             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10010                                     lEdges[i]->_simplices,
10011                                     ignoreShapes );
10012             usedNodes.erase( n );
10013           }
10014         }
10015       }
10016       // TODO: check effect of this additional smooth
10017       // additional laplacian smooth to increase allowed shrink step
10018       // for ( int st = 1; st; --st )
10019       // {
10020       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10021       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10022       //   {
10023       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10024       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
10025       //   }
10026       // }
10027
10028     } // while ( shrinked )
10029
10030     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10031     {
10032       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10033
10034       // remove faces
10035       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10036       {
10037         vector< const SMDS_MeshElement* > facesToRm;
10038         if ( psm )
10039         {
10040           facesToRm.reserve( psm->NbElements() );
10041           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10042             facesToRm.push_back( ite->next() );
10043
10044           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10045             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10046               psm->Clear();
10047         }
10048         for ( size_t i = 0; i < facesToRm.size(); ++i )
10049           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10050       }
10051       // remove nodes
10052       {
10053         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10054         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10055           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10056             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10057                                 subEOS[iS]->_edges[i]->_nodes.end() );
10058         }
10059         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10060         while ( itn->more() ) {
10061           const SMDS_MeshNode* n = itn->next();
10062           if ( !nodesToKeep.count( n ))
10063             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10064         }
10065       }
10066       // restore position and UV of target nodes
10067       gp_Pnt p;
10068       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10069         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10070         {
10071           _LayerEdge*       edge = subEOS[iS]->_edges[i];
10072           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10073           if ( edge->_pos.empty() ||
10074                edge->Is( _LayerEdge::SHRUNK )) continue;
10075           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10076           {
10077             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10078             pos->SetUParameter( edge->_pos[0].X() );
10079             pos->SetVParameter( edge->_pos[0].Y() );
10080             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10081           }
10082           else
10083           {
10084             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10085             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10086             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10087           }
10088           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10089           dumpMove( tgtNode );
10090         }
10091       // shrink EDGE sub-meshes and set proxy sub-meshes
10092       UVPtStructVec uvPtVec;
10093       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10094       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10095       {
10096         _Shrinker1D* shr = (*shrIt);
10097         shr->Compute( /*set3D=*/true, helper );
10098
10099         // set proxy mesh of EDGEs w/o layers
10100         map< double, const SMDS_MeshNode* > nodes;
10101         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10102         // remove refinement nodes
10103         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10104         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10105         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10106         if ( u2n->second == sn0 || u2n->second == sn1 )
10107         {
10108           while ( u2n->second != tn0 && u2n->second != tn1 )
10109             ++u2n;
10110           nodes.erase( nodes.begin(), u2n );
10111         }
10112         u2n = --nodes.end();
10113         if ( u2n->second == sn0 || u2n->second == sn1 )
10114         {
10115           while ( u2n->second != tn0 && u2n->second != tn1 )
10116             --u2n;
10117           nodes.erase( ++u2n, nodes.end() );
10118         }
10119         // set proxy sub-mesh
10120         uvPtVec.resize( nodes.size() );
10121         u2n = nodes.begin();
10122         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10123         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10124         {
10125           uvPtVec[ i ].node = u2n->second;
10126           uvPtVec[ i ].param = u2n->first;
10127           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10128         }
10129         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10130         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10131       }
10132
10133       // set proxy mesh of EDGEs with layers
10134       vector< _LayerEdge* > edges;
10135       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10136       {
10137         _EdgesOnShape& eos = * subEOS[ iS ];
10138         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10139
10140         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10141         data.SortOnEdge( E, eos._edges );
10142
10143         edges.clear();
10144         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10145           if ( !eov->_edges.empty() )
10146             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10147
10148         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10149
10150         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10151           if ( !eov->_edges.empty() )
10152             edges.push_back( eov->_edges[0] ); // on last VERTEX
10153
10154         uvPtVec.resize( edges.size() );
10155         for ( size_t i = 0; i < edges.size(); ++i )
10156         {
10157           uvPtVec[ i ].node = edges[i]->_nodes.back();
10158           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10159           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10160         }
10161         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10162         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10163         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10164       }
10165       // temporary clear the FACE sub-mesh from faces made by refine()
10166       vector< const SMDS_MeshElement* > elems;
10167       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10168       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10169         elems.push_back( ite->next() );
10170       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10171         elems.push_back( ite->next() );
10172       smDS->Clear();
10173
10174       // compute the mesh on the FACE
10175       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10176       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10177
10178       // re-fill proxy sub-meshes of the FACE
10179       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10180         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10181           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10182             psm->AddElement( ite->next() );
10183
10184       // re-fill smDS
10185       for ( size_t i = 0; i < elems.size(); ++i )
10186         smDS->AddElement( elems[i] );
10187
10188       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10189         return error( errMsg );
10190
10191     } // end of re-meshing in case of failed smoothing
10192     else
10193     {
10194       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10195       bool isStructuredFixed = false;
10196       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10197         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10198       if ( !isStructuredFixed )
10199       {
10200         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10201           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10202
10203         for ( int st = 3; st; --st )
10204         {
10205           switch( st ) {
10206           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10207           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10208           case 3: smoothType = _SmoothNode::ANGULAR; break;
10209           }
10210           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10211           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10212           {
10213             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10214                                      smoothType,/*set3D=*/st==1 );
10215           }
10216           dumpFunctionEnd();
10217         }
10218       }
10219       if ( !getMeshDS()->IsEmbeddedMode() )
10220         // Log node movement
10221         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10222         {
10223           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10224           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10225         }
10226     }
10227
10228     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10229     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10230
10231   } // loop on FACES to srink mesh on
10232
10233
10234   // Replace source nodes by target nodes in shrinked mesh edges
10235
10236   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10237   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10238     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10239
10240   return true;
10241 }
10242
10243 //================================================================================
10244 /*!
10245  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10246  */
10247 //================================================================================
10248
10249 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10250                                            _EdgesOnShape&         eos,
10251                                            SMESH_MesherHelper&    helper,
10252                                            const SMESHDS_SubMesh* faceSubMesh)
10253 {
10254   const SMDS_MeshNode* srcNode = edge._nodes[0];
10255   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10256
10257   if ( eos.SWOLType() == TopAbs_FACE )
10258   {
10259     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10260     {
10261       edge._pos.clear();
10262       edge.Set( _LayerEdge::SHRUNK );
10263       return srcNode == tgtNode;
10264     }
10265     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10266     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10267     gp_Vec2d uvDir( srcUV, tgtUV );
10268     double uvLen = uvDir.Magnitude();
10269     uvDir /= uvLen;
10270     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10271     edge._len = uvLen;
10272
10273     //edge._pos.resize(1);
10274     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10275
10276     // set UV of source node to target node
10277     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10278     pos->SetUParameter( srcUV.X() );
10279     pos->SetVParameter( srcUV.Y() );
10280   }
10281   else // _sWOL is TopAbs_EDGE
10282   {
10283     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10284     {
10285       edge._pos.clear();
10286       edge.Set( _LayerEdge::SHRUNK );
10287       return srcNode == tgtNode;
10288     }
10289     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10290     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10291     if ( !edgeSM || edgeSM->NbElements() == 0 )
10292       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10293
10294     const SMDS_MeshNode* n2 = 0;
10295     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10296     while ( eIt->more() && !n2 )
10297     {
10298       const SMDS_MeshElement* e = eIt->next();
10299       if ( !edgeSM->Contains(e)) continue;
10300       n2 = e->GetNode( 0 );
10301       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10302     }
10303     if ( !n2 )
10304       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10305
10306     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10307     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10308     double u2   = helper.GetNodeU( E, n2, srcNode );
10309
10310     //edge._pos.clear();
10311
10312     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10313     {
10314       // tgtNode is located so that it does not make faces with wrong orientation
10315       edge.Set( _LayerEdge::SHRUNK );
10316       return true;
10317     }
10318     //edge._pos.resize(1);
10319     edge._pos[0].SetCoord( U_TGT, uTgt );
10320     edge._pos[0].SetCoord( U_SRC, uSrc );
10321     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10322
10323     edge._simplices.resize( 1 );
10324     edge._simplices[0]._nPrev = n2;
10325
10326     // set U of source node to the target node
10327     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10328     pos->SetUParameter( uSrc );
10329   }
10330   return true;
10331 }
10332
10333 //================================================================================
10334 /*!
10335  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10336  */
10337 //================================================================================
10338
10339 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10340 {
10341   if ( edge._nodes.size() == 1 )
10342   {
10343     edge._pos.clear();
10344     edge._len = 0;
10345
10346     const SMDS_MeshNode* srcNode = edge._nodes[0];
10347     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10348     if ( S.IsNull() ) return;
10349
10350     gp_Pnt p;
10351
10352     switch ( S.ShapeType() )
10353     {
10354     case TopAbs_EDGE:
10355     {
10356       double f,l;
10357       TopLoc_Location loc;
10358       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10359       if ( curve.IsNull() ) return;
10360       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10361       p = curve->Value( ePos->GetUParameter() );
10362       break;
10363     }
10364     case TopAbs_VERTEX:
10365     {
10366       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10367       break;
10368     }
10369     default: return;
10370     }
10371     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10372     dumpMove( srcNode );
10373   }
10374 }
10375
10376 //================================================================================
10377 /*!
10378  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10379  */
10380 //================================================================================
10381
10382 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10383                                   SMESH_MesherHelper&         helper,
10384                                   const bool                  is2D,
10385                                   const int                   step,
10386                                   set<const SMDS_MeshNode*> * involvedNodes)
10387 {
10388   SMESH::Controls::AspectRatio qualifier;
10389   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10390   const double maxAspectRatio = is2D ? 4. : 2;
10391   _NodeCoordHelper xyz( F, helper, is2D );
10392
10393   // find bad triangles
10394
10395   vector< const SMDS_MeshElement* > badTrias;
10396   vector< double >                  badAspects;
10397   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10398   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10399   while ( fIt->more() )
10400   {
10401     const SMDS_MeshElement * f = fIt->next();
10402     if ( f->NbCornerNodes() != 3 ) continue;
10403     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10404     double aspect = qualifier.GetValue( points );
10405     if ( aspect > maxAspectRatio )
10406     {
10407       badTrias.push_back( f );
10408       badAspects.push_back( aspect );
10409     }
10410   }
10411   if ( step == 1 )
10412   {
10413     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10414     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10415     while ( fIt->more() )
10416     {
10417       const SMDS_MeshElement * f = fIt->next();
10418       if ( f->NbCornerNodes() == 3 )
10419         dumpChangeNodes( f );
10420     }
10421     dumpFunctionEnd();
10422   }
10423   if ( badTrias.empty() )
10424     return;
10425
10426   // find couples of faces to swap diagonal
10427
10428   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10429   vector< T2Trias > triaCouples; 
10430
10431   TIDSortedElemSet involvedFaces, emptySet;
10432   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10433   {
10434     T2Trias trias    [3];
10435     double  aspRatio [3];
10436     int i1, i2, i3;
10437
10438     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10439       continue;
10440     for ( int iP = 0; iP < 3; ++iP )
10441       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10442
10443     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10444     int bestCouple = -1;
10445     for ( int iSide = 0; iSide < 3; ++iSide )
10446     {
10447       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10448       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10449       trias [iSide].first  = badTrias[iTia];
10450       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10451                                                              & i1, & i2 );
10452       if (( ! trias[iSide].second ) ||
10453           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10454           ( ! sm->Contains( trias[iSide].second )))
10455         continue;
10456
10457       // aspect ratio of an adjacent tria
10458       for ( int iP = 0; iP < 3; ++iP )
10459         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10460       double aspectInit = qualifier.GetValue( points2 );
10461
10462       // arrange nodes as after diag-swaping
10463       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10464         i3 = helper.WrapIndex( i1-1, 3 );
10465       else
10466         i3 = helper.WrapIndex( i1+1, 3 );
10467       points1 = points;
10468       points1( 1+ iSide ) = points2( 1+ i3 );
10469       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10470
10471       // aspect ratio after diag-swaping
10472       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10473       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10474         continue;
10475
10476       // prevent inversion of a triangle
10477       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10478       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10479       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10480         continue;
10481
10482       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10483         bestCouple = iSide;
10484     }
10485
10486     if ( bestCouple >= 0 )
10487     {
10488       triaCouples.push_back( trias[bestCouple] );
10489       involvedFaces.insert ( trias[bestCouple].second );
10490     }
10491     else
10492     {
10493       involvedFaces.erase( badTrias[iTia] );
10494     }
10495   }
10496   if ( triaCouples.empty() )
10497     return;
10498
10499   // swap diagonals
10500
10501   SMESH_MeshEditor editor( helper.GetMesh() );
10502   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10503   for ( size_t i = 0; i < triaCouples.size(); ++i )
10504   {
10505     dumpChangeNodes( triaCouples[i].first );
10506     dumpChangeNodes( triaCouples[i].second );
10507     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10508   }
10509
10510   if ( involvedNodes )
10511     for ( size_t i = 0; i < triaCouples.size(); ++i )
10512     {
10513       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10514                              triaCouples[i].first->end_nodes() );
10515       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10516                              triaCouples[i].second->end_nodes() );
10517     }
10518
10519   // just for debug dump resulting triangles
10520   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10521   for ( size_t i = 0; i < triaCouples.size(); ++i )
10522   {
10523     dumpChangeNodes( triaCouples[i].first );
10524     dumpChangeNodes( triaCouples[i].second );
10525   }
10526 }
10527
10528 //================================================================================
10529 /*!
10530  * \brief Move target node to it's final position on the FACE during shrinking
10531  */
10532 //================================================================================
10533
10534 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10535                                  const TopoDS_Face&    F,
10536                                  _EdgesOnShape&        eos,
10537                                  SMESH_MesherHelper&   helper )
10538 {
10539   if ( Is( SHRUNK ))
10540     return false; // already at the target position
10541
10542   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10543
10544   if ( eos.SWOLType() == TopAbs_FACE )
10545   {
10546     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10547     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10548     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10549     const double uvLen = tgtUV.Distance( curUV );
10550     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10551
10552     // Select shrinking step such that not to make faces with wrong orientation.
10553     double stepSize = 1e100;
10554     for ( size_t i = 0; i < _simplices.size(); ++i )
10555     {
10556       if ( !_simplices[i]._nPrev->isMarked() ||
10557            !_simplices[i]._nNext->isMarked() )
10558         continue; // simplex of quadrangle created by addBoundaryElements()
10559
10560       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10561       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10562       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10563       gp_XY dirN = uvN2 - uvN1;
10564       double det = uvDir.Crossed( dirN );
10565       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10566       gp_XY dirN2Cur = curUV - uvN1;
10567       double step = dirN.Crossed( dirN2Cur ) / det;
10568       if ( step > 0 )
10569         stepSize = Min( step, stepSize );
10570     }
10571     gp_Pnt2d newUV;
10572     if ( uvLen <= stepSize )
10573     {
10574       newUV = tgtUV;
10575       Set( SHRUNK );
10576       //_pos.clear();
10577     }
10578     else if ( stepSize > 0 )
10579     {
10580       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10581     }
10582     else
10583     {
10584       return true;
10585     }
10586     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10587     pos->SetUParameter( newUV.X() );
10588     pos->SetVParameter( newUV.Y() );
10589
10590 #ifdef __myDEBUG
10591     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10592     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10593     dumpMove( tgtNode );
10594 #endif
10595   }
10596   else // _sWOL is TopAbs_EDGE
10597   {
10598     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10599     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10600     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10601
10602     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10603     const double uSrc   = _pos[0].Coord( U_SRC );
10604     const double lenTgt = _pos[0].Coord( LEN_TGT );
10605
10606     double newU = _pos[0].Coord( U_TGT );
10607     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10608     {
10609       Set( _LayerEdge::SHRUNK );
10610       //_pos.clear();
10611     }
10612     else
10613     {
10614       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10615     }
10616     tgtPos->SetUParameter( newU );
10617 #ifdef __myDEBUG
10618     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10619     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10620     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10621     dumpMove( tgtNode );
10622 #endif
10623   }
10624
10625   return true;
10626 }
10627
10628 //================================================================================
10629 /*!
10630  * \brief Perform smooth on the FACE
10631  *  \retval bool - true if the node has been moved
10632  */
10633 //================================================================================
10634
10635 bool _SmoothNode::Smooth(int&                  nbBad,
10636                          Handle(Geom_Surface)& surface,
10637                          SMESH_MesherHelper&   helper,
10638                          const double          refSign,
10639                          SmoothType            how,
10640                          bool                  set3D)
10641 {
10642   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10643
10644   // get uv of surrounding nodes
10645   vector<gp_XY> uv( _simplices.size() );
10646   for ( size_t i = 0; i < _simplices.size(); ++i )
10647     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10648
10649   // compute new UV for the node
10650   gp_XY newPos (0,0);
10651   if ( how == TFI && _simplices.size() == 4 )
10652   {
10653     gp_XY corners[4];
10654     for ( size_t i = 0; i < _simplices.size(); ++i )
10655       if ( _simplices[i]._nOpp )
10656         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10657       else
10658         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10659
10660     newPos = helper.calcTFI ( 0.5, 0.5,
10661                               corners[0], corners[1], corners[2], corners[3],
10662                               uv[1], uv[2], uv[3], uv[0] );
10663   }
10664   else if ( how == ANGULAR )
10665   {
10666     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10667   }
10668   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10669   {
10670     // average centers of diagonals wieghted with their reciprocal lengths
10671     if ( _simplices.size() == 4 )
10672     {
10673       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10674       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10675       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10676     }
10677     else
10678     {
10679       double sumWeight = 0;
10680       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10681       for ( int i = 0; i < nb; ++i )
10682       {
10683         int iFrom = i + 2;
10684         int iTo   = i + _simplices.size() - 1;
10685         for ( int j = iFrom; j < iTo; ++j )
10686         {
10687           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10688           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10689           sumWeight += w;
10690           newPos += w * ( uv[i]+uv[i2] );
10691         }
10692       }
10693       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10694     }
10695   }
10696   else
10697   {
10698     // Laplacian smooth
10699     for ( size_t i = 0; i < _simplices.size(); ++i )
10700       newPos += uv[i];
10701     newPos /= _simplices.size();
10702   }
10703
10704   // count quality metrics (orientation) of triangles around the node
10705   int nbOkBefore = 0;
10706   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10707   for ( size_t i = 0; i < _simplices.size(); ++i )
10708     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10709
10710   int nbOkAfter = 0;
10711   for ( size_t i = 0; i < _simplices.size(); ++i )
10712     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10713
10714   if ( nbOkAfter < nbOkBefore )
10715   {
10716     nbBad += _simplices.size() - nbOkBefore;
10717     return false;
10718   }
10719
10720   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10721   pos->SetUParameter( newPos.X() );
10722   pos->SetVParameter( newPos.Y() );
10723
10724 #ifdef __myDEBUG
10725   set3D = true;
10726 #endif
10727   if ( set3D )
10728   {
10729     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10730     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10731     dumpMove( _node );
10732   }
10733
10734   nbBad += _simplices.size() - nbOkAfter;
10735   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10736 }
10737
10738 //================================================================================
10739 /*!
10740  * \brief Computes new UV using angle based smoothing technic
10741  */
10742 //================================================================================
10743
10744 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10745                                      const gp_XY&   uvToFix,
10746                                      const double   refSign)
10747 {
10748   uv.push_back( uv.front() );
10749
10750   vector< gp_XY >  edgeDir ( uv.size() );
10751   vector< double > edgeSize( uv.size() );
10752   for ( size_t i = 1; i < edgeDir.size(); ++i )
10753   {
10754     edgeDir [i-1] = uv[i] - uv[i-1];
10755     edgeSize[i-1] = edgeDir[i-1].Modulus();
10756     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10757       edgeDir[i-1].SetX( 100 );
10758     else
10759       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10760   }
10761   edgeDir.back()  = edgeDir.front();
10762   edgeSize.back() = edgeSize.front();
10763
10764   gp_XY  newPos(0,0);
10765   //int    nbEdges = 0;
10766   double sumSize = 0;
10767   for ( size_t i = 1; i < edgeDir.size(); ++i )
10768   {
10769     if ( edgeDir[i-1].X() > 1. ) continue;
10770     int i1 = i-1;
10771     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10772     if ( i == edgeDir.size() ) break;
10773     gp_XY p = uv[i];
10774     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10775     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10776     gp_XY bisec = norm1 + norm2;
10777     double bisecSize = bisec.Modulus();
10778     if ( bisecSize < numeric_limits<double>::min() )
10779     {
10780       bisec = -edgeDir[i1] + edgeDir[i];
10781       bisecSize = bisec.Modulus();
10782     }
10783     bisec /= bisecSize;
10784
10785     gp_XY  dirToN  = uvToFix - p;
10786     double distToN = dirToN.Modulus();
10787     if ( bisec * dirToN < 0 )
10788       distToN = -distToN;
10789
10790     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10791     //++nbEdges;
10792     sumSize += edgeSize[i1] + edgeSize[i];
10793   }
10794   newPos /= /*nbEdges * */sumSize;
10795   return newPos;
10796 }
10797
10798 //================================================================================
10799 /*!
10800  * \brief Delete _SolidData
10801  */
10802 //================================================================================
10803
10804 _SolidData::~_SolidData()
10805 {
10806   TNode2Edge::iterator n2e = _n2eMap.begin();
10807   for ( ; n2e != _n2eMap.end(); ++n2e )
10808   {
10809     _LayerEdge* & e = n2e->second;
10810     if ( e )
10811     {
10812       delete e->_curvature;
10813       if ( e->_2neibors )
10814         delete e->_2neibors->_plnNorm;
10815       delete e->_2neibors;
10816     }
10817     delete e;
10818     e = 0;
10819   }
10820   _n2eMap.clear();
10821
10822   delete _helper;
10823   _helper = 0;
10824 }
10825
10826 //================================================================================
10827 /*!
10828  * \brief Keep a _LayerEdge inflated along the EDGE
10829  */
10830 //================================================================================
10831
10832 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10833                            _EdgesOnShape&      eos,
10834                            SMESH_MesherHelper& helper )
10835 {
10836   // init
10837   if ( _nodes.empty() )
10838   {
10839     _edges[0] = _edges[1] = 0;
10840     _done = false;
10841   }
10842   // check _LayerEdge
10843   if ( e == _edges[0] || e == _edges[1] )
10844     return;
10845   if ( eos.SWOLType() != TopAbs_EDGE )
10846     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10847   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10848     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10849
10850   // store _LayerEdge
10851   _geomEdge = TopoDS::Edge( eos._sWOL );
10852   double f,l;
10853   BRep_Tool::Range( _geomEdge, f,l );
10854   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10855   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10856
10857   // Update _nodes
10858
10859   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10860   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10861
10862   if ( _nodes.empty() )
10863   {
10864     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10865     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10866       return;
10867     TopLoc_Location loc;
10868     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10869     GeomAdaptor_Curve aCurve(C, f,l);
10870     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10871
10872     int nbExpectNodes = eSubMesh->NbNodes();
10873     _initU  .reserve( nbExpectNodes );
10874     _normPar.reserve( nbExpectNodes );
10875     _nodes  .reserve( nbExpectNodes );
10876     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10877     while ( nIt->more() )
10878     {
10879       const SMDS_MeshNode* node = nIt->next();
10880
10881       // skip refinement nodes
10882       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10883            node == tgtNode0 || node == tgtNode1 )
10884         continue;
10885       bool hasMarkedFace = false;
10886       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
10887       while ( fIt->more() && !hasMarkedFace )
10888         hasMarkedFace = fIt->next()->isMarked();
10889       if ( !hasMarkedFace )
10890         continue;
10891
10892       _nodes.push_back( node );
10893       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10894       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10895       _normPar.push_back(  len / totLen );
10896     }
10897   }
10898   else
10899   {
10900     // remove target node of the _LayerEdge from _nodes
10901     size_t nbFound = 0;
10902     for ( size_t i = 0; i < _nodes.size(); ++i )
10903       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10904         _nodes[i] = 0, nbFound++;
10905     if ( nbFound == _nodes.size() )
10906       _nodes.clear();
10907   }
10908 }
10909
10910 //================================================================================
10911 /*!
10912  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10913  */
10914 //================================================================================
10915
10916 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10917 {
10918   if ( _done || _nodes.empty())
10919     return;
10920   const _LayerEdge* e = _edges[0];
10921   if ( !e ) e = _edges[1];
10922   if ( !e ) return;
10923
10924   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
10925             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
10926
10927   double f,l;
10928   if ( set3D || _done )
10929   {
10930     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10931     GeomAdaptor_Curve aCurve(C, f,l);
10932
10933     if ( _edges[0] )
10934       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10935     if ( _edges[1] )
10936       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10937     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10938
10939     for ( size_t i = 0; i < _nodes.size(); ++i )
10940     {
10941       if ( !_nodes[i] ) continue;
10942       double len = totLen * _normPar[i];
10943       GCPnts_AbscissaPoint discret( aCurve, len, f );
10944       if ( !discret.IsDone() )
10945         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10946       double u = discret.Parameter();
10947       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10948       pos->SetUParameter( u );
10949       gp_Pnt p = C->Value( u );
10950       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10951     }
10952   }
10953   else
10954   {
10955     BRep_Tool::Range( _geomEdge, f,l );
10956     if ( _edges[0] )
10957       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10958     if ( _edges[1] )
10959       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10960     
10961     for ( size_t i = 0; i < _nodes.size(); ++i )
10962     {
10963       if ( !_nodes[i] ) continue;
10964       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10965       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10966       pos->SetUParameter( u );
10967     }
10968   }
10969 }
10970
10971 //================================================================================
10972 /*!
10973  * \brief Restore initial parameters of nodes on EDGE
10974  */
10975 //================================================================================
10976
10977 void _Shrinker1D::RestoreParams()
10978 {
10979   if ( _done )
10980     for ( size_t i = 0; i < _nodes.size(); ++i )
10981     {
10982       if ( !_nodes[i] ) continue;
10983       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10984       pos->SetUParameter( _initU[i] );
10985     }
10986   _done = false;
10987 }
10988
10989 //================================================================================
10990 /*!
10991  * \brief Replace source nodes by target nodes in shrinked mesh edges
10992  */
10993 //================================================================================
10994
10995 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10996 {
10997   const SMDS_MeshNode* nodes[3];
10998   for ( int i = 0; i < 2; ++i )
10999   {
11000     if ( !_edges[i] ) continue;
11001
11002     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11003     if ( !eSubMesh ) return;
11004     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11005     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11006     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11007     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11008     while ( eIt->more() )
11009     {
11010       const SMDS_MeshElement* e = eIt->next();
11011       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11012           continue;
11013       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11014       for ( int iN = 0; iN < e->NbNodes(); ++iN )
11015       {
11016         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11017         nodes[iN] = ( n == srcNode ? tgtNode : n );
11018       }
11019       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11020     }
11021   }
11022 }
11023
11024 //================================================================================
11025 /*!
11026  * \brief Creates 2D and 1D elements on boundaries of new prisms
11027  */
11028 //================================================================================
11029
11030 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11031 {
11032   SMESH_MesherHelper helper( *_mesh );
11033
11034   vector< const SMDS_MeshNode* > faceNodes;
11035
11036   //for ( size_t i = 0; i < _sdVec.size(); ++i )
11037   {
11038     //_SolidData& data = _sdVec[i];
11039     TopTools_IndexedMapOfShape geomEdges;
11040     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11041     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11042     {
11043       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11044       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
11045         continue;
11046
11047       // Get _LayerEdge's based on E
11048
11049       map< double, const SMDS_MeshNode* > u2nodes;
11050       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11051         continue;
11052
11053       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11054       TNode2Edge & n2eMap = data._n2eMap;
11055       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11056       {
11057         //check if 2D elements are needed on E
11058         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11059         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11060         ledges.push_back( n2e->second );
11061         u2n++;
11062         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11063           continue; // no layers on E
11064         ledges.push_back( n2eMap[ u2n->second ]);
11065
11066         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11067         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11068         int nbSharedPyram = 0;
11069         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11070         while ( vIt->more() )
11071         {
11072           const SMDS_MeshElement* v = vIt->next();
11073           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11074         }
11075         if ( nbSharedPyram > 1 )
11076           continue; // not free border of the pyramid
11077
11078         faceNodes.clear();
11079         faceNodes.push_back( ledges[0]->_nodes[0] );
11080         faceNodes.push_back( ledges[1]->_nodes[0] );
11081         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11082         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11083
11084         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11085           continue; // faces already created
11086       }
11087       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11088         ledges.push_back( n2eMap[ u2n->second ]);
11089
11090       // Find out orientation and type of face to create
11091
11092       bool reverse = false, isOnFace;
11093       
11094       map< TGeomID, TopoDS_Shape >::iterator e2f =
11095         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
11096       TopoDS_Shape F;
11097       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11098       {
11099         F = e2f->second.Oriented( TopAbs_FORWARD );
11100         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11101         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11102           reverse = !reverse, F.Reverse();
11103         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11104           reverse = !reverse;
11105       }
11106       else
11107       {
11108         // find FACE with layers sharing E
11109         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
11110         while ( fIt->more() && F.IsNull() )
11111         {
11112           const TopoDS_Shape* pF = fIt->next();
11113           if ( helper.IsSubShape( *pF, data._solid) &&
11114                !data._ignoreFaceIds.count( e2f->first ))
11115             F = *pF;
11116         }
11117       }
11118       // Find the sub-mesh to add new faces
11119       SMESHDS_SubMesh* sm = 0;
11120       if ( isOnFace )
11121         sm = getMeshDS()->MeshElements( F );
11122       else
11123         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11124       if ( !sm )
11125         return error("error in addBoundaryElements()", data._index);
11126
11127       // Make faces
11128       const int dj1 = reverse ? 0 : 1;
11129       const int dj2 = reverse ? 1 : 0;
11130       for ( size_t j = 1; j < ledges.size(); ++j )
11131       {
11132         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11133         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11134         if ( nn1.size() == nn2.size() )
11135         {
11136           if ( isOnFace )
11137             for ( size_t z = 1; z < nn1.size(); ++z )
11138               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11139           else
11140             for ( size_t z = 1; z < nn1.size(); ++z )
11141               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11142         }
11143         else if ( nn1.size() == 1 )
11144         {
11145           if ( isOnFace )
11146             for ( size_t z = 1; z < nn2.size(); ++z )
11147               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11148           else
11149             for ( size_t z = 1; z < nn2.size(); ++z )
11150               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11151         }
11152         else
11153         {
11154           if ( isOnFace )
11155             for ( size_t z = 1; z < nn1.size(); ++z )
11156               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11157           else
11158             for ( size_t z = 1; z < nn1.size(); ++z )
11159               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11160         }
11161       }
11162
11163       // Make edges
11164       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11165       {
11166         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11167         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11168         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11169         {
11170           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11171           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
11172             continue;
11173           helper.SetSubShape( eos->_sWOL );
11174           helper.SetElementsOnShape( true );
11175           for ( size_t z = 1; z < nn.size(); ++z )
11176             helper.AddEdge( nn[z-1], nn[z] );
11177         }
11178       }
11179
11180     } // loop on EDGE's
11181   } // loop on _SolidData's
11182
11183   return true;
11184 }