Salome HOME
IPAL53871: Non-conformal Viscous Layers
[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                   UNUSED_FLAG     = 0x0100000
443     };
444     bool Is   ( int flag ) const { return _flags & flag; }
445     void Set  ( int flag ) { _flags |= flag; }
446     void Unset( int flag ) { _flags &= ~flag; }
447
448     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
449     bool SetNewLength2d( Handle(Geom_Surface)& surface,
450                          const TopoDS_Face&    F,
451                          _EdgesOnShape&        eos,
452                          SMESH_MesherHelper&   helper );
453     void SetDataByNeighbors( const SMDS_MeshNode* n1,
454                              const SMDS_MeshNode* n2,
455                              const _EdgesOnShape& eos,
456                              SMESH_MesherHelper&  helper);
457     void Block( _SolidData& data );
458     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
459     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
460                             const TNode2Edge&     n2eMap);
461     void SmoothPos( const vector< double >& segLen, const double tol );
462     int  GetSmoothedPos( const double tol );
463     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
464     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
465     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
466     void SmoothWoCheck();
467     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
468                       const TopoDS_Face&             F,
469                       SMESH_MesherHelper&            helper);
470     void MoveNearConcaVer( const _EdgesOnShape*    eov,
471                            const _EdgesOnShape*    eos,
472                            const int               step,
473                            vector< _LayerEdge* > & badSmooEdges);
474     bool FindIntersection( SMESH_ElementSearcher&   searcher,
475                            double &                 distance,
476                            const double&            epsilon,
477                            _EdgesOnShape&           eos,
478                            const SMDS_MeshElement** face = 0);
479     bool SegTriaInter( const gp_Ax1&        lastSegment,
480                        const gp_XYZ&        p0,
481                        const gp_XYZ&        p1,
482                        const gp_XYZ&        p2,
483                        double&              dist,
484                        const double&        epsilon) const;
485     bool SegTriaInter( const gp_Ax1&        lastSegment,
486                        const SMDS_MeshNode* n0,
487                        const SMDS_MeshNode* n1,
488                        const SMDS_MeshNode* n2,
489                        double&              dist,
490                        const double&        epsilon) const
491     { return SegTriaInter( lastSegment,
492                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
493                            dist, epsilon );
494     }
495     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
496     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
497     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
498     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
499     bool   IsOnEdge() const { return _2neibors; }
500     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
501     void   SetCosin( double cosin );
502     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
503     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
504     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
505     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
506       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
507     }
508     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
509
510     gp_XYZ smoothLaplacian();
511     gp_XYZ smoothAngular();
512     gp_XYZ smoothLengthWeighted();
513     gp_XYZ smoothCentroidal();
514     gp_XYZ smoothNefPolygon();
515
516     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
517     static const int theNbSmooFuns = FUN_NB;
518     static PSmooFun _funs[theNbSmooFuns];
519     static const char* _funNames[theNbSmooFuns+1];
520     int smooFunID( PSmooFun fun=0) const;
521   };
522   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
523                                                             &_LayerEdge::smoothLengthWeighted,
524                                                             &_LayerEdge::smoothCentroidal,
525                                                             &_LayerEdge::smoothNefPolygon,
526                                                             &_LayerEdge::smoothAngular };
527   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
528                                                          "LengthWeighted",
529                                                          "Centroidal",
530                                                          "NefPolygon",
531                                                          "Angular",
532                                                          "None"};
533   struct _LayerEdgeCmp
534   {
535     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
536     {
537       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
538       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
539     }
540   };
541   //--------------------------------------------------------------------------------
542   /*!
543    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
544    */
545   struct _halfPlane
546   {
547     gp_XY _pos, _dir, _inNorm;
548     bool IsOut( const gp_XY p, const double tol ) const
549     {
550       return _inNorm * ( p - _pos ) < -tol;
551     }
552     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
553     {
554       //const double eps = 1e-10;
555       double D = _dir.Crossed( hp._dir );
556       if ( fabs(D) < std::numeric_limits<double>::min())
557         return false;
558       gp_XY vec21 = _pos - hp._pos; 
559       double u = hp._dir.Crossed( vec21 ) / D; 
560       intPnt = _pos + _dir * u;
561       return true;
562     }
563   };
564   //--------------------------------------------------------------------------------
565   /*!
566    * Structure used to smooth a _LayerEdge based on an EDGE.
567    */
568   struct _2NearEdges
569   {
570     double               _wgt  [2]; // weights of _nodes
571     _LayerEdge*          _edges[2];
572
573      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
574     gp_XYZ*              _plnNorm;
575
576     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
577     const SMDS_MeshNode* tgtNode(bool is2nd) {
578       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
579     }
580     const SMDS_MeshNode* srcNode(bool is2nd) {
581       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
582     }
583     void reverse() {
584       std::swap( _wgt  [0], _wgt  [1] );
585       std::swap( _edges[0], _edges[1] );
586     }
587     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
588       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
589     }
590     bool include( const _LayerEdge* e ) {
591       return ( _edges[0] == e || _edges[1] == e );
592     }
593   };
594
595
596   //--------------------------------------------------------------------------------
597   /*!
598    * \brief Layers parameters got by averaging several hypotheses
599    */
600   struct AverageHyp
601   {
602     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
603       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
604     {
605       Add( hyp );
606     }
607     void Add( const StdMeshers_ViscousLayers* hyp )
608     {
609       if ( hyp )
610       {
611         _nbHyps++;
612         _nbLayers       = hyp->GetNumberLayers();
613         //_thickness     += hyp->GetTotalThickness();
614         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
615         _stretchFactor += hyp->GetStretchFactor();
616         _method         = hyp->GetMethod();
617       }
618     }
619     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
620     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
621     int    GetNumberLayers()   const { return _nbLayers; }
622     int    GetMethod()         const { return _method; }
623
624     bool   UseSurfaceNormal()  const
625     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
626     bool   ToSmooth()          const
627     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628     bool   IsOffsetMethod()    const
629     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
630
631   private:
632     int     _nbLayers, _nbHyps, _method;
633     double  _thickness, _stretchFactor;
634   };
635
636   //--------------------------------------------------------------------------------
637   /*!
638    * \brief _LayerEdge's on a shape and other shape data
639    */
640   struct _EdgesOnShape
641   {
642     vector< _LayerEdge* > _edges;
643
644     TopoDS_Shape          _shape;
645     TGeomID               _shapeID;
646     SMESH_subMesh *       _subMesh;
647     // face or edge w/o layer along or near which _edges are inflated
648     TopoDS_Shape          _sWOL;
649     bool                  _isRegularSWOL; // w/o singularities
650     // averaged StdMeshers_ViscousLayers parameters
651     AverageHyp            _hyp;
652     bool                  _toSmooth;
653     _Smoother1D*          _edgeSmoother;
654     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
655     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
656
657     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
658     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
659
660     Handle(ShapeAnalysis_Surface) _offsetSurf;
661     _LayerEdge*                   _edgeForOffset;
662
663     _SolidData*            _data; // parent SOLID
664
665     TopAbs_ShapeEnum ShapeType() const
666     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
667     TopAbs_ShapeEnum SWOLType() const
668     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
669     bool             HasC1( const _EdgesOnShape* other ) const
670     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
671     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
672     _SolidData&      GetData() const { return *_data; }
673
674     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
675   };
676
677   //--------------------------------------------------------------------------------
678   /*!
679    * \brief Convex FACE whose radius of curvature is less than the thickness of 
680    *        layers. It is used to detect distortion of prisms based on a convex
681    *        FACE and to update normals to enable further increasing the thickness
682    */
683   struct _ConvexFace
684   {
685     TopoDS_Face                     _face;
686
687     // edges whose _simplices are used to detect prism distortion
688     vector< _LayerEdge* >           _simplexTestEdges;
689
690     // map a sub-shape to _SolidData::_edgesOnShape
691     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
692
693     bool                            _normalsFixed;
694
695     bool GetCenterOfCurvature( _LayerEdge*         ledge,
696                                BRepLProp_SLProps&  surfProp,
697                                SMESH_MesherHelper& helper,
698                                gp_Pnt &            center ) const;
699     bool CheckPrisms() const;
700   };
701
702   //--------------------------------------------------------------------------------
703   /*!
704    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
705    *        at inflation up to the full thickness. A detected collision
706    *        is fixed in updateNormals()
707    */
708   struct _CollisionEdges
709   {
710     _LayerEdge*           _edge;
711     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
712     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
713     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
714   };
715
716   //--------------------------------------------------------------------------------
717   /*!
718    * \brief Data of a SOLID
719    */
720   struct _SolidData
721   {
722     typedef const StdMeshers_ViscousLayers* THyp;
723     TopoDS_Shape                    _solid;
724     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
725     TGeomID                         _index; // SOLID id
726     _MeshOfSolid*                   _proxyMesh;
727     list< THyp >                    _hyps;
728     list< TopoDS_Shape >            _hypShapes;
729     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
730     set< TGeomID >                  _reversedFaceIds;
731     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
732
733     double                          _stepSize, _stepSizeCoeff, _geomSize;
734     const SMDS_MeshNode*            _stepSizeNodes[2];
735
736     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
737
738     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
739     map< TGeomID, TNode2Edge* >     _s2neMap;
740     // _LayerEdge's with underlying shapes
741     vector< _EdgesOnShape >         _edgesOnShape;
742
743     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
744     //        layers and a FACE w/o layers
745     // value: the shape (FACE or EDGE) to shrink mesh on.
746     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
747     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
748
749     // Convex FACEs whose radius of curvature is less than the thickness of layers
750     map< TGeomID, _ConvexFace >      _convexFaces;
751
752     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
753     // the adjacent SOLID
754     set< TGeomID >                   _noShrinkShapes;
755
756     int                              _nbShapesToSmooth;
757
758     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
759
760     vector< _CollisionEdges >        _collisionEdges;
761     set< TGeomID >                   _concaveFaces;
762
763     double                           _maxThickness; // of all _hyps
764     double                           _minThickness; // of all _hyps
765
766     double                           _epsilon; // precision for SegTriaInter()
767
768     SMESH_MesherHelper*              _helper;
769
770     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
771                _MeshOfSolid*       m=0)
772       :_solid(s), _proxyMesh(m), _helper(0) {}
773     ~_SolidData();
774
775     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
776     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
777
778     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
779       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
780       return id2face == _convexFaces.end() ? 0 : & id2face->second;
781     }
782     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
783     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
784     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
785     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
786
787     SMESH_MesherHelper& GetHelper() const { return *_helper; }
788
789     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
790       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
791         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
792           _edgesOnShape[i]._edges[j]->Unset( flag );
793     }
794     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
795                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
796
797     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
798   };
799   //--------------------------------------------------------------------------------
800   /*!
801    * \brief Offset plane used in getNormalByOffset()
802    */
803   struct _OffsetPlane
804   {
805     gp_Pln _plane;
806     int    _faceIndex;
807     int    _faceIndexNext[2];
808     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
809     bool   _isLineOK[2];
810     _OffsetPlane() {
811       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
812     }
813     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
814                                     const TopoDS_Edge&   E,
815                                     const TopoDS_Vertex& V );
816     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
817     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
818   };
819   //--------------------------------------------------------------------------------
820   /*!
821    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
822    */
823   struct _CentralCurveOnEdge
824   {
825     bool                  _isDegenerated;
826     vector< gp_Pnt >      _curvaCenters;
827     vector< _LayerEdge* > _ledges;
828     vector< gp_XYZ >      _normals; // new normal for each of _ledges
829     vector< double >      _segLength2;
830
831     TopoDS_Edge           _edge;
832     TopoDS_Face           _adjFace;
833     bool                  _adjFaceToSmooth;
834
835     void Append( const gp_Pnt& center, _LayerEdge* ledge )
836     {
837       if ( _curvaCenters.size() > 0 )
838         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
839       _curvaCenters.push_back( center );
840       _ledges.push_back( ledge );
841       _normals.push_back( ledge->_normal );
842     }
843     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
844     void SetShapes( const TopoDS_Edge&  edge,
845                     const _ConvexFace&  convFace,
846                     _SolidData&         data,
847                     SMESH_MesherHelper& helper);
848   };
849   //--------------------------------------------------------------------------------
850   /*!
851    * \brief Data of node on a shrinked FACE
852    */
853   struct _SmoothNode
854   {
855     const SMDS_MeshNode*         _node;
856     vector<_Simplex>             _simplices; // for quality check
857
858     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
859
860     bool Smooth(int&                  badNb,
861                 Handle(Geom_Surface)& surface,
862                 SMESH_MesherHelper&   helper,
863                 const double          refSign,
864                 SmoothType            how,
865                 bool                  set3D);
866
867     gp_XY computeAngularPos(vector<gp_XY>& uv,
868                             const gp_XY&   uvToFix,
869                             const double   refSign );
870   };
871   //--------------------------------------------------------------------------------
872   /*!
873    * \brief Builder of viscous layers
874    */
875   class _ViscousBuilder
876   {
877   public:
878     _ViscousBuilder();
879     // does it's job
880     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
881                                   const TopoDS_Shape& shape);
882     // check validity of hypotheses
883     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
884                                            const TopoDS_Shape& shape );
885
886     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
887     void RestoreListeners();
888
889     // computes SMESH_ProxyMesh::SubMesh::_n2n;
890     bool MakeN2NMap( _MeshOfSolid* pm );
891
892   private:
893
894     bool findSolidsWithLayers();
895     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
896     bool findFacesWithLayers(const bool onlyWith=false);
897     void getIgnoreFaces(const TopoDS_Shape&             solid,
898                         const StdMeshers_ViscousLayers* hyp,
899                         const TopoDS_Shape&             hypShape,
900                         set<TGeomID>&                   ignoreFaces);
901     bool makeLayer(_SolidData& data);
902     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
903     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
904                       SMESH_MesherHelper& helper, _SolidData& data);
905     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
906                          const TopoDS_Face&   face,
907                          SMESH_MesherHelper&  helper,
908                          bool&                isOK,
909                          bool                 shiftInside=false);
910     bool getFaceNormalAtSingularity(const gp_XY&        uv,
911                                     const TopoDS_Face&  face,
912                                     SMESH_MesherHelper& helper,
913                                     gp_Dir&             normal );
914     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
915     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
916                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
917                               int                              nbFaces,
918                               bool                             lastNoOffset = false);
919     bool findNeiborsOnEdge(const _LayerEdge*     edge,
920                            const SMDS_MeshNode*& n1,
921                            const SMDS_MeshNode*& n2,
922                            _EdgesOnShape&        eos,
923                            _SolidData&           data);
924     void findSimplexTestEdges( _SolidData&                    data,
925                                vector< vector<_LayerEdge*> >& edgesByGeom);
926     void computeGeomSize( _SolidData& data );
927     bool findShapesToSmooth( _SolidData& data);
928     void limitStepSizeByCurvature( _SolidData&  data );
929     void limitStepSize( _SolidData&             data,
930                         const SMDS_MeshElement* face,
931                         const _LayerEdge*       maxCosinEdge );
932     void limitStepSize( _SolidData& data, const double minSize);
933     bool inflate(_SolidData& data);
934     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
935     int  invalidateBadSmooth( _SolidData&               data,
936                               SMESH_MesherHelper&       helper,
937                               vector< _LayerEdge* >&    badSmooEdges,
938                               vector< _EdgesOnShape* >& eosC1,
939                               const int                 infStep );
940     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
941     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
942                              vector< _EdgesOnShape* >& eosC1,
943                              int smooStep=0, bool moveAll=false );
944     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
945     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
946     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
947                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
948                                  SMESH_MesherHelper& helper );
949     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
950     bool updateNormalsOfConvexFaces( _SolidData&         data,
951                                      SMESH_MesherHelper& helper,
952                                      int                 stepNb );
953     void updateNormalsOfC1Vertices( _SolidData& data );
954     bool updateNormalsOfSmoothed( _SolidData&         data,
955                                   SMESH_MesherHelper& helper,
956                                   const int           nbSteps,
957                                   const double        stepSize );
958     bool isNewNormalOk( _SolidData&   data,
959                         _LayerEdge&   edge,
960                         const gp_XYZ& newNormal);
961     bool refine(_SolidData& data);
962     bool shrink(_SolidData& data);
963     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
964                               SMESH_MesherHelper& helper,
965                               const SMESHDS_SubMesh* faceSubMesh );
966     void restoreNoShrink( _LayerEdge& edge ) const;
967     void fixBadFaces(const TopoDS_Face&          F,
968                      SMESH_MesherHelper&         helper,
969                      const bool                  is2D,
970                      const int                   step,
971                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
972     bool addBoundaryElements(_SolidData& data);
973
974     bool error( const string& text, int solidID=-1 );
975     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
976
977     // debug
978     void makeGroupOfLE();
979
980     SMESH_Mesh*                _mesh;
981     SMESH_ComputeErrorPtr      _error;
982
983     vector<                    _SolidData >  _sdVec;
984     TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
985     TopTools_MapOfShape        _shrinkedFaces;
986
987     int                        _tmpFaceID;
988   };
989   //--------------------------------------------------------------------------------
990   /*!
991    * \brief Shrinker of nodes on the EDGE
992    */
993   class _Shrinker1D
994   {
995     TopoDS_Edge                   _geomEdge;
996     vector<double>                _initU;
997     vector<double>                _normPar;
998     vector<const SMDS_MeshNode*>  _nodes;
999     const _LayerEdge*             _edges[2];
1000     bool                          _done;
1001   public:
1002     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1003     void Compute(bool set3D, SMESH_MesherHelper& helper);
1004     void RestoreParams();
1005     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1006     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1007     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1008     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1009     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1010     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1011   };
1012   //--------------------------------------------------------------------------------
1013   /*!
1014    * \brief Smoother of _LayerEdge's on EDGE.
1015    */
1016   struct _Smoother1D
1017   {
1018     struct OffPnt // point of the offsetted EDGE
1019     {
1020       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1021       double      _len;    // length reached at previous inflation step
1022       double      _param;  // on EDGE
1023       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1024       gp_XYZ      _edgeDir;// EDGE tangent at _param
1025       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1026     };
1027     vector< OffPnt >   _offPoints;
1028     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1029     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1030     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1031     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1032     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1033     _EdgesOnShape&     _eos;
1034     double             _curveLen; // length of the EDGE
1035
1036     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1037                                               _EdgesOnShape&      eos,
1038                                               SMESH_MesherHelper& helper);
1039
1040     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1041                  _EdgesOnShape&     eos )
1042       : _anaCurve( curveForSmooth ), _eos( eos )
1043     {
1044     }
1045     bool Perform(_SolidData&                    data,
1046                  Handle(ShapeAnalysis_Surface)& surface,
1047                  const TopoDS_Face&             F,
1048                  SMESH_MesherHelper&            helper )
1049     {
1050       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1051         prepare( data );
1052
1053       if ( isAnalytic() )
1054         return smoothAnalyticEdge( data, surface, F, helper );
1055       else
1056         return smoothComplexEdge ( data, surface, F, helper );
1057     }
1058     void prepare(_SolidData& data );
1059
1060     bool smoothAnalyticEdge( _SolidData&                    data,
1061                              Handle(ShapeAnalysis_Surface)& surface,
1062                              const TopoDS_Face&             F,
1063                              SMESH_MesherHelper&            helper);
1064
1065     bool smoothComplexEdge( _SolidData&                    data,
1066                             Handle(ShapeAnalysis_Surface)& surface,
1067                             const TopoDS_Face&             F,
1068                             SMESH_MesherHelper&            helper);
1069
1070     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1071                             const gp_XYZ&  edgeDir);
1072
1073     _LayerEdge* getLEdgeOnV( bool is2nd )
1074     {
1075       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1076     }
1077     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1078   };
1079   //--------------------------------------------------------------------------------
1080   /*!
1081    * \brief Class of temporary mesh face.
1082    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1083    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1084    */
1085   struct _TmpMeshFace : public SMDS_MeshElement
1086   {
1087     vector<const SMDS_MeshNode* > _nn;
1088     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1089                   int id, int faceID=-1, int idInFace=-1):
1090       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1091     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1092     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1093     virtual vtkIdType GetVtkType() const                      { return -1; }
1094     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1095     virtual SMDSAbs_GeometryType GetGeomType() const
1096     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1097     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1098     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1099   };
1100   //--------------------------------------------------------------------------------
1101   /*!
1102    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1103    */
1104   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1105   {
1106     _LayerEdge *_le1, *_le2;
1107     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1108       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1109     {
1110       _nn[0]=_le1->_nodes[0];
1111       _nn[1]=_le1->_nodes.back();
1112       _nn[2]=_le2->_nodes.back();
1113       _nn[3]=_le2->_nodes[0];
1114     }
1115     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1116     {
1117       SMESH_TNodeXYZ p0s( _nn[0] );
1118       SMESH_TNodeXYZ p0t( _nn[1] );
1119       SMESH_TNodeXYZ p1t( _nn[2] );
1120       SMESH_TNodeXYZ p1s( _nn[3] );
1121       gp_XYZ  v0 = p0t - p0s;
1122       gp_XYZ  v1 = p1t - p1s;
1123       gp_XYZ v01 = p1s - p0s;
1124       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1125       gp_XYZ   d = v01 ^ n;
1126       d.Normalize();
1127       return d;
1128     }
1129     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1130     {
1131       _nn[0]=le1->_nodes[0];
1132       _nn[1]=le1->_nodes.back();
1133       _nn[2]=le2->_nodes.back();
1134       _nn[3]=le2->_nodes[0];
1135       return GetDir();
1136     }
1137   };
1138   //--------------------------------------------------------------------------------
1139   /*!
1140    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1141    * \warning Location of a surface is ignored
1142    */
1143   struct _NodeCoordHelper
1144   {
1145     SMESH_MesherHelper&        _helper;
1146     const TopoDS_Face&         _face;
1147     Handle(Geom_Surface)       _surface;
1148     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1149
1150     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1151       : _helper( helper ), _face( F )
1152     {
1153       if ( is2D )
1154       {
1155         TopLoc_Location loc;
1156         _surface = BRep_Tool::Surface( _face, loc );
1157       }
1158       if ( _surface.IsNull() )
1159         _fun = & _NodeCoordHelper::direct;
1160       else
1161         _fun = & _NodeCoordHelper::byUV;
1162     }
1163     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1164
1165   private:
1166     gp_XYZ direct(const SMDS_MeshNode* n) const
1167     {
1168       return SMESH_TNodeXYZ( n );
1169     }
1170     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1171     {
1172       gp_XY uv = _helper.GetNodeUV( _face, n );
1173       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1174     }
1175   };
1176
1177   //================================================================================
1178   /*!
1179    * \brief Check angle between vectors 
1180    */
1181   //================================================================================
1182
1183   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1184   {
1185     double dot = v1 * v2; // cos * |v1| * |v2|
1186     double l1  = v1.SquareMagnitude();
1187     double l2  = v2.SquareMagnitude();
1188     return (( dot * cos >= 0 ) && 
1189             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1190   }
1191
1192 } // namespace VISCOUS_3D
1193
1194
1195
1196 //================================================================================
1197 // StdMeshers_ViscousLayers hypothesis
1198 //
1199 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1200   :SMESH_Hypothesis(hypId, studyId, gen),
1201    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1202    _method( SURF_OFFSET_SMOOTH )
1203 {
1204   _name = StdMeshers_ViscousLayers::GetHypType();
1205   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1206 } // --------------------------------------------------------------------------------
1207 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1208 {
1209   if ( faceIds != _shapeIds )
1210     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1211   if ( _isToIgnoreShapes != toIgnore )
1212     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1213 } // --------------------------------------------------------------------------------
1214 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1215 {
1216   if ( thickness != _thickness )
1217     _thickness = thickness, NotifySubMeshesHypothesisModification();
1218 } // --------------------------------------------------------------------------------
1219 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1220 {
1221   if ( _nbLayers != nb )
1222     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1223 } // --------------------------------------------------------------------------------
1224 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1225 {
1226   if ( _stretchFactor != factor )
1227     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1228 } // --------------------------------------------------------------------------------
1229 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1230 {
1231   if ( _method != method )
1232     _method = method, NotifySubMeshesHypothesisModification();
1233 } // --------------------------------------------------------------------------------
1234 SMESH_ProxyMesh::Ptr
1235 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1236                                   const TopoDS_Shape& theShape,
1237                                   const bool          toMakeN2NMap) const
1238 {
1239   using namespace VISCOUS_3D;
1240   _ViscousBuilder builder;
1241   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1242   if ( err && !err->IsOK() )
1243     return SMESH_ProxyMesh::Ptr();
1244
1245   vector<SMESH_ProxyMesh::Ptr> components;
1246   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1247   for ( ; exp.More(); exp.Next() )
1248   {
1249     if ( _MeshOfSolid* pm =
1250          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1251     {
1252       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1253         if ( !builder.MakeN2NMap( pm ))
1254           return SMESH_ProxyMesh::Ptr();
1255       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1256       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1257
1258       if ( pm->_warning && !pm->_warning->IsOK() )
1259       {
1260         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1261         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1262         if ( !smError || smError->IsOK() )
1263           smError = pm->_warning;
1264       }
1265     }
1266     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1267   }
1268   switch ( components.size() )
1269   {
1270   case 0: break;
1271
1272   case 1: return components[0];
1273
1274   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1275   }
1276   return SMESH_ProxyMesh::Ptr();
1277 } // --------------------------------------------------------------------------------
1278 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1279 {
1280   save << " " << _nbLayers
1281        << " " << _thickness
1282        << " " << _stretchFactor
1283        << " " << _shapeIds.size();
1284   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1285     save << " " << _shapeIds[i];
1286   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1287   save << " " << _method;
1288   return save;
1289 } // --------------------------------------------------------------------------------
1290 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1291 {
1292   int nbFaces, faceID, shapeToTreat, method;
1293   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1294   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1295     _shapeIds.push_back( faceID );
1296   if ( load >> shapeToTreat ) {
1297     _isToIgnoreShapes = !shapeToTreat;
1298     if ( load >> method )
1299       _method = (ExtrusionMethod) method;
1300   }
1301   else {
1302     _isToIgnoreShapes = true; // old behavior
1303   }
1304   return load;
1305 } // --------------------------------------------------------------------------------
1306 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1307                                                    const TopoDS_Shape& theShape)
1308 {
1309   // TODO
1310   return false;
1311 } // --------------------------------------------------------------------------------
1312 SMESH_ComputeErrorPtr
1313 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1314                                           const TopoDS_Shape&                  theShape,
1315                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1316 {
1317   VISCOUS_3D::_ViscousBuilder builder;
1318   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1319   if ( err && !err->IsOK() )
1320     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1321   else
1322     theStatus = SMESH_Hypothesis::HYP_OK;
1323
1324   return err;
1325 }
1326 // --------------------------------------------------------------------------------
1327 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1328 {
1329   bool isIn =
1330     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1331   return IsToIgnoreShapes() ? !isIn : isIn;
1332 }
1333 // END StdMeshers_ViscousLayers hypothesis
1334 //================================================================================
1335
1336 namespace VISCOUS_3D
1337 {
1338   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1339   {
1340     gp_Vec dir;
1341     double f,l;
1342     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1343     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1344     gp_Pnt p = BRep_Tool::Pnt( fromV );
1345     double distF = p.SquareDistance( c->Value( f ));
1346     double distL = p.SquareDistance( c->Value( l ));
1347     c->D1(( distF < distL ? f : l), p, dir );
1348     if ( distL < distF ) dir.Reverse();
1349     return dir.XYZ();
1350   }
1351   //--------------------------------------------------------------------------------
1352   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1353                      SMESH_MesherHelper& helper)
1354   {
1355     gp_Vec dir;
1356     double f,l; gp_Pnt p;
1357     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1358     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1359     double u = helper.GetNodeU( E, atNode );
1360     c->D1( u, p, dir );
1361     return dir.XYZ();
1362   }
1363   //--------------------------------------------------------------------------------
1364   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1365                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1366                      double* cosin=0);
1367   //--------------------------------------------------------------------------------
1368   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1369                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1370   {
1371     double f,l;
1372     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1373     if ( c.IsNull() )
1374     {
1375       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1376       return getFaceDir( F, v, node, helper, ok );
1377     }
1378     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1379     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1380     gp_Pnt p; gp_Vec du, dv, norm;
1381     surface->D1( uv.X(),uv.Y(), p, du,dv );
1382     norm = du ^ dv;
1383
1384     double u = helper.GetNodeU( fromE, node, 0, &ok );
1385     c->D1( u, p, du );
1386     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1387     if ( o == TopAbs_REVERSED )
1388       du.Reverse();
1389
1390     gp_Vec dir = norm ^ du;
1391
1392     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1393          helper.IsClosedEdge( fromE ))
1394     {
1395       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1396       else                        c->D1( f, p, dv );
1397       if ( o == TopAbs_REVERSED )
1398         dv.Reverse();
1399       gp_Vec dir2 = norm ^ dv;
1400       dir = dir.Normalized() + dir2.Normalized();
1401     }
1402     return dir.XYZ();
1403   }
1404   //--------------------------------------------------------------------------------
1405   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1406                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1407                      bool& ok, double* cosin)
1408   {
1409     TopoDS_Face faceFrw = F;
1410     faceFrw.Orientation( TopAbs_FORWARD );
1411     //double f,l; TopLoc_Location loc;
1412     TopoDS_Edge edges[2]; // sharing a vertex
1413     size_t nbEdges = 0;
1414     {
1415       TopoDS_Vertex VV[2];
1416       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1417       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1418       {
1419         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1420         if ( SMESH_Algo::isDegenerated( e )) continue;
1421         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1422         if ( VV[1].IsSame( fromV )) {
1423           nbEdges += edges[ 0 ].IsNull();
1424           edges[ 0 ] = e;
1425         }
1426         else if ( VV[0].IsSame( fromV )) {
1427           nbEdges += edges[ 1 ].IsNull();
1428           edges[ 1 ] = e;
1429         }
1430       }
1431     }
1432     gp_XYZ dir(0,0,0), edgeDir[2];
1433     if ( nbEdges == 2 )
1434     {
1435       // get dirs of edges going fromV
1436       ok = true;
1437       for ( size_t i = 0; i < nbEdges && ok; ++i )
1438       {
1439         edgeDir[i] = getEdgeDir( edges[i], fromV );
1440         double size2 = edgeDir[i].SquareModulus();
1441         if (( ok = size2 > numeric_limits<double>::min() ))
1442           edgeDir[i] /= sqrt( size2 );
1443       }
1444       if ( !ok ) return dir;
1445
1446       // get angle between the 2 edges
1447       gp_Vec faceNormal;
1448       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1449       if ( Abs( angle ) < 5 * M_PI/180 )
1450       {
1451         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1452       }
1453       else
1454       {
1455         dir = edgeDir[0] + edgeDir[1];
1456         if ( angle < 0 )
1457           dir.Reverse();
1458       }
1459       if ( cosin ) {
1460         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1461         *cosin = Cos( angle );
1462       }
1463     }
1464     else if ( nbEdges == 1 )
1465     {
1466       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1467       if ( cosin ) *cosin = 1.;
1468     }
1469     else
1470     {
1471       ok = false;
1472     }
1473
1474     return dir;
1475   }
1476
1477   //================================================================================
1478   /*!
1479    * \brief Finds concave VERTEXes of a FACE
1480    */
1481   //================================================================================
1482
1483   bool getConcaveVertices( const TopoDS_Face&  F,
1484                            SMESH_MesherHelper& helper,
1485                            set< TGeomID >*     vertices = 0)
1486   {
1487     // check angles at VERTEXes
1488     TError error;
1489     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1490     for ( size_t iW = 0; iW < wires.size(); ++iW )
1491     {
1492       const int nbEdges = wires[iW]->NbEdges();
1493       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1494         continue;
1495       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1496       {
1497         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1498         int iE2 = ( iE1 + 1 ) % nbEdges;
1499         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1500           iE2 = ( iE2 + 1 ) % nbEdges;
1501         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1502         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1503                                         wires[iW]->Edge( iE2 ), F, V );
1504         if ( angle < -5. * M_PI / 180. )
1505         {
1506           if ( !vertices )
1507             return true;
1508           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1509         }
1510       }
1511     }
1512     return vertices ? !vertices->empty() : false;
1513   }
1514
1515   //================================================================================
1516   /*!
1517    * \brief Returns true if a FACE is bound by a concave EDGE
1518    */
1519   //================================================================================
1520
1521   bool isConcave( const TopoDS_Face&  F,
1522                   SMESH_MesherHelper& helper,
1523                   set< TGeomID >*     vertices = 0 )
1524   {
1525     bool isConcv = false;
1526     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1527     //   return true;
1528     gp_Vec2d drv1, drv2;
1529     gp_Pnt2d p;
1530     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1531     for ( ; eExp.More(); eExp.Next() )
1532     {
1533       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1534       if ( SMESH_Algo::isDegenerated( E )) continue;
1535       // check if 2D curve is concave
1536       BRepAdaptor_Curve2d curve( E, F );
1537       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1538       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1539       curve.Intervals( intervals, GeomAbs_C2 );
1540       bool isConvex = true;
1541       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1542       {
1543         double u1 = intervals( i );
1544         double u2 = intervals( i+1 );
1545         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1546         double cross = drv1 ^ drv2;
1547         if ( E.Orientation() == TopAbs_REVERSED )
1548           cross = -cross;
1549         isConvex = ( cross > -1e-9 ); // 0.1 );
1550       }
1551       if ( !isConvex )
1552       {
1553         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1554         isConcv = true;
1555         if ( vertices )
1556           break;
1557         else
1558           return true;
1559       }
1560     }
1561
1562     // check angles at VERTEXes
1563     if ( getConcaveVertices( F, helper, vertices ))
1564       isConcv = true;
1565
1566     return isConcv;
1567   }
1568
1569   //================================================================================
1570   /*!
1571    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1572    *  \param [in] face - the mesh face to treat
1573    *  \param [in] nodeOnEdge - a node on the EDGE
1574    *  \param [out] faceSize - the computed distance
1575    *  \return bool - true if faceSize computed
1576    */
1577   //================================================================================
1578
1579   bool getDistFromEdge( const SMDS_MeshElement* face,
1580                         const SMDS_MeshNode*    nodeOnEdge,
1581                         double &                faceSize )
1582   {
1583     faceSize = Precision::Infinite();
1584     bool done = false;
1585
1586     int nbN  = face->NbCornerNodes();
1587     int iOnE = face->GetNodeIndex( nodeOnEdge );
1588     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1589                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1590     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1591                                       face->GetNode( iNext[1] ) };
1592     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1593     double segLen = -1.;
1594     // look for two neighbor not in-FACE nodes of face
1595     for ( int i = 0; i < 2; ++i )
1596     {
1597       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1598            nNext[i]->GetID() < nodeOnEdge->GetID() )
1599       {
1600         // look for an in-FACE node
1601         for ( int iN = 0; iN < nbN; ++iN )
1602         {
1603           if ( iN == iOnE || iN == iNext[i] )
1604             continue;
1605           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1606           gp_XYZ v = pInFace - segEnd;
1607           if ( segLen < 0 )
1608           {
1609             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1610             segLen = segVec.Modulus();
1611           }
1612           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1613           faceSize = Min( faceSize, distToSeg );
1614           done = true;
1615         }
1616         segLen = -1;
1617       }
1618     }
1619     return done;
1620   }
1621   //================================================================================
1622   /*!
1623    * \brief Return direction of axis or revolution of a surface
1624    */
1625   //================================================================================
1626
1627   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1628                           gp_Dir &                 axis )
1629   {
1630     switch ( surface.GetType() ) {
1631     case GeomAbs_Cone:
1632     {
1633       gp_Cone cone = surface.Cone();
1634       axis = cone.Axis().Direction();
1635       break;
1636     }
1637     case GeomAbs_Sphere:
1638     {
1639       gp_Sphere sphere = surface.Sphere();
1640       axis = sphere.Position().Direction();
1641       break;
1642     }
1643     case GeomAbs_SurfaceOfRevolution:
1644     {
1645       axis = surface.AxeOfRevolution().Direction();
1646       break;
1647     }
1648     //case GeomAbs_SurfaceOfExtrusion:
1649     case GeomAbs_OffsetSurface:
1650     {
1651       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1652       return getRovolutionAxis( base->Surface(), axis );
1653     }
1654     default: return false;
1655     }
1656     return true;
1657   }
1658
1659   //--------------------------------------------------------------------------------
1660   // DEBUG. Dump intermediate node positions into a python script
1661   // HOWTO use: run python commands written in a console to see
1662   //  construction steps of viscous layers
1663 #ifdef __myDEBUG
1664   ofstream* py;
1665   int       theNbPyFunc;
1666   struct PyDump {
1667     PyDump(SMESH_Mesh& m) {
1668       int tag = 3 + m.GetId();
1669       const char* fname = "/tmp/viscous.py";
1670       cout << "execfile('"<<fname<<"')"<<endl;
1671       py = new ofstream(fname);
1672       *py << "import SMESH" << endl
1673           << "from salome.smesh import smeshBuilder" << endl
1674           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1675           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1676           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1677       theNbPyFunc = 0;
1678     }
1679     void Finish() {
1680       if (py) {
1681         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1682           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1683         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1684           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1685       }
1686       delete py; py=0;
1687     }
1688     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1689   };
1690 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1691 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1692 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1693 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1694   void _dumpFunction(const string& fun, int ln)
1695   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1696   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1697   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1698                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1699   void _dumpCmd(const string& txt, int ln)
1700   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1701   void dumpFunctionEnd()
1702   { if (py) *py<< "  return"<< endl; }
1703   void dumpChangeNodes( const SMDS_MeshElement* f )
1704   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1705       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1706       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1707 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1708
1709 #else
1710
1711   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1712 #define dumpFunction(f) f
1713 #define dumpMove(n)
1714 #define dumpMoveComm(n,txt)
1715 #define dumpCmd(txt)
1716 #define dumpFunctionEnd()
1717 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1718 #define debugMsg( txt ) {}
1719
1720 #endif
1721 }
1722
1723 using namespace VISCOUS_3D;
1724
1725 //================================================================================
1726 /*!
1727  * \brief Constructor of _ViscousBuilder
1728  */
1729 //================================================================================
1730
1731 _ViscousBuilder::_ViscousBuilder()
1732 {
1733   _error = SMESH_ComputeError::New(COMPERR_OK);
1734   _tmpFaceID = 0;
1735 }
1736
1737 //================================================================================
1738 /*!
1739  * \brief Stores error description and returns false
1740  */
1741 //================================================================================
1742
1743 bool _ViscousBuilder::error(const string& text, int solidId )
1744 {
1745   const string prefix = string("Viscous layers builder: ");
1746   _error->myName    = COMPERR_ALGO_FAILED;
1747   _error->myComment = prefix + text;
1748   if ( _mesh )
1749   {
1750     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1751     if ( !sm && !_sdVec.empty() )
1752       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1753     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1754     {
1755       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1756       if ( smError && smError->myAlgo )
1757         _error->myAlgo = smError->myAlgo;
1758       smError = _error;
1759       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1760     }
1761     // set KO to all solids
1762     for ( size_t i = 0; i < _sdVec.size(); ++i )
1763     {
1764       if ( _sdVec[i]._index == solidId )
1765         continue;
1766       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1767       if ( !sm->IsEmpty() )
1768         continue;
1769       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1770       if ( !smError || smError->IsOK() )
1771       {
1772         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1773         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1774       }
1775     }
1776   }
1777   makeGroupOfLE(); // debug
1778
1779   return false;
1780 }
1781
1782 //================================================================================
1783 /*!
1784  * \brief At study restoration, restore event listeners used to clear an inferior
1785  *  dim sub-mesh modified by viscous layers
1786  */
1787 //================================================================================
1788
1789 void _ViscousBuilder::RestoreListeners()
1790 {
1791   // TODO
1792 }
1793
1794 //================================================================================
1795 /*!
1796  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1797  */
1798 //================================================================================
1799
1800 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1801 {
1802   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1803   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1804   for ( ; fExp.More(); fExp.Next() )
1805   {
1806     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1807     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1808
1809     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1810       continue;
1811     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1812       continue;
1813
1814     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1815       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1816
1817     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1818     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1819     while( prxIt->more() )
1820     {
1821       const SMDS_MeshElement* fSrc = srcIt->next();
1822       const SMDS_MeshElement* fPrx = prxIt->next();
1823       if ( fSrc->NbNodes() != fPrx->NbNodes())
1824         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1825       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1826         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1827     }
1828   }
1829   pm->_n2nMapComputed = true;
1830   return true;
1831 }
1832
1833 //================================================================================
1834 /*!
1835  * \brief Does its job
1836  */
1837 //================================================================================
1838
1839 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1840                                                const TopoDS_Shape& theShape)
1841 {
1842   _mesh = & theMesh;
1843
1844   // check if proxy mesh already computed
1845   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1846   if ( !exp.More() )
1847     return error("No SOLID's in theShape"), _error;
1848
1849   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1850     return SMESH_ComputeErrorPtr(); // everything already computed
1851
1852   PyDump debugDump( theMesh );
1853
1854   // TODO: ignore already computed SOLIDs 
1855   if ( !findSolidsWithLayers())
1856     return _error;
1857
1858   if ( !findFacesWithLayers() )
1859     return _error;
1860
1861   for ( size_t i = 0; i < _sdVec.size(); ++i )
1862   {
1863     size_t iSD = 0;
1864     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1865       if ( _sdVec[iSD]._before.IsEmpty() &&
1866            _sdVec[iSD]._n2eMap.empty() )
1867         break;
1868
1869     if ( ! makeLayer(_sdVec[iSD]) )
1870       return _error;
1871
1872     if ( _sdVec[iSD]._n2eMap.size() == 0 )
1873       continue;
1874     
1875     if ( ! inflate(_sdVec[iSD]) )
1876       return _error;
1877
1878     if ( ! refine(_sdVec[iSD]) )
1879       return _error;
1880
1881     if ( !shrink(_sdVec[iSD]) )
1882       return _error;
1883
1884     addBoundaryElements(_sdVec[iSD]);
1885
1886     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1887     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1888       _sdVec[iSD]._before.Remove( solid );
1889   }
1890
1891   makeGroupOfLE(); // debug
1892   debugDump.Finish();
1893
1894   return _error;
1895 }
1896
1897 //================================================================================
1898 /*!
1899  * \brief Check validity of hypotheses
1900  */
1901 //================================================================================
1902
1903 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1904                                                         const TopoDS_Shape& shape )
1905 {
1906   _mesh = & mesh;
1907
1908   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1909     return SMESH_ComputeErrorPtr(); // everything already computed
1910
1911
1912   findSolidsWithLayers();
1913   bool ok = findFacesWithLayers( true );
1914
1915   // remove _MeshOfSolid's of _SolidData's
1916   for ( size_t i = 0; i < _sdVec.size(); ++i )
1917     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1918
1919   if ( !ok )
1920     return _error;
1921
1922   return SMESH_ComputeErrorPtr();
1923 }
1924
1925 //================================================================================
1926 /*!
1927  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1928  */
1929 //================================================================================
1930
1931 bool _ViscousBuilder::findSolidsWithLayers()
1932 {
1933   // get all solids
1934   TopTools_IndexedMapOfShape allSolids;
1935   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1936   _sdVec.reserve( allSolids.Extent());
1937
1938   SMESH_HypoFilter filter;
1939   for ( int i = 1; i <= allSolids.Extent(); ++i )
1940   {
1941     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1942     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1943     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1944       continue; // solid is already meshed
1945     SMESH_Algo* algo = sm->GetAlgo();
1946     if ( !algo ) continue;
1947     // TODO: check if algo is hidden
1948     const list <const SMESHDS_Hypothesis *> & allHyps =
1949       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1950     _SolidData* soData = 0;
1951     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1952     const StdMeshers_ViscousLayers* viscHyp = 0;
1953     for ( ; hyp != allHyps.end(); ++hyp )
1954       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1955       {
1956         TopoDS_Shape hypShape;
1957         filter.Init( filter.Is( viscHyp ));
1958         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1959
1960         if ( !soData )
1961         {
1962           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1963                                                                     allSolids(i),
1964                                                                     /*toCreate=*/true);
1965           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1966           soData = & _sdVec.back();
1967           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1968           soData->_helper = new SMESH_MesherHelper( *_mesh );
1969           soData->_helper->SetSubShape( allSolids(i) );
1970           _solids.Add( allSolids(i) );
1971         }
1972         soData->_hyps.push_back( viscHyp );
1973         soData->_hypShapes.push_back( hypShape );
1974       }
1975   }
1976   if ( _sdVec.empty() )
1977     return error
1978       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1979
1980   return true;
1981 }
1982
1983 //================================================================================
1984 /*!
1985  * \brief Set a _SolidData to be computed before another
1986  */
1987 //================================================================================
1988
1989 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
1990 {
1991   // check possibility to set this order; get all solids before solidBefore
1992   TopTools_IndexedMapOfShape allSolidsBefore;
1993   allSolidsBefore.Add( solidBefore._solid );
1994   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
1995   {
1996     int iSD = _solids.FindIndex( allSolidsBefore(i) );
1997     if ( iSD )
1998     {
1999       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2000       for ( ; soIt.More(); soIt.Next() )
2001         allSolidsBefore.Add( soIt.Value() );
2002     }
2003   }
2004   if ( allSolidsBefore.Contains( solidAfter._solid ))
2005     return false;
2006
2007   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2008     solidAfter._before.Add( allSolidsBefore(i) );
2009
2010   return true;
2011 }
2012
2013 //================================================================================
2014 /*!
2015  * \brief
2016  */
2017 //================================================================================
2018
2019 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2020 {
2021   SMESH_MesherHelper helper( *_mesh );
2022   TopExp_Explorer exp;
2023
2024   // collect all faces-to-ignore defined by hyp
2025   for ( size_t i = 0; i < _sdVec.size(); ++i )
2026   {
2027     // get faces-to-ignore defined by each hyp
2028     typedef const StdMeshers_ViscousLayers* THyp;
2029     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2030     list< TFacesOfHyp > ignoreFacesOfHyps;
2031     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2032     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2033     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2034     {
2035       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2036       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2037     }
2038
2039     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2040     const int nbHyps = _sdVec[i]._hyps.size();
2041     if ( nbHyps > 1 )
2042     {
2043       // check if two hypotheses define different parameters for the same FACE
2044       list< TFacesOfHyp >::iterator igFacesOfHyp;
2045       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2046       {
2047         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2048         THyp hyp = 0;
2049         igFacesOfHyp = ignoreFacesOfHyps.begin();
2050         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2051           if ( ! igFacesOfHyp->first.count( faceID ))
2052           {
2053             if ( hyp )
2054               return error(SMESH_Comment("Several hypotheses define "
2055                                          "Viscous Layers on the face #") << faceID );
2056             hyp = igFacesOfHyp->second;
2057           }
2058         if ( hyp )
2059           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2060         else
2061           _sdVec[i]._ignoreFaceIds.insert( faceID );
2062       }
2063
2064       // check if two hypotheses define different number of viscous layers for
2065       // adjacent faces of a solid
2066       set< int > nbLayersSet;
2067       igFacesOfHyp = ignoreFacesOfHyps.begin();
2068       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2069       {
2070         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2071       }
2072       if ( nbLayersSet.size() > 1 )
2073       {
2074         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2075         {
2076           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2077           THyp hyp1 = 0, hyp2 = 0;
2078           while( const TopoDS_Shape* face = fIt->next() )
2079           {
2080             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2081             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2082             if ( f2h != _sdVec[i]._face2hyp.end() )
2083             {
2084               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2085             }
2086           }
2087           if ( hyp1 && hyp2 &&
2088                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2089           {
2090             return error("Two hypotheses define different number of "
2091                          "viscous layers on adjacent faces");
2092           }
2093         }
2094       }
2095     } // if ( nbHyps > 1 )
2096     else
2097     {
2098       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2099     }
2100   } // loop on _sdVec
2101
2102   if ( onlyWith ) // is called to check hypotheses compatibility only
2103     return true;
2104
2105   // fill _SolidData::_reversedFaceIds
2106   for ( size_t i = 0; i < _sdVec.size(); ++i )
2107   {
2108     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2109     for ( ; exp.More(); exp.Next() )
2110     {
2111       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2112       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2113       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2114           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2115           helper.IsReversedSubMesh( face ))
2116       {
2117         _sdVec[i]._reversedFaceIds.insert( faceID );
2118       }
2119     }
2120   }
2121
2122   // Find faces to shrink mesh on (solution 2 in issue 0020832);
2123   TopTools_IndexedMapOfShape shapes;
2124   std::string structAlgoName = "Hexa_3D";
2125   for ( size_t i = 0; i < _sdVec.size(); ++i )
2126   {
2127     shapes.Clear();
2128     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2129     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2130     {
2131       const TopoDS_Shape& edge = shapes(iE);
2132       // find 2 faces sharing an edge
2133       TopoDS_Shape FF[2];
2134       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2135       while ( fIt->more())
2136       {
2137         const TopoDS_Shape* f = fIt->next();
2138         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2139           FF[ int( !FF[0].IsNull()) ] = *f;
2140       }
2141       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2142       // check presence of layers on them
2143       int ignore[2];
2144       for ( int j = 0; j < 2; ++j )
2145         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2146       if ( ignore[0] == ignore[1] )
2147         continue; // nothing interesting
2148       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2149       // check presence of layers on fWOL within an adjacent SOLID
2150       bool collision = false;
2151       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2152       while ( const TopoDS_Shape* solid = sIt->next() )
2153         if ( !solid->IsSame( _sdVec[i]._solid ))
2154         {
2155           int iSolid = _solids.FindIndex( *solid );
2156           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
2157           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2158           {
2159             // check if solid's mesh is unstructured and then try to set it
2160             // to be computed after the i-th solid
2161             SMESH_Algo*  algo = _mesh->GetSubMesh( *solid )->GetAlgo();
2162             bool isStructured = ( algo->GetName() == structAlgoName );
2163             if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid-1 ] ))
2164               collision = true; // don't shrink fWOL
2165             break;
2166           }
2167         }
2168       // add edge to maps
2169       if ( !fWOL.IsNull())
2170       {
2171         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2172         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2173         if ( collision )
2174         {
2175           // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2176           // on the edge but shrink won't be performed
2177           _sdVec[i]._noShrinkShapes.insert( edgeInd );
2178           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2179             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2180         }
2181       }
2182     }
2183   }
2184   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2185   // the algo of the SOLID sharing the FACE does not support it
2186   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2187   for ( size_t i = 0; i < _sdVec.size(); ++i )
2188   {
2189     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2190     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2191     {
2192       const TopoDS_Shape& fWOL = e2f->second;
2193       const TGeomID     edgeID = e2f->first;
2194       bool notShrinkFace = false;
2195       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2196       while ( soIt->more() )
2197       {
2198         const TopoDS_Shape* solid = soIt->next();
2199         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2200         SMESH_Algo* algo = _mesh->GetSubMesh( *solid )->GetAlgo();
2201         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2202         notShrinkFace = true;
2203         size_t iSolid = 0;
2204         for ( ; iSolid < _sdVec.size(); ++iSolid )
2205         {
2206           if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2207             if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2208               notShrinkFace = false;
2209             break;
2210           }
2211         }
2212         if ( notShrinkFace )
2213         {
2214           _sdVec[i]._noShrinkShapes.insert( edgeID );
2215
2216           // add VERTEXes of the edge in _noShrinkShapes
2217           TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2218           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2219             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2220
2221           // check if there is a collision with to-shrink-from EDGEs in iSolid
2222           if ( iSolid == _sdVec.size() )
2223             continue; // no VL in the solid
2224           shapes.Clear();
2225           TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2226           for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2227           {
2228             const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2229             const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2230             if ( eID == edgeID ||
2231                  !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2232                  _sdVec[i]._noShrinkShapes.count( eID ))
2233               continue;
2234             for ( int is1st = 0; is1st < 2; ++is1st )
2235             {
2236               TopoDS_Vertex V = helper.IthVertex( is1st, E );
2237               if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2238               {
2239                 // _sdVec[i]._noShrinkShapes.insert( eID );
2240                 // V = helper.IthVertex( !is1st, E );
2241                 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2242                 //iE = 0; // re-start the loop on EDGEs of fWOL
2243                 return error("No way to make a conformal mesh with "
2244                              "the given set of faces with layers", _sdVec[i]._index);
2245               }
2246             }
2247           }
2248         }
2249
2250       } // while ( soIt->more() )
2251     } // loop on _sdVec[i]._shrinkShape2Shape
2252   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2253
2254   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2255
2256   for ( size_t i = 0; i < _sdVec.size(); ++i )
2257   {
2258     shapes.Clear();
2259     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2260     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2261     {
2262       const TopoDS_Shape& vertex = shapes(iV);
2263       // find faces WOL sharing the vertex
2264       vector< TopoDS_Shape > facesWOL;
2265       size_t totalNbFaces = 0;
2266       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2267       while ( fIt->more())
2268       {
2269         const TopoDS_Shape* f = fIt->next();
2270         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2271         {
2272           totalNbFaces++;
2273           const int fID = getMeshDS()->ShapeToIndex( *f );
2274           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2275                !_sdVec[i]._noShrinkShapes.count( fID )*/)
2276             facesWOL.push_back( *f );
2277         }
2278       }
2279       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2280         continue; // no layers at this vertex or no WOL
2281       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2282       switch ( facesWOL.size() )
2283       {
2284       case 1:
2285       {
2286         helper.SetSubShape( facesWOL[0] );
2287         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2288         {
2289           TopoDS_Shape seamEdge;
2290           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2291           while ( eIt->more() && seamEdge.IsNull() )
2292           {
2293             const TopoDS_Shape* e = eIt->next();
2294             if ( helper.IsRealSeam( *e ) )
2295               seamEdge = *e;
2296           }
2297           if ( !seamEdge.IsNull() )
2298           {
2299             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2300             break;
2301           }
2302         }
2303         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2304         break;
2305       }
2306       case 2:
2307       {
2308         // find an edge shared by 2 faces
2309         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2310         while ( eIt->more())
2311         {
2312           const TopoDS_Shape* e = eIt->next();
2313           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2314                helper.IsSubShape( *e, facesWOL[1]))
2315           {
2316             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2317           }
2318         }
2319         break;
2320       }
2321       default:
2322         return error("Not yet supported case", _sdVec[i]._index);
2323       }
2324     }
2325   }
2326
2327   // add FACEs of other SOLIDs to _ignoreFaceIds
2328   for ( size_t i = 0; i < _sdVec.size(); ++i )
2329   {
2330     shapes.Clear();
2331     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2332
2333     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2334     {
2335       if ( !shapes.Contains( exp.Current() ))
2336         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2337     }
2338   }
2339
2340   return true;
2341 }
2342
2343 //================================================================================
2344 /*!
2345  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2346  */
2347 //================================================================================
2348
2349 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2350                                      const StdMeshers_ViscousLayers* hyp,
2351                                      const TopoDS_Shape&             hypShape,
2352                                      set<TGeomID>&                   ignoreFaceIds)
2353 {
2354   TopExp_Explorer exp;
2355
2356   vector<TGeomID> ids = hyp->GetBndShapes();
2357   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2358   {
2359     for ( size_t ii = 0; ii < ids.size(); ++ii )
2360     {
2361       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2362       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2363         ignoreFaceIds.insert( ids[ii] );
2364     }
2365   }
2366   else // FACEs with layers are given
2367   {
2368     exp.Init( solid, TopAbs_FACE );
2369     for ( ; exp.More(); exp.Next() )
2370     {
2371       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2372       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2373         ignoreFaceIds.insert( faceInd );
2374     }
2375   }
2376
2377   // ignore internal FACEs if inlets and outlets are specified
2378   if ( hyp->IsToIgnoreShapes() )
2379   {
2380     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2381     TopExp::MapShapesAndAncestors( hypShape,
2382                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2383
2384     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2385     {
2386       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2387       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2388         continue;
2389
2390       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2391       if ( nbSolids > 1 )
2392         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2393     }
2394   }
2395 }
2396
2397 //================================================================================
2398 /*!
2399  * \brief Create the inner surface of the viscous layer and prepare data for infation
2400  */
2401 //================================================================================
2402
2403 bool _ViscousBuilder::makeLayer(_SolidData& data)
2404 {
2405   // get all sub-shapes to make layers on
2406   set<TGeomID> subIds, faceIds;
2407   subIds = data._noShrinkShapes;
2408   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2409   for ( ; exp.More(); exp.Next() )
2410   {
2411     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2412     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2413       faceIds.insert( fSubM->GetId() );
2414   }
2415
2416   // make a map to find new nodes on sub-shapes shared with other SOLID
2417   map< TGeomID, TNode2Edge* >::iterator s2ne;
2418   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2419   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2420   {
2421     TGeomID shapeInd = s2s->first;
2422     for ( size_t i = 0; i < _sdVec.size(); ++i )
2423     {
2424       if ( _sdVec[i]._index == data._index ) continue;
2425       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2426       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2427            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2428       {
2429         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2430         break;
2431       }
2432     }
2433   }
2434
2435   // Create temporary faces and _LayerEdge's
2436
2437   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2438
2439   data._stepSize = Precision::Infinite();
2440   data._stepSizeNodes[0] = 0;
2441
2442   SMESH_MesherHelper helper( *_mesh );
2443   helper.SetSubShape( data._solid );
2444   helper.SetElementsOnShape( true );
2445
2446   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2447   TNode2Edge::iterator n2e2;
2448
2449   // collect _LayerEdge's of shapes they are based on
2450   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2451   const int nbShapes = getMeshDS()->MaxShapeIndex();
2452   edgesByGeom.resize( nbShapes+1 );
2453
2454   // set data of _EdgesOnShape's
2455   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2456   {
2457     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2458     while ( smIt->more() )
2459     {
2460       sm = smIt->next();
2461       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2462            !faceIds.count( sm->GetId() ))
2463         continue;
2464       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2465     }
2466   }
2467   // make _LayerEdge's
2468   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2469   {
2470     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2471     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2472     SMESH_ProxyMesh::SubMesh* proxySub =
2473       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2474
2475     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2476     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2477
2478     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2479     while ( eIt->more() )
2480     {
2481       const SMDS_MeshElement* face = eIt->next();
2482       double          faceMaxCosin = -1;
2483       _LayerEdge*     maxCosinEdge = 0;
2484       int             nbDegenNodes = 0;
2485
2486       newNodes.resize( face->NbCornerNodes() );
2487       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2488       {
2489         const SMDS_MeshNode* n = face->GetNode( i );
2490         const int      shapeID = n->getshapeId();
2491         const bool onDegenShap = helper.IsDegenShape( shapeID );
2492         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2493         if ( onDegenShap )
2494         {
2495           if ( onDegenEdge )
2496           {
2497             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2498             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2499             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2500             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2501               n = vN;
2502               nbDegenNodes++;
2503             }
2504           }
2505           else
2506           {
2507             nbDegenNodes++;
2508           }
2509         }
2510         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2511         if ( !(*n2e).second )
2512         {
2513           // add a _LayerEdge
2514           _LayerEdge* edge = new _LayerEdge();
2515           edge->_nodes.push_back( n );
2516           n2e->second = edge;
2517           edgesByGeom[ shapeID ]._edges.push_back( edge );
2518           const bool noShrink = data._noShrinkShapes.count( shapeID );
2519
2520           SMESH_TNodeXYZ xyz( n );
2521
2522           // set edge data or find already refined _LayerEdge and get data from it
2523           if (( !noShrink                                                     ) &&
2524               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2525               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2526               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2527           {
2528             _LayerEdge* foundEdge = (*n2e2).second;
2529             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2530             foundEdge->_pos.push_back( lastPos );
2531             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2532             const_cast< SMDS_MeshNode* >
2533               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2534           }
2535           else
2536           {
2537             if ( !noShrink )
2538             {
2539               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2540             }
2541             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2542               return false;
2543
2544             if ( edge->_nodes.size() < 2 )
2545               edge->Block( data );
2546               //data._noShrinkShapes.insert( shapeID );
2547           }
2548           dumpMove(edge->_nodes.back());
2549
2550           if ( edge->_cosin > faceMaxCosin )
2551           {
2552             faceMaxCosin = edge->_cosin;
2553             maxCosinEdge = edge;
2554           }
2555         }
2556         newNodes[ i ] = n2e->second->_nodes.back();
2557
2558         if ( onDegenEdge )
2559           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2560       }
2561       if ( newNodes.size() - nbDegenNodes < 2 )
2562         continue;
2563
2564       // create a temporary face
2565       const SMDS_MeshElement* newFace =
2566         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2567       proxySub->AddElement( newFace );
2568
2569       // compute inflation step size by min size of element on a convex surface
2570       if ( faceMaxCosin > theMinSmoothCosin )
2571         limitStepSize( data, face, maxCosinEdge );
2572
2573     } // loop on 2D elements on a FACE
2574   } // loop on FACEs of a SOLID to create _LayerEdge's
2575
2576
2577   // Set _LayerEdge::_neibors
2578   TNode2Edge::iterator n2e;
2579   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2580   {
2581     _EdgesOnShape& eos = data._edgesOnShape[iS];
2582     for ( size_t i = 0; i < eos._edges.size(); ++i )
2583     {
2584       _LayerEdge* edge = eos._edges[i];
2585       TIDSortedNodeSet nearNodes;
2586       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2587       while ( fIt->more() )
2588       {
2589         const SMDS_MeshElement* f = fIt->next();
2590         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2591           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2592       }
2593       nearNodes.erase( edge->_nodes[0] );
2594       edge->_neibors.reserve( nearNodes.size() );
2595       TIDSortedNodeSet::iterator node = nearNodes.begin();
2596       for ( ; node != nearNodes.end(); ++node )
2597         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2598           edge->_neibors.push_back( n2e->second );
2599     }
2600   }
2601
2602   data._epsilon = 1e-7;
2603   if ( data._stepSize < 1. )
2604     data._epsilon *= data._stepSize;
2605
2606   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2607     return false;
2608
2609   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2610   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2611
2612   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2613   const SMDS_MeshNode* nn[2];
2614   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2615   {
2616     _EdgesOnShape& eos = data._edgesOnShape[iS];
2617     for ( size_t i = 0; i < eos._edges.size(); ++i )
2618     {
2619       _LayerEdge* edge = eos._edges[i];
2620       if ( edge->IsOnEdge() )
2621       {
2622         // get neighbor nodes
2623         bool hasData = ( edge->_2neibors->_edges[0] );
2624         if ( hasData ) // _LayerEdge is a copy of another one
2625         {
2626           nn[0] = edge->_2neibors->srcNode(0);
2627           nn[1] = edge->_2neibors->srcNode(1);
2628         }
2629         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2630         {
2631           return false;
2632         }
2633         // set neighbor _LayerEdge's
2634         for ( int j = 0; j < 2; ++j )
2635         {
2636           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2637             return error("_LayerEdge not found by src node", data._index);
2638           edge->_2neibors->_edges[j] = n2e->second;
2639         }
2640         if ( !hasData )
2641           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2642       }
2643
2644       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2645       {
2646         _Simplex& s = edge->_simplices[j];
2647         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2648         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2649       }
2650
2651       // For an _LayerEdge on a degenerated EDGE, copy some data from
2652       // a corresponding _LayerEdge on a VERTEX
2653       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2654       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2655       {
2656         // Generally we should not get here
2657         if ( eos.ShapeType() != TopAbs_EDGE )
2658           continue;
2659         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2660         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2661         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2662           continue;
2663         const _LayerEdge* vEdge = n2e->second;
2664         edge->_normal    = vEdge->_normal;
2665         edge->_lenFactor = vEdge->_lenFactor;
2666         edge->_cosin     = vEdge->_cosin;
2667       }
2668
2669     } // loop on data._edgesOnShape._edges
2670   } // loop on data._edgesOnShape
2671
2672   // fix _LayerEdge::_2neibors on EDGEs to smooth
2673   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2674   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2675   //   if ( !e2c->second.IsNull() )
2676   //   {
2677   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2678   //       data.Sort2NeiborsOnEdge( eos->_edges );
2679   //   }
2680
2681   dumpFunctionEnd();
2682   return true;
2683 }
2684
2685 //================================================================================
2686 /*!
2687  * \brief Compute inflation step size by min size of element on a convex surface
2688  */
2689 //================================================================================
2690
2691 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2692                                      const SMDS_MeshElement* face,
2693                                      const _LayerEdge*       maxCosinEdge )
2694 {
2695   int iN = 0;
2696   double minSize = 10 * data._stepSize;
2697   const int nbNodes = face->NbCornerNodes();
2698   for ( int i = 0; i < nbNodes; ++i )
2699   {
2700     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2701     const SMDS_MeshNode*  curN = face->GetNode( i );
2702     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2703          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2704     {
2705       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2706       if ( dist < minSize )
2707         minSize = dist, iN = i;
2708     }
2709   }
2710   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2711   if ( newStep < data._stepSize )
2712   {
2713     data._stepSize = newStep;
2714     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2715     data._stepSizeNodes[0] = face->GetNode( iN );
2716     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2717   }
2718 }
2719
2720 //================================================================================
2721 /*!
2722  * \brief Compute inflation step size by min size of element on a convex surface
2723  */
2724 //================================================================================
2725
2726 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2727 {
2728   if ( minSize < data._stepSize )
2729   {
2730     data._stepSize = minSize;
2731     if ( data._stepSizeNodes[0] )
2732     {
2733       double dist =
2734         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2735       data._stepSizeCoeff = data._stepSize / dist;
2736     }
2737   }
2738 }
2739
2740 //================================================================================
2741 /*!
2742  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2743  */
2744 //================================================================================
2745
2746 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2747 {
2748   SMESH_MesherHelper helper( *_mesh );
2749
2750   const int nbTestPnt = 5; // on a FACE sub-shape
2751
2752   BRepLProp_SLProps surfProp( 2, 1e-6 );
2753   data._convexFaces.clear();
2754
2755   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2756   {
2757     _EdgesOnShape& eof = data._edgesOnShape[iS];
2758     if ( eof.ShapeType() != TopAbs_FACE ||
2759          data._ignoreFaceIds.count( eof._shapeID ))
2760       continue;
2761
2762     TopoDS_Face        F = TopoDS::Face( eof._shape );
2763     SMESH_subMesh *   sm = eof._subMesh;
2764     const TGeomID faceID = eof._shapeID;
2765
2766     BRepAdaptor_Surface surface( F, false );
2767     surfProp.SetSurface( surface );
2768
2769     bool isTooCurved = false;
2770
2771     _ConvexFace cnvFace;
2772     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2773     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2774     while ( smIt->more() )
2775     {
2776       sm = smIt->next();
2777       const TGeomID subID = sm->GetId();
2778       // find _LayerEdge's of a sub-shape
2779       _EdgesOnShape* eos;
2780       if (( eos = data.GetShapeEdges( subID )))
2781         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2782       else
2783         continue;
2784       // check concavity and curvature and limit data._stepSize
2785       const double minCurvature =
2786         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2787       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2788       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2789       {
2790         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2791         surfProp.SetParameters( uv.X(), uv.Y() );
2792         if ( !surfProp.IsCurvatureDefined() )
2793           continue;
2794         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2795         {
2796           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2797           isTooCurved = true;
2798         }
2799         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2800         {
2801           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2802           isTooCurved = true;
2803         }
2804       }
2805     } // loop on sub-shapes of the FACE
2806
2807     if ( !isTooCurved ) continue;
2808
2809     _ConvexFace & convFace =
2810       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2811
2812     convFace._face = F;
2813     convFace._normalsFixed = false;
2814
2815     // skip a closed surface (data._convexFaces is useful anyway)
2816     bool isClosedF = false;
2817     helper.SetSubShape( F );
2818     if ( helper.HasRealSeam() )
2819     {
2820       // in the closed surface there must be a closed EDGE
2821       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2822         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2823     }
2824     if ( isClosedF )
2825     {
2826       // limit _LayerEdge::_maxLen on the FACE
2827       const double minCurvature =
2828         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2829       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2830       if ( id2eos != cnvFace._subIdToEOS.end() )
2831       {
2832         _EdgesOnShape& eos = * id2eos->second;
2833         for ( size_t i = 0; i < eos._edges.size(); ++i )
2834         {
2835           _LayerEdge* ledge = eos._edges[ i ];
2836           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2837           surfProp.SetParameters( uv.X(), uv.Y() );
2838           if ( !surfProp.IsCurvatureDefined() )
2839             continue;
2840
2841           if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2842             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2843
2844           if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2845             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2846         }
2847       }
2848       continue;
2849     }
2850
2851     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2852     // prism distortion.
2853     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2854     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2855     {
2856       // there are _LayerEdge's on the FACE it-self;
2857       // select _LayerEdge's near EDGEs
2858       _EdgesOnShape& eos = * id2eos->second;
2859       for ( size_t i = 0; i < eos._edges.size(); ++i )
2860       {
2861         _LayerEdge* ledge = eos._edges[ i ];
2862         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2863           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2864           {
2865             convFace._simplexTestEdges.push_back( ledge );
2866             break;
2867           }
2868       }
2869     }
2870     else
2871     {
2872       // where there are no _LayerEdge's on a _ConvexFace,
2873       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2874       // so that collision of viscous internal faces is not detected by check of
2875       // intersection of _LayerEdge's with the viscous internal faces.
2876
2877       set< const SMDS_MeshNode* > usedNodes;
2878
2879       // look for _LayerEdge's with null _sWOL
2880       id2eos = convFace._subIdToEOS.begin();
2881       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2882       {
2883         _EdgesOnShape& eos = * id2eos->second;
2884         if ( !eos._sWOL.IsNull() )
2885           continue;
2886         for ( size_t i = 0; i < eos._edges.size(); ++i )
2887         {
2888           _LayerEdge* ledge = eos._edges[ i ];
2889           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2890           if ( !usedNodes.insert( srcNode ).second ) continue;
2891
2892           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2893           {
2894             usedNodes.insert( ledge->_simplices[i]._nPrev );
2895             usedNodes.insert( ledge->_simplices[i]._nNext );
2896           }
2897           convFace._simplexTestEdges.push_back( ledge );
2898         }
2899       }
2900     }
2901   } // loop on FACEs of data._solid
2902 }
2903
2904 //================================================================================
2905 /*!
2906  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2907  */
2908 //================================================================================
2909
2910 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2911 {
2912   // define allowed thickness
2913   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2914
2915   data._maxThickness = 0;
2916   data._minThickness = 1e100;
2917   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2918   for ( ; hyp != data._hyps.end(); ++hyp )
2919   {
2920     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2921     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2922   }
2923   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2924
2925   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2926   // boundry inclined to the shape at a sharp angle
2927
2928   //list< TGeomID > shapesToSmooth;
2929   TopTools_MapOfShape edgesOfSmooFaces;
2930
2931   SMESH_MesherHelper helper( *_mesh );
2932   bool ok = true;
2933
2934   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2935   data._nbShapesToSmooth = 0;
2936
2937   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2938   {
2939     _EdgesOnShape& eos = edgesByGeom[iS];
2940     eos._toSmooth = false;
2941     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2942       continue;
2943
2944     double tgtThick = eos._hyp.GetTotalThickness();
2945     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2946     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2947     {
2948       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2949       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2950       if ( eE.empty() ) continue;
2951
2952       double faceSize;
2953       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2954         if ( eE[i]->_cosin > theMinSmoothCosin )
2955         {
2956           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2957           while ( fIt->more() && !eos._toSmooth )
2958           {
2959             const SMDS_MeshElement* face = fIt->next();
2960             if ( face->getshapeId() == eos._shapeID &&
2961                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2962             {
2963               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2964             }
2965           }
2966         }
2967     }
2968     if ( eos._toSmooth )
2969     {
2970       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2971         edgesOfSmooFaces.Add( eExp.Current() );
2972
2973       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2974     }
2975     data._nbShapesToSmooth += eos._toSmooth;
2976
2977   }  // check FACEs
2978
2979   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2980   {
2981     _EdgesOnShape& eos = edgesByGeom[iS];
2982     eos._edgeSmoother = NULL;
2983     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2984     if ( !eos._hyp.ToSmooth() ) continue;
2985
2986     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2987     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2988       continue;
2989
2990     double tgtThick = eos._hyp.GetTotalThickness();
2991     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2992     {
2993       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2994       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2995       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
2996       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2997       double angle    = eDir.Angle( eV[0]->_normal );
2998       double cosin    = Cos( angle );
2999       double cosinAbs = Abs( cosin );
3000       if ( cosinAbs > theMinSmoothCosin )
3001       {
3002         // always smooth analytic EDGEs
3003         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3004         eos._toSmooth = ! curve.IsNull();
3005
3006         // compare tgtThick with the length of an end segment
3007         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3008         while ( eIt->more() && !eos._toSmooth )
3009         {
3010           const SMDS_MeshElement* endSeg = eIt->next();
3011           if ( endSeg->getshapeId() == (int) iS )
3012           {
3013             double segLen =
3014               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3015             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3016           }
3017         }
3018         if ( eos._toSmooth )
3019         {
3020           eos._edgeSmoother = new _Smoother1D( curve, eos );
3021
3022           for ( size_t i = 0; i < eos._edges.size(); ++i )
3023             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3024         }
3025       }
3026     }
3027     data._nbShapesToSmooth += eos._toSmooth;
3028
3029   } // check EDGEs
3030
3031   // Reset _cosin if no smooth is allowed by the user
3032   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3033   {
3034     _EdgesOnShape& eos = edgesByGeom[iS];
3035     if ( eos._edges.empty() ) continue;
3036
3037     if ( !eos._hyp.ToSmooth() )
3038       for ( size_t i = 0; i < eos._edges.size(); ++i )
3039         eos._edges[i]->SetCosin( 0 );
3040   }
3041
3042
3043   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3044
3045   TopTools_MapOfShape c1VV;
3046
3047   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3048   {
3049     _EdgesOnShape& eos = edgesByGeom[iS];
3050     if ( eos._edges.empty() ||
3051          eos.ShapeType() != TopAbs_FACE ||
3052          !eos._toSmooth )
3053       continue;
3054
3055     // check EDGEs of a FACE
3056     TopTools_MapOfShape checkedEE, allVV;
3057     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3058     while ( !smQueue.empty() )
3059     {
3060       SMESH_subMesh* sm = smQueue.front();
3061       smQueue.pop_front();
3062       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3063       while ( smIt->more() )
3064       {
3065         sm = smIt->next();
3066         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3067           allVV.Add( sm->GetSubShape() );
3068         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3069              !checkedEE.Add( sm->GetSubShape() ))
3070           continue;
3071
3072         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3073         vector<_LayerEdge*>& eE = eoe->_edges;
3074         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3075           continue;
3076
3077         bool isC1 = true; // check continuity along an EDGE
3078         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3079           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3080         if ( !isC1 )
3081           continue;
3082
3083         // check that mesh faces are C1 as well
3084         {
3085           gp_XYZ norm1, norm2;
3086           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3087           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3088           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3089             continue;
3090           while ( fIt->more() && isC1 )
3091             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3092                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3093           if ( !isC1 )
3094             continue;
3095         }
3096
3097         // add the EDGE and an adjacent FACE to _eosC1
3098         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3099         while ( const TopoDS_Shape* face = fIt->next() )
3100         {
3101           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3102           if ( !eof ) continue; // other solid
3103           if ( !eos.HasC1( eoe ))
3104           {
3105             eos._eosC1.push_back( eoe );
3106             eoe->_toSmooth = false;
3107             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3108           }
3109           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3110           {
3111             eos._eosC1.push_back( eof );
3112             eof->_toSmooth = false;
3113             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3114             smQueue.push_back( eof->_subMesh );
3115           }
3116         }
3117       }
3118     }
3119     if ( eos._eosC1.empty() )
3120       continue;
3121
3122     // check VERTEXes of C1 FACEs
3123     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3124     for ( ; vIt.More(); vIt.Next() )
3125     {
3126       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3127       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3128         continue;
3129
3130       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3131       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3132       while ( const TopoDS_Shape* face = fIt->next() )
3133       {
3134         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3135         if ( !eof ) continue; // other solid
3136         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3137         if ( !isC1 )
3138           break;
3139       }
3140       if ( isC1 )
3141       {
3142         eos._eosC1.push_back( eov );
3143         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3144         c1VV.Add( eov->_shape );
3145       }
3146     }
3147
3148   } // fill _eosC1 of FACEs
3149
3150
3151   // Find C1 EDGEs
3152
3153   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3154
3155   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3156   {
3157     _EdgesOnShape& eov = edgesByGeom[iS];
3158     if ( eov._edges.empty() ||
3159          eov.ShapeType() != TopAbs_VERTEX ||
3160          c1VV.Contains( eov._shape ))
3161       continue;
3162     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3163
3164     // get directions of surrounding EDGEs
3165     dirOfEdges.clear();
3166     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3167     while ( const TopoDS_Shape* e = fIt->next() )
3168     {
3169       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3170       if ( !eoe ) continue; // other solid
3171       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3172       if ( !Precision::IsInfinite( eDir.X() ))
3173         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3174     }
3175
3176     // find EDGEs with C1 directions
3177     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3178       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3179         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3180         {
3181           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3182           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3183           if ( isC1 )
3184           {
3185             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3186             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3187             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3188             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3189             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3190             dirOfEdges[i].first = 0;
3191             dirOfEdges[j].first = 0;
3192           }
3193         }
3194   } // fill _eosC1 of VERTEXes
3195
3196
3197
3198   return ok;
3199 }
3200
3201 //================================================================================
3202 /*!
3203  * \brief initialize data of _EdgesOnShape
3204  */
3205 //================================================================================
3206
3207 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3208                                     SMESH_subMesh* sm,
3209                                     _SolidData&    data )
3210 {
3211   if ( !eos._shape.IsNull() ||
3212        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3213     return;
3214
3215   SMESH_MesherHelper helper( *_mesh );
3216
3217   eos._subMesh = sm;
3218   eos._shapeID = sm->GetId();
3219   eos._shape   = sm->GetSubShape();
3220   if ( eos.ShapeType() == TopAbs_FACE )
3221     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3222   eos._toSmooth = false;
3223   eos._data = &data;
3224
3225   // set _SWOL
3226   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3227     data._shrinkShape2Shape.find( eos._shapeID );
3228   if ( s2s != data._shrinkShape2Shape.end() )
3229     eos._sWOL = s2s->second;
3230
3231   eos._isRegularSWOL = true;
3232   if ( eos.SWOLType() == TopAbs_FACE )
3233   {
3234     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3235     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3236     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3237   }
3238
3239   // set _hyp
3240   if ( data._hyps.size() == 1 )
3241   {
3242     eos._hyp = data._hyps.back();
3243   }
3244   else
3245   {
3246     // compute average StdMeshers_ViscousLayers parameters
3247     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3248     if ( eos.ShapeType() == TopAbs_FACE )
3249     {
3250       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3251         eos._hyp = f2hyp->second;
3252     }
3253     else
3254     {
3255       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3256       while ( const TopoDS_Shape* face = fIt->next() )
3257       {
3258         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3259         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3260           eos._hyp.Add( f2hyp->second );
3261       }
3262     }
3263   }
3264
3265   // set _faceNormals
3266   if ( ! eos._hyp.UseSurfaceNormal() )
3267   {
3268     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3269     {
3270       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3271       eos._faceNormals.resize( smDS->NbElements() );
3272
3273       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3274       for ( int iF = 0; eIt->more(); ++iF )
3275       {
3276         const SMDS_MeshElement* face = eIt->next();
3277         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3278           eos._faceNormals[iF].SetCoord( 0,0,0 );
3279       }
3280
3281       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3282         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3283           eos._faceNormals[iF].Reverse();
3284     }
3285     else // find EOS of adjacent FACEs
3286     {
3287       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3288       while ( const TopoDS_Shape* face = fIt->next() )
3289       {
3290         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3291         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3292         if ( eos._faceEOS.back()->_shape.IsNull() )
3293           // avoid using uninitialised _shapeID in GetNormal()
3294           eos._faceEOS.back()->_shapeID = faceID;
3295       }
3296     }
3297   }
3298 }
3299
3300 //================================================================================
3301 /*!
3302  * \brief Returns normal of a face
3303  */
3304 //================================================================================
3305
3306 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3307 {
3308   bool ok = false;
3309   const _EdgesOnShape* eos = 0;
3310
3311   if ( face->getshapeId() == _shapeID )
3312   {
3313     eos = this;
3314   }
3315   else
3316   {
3317     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3318       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3319         eos = _faceEOS[ iF ];
3320   }
3321
3322   if (( eos ) &&
3323       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3324   {
3325     norm = eos->_faceNormals[ face->getIdInShape() ];
3326   }
3327   else if ( !eos )
3328   {
3329     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3330               << " on _shape #" << _shapeID );
3331   }
3332   return ok;
3333 }
3334
3335
3336 //================================================================================
3337 /*!
3338  * \brief Set data of _LayerEdge needed for smoothing
3339  */
3340 //================================================================================
3341
3342 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3343                                   _EdgesOnShape&      eos,
3344                                   SMESH_MesherHelper& helper,
3345                                   _SolidData&         data)
3346 {
3347   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3348
3349   edge._len       = 0;
3350   edge._maxLen    = Precision::Infinite();
3351   edge._minAngle  = 0;
3352   edge._2neibors  = 0;
3353   edge._curvature = 0;
3354   edge._flags     = 0;
3355
3356   // --------------------------
3357   // Compute _normal and _cosin
3358   // --------------------------
3359
3360   edge._cosin     = 0;
3361   edge._lenFactor = 1.;
3362   edge._normal.SetCoord(0,0,0);
3363   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3364
3365   int totalNbFaces = 0;
3366   TopoDS_Face F;
3367   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3368   gp_Vec geomNorm;
3369   bool normOK = true;
3370
3371   const bool onShrinkShape = !eos._sWOL.IsNull();
3372   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3373                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3374
3375   // get geom FACEs the node lies on
3376   //if ( useGeometry )
3377   {
3378     set<TGeomID> faceIds;
3379     if  ( eos.ShapeType() == TopAbs_FACE )
3380     {
3381       faceIds.insert( eos._shapeID );
3382     }
3383     else
3384     {
3385       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3386       while ( fIt->more() )
3387         faceIds.insert( fIt->next()->getshapeId() );
3388     }
3389     set<TGeomID>::iterator id = faceIds.begin();
3390     for ( ; id != faceIds.end(); ++id )
3391     {
3392       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3393       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3394         continue;
3395       F = TopoDS::Face( s );
3396       face2Norm[ totalNbFaces ].first = F;
3397       totalNbFaces++;
3398     }
3399   }
3400
3401   // find _normal
3402   if ( useGeometry )
3403   {
3404     bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3405                       eos.SWOLType()  == TopAbs_FACE  &&
3406                       totalNbFaces > 1 );
3407
3408     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3409     {
3410       if ( eos.SWOLType() == TopAbs_EDGE )
3411       {
3412         // inflate from VERTEX along EDGE
3413         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3414       }
3415       else if ( eos.ShapeType() == TopAbs_VERTEX )
3416       {
3417         // inflate from VERTEX along FACE
3418         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3419                                    node, helper, normOK, &edge._cosin);
3420       }
3421       else
3422       {
3423         // inflate from EDGE along FACE
3424         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3425                                    node, helper, normOK);
3426       }
3427     }
3428     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3429     {
3430       if ( fromVonF )
3431         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3432
3433       int nbOkNorms = 0;
3434       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3435       {
3436         F = face2Norm[ iF ].first;
3437         geomNorm = getFaceNormal( node, F, helper, normOK );
3438         if ( !normOK ) continue;
3439         nbOkNorms++;
3440
3441         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3442           geomNorm.Reverse();
3443         face2Norm[ iF ].second = geomNorm.XYZ();
3444         edge._normal += geomNorm.XYZ();
3445       }
3446       if ( nbOkNorms == 0 )
3447         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3448
3449       if ( totalNbFaces >= 3 )
3450       {
3451         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3452       }
3453
3454       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3455       {
3456         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3457         edge._normal.SetCoord( 0,0,0 );
3458         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3459         {
3460           const TopoDS_Face& F = face2Norm[iF].first;
3461           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3462           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3463             geomNorm.Reverse();
3464           if ( normOK )
3465             face2Norm[ iF ].second = geomNorm.XYZ();
3466           edge._normal += face2Norm[ iF ].second;
3467         }
3468       }
3469     }
3470   }
3471   else // !useGeometry - get _normal using surrounding mesh faces
3472   {
3473     edge._normal = getWeigthedNormal( &edge );
3474
3475     // set<TGeomID> faceIds;
3476     //
3477     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3478     // while ( fIt->more() )
3479     // {
3480     //   const SMDS_MeshElement* face = fIt->next();
3481     //   if ( eos.GetNormal( face, geomNorm ))
3482     //   {
3483     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3484     //       continue; // use only one mesh face on FACE
3485     //     edge._normal += geomNorm.XYZ();
3486     //     totalNbFaces++;
3487     //   }
3488     // }
3489   }
3490
3491   // compute _cosin
3492   //if ( eos._hyp.UseSurfaceNormal() )
3493   {
3494     switch ( eos.ShapeType() )
3495     {
3496     case TopAbs_FACE: {
3497       edge._cosin = 0;
3498       break;
3499     }
3500     case TopAbs_EDGE: {
3501       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3502       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3503       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3504       edge._cosin      = Cos( angle );
3505       break;
3506     }
3507     case TopAbs_VERTEX: {
3508       //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3509       {
3510         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3511         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3512         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3513         edge._cosin      = Cos( angle );
3514         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3515           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3516           {
3517             F = face2Norm[ iF ].first;
3518             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3519             if ( normOK ) {
3520               double angle = inFaceDir.Angle( edge._normal );
3521               double cosin = Cos( angle );
3522               if ( Abs( cosin ) > Abs( edge._cosin ))
3523                 edge._cosin = cosin;
3524             }
3525           }
3526       }
3527       break;
3528     }
3529     default:
3530       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3531     }
3532   }
3533
3534   double normSize = edge._normal.SquareModulus();
3535   if ( normSize < numeric_limits<double>::min() )
3536     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3537
3538   edge._normal /= sqrt( normSize );
3539
3540   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3541   {
3542     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3543     edge._nodes.resize( 1 );
3544     edge._normal.SetCoord( 0,0,0 );
3545     edge._maxLen = 0;
3546   }
3547
3548   // Set the rest data
3549   // --------------------
3550
3551   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3552
3553   if ( onShrinkShape )
3554   {
3555     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3556     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3557       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3558
3559     // set initial position which is parameters on _sWOL in this case
3560     if ( eos.SWOLType() == TopAbs_EDGE )
3561     {
3562       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3563       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3564       if ( edge._nodes.size() > 1 )
3565         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3566     }
3567     else // eos.SWOLType() == TopAbs_FACE
3568     {
3569       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3570       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3571       if ( edge._nodes.size() > 1 )
3572         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3573     }
3574
3575     if ( edge._nodes.size() > 1 )
3576     {
3577       // check if an angle between a FACE with layers and SWOL is sharp,
3578       // else the edge should not inflate
3579       F.Nullify();
3580       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3581         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3582           F = face2Norm[iF].first;
3583       if ( !F.IsNull())
3584       {
3585         geomNorm = getFaceNormal( node, F, helper, normOK );
3586         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3587           geomNorm.Reverse(); // inside the SOLID
3588         if ( geomNorm * edge._normal < -0.001 )
3589         {
3590           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3591           edge._nodes.resize( 1 );
3592         }
3593         else if ( edge._lenFactor > 3 )
3594         {
3595           edge._lenFactor = 2;
3596           edge.Set( _LayerEdge::RISKY_SWOL );
3597         }
3598       }
3599     }
3600   }
3601   else
3602   {
3603     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3604
3605     if ( eos.ShapeType() == TopAbs_FACE )
3606     {
3607       double angle;
3608       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3609       {
3610         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3611         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3612       }
3613     }
3614   }
3615
3616   // Set neighbor nodes for a _LayerEdge based on EDGE
3617
3618   if ( eos.ShapeType() == TopAbs_EDGE /*||
3619        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3620   {
3621     edge._2neibors = new _2NearEdges;
3622     // target nodes instead of source ones will be set later
3623   }
3624
3625   return true;
3626 }
3627
3628 //================================================================================
3629 /*!
3630  * \brief Return normal to a FACE at a node
3631  *  \param [in] n - node
3632  *  \param [in] face - FACE
3633  *  \param [in] helper - helper
3634  *  \param [out] isOK - true or false
3635  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3636  *  \return gp_XYZ - normal
3637  */
3638 //================================================================================
3639
3640 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3641                                       const TopoDS_Face&   face,
3642                                       SMESH_MesherHelper&  helper,
3643                                       bool&                isOK,
3644                                       bool                 shiftInside)
3645 {
3646   gp_XY uv;
3647   if ( shiftInside )
3648   {
3649     // get a shifted position
3650     gp_Pnt p = SMESH_TNodeXYZ( node );
3651     gp_XYZ shift( 0,0,0 );
3652     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3653     switch ( S.ShapeType() ) {
3654     case TopAbs_VERTEX:
3655     {
3656       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3657       break;
3658     }
3659     case TopAbs_EDGE:
3660     {
3661       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3662       break;
3663     }
3664     default:
3665       isOK = false;
3666     }
3667     if ( isOK )
3668       shift.Normalize();
3669     p.Translate( shift * 1e-5 );
3670
3671     TopLoc_Location loc;
3672     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3673
3674     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3675     
3676     projector.Perform( p );
3677     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3678     {
3679       isOK = false;
3680       return p.XYZ();
3681     }
3682     Quantity_Parameter U,V;
3683     projector.LowerDistanceParameters(U,V);
3684     uv.SetCoord( U,V );
3685   }
3686   else
3687   {
3688     uv = helper.GetNodeUV( face, node, 0, &isOK );
3689   }
3690
3691   gp_Dir normal;
3692   isOK = false;
3693
3694   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3695
3696   if ( !shiftInside &&
3697        helper.IsDegenShape( node->getshapeId() ) &&
3698        getFaceNormalAtSingularity( uv, face, helper, normal ))
3699   {
3700     isOK = true;
3701     return normal.XYZ();
3702   }
3703
3704   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3705   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3706
3707   if ( pointKind == IMPOSSIBLE &&
3708        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3709   {
3710     // probably NormEstim() failed due to a too high tolerance
3711     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3712     isOK = ( pointKind < IMPOSSIBLE );
3713   }
3714   if ( pointKind < IMPOSSIBLE )
3715   {
3716     if ( pointKind != REGULAR &&
3717          !shiftInside &&
3718          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3719     {
3720       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3721       if ( normShift * normal.XYZ() < 0. )
3722         normal = normShift;
3723     }
3724     isOK = true;
3725   }
3726
3727   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3728   {
3729     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3730
3731     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3732     while ( fIt->more() )
3733     {
3734       const SMDS_MeshElement* f = fIt->next();
3735       if ( f->getshapeId() == faceID )
3736       {
3737         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3738         if ( isOK )
3739         {
3740           TopoDS_Face ff = face;
3741           ff.Orientation( TopAbs_FORWARD );
3742           if ( helper.IsReversedSubMesh( ff ))
3743             normal.Reverse();
3744           break;
3745         }
3746       }
3747     }
3748   }
3749   return normal.XYZ();
3750 }
3751
3752 //================================================================================
3753 /*!
3754  * \brief Try to get normal at a singularity of a surface basing on it's nature
3755  */
3756 //================================================================================
3757
3758 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3759                                                   const TopoDS_Face&  face,
3760                                                   SMESH_MesherHelper& helper,
3761                                                   gp_Dir&             normal )
3762 {
3763   BRepAdaptor_Surface surface( face );
3764   gp_Dir axis;
3765   if ( !getRovolutionAxis( surface, axis ))
3766     return false;
3767
3768   double f,l, d, du, dv;
3769   f = surface.FirstUParameter();
3770   l = surface.LastUParameter();
3771   d = ( uv.X() - f ) / ( l - f );
3772   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3773   f = surface.FirstVParameter();
3774   l = surface.LastVParameter();
3775   d = ( uv.Y() - f ) / ( l - f );
3776   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3777
3778   gp_Dir refDir;
3779   gp_Pnt2d testUV = uv;
3780   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3781   double tol = 1e-5;
3782   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3783   for ( int iLoop = 0; true ; ++iLoop )
3784   {
3785     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3786     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3787       break;
3788     if ( iLoop > 20 )
3789       return false;
3790     tol /= 10.;
3791   }
3792
3793   if ( axis * refDir < 0. )
3794     axis.Reverse();
3795
3796   normal = axis;
3797
3798   return true;
3799 }
3800
3801 //================================================================================
3802 /*!
3803  * \brief Return a normal at a node weighted with angles taken by faces
3804  */
3805 //================================================================================
3806
3807 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3808 {
3809   const SMDS_MeshNode* n = edge->_nodes[0];
3810
3811   gp_XYZ resNorm(0,0,0);
3812   SMESH_TNodeXYZ p0( n ), pP, pN;
3813   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3814   {
3815     pP.Set( edge->_simplices[i]._nPrev );
3816     pN.Set( edge->_simplices[i]._nNext );
3817     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3818     double l0P = v0P.SquareMagnitude();
3819     double l0N = v0N.SquareMagnitude();
3820     double lPN = vPN.SquareMagnitude();
3821     if ( l0P < std::numeric_limits<double>::min() ||
3822          l0N < std::numeric_limits<double>::min() ||
3823          lPN < std::numeric_limits<double>::min() )
3824       continue;
3825     double lNorm = norm.SquareMagnitude();
3826     double  sin2 = lNorm / l0P / l0N;
3827     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3828
3829     double weight = sin2 * angle / lPN;
3830     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3831   }
3832
3833   return resNorm;
3834 }
3835
3836 //================================================================================
3837 /*!
3838  * \brief Return a normal at a node by getting a common point of offset planes
3839  *        defined by the FACE normals
3840  */
3841 //================================================================================
3842
3843 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3844                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3845                                            int                              nbFaces,
3846                                            bool                             lastNoOffset)
3847 {
3848   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3849
3850   gp_XYZ resNorm(0,0,0);
3851   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3852   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3853   {
3854     for ( int i = 0; i < nbFaces; ++i )
3855       resNorm += f2Normal[i].second;
3856     return resNorm;
3857   }
3858
3859   // prepare _OffsetPlane's
3860   vector< _OffsetPlane > pln( nbFaces );
3861   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3862   {
3863     pln[i]._faceIndex = i;
3864     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3865   }
3866   if ( lastNoOffset )
3867   {
3868     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3869     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3870   }
3871
3872   // intersect neighboring OffsetPlane's
3873   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3874   while ( const TopoDS_Shape* edge = edgeIt->next() )
3875   {
3876     int f1 = -1, f2 = -1;
3877     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3878       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3879         (( f1 < 0 ) ? f1 : f2 ) = i;
3880
3881     if ( f2 >= 0 )
3882       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3883   }
3884
3885   // get a common point
3886   gp_XYZ commonPnt( 0, 0, 0 );
3887   int nbPoints = 0;
3888   bool isPointFound;
3889   for ( int i = 0; i < nbFaces; ++i )
3890   {
3891     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3892     nbPoints  += isPointFound;
3893   }
3894   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3895   if ( nbPoints == 0 )
3896     return wgtNorm;
3897
3898   commonPnt /= nbPoints;
3899   resNorm = commonPnt - p0;
3900   if ( lastNoOffset )
3901     return resNorm;
3902
3903   // choose the best among resNorm and wgtNorm
3904   resNorm.Normalize();
3905   wgtNorm.Normalize();
3906   double resMinDot = std::numeric_limits<double>::max();
3907   double wgtMinDot = std::numeric_limits<double>::max();
3908   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3909   {
3910     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3911     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3912   }
3913
3914   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3915   {
3916     edge->Set( _LayerEdge::MULTI_NORMAL );
3917   }
3918
3919   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3920 }
3921
3922 //================================================================================
3923 /*!
3924  * \brief Compute line of intersection of 2 planes
3925  */
3926 //================================================================================
3927
3928 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3929                                             const TopoDS_Edge&   E,
3930                                             const TopoDS_Vertex& V )
3931 {
3932   int iNext = bool( _faceIndexNext[0] >= 0 );
3933   _faceIndexNext[ iNext ] = pln._faceIndex;
3934
3935   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3936   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3937
3938   gp_XYZ lineDir = n1 ^ n2;
3939
3940   double x = Abs( lineDir.X() );
3941   double y = Abs( lineDir.Y() );
3942   double z = Abs( lineDir.Z() );
3943
3944   int cooMax; // max coordinate
3945   if (x > y) {
3946     if (x > z) cooMax = 1;
3947     else       cooMax = 3;
3948   }
3949   else {
3950     if (y > z) cooMax = 2;
3951     else       cooMax = 3;
3952   }
3953
3954   gp_Pnt linePos;
3955   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3956   {
3957     // parallel planes - intersection is an offset of the common EDGE
3958     gp_Pnt p = BRep_Tool::Pnt( V );
3959     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3960     lineDir  = getEdgeDir( E, V );
3961   }
3962   else
3963   {
3964     // the constants in the 2 plane equations
3965     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3966     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3967
3968     switch ( cooMax ) {
3969     case 1:
3970       linePos.SetX(  0 );
3971       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3972       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3973       break;
3974     case 2:
3975       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3976       linePos.SetY(  0 );
3977       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3978       break;
3979     case 3:
3980       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3981       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3982       linePos.SetZ(  0 );
3983     }
3984   }
3985   gp_Lin& line = _lines[ iNext ];
3986   line.SetDirection( lineDir );
3987   line.SetLocation ( linePos );
3988
3989   _isLineOK[ iNext ] = true;
3990
3991
3992   iNext = bool( pln._faceIndexNext[0] >= 0 );
3993   pln._lines        [ iNext ] = line;
3994   pln._faceIndexNext[ iNext ] = this->_faceIndex;
3995   pln._isLineOK     [ iNext ] = true;
3996 }
3997
3998 //================================================================================
3999 /*!
4000  * \brief Computes intersection point of two _lines
4001  */
4002 //================================================================================
4003
4004 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4005                                     const TopoDS_Vertex & V) const
4006 {
4007   gp_XYZ p( 0,0,0 );
4008   isFound = false;
4009
4010   if ( NbLines() == 2 )
4011   {
4012     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4013     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4014     if ( Abs( dot01 ) > 0.05 )
4015     {
4016       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4017       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4018       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4019       isFound = true;
4020     }
4021     else
4022     {
4023       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4024       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4025       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4026       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4027       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4028       isFound = true;
4029     }
4030   }
4031
4032   return p;
4033 }
4034
4035 //================================================================================
4036 /*!
4037  * \brief Find 2 neigbor nodes of a node on EDGE
4038  */
4039 //================================================================================
4040
4041 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4042                                         const SMDS_MeshNode*& n1,
4043                                         const SMDS_MeshNode*& n2,
4044                                         _EdgesOnShape&        eos,
4045                                         _SolidData&           data)
4046 {
4047   const SMDS_MeshNode* node = edge->_nodes[0];
4048   const int        shapeInd = eos._shapeID;
4049   SMESHDS_SubMesh*   edgeSM = 0;
4050   if ( eos.ShapeType() == TopAbs_EDGE )
4051   {
4052     edgeSM = eos._subMesh->GetSubMeshDS();
4053     if ( !edgeSM || edgeSM->NbElements() == 0 )
4054       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4055   }
4056   int iN = 0;
4057   n2 = 0;
4058   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4059   while ( eIt->more() && !n2 )
4060   {
4061     const SMDS_MeshElement* e = eIt->next();
4062     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4063     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4064     if ( edgeSM )
4065     {
4066       if (!edgeSM->Contains(e)) continue;
4067     }
4068     else
4069     {
4070       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4071       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4072     }
4073     ( iN++ ? n2 : n1 ) = nNeibor;
4074   }
4075   if ( !n2 )
4076     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4077   return true;
4078 }
4079
4080 //================================================================================
4081 /*!
4082  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4083  */
4084 //================================================================================
4085
4086 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4087                                      const SMDS_MeshNode* n2,
4088                                      const _EdgesOnShape& eos,
4089                                      SMESH_MesherHelper&  helper)
4090 {
4091   if ( eos.ShapeType() != TopAbs_EDGE )
4092     return;
4093
4094   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4095   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4096   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4097
4098   // Set _curvature
4099
4100   double      sumLen = vec1.Modulus() + vec2.Modulus();
4101   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4102   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4103   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4104   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4105   if ( _curvature ) delete _curvature;
4106   _curvature = _Curvature::New( avgNormProj, avgLen );
4107   // if ( _curvature )
4108   //   debugMsg( _nodes[0]->GetID()
4109   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4110   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4111   //             << _curvature->lenDelta(0) );
4112
4113   // Set _plnNorm
4114
4115   if ( eos._sWOL.IsNull() )
4116   {
4117     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4118     // if ( SMESH_Algo::isDegenerated( E ))
4119     //   return;
4120     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4121     gp_XYZ plnNorm = dirE ^ _normal;
4122     double proj0   = plnNorm * vec1;
4123     double proj1   = plnNorm * vec2;
4124     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4125     {
4126       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4127       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4128     }
4129   }
4130 }
4131
4132 //================================================================================
4133 /*!
4134  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4135  * this and other _LayerEdge's are inflated along a FACE or an EDGE
4136  */
4137 //================================================================================
4138
4139 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4140                          _EdgesOnShape&      eos,
4141                          SMESH_MesherHelper& helper )
4142 {
4143   _nodes     = other._nodes;
4144   _normal    = other._normal;
4145   _len       = 0;
4146   _lenFactor = other._lenFactor;
4147   _cosin     = other._cosin;
4148   _2neibors  = other._2neibors;
4149   _curvature = 0; std::swap( _curvature, other._curvature );
4150   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4151
4152   gp_XYZ lastPos( 0,0,0 );
4153   if ( eos.SWOLType() == TopAbs_EDGE )
4154   {
4155     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4156     _pos.push_back( gp_XYZ( u, 0, 0));
4157
4158     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4159     lastPos.SetX( u );
4160   }
4161   else // TopAbs_FACE
4162   {
4163     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4164     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4165
4166     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4167     lastPos.SetX( uv.X() );
4168     lastPos.SetY( uv.Y() );
4169   }
4170   return lastPos;
4171 }
4172
4173 //================================================================================
4174 /*!
4175  * \brief Set _cosin and _lenFactor
4176  */
4177 //================================================================================
4178
4179 void _LayerEdge::SetCosin( double cosin )
4180 {
4181   _cosin = cosin;
4182   cosin = Abs( _cosin );
4183   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4184   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4185 }
4186
4187 //================================================================================
4188 /*!
4189  * \brief Check if another _LayerEdge is a neighbor on EDGE
4190  */
4191 //================================================================================
4192
4193 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4194 {
4195   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4196           ( edge->_2neibors && edge->_2neibors->include( this )));
4197 }
4198
4199 //================================================================================
4200 /*!
4201  * \brief Fills a vector<_Simplex > 
4202  */
4203 //================================================================================
4204
4205 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4206                              vector<_Simplex>&    simplices,
4207                              const set<TGeomID>&  ingnoreShapes,
4208                              const _SolidData*    dataToCheckOri,
4209                              const bool           toSort)
4210 {
4211   simplices.clear();
4212   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4213   while ( fIt->more() )
4214   {
4215     const SMDS_MeshElement* f = fIt->next();
4216     const TGeomID    shapeInd = f->getshapeId();
4217     if ( ingnoreShapes.count( shapeInd )) continue;
4218     const int nbNodes = f->NbCornerNodes();
4219     const int  srcInd = f->GetNodeIndex( node );
4220     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4221     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4222     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4223     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4224       std::swap( nPrev, nNext );
4225     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4226   }
4227
4228   if ( toSort )
4229     SortSimplices( simplices );
4230 }
4231
4232 //================================================================================
4233 /*!
4234  * \brief Set neighbor simplices side by side
4235  */
4236 //================================================================================
4237
4238 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4239 {
4240   vector<_Simplex> sortedSimplices( simplices.size() );
4241   sortedSimplices[0] = simplices[0];
4242   size_t nbFound = 0;
4243   for ( size_t i = 1; i < simplices.size(); ++i )
4244   {
4245     for ( size_t j = 1; j < simplices.size(); ++j )
4246       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4247       {
4248         sortedSimplices[i] = simplices[j];
4249         nbFound++;
4250         break;
4251       }
4252   }
4253   if ( nbFound == simplices.size() - 1 )
4254     simplices.swap( sortedSimplices );
4255 }
4256
4257 //================================================================================
4258 /*!
4259  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4260  */
4261 //================================================================================
4262
4263 void _ViscousBuilder::makeGroupOfLE()
4264 {
4265 #ifdef _DEBUG_
4266   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4267   {
4268     if ( _sdVec[i]._n2eMap.empty() ) continue;
4269
4270     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4271     TNode2Edge::iterator n2e;
4272     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4273     {
4274       _LayerEdge* le = n2e->second;
4275       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4276       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4277       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4278       if ( le ) {
4279         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4280                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4281       }
4282     }
4283     dumpFunctionEnd();
4284
4285     dumpFunction( SMESH_Comment("makeNormals") << i );
4286     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4287     {
4288       _LayerEdge* edge = n2e->second;
4289       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4290       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4291       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4292               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4293     }
4294     dumpFunctionEnd();
4295
4296     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4297     dumpCmd( "faceId1 = mesh.NbElements()" );
4298     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4299     for ( ; fExp.More(); fExp.Next() )
4300     {
4301       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4302       {
4303         if ( sm->NbElements() == 0 ) continue;
4304         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4305         while ( fIt->more())
4306         {
4307           const SMDS_MeshElement* e = fIt->next();
4308           SMESH_Comment cmd("mesh.AddFace([");
4309           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4310             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4311           dumpCmd( cmd );
4312         }
4313       }
4314     }
4315     dumpCmd( "faceId2 = mesh.NbElements()" );
4316     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4317              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4318              << "'%s-%s' % (faceId1+1, faceId2))");
4319     dumpFunctionEnd();
4320   }
4321 #endif
4322 }
4323
4324 //================================================================================
4325 /*!
4326  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4327  */
4328 //================================================================================
4329
4330 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4331 {
4332   data._geomSize = Precision::Infinite();
4333   double intersecDist;
4334   const SMDS_MeshElement* face;
4335   SMESH_MesherHelper helper( *_mesh );
4336
4337   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4338     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4339                                            data._proxyMesh->GetFaces( data._solid )));
4340
4341   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4342   {
4343     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4344     if ( eos._edges.empty() )
4345       continue;
4346     // get neighbor faces intersection with which should not be considered since
4347     // collisions are avoided by means of smoothing
4348     set< TGeomID > neighborFaces;
4349     if ( eos._hyp.ToSmooth() )
4350     {
4351       SMESH_subMeshIteratorPtr subIt =
4352         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4353       while ( subIt->more() )
4354       {
4355         SMESH_subMesh* sm = subIt->next();
4356         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4357         while ( const TopoDS_Shape* face = fIt->next() )
4358           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4359       }
4360     }
4361     // find intersections
4362     double thinkness = eos._hyp.GetTotalThickness();
4363     for ( size_t i = 0; i < eos._edges.size(); ++i )
4364     {
4365       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4366       eos._edges[i]->_maxLen = thinkness;
4367       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4368       if ( intersecDist > 0 && face )
4369       {
4370         data._geomSize = Min( data._geomSize, intersecDist );
4371         if ( !neighborFaces.count( face->getshapeId() ))
4372           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4373       }
4374     }
4375   }
4376 }
4377
4378 //================================================================================
4379 /*!
4380  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4381  */
4382 //================================================================================
4383
4384 bool _ViscousBuilder::inflate(_SolidData& data)
4385 {
4386   SMESH_MesherHelper helper( *_mesh );
4387
4388   // Limit inflation step size by geometry size found by itersecting
4389   // normals of _LayerEdge's with mesh faces
4390   if ( data._stepSize > 0.3 * data._geomSize )
4391     limitStepSize( data, 0.3 * data._geomSize );
4392
4393   const double tgtThick = data._maxThickness;
4394   if ( data._stepSize > data._minThickness )
4395     limitStepSize( data, data._minThickness );
4396
4397   if ( data._stepSize < 1. )
4398     data._epsilon = data._stepSize * 1e-7;
4399
4400   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4401
4402   findCollisionEdges( data, helper );
4403
4404   limitMaxLenByCurvature( data, helper );
4405
4406   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4407   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4408     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4409          data._edgesOnShape[i]._edges.size() > 0 &&
4410          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4411     {
4412       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4413       data._edgesOnShape[i]._edges[0]->Block( data );
4414     }
4415
4416   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4417
4418   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4419   int nbSteps = 0, nbRepeats = 0;
4420   while ( avgThick < 0.99 )
4421   {
4422     // new target length
4423     double prevThick = curThick;
4424     curThick += data._stepSize;
4425     if ( curThick > tgtThick )
4426     {
4427       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4428       nbRepeats++;
4429     }
4430
4431     double stepSize = curThick - prevThick;
4432     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4433
4434     // Elongate _LayerEdge's
4435     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4436     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4437     {
4438       _EdgesOnShape& eos = data._edgesOnShape[iS];
4439       if ( eos._edges.empty() ) continue;
4440
4441       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4442       for ( size_t i = 0; i < eos._edges.size(); ++i )
4443       {
4444         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4445       }
4446     }
4447     dumpFunctionEnd();
4448
4449     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4450       return false;
4451
4452     // Improve and check quality
4453     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4454     {
4455       if ( nbSteps > 0 )
4456       {
4457 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4458         debugMsg("NOT INVALIDATED STEP!");
4459         return error("Smoothing failed", data._index);
4460 #endif
4461         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4462         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4463         {
4464           _EdgesOnShape& eos = data._edgesOnShape[iS];
4465           for ( size_t i = 0; i < eos._edges.size(); ++i )
4466             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4467         }
4468         dumpFunctionEnd();
4469       }
4470       break; // no more inflating possible
4471     }
4472     nbSteps++;
4473
4474     // Evaluate achieved thickness
4475     avgThick = 0;
4476     int nbActiveEdges = 0;
4477     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4478     {
4479       _EdgesOnShape& eos = data._edgesOnShape[iS];
4480       if ( eos._edges.empty() ) continue;
4481
4482       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4483       for ( size_t i = 0; i < eos._edges.size(); ++i )
4484       {
4485         avgThick      += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4486         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4487       }
4488     }
4489     avgThick /= data._n2eMap.size();
4490     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4491
4492 #ifdef BLOCK_INFLATION
4493     if ( nbActiveEdges == 0 )
4494     {
4495       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4496       break;
4497     }
4498 #else
4499     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4500     {
4501       debugMsg( "-- Stop inflation since "
4502                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4503                 << tgtThick * avgThick << " ) * " << safeFactor );
4504       break;
4505     }
4506 #endif
4507     // new step size
4508     limitStepSize( data, 0.25 * distToIntersection );
4509     if ( data._stepSizeNodes[0] )
4510       data._stepSize = data._stepSizeCoeff *
4511         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4512
4513   } // while ( avgThick < 0.99 )
4514
4515   if ( nbSteps == 0 )
4516     return error("failed at the very first inflation step", data._index);
4517
4518   if ( avgThick < 0.99 )
4519   {
4520     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4521     {
4522       data._proxyMesh->_warning.reset
4523         ( new SMESH_ComputeError (COMPERR_WARNING,
4524                                   SMESH_Comment("Thickness ") << tgtThick <<
4525                                   " of viscous layers not reached,"
4526                                   " average reached thickness is " << avgThick*tgtThick));
4527     }
4528   }
4529
4530   // Restore position of src nodes moved by inflation on _noShrinkShapes
4531   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4532   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4533   {
4534     _EdgesOnShape& eos = data._edgesOnShape[iS];
4535     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4536       for ( size_t i = 0; i < eos._edges.size(); ++i )
4537       {
4538         restoreNoShrink( *eos._edges[ i ] );
4539       }
4540   }
4541   dumpFunctionEnd();
4542
4543   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4544 }
4545
4546 //================================================================================
4547 /*!
4548  * \brief Improve quality of layer inner surface and check intersection
4549  */
4550 //================================================================================
4551
4552 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4553                                      const int   infStep,
4554                                      double &    distToIntersection)
4555 {
4556   if ( data._nbShapesToSmooth == 0 )
4557     return true; // no shapes needing smoothing
4558
4559   bool moved, improved;
4560   double vol;
4561   vector< _LayerEdge* >    movedEdges, badEdges;
4562   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4563   vector< bool >           isConcaveFace;
4564
4565   SMESH_MesherHelper helper(*_mesh);
4566   Handle(ShapeAnalysis_Surface) surface;
4567   TopoDS_Face F;
4568
4569   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4570   {
4571     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4572
4573     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4574     {
4575       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4576       if ( !eos._toSmooth ||
4577            eos.ShapeType() != shapeType ||
4578            eos._edges.empty() )
4579         continue;
4580
4581       // already smoothed?
4582       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4583       // if ( !toSmooth ) continue;
4584
4585       if ( !eos._hyp.ToSmooth() )
4586       {
4587         // smooth disabled by the user; check validy only
4588         if ( !isFace ) continue;
4589         badEdges.clear();
4590         for ( size_t i = 0; i < eos._edges.size(); ++i )
4591         {
4592           _LayerEdge* edge = eos._edges[i];
4593           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4594             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4595             {
4596               // debugMsg( "-- Stop inflation. Bad simplex ("
4597               //           << " "<< edge->_nodes[0]->GetID()
4598               //           << " "<< edge->_nodes.back()->GetID()
4599               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4600               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4601               // return false;
4602               badEdges.push_back( edge );
4603             }
4604         }
4605         if ( !badEdges.empty() )
4606         {
4607           eosC1.resize(1);
4608           eosC1[0] = &eos;
4609           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4610           if ( nbBad > 0 )
4611             return false;
4612         }
4613         continue; // goto the next EDGE or FACE
4614       }
4615
4616       // prepare data
4617       if ( eos.SWOLType() == TopAbs_FACE )
4618       {
4619         if ( !F.IsSame( eos._sWOL )) {
4620           F = TopoDS::Face( eos._sWOL );
4621           helper.SetSubShape( F );
4622           surface = helper.GetSurface( F );
4623         }
4624       }
4625       else
4626       {
4627         F.Nullify(); surface.Nullify();
4628       }
4629       const TGeomID sInd = eos._shapeID;
4630
4631       // perform smoothing
4632
4633       if ( eos.ShapeType() == TopAbs_EDGE )
4634       {
4635         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4636
4637         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4638         {
4639           // smooth on EDGE's (normally we should not get here)
4640           int step = 0;
4641           do {
4642             moved = false;
4643             for ( size_t i = 0; i < eos._edges.size(); ++i )
4644             {
4645               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4646             }
4647             dumpCmd( SMESH_Comment("# end step ")<<step);
4648           }
4649           while ( moved && step++ < 5 );
4650         }
4651         dumpFunctionEnd();
4652       }
4653
4654       else // smooth on FACE
4655       {
4656         eosC1.clear();
4657         eosC1.push_back( & eos );
4658         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4659
4660         movedEdges.clear();
4661         isConcaveFace.resize( eosC1.size() );
4662         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4663         {
4664           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4665           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4666           for ( size_t i = 0; i < edges.size(); ++i )
4667             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4668                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4669               movedEdges.push_back( edges[i] );
4670
4671           makeOffsetSurface( *eosC1[ iEOS ], helper );
4672         }
4673
4674         int step = 0, stepLimit = 5, nbBad = 0;
4675         while (( ++step <= stepLimit ) || improved )
4676         {
4677           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4678                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4679           int oldBadNb = nbBad;
4680           badEdges.clear();
4681
4682 #ifdef INCREMENTAL_SMOOTH
4683           bool findBest = false; // ( step == stepLimit );
4684           for ( size_t i = 0; i < movedEdges.size(); ++i )
4685           {
4686             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4687             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4688               badEdges.push_back( movedEdges[i] );
4689           }
4690 #else
4691           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4692           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4693           {
4694             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4695             for ( size_t i = 0; i < edges.size(); ++i )
4696             {
4697               edges[i]->Unset( _LayerEdge::SMOOTHED );
4698               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4699                 badEdges.push_back( eos._edges[i] );
4700             }
4701           }
4702 #endif
4703           nbBad = badEdges.size();
4704
4705           if ( nbBad > 0 )
4706             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4707
4708           if ( !badEdges.empty() && step >= stepLimit / 2 )
4709           {
4710             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4711               stepLimit = 9;
4712
4713             // resolve hard smoothing situation around concave VERTEXes
4714             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4715             {
4716               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4717               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4718                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4719                                                          step, badEdges );
4720             }
4721             // look for the best smooth of _LayerEdge's neighboring badEdges
4722             nbBad = 0;
4723             for ( size_t i = 0; i < badEdges.size(); ++i )
4724             {
4725               _LayerEdge* ledge = badEdges[i];
4726               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4727               {
4728                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4729                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4730               }
4731               ledge->Unset( _LayerEdge::SMOOTHED );
4732               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4733             }
4734             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4735           }
4736
4737           if ( nbBad == oldBadNb  &&
4738                nbBad > 0 &&
4739                step < stepLimit ) // smooth w/o chech of validity
4740           {
4741             dumpFunctionEnd();
4742             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4743                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4744             for ( size_t i = 0; i < movedEdges.size(); ++i )
4745             {
4746               movedEdges[i]->SmoothWoCheck();
4747             }
4748             if ( stepLimit < 9 )
4749               stepLimit++;
4750           }
4751
4752           improved = ( nbBad < oldBadNb );
4753
4754           dumpFunctionEnd();
4755
4756           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4757             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4758             {
4759               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4760             }
4761
4762         } // smoothing steps
4763
4764         // project -- to prevent intersections or fix bad simplices
4765         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4766         {
4767           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4768             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4769         }
4770
4771         //if ( !badEdges.empty() )
4772         {
4773           badEdges.clear();
4774           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4775           {
4776             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4777             {
4778               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4779
4780               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4781               edge->CheckNeiborsOnBoundary( & badEdges );
4782               if (( nbBad > 0 ) ||
4783                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4784               {
4785                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4786                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4787                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4788                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4789                   {
4790                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4791                              << " "<< tgtXYZ._node->GetID()
4792                              << " "<< edge->_simplices[j]._nPrev->GetID()
4793                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4794                     badEdges.push_back( edge );
4795                     break;
4796                   }
4797               }
4798             }
4799           }
4800
4801           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4802           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4803
4804           if ( nbBad > 0 )
4805             return false;
4806         }
4807
4808       } // // smooth on FACE's
4809     } // loop on shapes
4810   } // smooth on [ EDGEs, FACEs ]
4811
4812   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4813   eosC1.resize(1);
4814   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4815   {
4816     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4817     if ( eos.ShapeType() == TopAbs_FACE ||
4818          eos._edges.empty() ||
4819          !eos._sWOL.IsNull() )
4820       continue;
4821
4822     badEdges.clear();
4823     for ( size_t i = 0; i < eos._edges.size(); ++i )
4824     {
4825       _LayerEdge*      edge = eos._edges[i];
4826       if ( edge->_nodes.size() < 2 ) continue;
4827       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4828       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4829       //const gp_XYZ& prevXYZ = edge->PrevPos();
4830       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4831         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4832         {
4833           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4834                    << " "<< tgtXYZ._node->GetID()
4835                    << " "<< edge->_simplices[j]._nPrev->GetID()
4836                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4837           badEdges.push_back( edge );
4838           break;
4839         }
4840     }
4841
4842     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4843     eosC1[0] = &eos;
4844     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4845     if ( nbBad > 0 )
4846       return false;
4847   }
4848
4849
4850   // Check if the last segments of _LayerEdge intersects 2D elements;
4851   // checked elements are either temporary faces or faces on surfaces w/o the layers
4852
4853   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4854     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4855                                            data._proxyMesh->GetFaces( data._solid )) );
4856
4857 #ifdef BLOCK_INFLATION
4858   const bool toBlockInfaltion = true;
4859 #else
4860   const bool toBlockInfaltion = false;
4861 #endif
4862   distToIntersection = Precision::Infinite();
4863   double dist;
4864   const SMDS_MeshElement* intFace = 0;
4865   const SMDS_MeshElement* closestFace = 0;
4866   _LayerEdge* le = 0;
4867   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4868   {
4869     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4870     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4871       continue;
4872     for ( size_t i = 0; i < eos._edges.size(); ++i )
4873     {
4874       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4875            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4876         continue;
4877       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4878       {
4879         return false;
4880         // commented due to "Illegal hash-positionPosition" error in NETGEN
4881         // on Debian60 on viscous_layers_01/B2 case
4882         // Collision; try to deflate _LayerEdge's causing it
4883         // badEdges.clear();
4884         // badEdges.push_back( eos._edges[i] );
4885         // eosC1[0] = & eos;
4886         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4887         // if ( nbBad > 0 )
4888         //   return false;
4889
4890         // badEdges.clear();
4891         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4892         // {
4893         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4894         //   {
4895         //     const SMDS_MeshElement* srcFace =
4896         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4897         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4898         //     while ( nIt->more() )
4899         //     {
4900         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4901         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4902         //       if ( n2e != data._n2eMap.end() )
4903         //         badEdges.push_back( n2e->second );
4904         //     }
4905         //     eosC1[0] = eof;
4906         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4907         //     if ( nbBad > 0 )
4908         //       return false;
4909         //   }
4910         // }
4911         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4912         //   return false;
4913         // else
4914         //   continue;
4915       }
4916       if ( !intFace )
4917       {
4918         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4919         debugMsg( msg );
4920         continue;
4921       }
4922
4923       const bool isShorterDist = ( distToIntersection > dist );
4924       if ( toBlockInfaltion || isShorterDist )
4925       {
4926         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4927         // lying on this _ConvexFace
4928         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4929           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4930             continue;
4931
4932         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4933         // ( avoid limiting the thickness on the case of issue 22576)
4934         if ( intFace->getshapeId() == eos._shapeID  )
4935           continue;
4936
4937         // ignore intersection with intFace of an adjacent FACE
4938         if ( dist > 0 )
4939         {
4940           bool toIgnore = false;
4941           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4942           {
4943             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4944             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4945             {
4946               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4947               for ( ; !toIgnore && edge.More(); edge.Next() )
4948                 // is adjacent - has a common EDGE
4949                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4950
4951               if ( toIgnore ) // check angle between normals
4952               {
4953                 gp_XYZ normal;
4954                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4955                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4956               }
4957             }
4958           }
4959           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4960           {
4961             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4962             {
4963               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4964               toIgnore = ( nInd >= 0 );
4965             }
4966           }
4967           if ( toIgnore )
4968             continue;
4969         }
4970
4971         // intersection not ignored
4972
4973         if ( toBlockInfaltion &&
4974              dist < ( eos._edges[i]->_len * theThickToIntersection ))
4975         {
4976           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4977           eos._edges[i]->Block( data );                  // not to inflate
4978
4979           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4980           {
4981             // block _LayerEdge's, on top of which intFace is
4982             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4983             {
4984               const SMDS_MeshElement* srcFace =
4985                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4986               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4987               while ( nIt->more() )
4988               {
4989                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4990                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4991                 if ( n2e != data._n2eMap.end() )
4992                   n2e->second->Block( data );
4993               }
4994             }
4995           }
4996         }
4997
4998         if ( isShorterDist )
4999         {
5000           distToIntersection = dist;
5001           le = eos._edges[i];
5002           closestFace = intFace;
5003         }
5004
5005       } // if ( toBlockInfaltion || isShorterDist )
5006     } // loop on eos._edges
5007   } // loop on data._edgesOnShape
5008
5009   if ( closestFace && le )
5010   {
5011 #ifdef __myDEBUG
5012     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5013     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5014          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5015          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5016          << ") distance = " << distToIntersection<< endl;
5017 #endif
5018   }
5019
5020   return true;
5021 }
5022
5023 //================================================================================
5024 /*!
5025  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5026  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5027  *  \return int - resulting nb of bad _LayerEdge's
5028  */
5029 //================================================================================
5030
5031 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5032                                           SMESH_MesherHelper&       helper,
5033                                           vector< _LayerEdge* >&    badSmooEdges,
5034                                           vector< _EdgesOnShape* >& eosC1,
5035                                           const int                 infStep )
5036 {
5037   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5038
5039   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5040
5041   enum {
5042     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5043     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5044     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5045   };
5046   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5047
5048   double vol;
5049   bool haveInvalidated = true;
5050   while ( haveInvalidated )
5051   {
5052     haveInvalidated = false;
5053     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5054     {
5055       _LayerEdge*   edge = badSmooEdges[i];
5056       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5057       edge->Set( ADDED );
5058       bool invalidated = false;
5059       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5060       {
5061         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5062         edge->Block( data );
5063         edge->Set( INVALIDATED );
5064         edge->Unset( TO_INVALIDATE );
5065         invalidated = true;
5066         haveInvalidated = true;
5067       }
5068
5069       // look for _LayerEdge's of bad _simplices
5070       int nbBad = 0;
5071       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5072       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5073       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5074       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5075       {
5076         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5077             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5078           continue;
5079
5080         bool isBad = true;
5081         _LayerEdge* ee[2] = { 0,0 };
5082         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5083           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5084             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5085
5086         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5087         while ( maxNbSteps > edge->NbSteps() && isBad )
5088         {
5089           --maxNbSteps;
5090           for ( int iE = 0; iE < 2; ++iE )
5091           {
5092             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5093                  ee[ iE ]->NbSteps() > 1 )
5094             {
5095               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5096               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5097               ee[ iE ]->Block( data );
5098               ee[ iE ]->Set( INVALIDATED );
5099               haveInvalidated = true;
5100             }
5101           }
5102           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5103               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5104             isBad = false;
5105         }
5106         nbBad += isBad;
5107         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5108         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5109         ee[0]->Set( ADDED );
5110         ee[1]->Set( ADDED );
5111         if ( isBad )
5112         {
5113           ee[0]->Set( TO_INVALIDATE );
5114           ee[1]->Set( TO_INVALIDATE );
5115         }
5116       }
5117
5118       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5119       {
5120         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5121         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5122         edge->Block( data );
5123         edge->Set( INVALIDATED );
5124         edge->Unset( TO_INVALIDATE );
5125         haveInvalidated = true;
5126       }
5127     } // loop on badSmooEdges
5128   } // while ( haveInvalidated )
5129
5130   // re-smooth on analytical EDGEs
5131   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5132   {
5133     _LayerEdge* edge = badSmooEdges[i];
5134     if ( !edge->Is( INVALIDATED )) continue;
5135
5136     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5137     if ( eos->ShapeType() == TopAbs_VERTEX )
5138     {
5139       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5140       while ( const TopoDS_Shape* e = eIt->next() )
5141         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5142           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5143           {
5144             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5145             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5146             //   F       = TopoDS::Face( eoe->_sWOL );
5147             //   surface = helper.GetSurface( F );
5148             // }
5149             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5150             eoe->_edgeSmoother->_anaCurve.Nullify();
5151           }
5152     }
5153   }
5154
5155
5156   // check result of invalidation
5157
5158   int nbBad = 0;
5159   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5160   {
5161     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5162     {
5163       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5164       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5165       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5166       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5167       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5168         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5169         {
5170           ++nbBad;
5171           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5172                    << " "<< tgtXYZ._node->GetID()
5173                    << " "<< edge->_simplices[j]._nPrev->GetID()
5174                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5175         }
5176     }
5177   }
5178   dumpFunctionEnd();
5179
5180   return nbBad;
5181 }
5182
5183 //================================================================================
5184 /*!
5185  * \brief Create an offset surface
5186  */
5187 //================================================================================
5188
5189 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5190 {
5191   if ( eos._offsetSurf.IsNull() ||
5192        eos._edgeForOffset == 0 ||
5193        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5194     return;
5195
5196   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5197
5198   // find offset
5199   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5200   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5201   double offset = baseSurface->Gap();
5202
5203   eos._offsetSurf.Nullify();
5204
5205   try
5206   {
5207     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5208     if ( !offsetMaker.IsDone() ) return;
5209
5210     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5211     if ( !fExp.More() ) return;
5212
5213     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5214     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5215     if ( surf.IsNull() ) return;
5216
5217     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5218   }
5219   catch ( Standard_Failure )
5220   {
5221   }
5222 }
5223
5224 //================================================================================
5225 /*!
5226  * \brief Put nodes of a curved FACE to its offset surface
5227  */
5228 //================================================================================
5229
5230 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5231                                           int                       infStep,
5232                                           vector< _EdgesOnShape* >& eosC1,
5233                                           int                       smooStep,
5234                                           bool                      moveAll )
5235 {
5236   _EdgesOnShape * eof = & eos;
5237   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5238   {
5239     eof = 0;
5240     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5241     {
5242       if ( eosC1[i]->_offsetSurf.IsNull() ||
5243            eosC1[i]->ShapeType() != TopAbs_FACE ||
5244            eosC1[i]->_edgeForOffset == 0 ||
5245            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5246         continue;
5247       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5248         eof = eosC1[i];
5249     }
5250   }
5251   if ( !eof ||
5252        eof->_offsetSurf.IsNull() ||
5253        eof->ShapeType() != TopAbs_FACE ||
5254        eof->_edgeForOffset == 0 ||
5255        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5256     return;
5257
5258   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5259   for ( size_t i = 0; i < eos._edges.size(); ++i )
5260   {
5261     _LayerEdge* edge = eos._edges[i];
5262     edge->Unset( _LayerEdge::MARKED );
5263     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5264       continue;
5265     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5266         continue;
5267
5268     int nbBlockedAround = 0;
5269     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5270       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5271     if ( nbBlockedAround > 1 )
5272       continue;
5273
5274     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5275     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5276     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5277     edge->_curvature->_uv = uv;
5278     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5279
5280     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5281     gp_XYZ prevP = edge->PrevCheckPos();
5282     bool      ok = true;
5283     if ( !moveAll )
5284       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5285       {
5286         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5287       }
5288     if ( ok )
5289     {
5290       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5291       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5292       edge->_pos.back() = newP;
5293
5294       edge->Set( _LayerEdge::MARKED );
5295     }
5296   }
5297
5298 #ifdef _DEBUG_
5299   // dumpMove() for debug
5300   size_t i = 0;
5301   for ( ; i < eos._edges.size(); ++i )
5302     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5303       break;
5304   if ( i < eos._edges.size() )
5305   {
5306     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5307                  << "_InfStep" << infStep << "_" << smooStep );
5308     for ( ; i < eos._edges.size(); ++i )
5309     {
5310       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5311         dumpMove( eos._edges[i]->_nodes.back() );
5312     }
5313     dumpFunctionEnd();
5314   }
5315 #endif
5316 }
5317
5318 //================================================================================
5319 /*!
5320  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5321  *        _LayerEdge's to be in a consequent order
5322  */
5323 //================================================================================
5324
5325 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5326                                                 _EdgesOnShape&      eos,
5327                                                 SMESH_MesherHelper& helper)
5328 {
5329   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5330
5331   TopLoc_Location loc; double f,l;
5332
5333   Handle(Geom_Line)   line;
5334   Handle(Geom_Circle) circle;
5335   bool isLine, isCirc;
5336   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5337   {
5338     // check if the EDGE is a line
5339     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5340     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5341       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5342
5343     line   = Handle(Geom_Line)::DownCast( curve );
5344     circle = Handle(Geom_Circle)::DownCast( curve );
5345     isLine = (!line.IsNull());
5346     isCirc = (!circle.IsNull());
5347
5348     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5349     {
5350       isLine = SMESH_Algo::IsStraight( E );
5351
5352       if ( isLine )
5353         line = new Geom_Line( gp::OX() ); // only type does matter
5354     }
5355     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5356     {
5357       // TODO
5358     }
5359   }
5360   else //////////////////////////////////////////////////////////////////////// 2D case
5361   {
5362     if ( !eos._isRegularSWOL ) // 23190
5363       return NULL;
5364
5365     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5366
5367     // check if the EDGE is a line
5368     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5369     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5370       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5371
5372     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5373     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5374     isLine = (!line2d.IsNull());
5375     isCirc = (!circle2d.IsNull());
5376
5377     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5378     {
5379       Bnd_B2d bndBox;
5380       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5381       while ( nIt->more() )
5382         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5383       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5384
5385       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5386       for ( int i = 0; i < 2 && !isLine; ++i )
5387         isLine = ( size.Coord( i+1 ) <= lineTol );
5388     }
5389     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5390     {
5391       // TODO
5392     }
5393     if ( isLine )
5394     {
5395       line = new Geom_Line( gp::OX() ); // only type does matter
5396     }
5397     else if ( isCirc )
5398     {
5399       gp_Pnt2d p = circle2d->Location();
5400       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5401       circle = new Geom_Circle( ax, 1.); // only center position does matter
5402     }
5403   }
5404
5405   if ( isLine )
5406     return line;
5407   if ( isCirc )
5408     return circle;
5409
5410   return Handle(Geom_Curve)();
5411 }
5412
5413 //================================================================================
5414 /*!
5415  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5416  */
5417 //================================================================================
5418
5419 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5420                                       Handle(ShapeAnalysis_Surface)& surface,
5421                                       const TopoDS_Face&             F,
5422                                       SMESH_MesherHelper&            helper)
5423 {
5424   if ( !isAnalytic() ) return false;
5425
5426   const size_t iFrom = 0, iTo = _eos._edges.size();
5427
5428   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5429   {
5430     if ( F.IsNull() ) // 3D
5431     {
5432       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5433       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5434       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5435       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5436       gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5437       _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5438       _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5439       bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5440                          vLE0->Is( _LayerEdge::BLOCKED ) ||
5441                          vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5442                          vLE1->Is( _LayerEdge::BLOCKED ));
5443       for ( size_t i = iFrom; i < iTo; ++i )
5444       {
5445         _LayerEdge*       edge = _eos._edges[i];
5446         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5447         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5448
5449         if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5450         {
5451           gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5452           double  shift = ( lineDir * ( newPos - pSrc0 ) -
5453                             lineDir * ( curPos - pSrc0 ));
5454           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5455         }
5456         if ( edge->Is( _LayerEdge::BLOCKED ))
5457         {
5458           SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5459           double curThick = pSrc.SquareDistance( tgtNode );
5460           double newThink = ( pSrc - newPos ).SquareModulus();
5461           if ( newThink > curThick )
5462             continue;
5463         }
5464         edge->_pos.back() = newPos;
5465         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5466         dumpMove( tgtNode );
5467       }
5468     }
5469     else // 2D
5470     {
5471       _LayerEdge* e0 = getLEdgeOnV( 0 );
5472       _LayerEdge* e1 = getLEdgeOnV( 1 );
5473       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5474       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5475       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5476       {
5477         int iPeriodic = helper.GetPeriodicIndex();
5478         if ( iPeriodic == 1 || iPeriodic == 2 )
5479         {
5480           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5481           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5482             std::swap( uv0, uv1 );
5483         }
5484       }
5485       const gp_XY rangeUV = uv1 - uv0;
5486       for ( size_t i = iFrom; i < iTo; ++i )
5487       {
5488         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5489         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5490         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5491
5492         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5493         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5494         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5495         dumpMove( tgtNode );
5496
5497         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5498         pos->SetUParameter( newUV.X() );
5499         pos->SetVParameter( newUV.Y() );
5500       }
5501     }
5502     return true;
5503   }
5504
5505   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5506   {
5507     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5508     gp_Pnt center3D = circle->Location();
5509
5510     if ( F.IsNull() ) // 3D
5511     {
5512       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5513         return true; // closed EDGE - nothing to do
5514
5515       // circle is a real curve of EDGE
5516       gp_Circ circ = circle->Circ();
5517
5518       // new center is shifted along its axis
5519       const gp_Dir& axis = circ.Axis().Direction();
5520       _LayerEdge*     e0 = getLEdgeOnV(0);
5521       _LayerEdge*     e1 = getLEdgeOnV(1);
5522       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5523       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5524       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5525       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5526       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5527
5528       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5529
5530       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5531       gp_Circ newCirc( newAxis, newRadius );
5532       gp_Vec  vecC1  ( newCenter, p1 );
5533
5534       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5535       if ( uLast < 0 )
5536         uLast += 2 * M_PI;
5537       
5538       for ( size_t i = iFrom; i < iTo; ++i )
5539       {
5540         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5541         double u = uLast * _leParams[i];
5542         gp_Pnt p = ElCLib::Value( u, newCirc );
5543         _eos._edges[i]->_pos.back() = p.XYZ();
5544
5545         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5546         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5547         dumpMove( tgtNode );
5548       }
5549       return true;
5550     }
5551     else // 2D
5552     {
5553       const gp_XY center( center3D.X(), center3D.Y() );
5554
5555       _LayerEdge* e0 = getLEdgeOnV(0);
5556       _LayerEdge* eM = _eos._edges[ 0 ];
5557       _LayerEdge* e1 = getLEdgeOnV(1);
5558       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5559       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5560       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5561       gp_Vec2d vec0( center, uv0 );
5562       gp_Vec2d vecM( center, uvM );
5563       gp_Vec2d vec1( center, uv1 );
5564       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5565       double uMidl = vec0.Angle( vecM );
5566       if ( uLast * uMidl <= 0. )
5567         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5568       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5569
5570       gp_Ax2d   axis( center, vec0 );
5571       gp_Circ2d circ( axis, radius );
5572       for ( size_t i = iFrom; i < iTo; ++i )
5573       {
5574         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5575         double    newU = uLast * _leParams[i];
5576         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5577         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5578
5579         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5580         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5581         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5582         dumpMove( tgtNode );
5583
5584         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5585         pos->SetUParameter( newUV.X() );
5586         pos->SetVParameter( newUV.Y() );
5587       }
5588     }
5589     return true;
5590   }
5591
5592   return false;
5593 }
5594
5595 //================================================================================
5596 /*!
5597  * \brief smooth _LayerEdge's on a an EDGE
5598  */
5599 //================================================================================
5600
5601 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5602                                      Handle(ShapeAnalysis_Surface)& surface,
5603                                      const TopoDS_Face&             F,
5604                                      SMESH_MesherHelper&            helper)
5605 {
5606   if ( _offPoints.empty() )
5607     return false;
5608
5609   // move _offPoints along normals of _LayerEdge's
5610
5611   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5612   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5613     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5614   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5615     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5616   _leOnV[0]._len = e[0]->_len;
5617   _leOnV[1]._len = e[1]->_len;
5618   for ( size_t i = 0; i < _offPoints.size(); i++ )
5619   {
5620     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5621     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5622     const double w0 = _offPoints[i]._2edges._wgt[0];
5623     const double w1 = _offPoints[i]._2edges._wgt[1];
5624     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5625     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5626     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5627     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5628          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5629       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5630
5631     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5632     _offPoints[i]._len  = avgLen;
5633   }
5634
5635   double fTol = 0;
5636   if ( !surface.IsNull() ) // project _offPoints to the FACE
5637   {
5638     fTol = 100 * BRep_Tool::Tolerance( F );
5639     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5640
5641     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5642     //if ( surface->Gap() < 0.5 * segLen )
5643       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5644
5645     for ( size_t i = 1; i < _offPoints.size(); ++i )
5646     {
5647       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5648       //if ( surface->Gap() < 0.5 * segLen )
5649         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5650     }
5651   }
5652
5653   // project tgt nodes of extreme _LayerEdge's to the offset segments
5654
5655   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5656   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5657
5658   gp_Pnt pExtreme[2], pProj[2];
5659   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5660   {
5661     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5662     int  i = _iSeg[ is2nd ];
5663     int di = is2nd ? -1 : +1;
5664     bool projected = false;
5665     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5666     int nbWorse = 0;
5667     do {
5668       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5669       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5670       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5671       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5672       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5673       if ( dist < distMin || projected )
5674       {
5675         _iSeg[ is2nd ] = i;
5676         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5677         distMin = dist;
5678       }
5679       else if ( dist > distPrev )
5680       {
5681         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5682           break;
5683       }
5684       distPrev = dist;
5685       i += di;
5686     }
5687     while ( !projected &&
5688             i >= 0 && i+1 < (int)_offPoints.size() );
5689
5690     if ( !projected )
5691     {
5692       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5693       {
5694         _iSeg[0] = 0;
5695         _iSeg[1] = _offPoints.size()-2;
5696         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5697         return false;
5698       }
5699     }
5700   }
5701   if ( _iSeg[0] > _iSeg[1] )
5702   {
5703     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5704     return false;
5705   }
5706
5707   // adjust length of extreme LE (test viscous_layers_01/B7)
5708   gp_Vec vDiv0( pExtreme[0], pProj[0] );
5709   gp_Vec vDiv1( pExtreme[1], pProj[1] );
5710   double d0 = vDiv0.Magnitude();
5711   double d1 = vDiv1.Magnitude();
5712   if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5713   else                                   e[0]->_len -= d0;
5714   if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5715   else                                   e[1]->_len -= d1;
5716
5717   // compute normalized length of the offset segments located between the projections
5718
5719   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5720   vector< double > len( nbSeg + 1 );
5721   len[ iSeg++ ] = 0;
5722   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5723   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5724   {
5725     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5726   }
5727   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5728
5729   // d0 *= e[0]->_lenFactor;
5730   // d1 *= e[1]->_lenFactor;
5731   double fullLen = len.back() - d0 - d1;
5732   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5733     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5734
5735   // temporary replace extreme _offPoints by pExtreme
5736   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5737                    _offPoints[ _iSeg[1]+1 ]._xyz };
5738   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5739   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5740
5741   // distribute tgt nodes of _LayerEdge's between the projections
5742
5743   iSeg = 0;
5744   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5745   {
5746     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5747     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5748       iSeg++;
5749     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5750     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5751                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5752
5753     if ( surface.IsNull() )
5754     {
5755       _eos._edges[i]->_pos.back() = p;
5756     }
5757     else // project a new node position to a FACE
5758     {
5759       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5760       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5761
5762       p = surface->Value( uv2 ).XYZ();
5763       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5764     }
5765     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5766     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5767     dumpMove( tgtNode );
5768   }
5769
5770   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5771   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5772
5773   return true;
5774 }
5775
5776 //================================================================================
5777 /*!
5778  * \brief Prepare for smoothing
5779  */
5780 //================================================================================
5781
5782 void _Smoother1D::prepare(_SolidData& data)
5783 {
5784   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5785   _curveLen = SMESH_Algo::EdgeLength( E );
5786
5787   // sort _LayerEdge's by position on the EDGE
5788   data.SortOnEdge( E, _eos._edges );
5789
5790   // compute normalized param of _eos._edges on EDGE
5791   _leParams.resize( _eos._edges.size() + 1 );
5792   {
5793     double curLen;
5794     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5795     _leParams[0] = 0;
5796     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5797     {
5798       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5799       curLen         = p.Distance( pPrev );
5800       _leParams[i+1] = _leParams[i] + curLen;
5801       pPrev          = p;
5802     }
5803     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5804     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5805       _leParams[i] = _leParams[i+1] / fullLen;
5806   }
5807
5808   if ( isAnalytic() )
5809     return;
5810
5811   // divide E to have offset segments with low deflection
5812   BRepAdaptor_Curve c3dAdaptor( E );
5813   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5814   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5815   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5816   if ( discret.NbPoints() <= 2 )
5817   {
5818     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5819     return;
5820   }
5821
5822   const double u0 = c3dAdaptor.FirstParameter();
5823   gp_Pnt p; gp_Vec tangent;
5824   _offPoints.resize( discret.NbPoints() );
5825   for ( size_t i = 0; i < _offPoints.size(); i++ )
5826   {
5827     double u = discret.Parameter( i+1 );
5828     c3dAdaptor.D1( u, p, tangent );
5829     _offPoints[i]._xyz     = p.XYZ();
5830     _offPoints[i]._edgeDir = tangent.XYZ();
5831     _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5832   }
5833
5834   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5835
5836   // set _2edges
5837   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5838   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5839   _2NearEdges tmp2edges;
5840   tmp2edges._edges[1] = _eos._edges[0];
5841   _leOnV[0]._2neibors = & tmp2edges;
5842   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5843   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5844   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5845   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5846   {
5847     // find _LayerEdge's located before and after an offset point
5848     // (_eos._edges[ iLE ] is next after ePrev)
5849     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5850       ePrev = _eos._edges[ iLE++ ];
5851     eNext = ePrev->_2neibors->_edges[1];
5852
5853     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5854     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5855     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5856     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5857   }
5858
5859   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5860   for ( size_t i = 0; i < _offPoints.size(); i++ )
5861     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5862       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5863     else break;
5864   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5865     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5866       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5867     else break;
5868
5869   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5870
5871   int iLBO = _offPoints.size() - 2; // last but one
5872
5873   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5874   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5875
5876   _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5877   _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5878   _leOnV[ 0 ]._len = 0;
5879   _leOnV[ 1 ]._len = 0;
5880   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5881   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5882
5883   _iSeg[0] = 0;
5884   _iSeg[1] = _offPoints.size()-2;
5885
5886   // initialize OffPnt::_len
5887   for ( size_t i = 0; i < _offPoints.size(); ++i )
5888     _offPoints[i]._len = 0;
5889
5890   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5891   {
5892     _leOnV[0]._len = leOnV[0]->_len;
5893     _leOnV[1]._len = leOnV[1]->_len;
5894     for ( size_t i = 0; i < _offPoints.size(); i++ )
5895     {
5896       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5897       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5898       const double w0 = _offPoints[i]._2edges._wgt[0];
5899       const double w1 = _offPoints[i]._2edges._wgt[1];
5900       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5901       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5902                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5903       _offPoints[i]._xyz = avgXYZ;
5904       _offPoints[i]._len = avgLen;
5905     }
5906   }
5907 }
5908
5909 //================================================================================
5910 /*!
5911  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5912  */
5913 //================================================================================
5914
5915 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5916                                      const gp_XYZ&  edgeDir)
5917 {
5918   gp_XYZ cross = normal ^ edgeDir;
5919   gp_XYZ  norm = edgeDir ^ cross;
5920   double  size = norm.Modulus();
5921
5922   return norm / size;
5923 }
5924
5925 //================================================================================
5926 /*!
5927  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5928  */
5929 //================================================================================
5930
5931 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5932                              vector< _LayerEdge* >& edges)
5933 {
5934   map< double, _LayerEdge* > u2edge;
5935   for ( size_t i = 0; i < edges.size(); ++i )
5936     u2edge.insert( u2edge.end(),
5937                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5938
5939   ASSERT( u2edge.size() == edges.size() );
5940   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5941   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5942     edges[i] = u2e->second;
5943
5944   Sort2NeiborsOnEdge( edges );
5945 }
5946
5947 //================================================================================
5948 /*!
5949  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5950  */
5951 //================================================================================
5952
5953 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5954 {
5955   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5956
5957   for ( size_t i = 0; i < edges.size()-1; ++i )
5958     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5959       edges[i]->_2neibors->reverse();
5960
5961   const size_t iLast = edges.size() - 1;
5962   if ( edges.size() > 1 &&
5963        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5964     edges[iLast]->_2neibors->reverse();
5965 }
5966
5967 //================================================================================
5968 /*!
5969  * \brief Return _EdgesOnShape* corresponding to the shape
5970  */
5971 //================================================================================
5972
5973 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5974 {
5975   if ( shapeID < (int)_edgesOnShape.size() &&
5976        _edgesOnShape[ shapeID ]._shapeID == shapeID )
5977     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5978
5979   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5980     if ( _edgesOnShape[i]._shapeID == shapeID )
5981       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5982
5983   return 0;
5984 }
5985
5986 //================================================================================
5987 /*!
5988  * \brief Return _EdgesOnShape* corresponding to the shape
5989  */
5990 //================================================================================
5991
5992 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5993 {
5994   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5995   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5996 }
5997
5998 //================================================================================
5999 /*!
6000  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6001  */
6002 //================================================================================
6003
6004 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6005 {
6006   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6007
6008   set< TGeomID > vertices;
6009   TopoDS_Face F;
6010   if ( eos->ShapeType() == TopAbs_FACE )
6011   {
6012     // check FACE concavity and get concave VERTEXes
6013     F = TopoDS::Face( eos->_shape );
6014     if ( isConcave( F, helper, &vertices ))
6015       _concaveFaces.insert( eos->_shapeID );
6016
6017     // set eos._eosConcaVer
6018     eos->_eosConcaVer.clear();
6019     eos->_eosConcaVer.reserve( vertices.size() );
6020     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6021     {
6022       _EdgesOnShape* eov = GetShapeEdges( *v );
6023       if ( eov && eov->_edges.size() == 1 )
6024       {
6025         eos->_eosConcaVer.push_back( eov );
6026         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6027           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6028       }
6029     }
6030
6031     // SetSmooLen() to _LayerEdge's on FACE
6032     for ( size_t i = 0; i < eos->_edges.size(); ++i )
6033     {
6034       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6035     }
6036     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6037     while ( smIt->more() ) // loop on sub-shapes of the FACE
6038     {
6039       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6040       if ( !eoe ) continue;
6041
6042       vector<_LayerEdge*>& eE = eoe->_edges;
6043       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6044       {
6045         if ( eE[iE]->_cosin <= theMinSmoothCosin )
6046           continue;
6047
6048         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6049         while ( segIt->more() )
6050         {
6051           const SMDS_MeshElement* seg = segIt->next();
6052           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6053             continue;
6054           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6055             continue; // not to check a seg twice
6056           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6057           {
6058             _LayerEdge* eN = eE[iE]->_neibors[iN];
6059             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6060               continue;
6061             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6062             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6063             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6064             eN->Set( _LayerEdge::NEAR_BOUNDARY );
6065           }
6066         }
6067       }
6068     }
6069   } // if ( eos->ShapeType() == TopAbs_FACE )
6070
6071   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6072   {
6073     eos->_edges[i]->_smooFunction = 0;
6074     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6075   }
6076   bool isCurved = false;
6077   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6078   {
6079     _LayerEdge* edge = eos->_edges[i];
6080
6081     // get simplices sorted
6082     _Simplex::SortSimplices( edge->_simplices );
6083
6084     // smoothing function
6085     edge->ChooseSmooFunction( vertices, _n2eMap );
6086
6087     // set _curvature
6088     double avgNormProj = 0, avgLen = 0;
6089     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6090     {
6091       _Simplex& s = edge->_simplices[iS];
6092
6093       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6094       avgNormProj += edge->_normal * vec;
6095       avgLen      += vec.Modulus();
6096       if ( substituteSrcNodes )
6097       {
6098         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6099         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6100       }
6101     }
6102     avgNormProj /= edge->_simplices.size();
6103     avgLen      /= edge->_simplices.size();
6104     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6105     {
6106       isCurved = true;
6107       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6108       if ( !fPos )
6109         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6110           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6111       if ( fPos )
6112         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6113     }
6114   }
6115
6116   // prepare for putOnOffsetSurface()
6117   if (( eos->ShapeType() == TopAbs_FACE ) &&
6118       ( isCurved || !eos->_eosConcaVer.empty() ))
6119   {
6120     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6121     eos->_edgeForOffset = 0;
6122
6123     double maxCosin = -1;
6124     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6125     {
6126       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6127       if ( !eoe || eoe->_edges.empty() ) continue;
6128
6129       vector<_LayerEdge*>& eE = eoe->_edges;
6130       _LayerEdge* e = eE[ eE.size() / 2 ];
6131       if ( e->_cosin > maxCosin )
6132       {
6133         eos->_edgeForOffset = e;
6134         maxCosin = e->_cosin;
6135       }
6136     }
6137   }
6138 }
6139
6140 //================================================================================
6141 /*!
6142  * \brief Add faces for smoothing
6143  */
6144 //================================================================================
6145
6146 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6147                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6148 {
6149   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6150   for ( ; eos != eosToSmooth.end(); ++eos )
6151   {
6152     if ( !*eos || (*eos)->_toSmooth ) continue;
6153
6154     (*eos)->_toSmooth = true;
6155
6156     if ( (*eos)->ShapeType() == TopAbs_FACE )
6157     {
6158       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6159       (*eos)->_toSmooth = true;
6160     }
6161   }
6162
6163   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6164   if ( edgesNoAnaSmooth )
6165     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6166     {
6167       if ( (*eos)->_edgeSmoother )
6168         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6169     }
6170 }
6171
6172 //================================================================================
6173 /*!
6174  * \brief Limit _LayerEdge::_maxLen according to local curvature
6175  */
6176 //================================================================================
6177
6178 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6179 {
6180   // find intersection of neighbor _LayerEdge's to limit _maxLen
6181   // according to local curvature (IPAL52648)
6182
6183   // This method must be called after findCollisionEdges() where _LayerEdge's
6184   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6185
6186   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6187   {
6188     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6189     if ( eosI._edges.empty() ) continue;
6190     if ( !eosI._hyp.ToSmooth() )
6191     {
6192       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6193       {
6194         _LayerEdge* eI = eosI._edges[i];
6195         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6196         {
6197           _LayerEdge* eN = eI->_neibors[iN];
6198           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6199           {
6200             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6201             limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6202           }
6203         }
6204       }
6205     }
6206     else if ( eosI.ShapeType() == TopAbs_EDGE )
6207     {
6208       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6209       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6210
6211       _LayerEdge* e0 = eosI._edges[0];
6212       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6213       {
6214         _LayerEdge* eI = eosI._edges[i];
6215         limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6216         e0 = eI;
6217       }
6218     }
6219   }
6220 }
6221
6222 //================================================================================
6223 /*!
6224  * \brief Limit _LayerEdge::_maxLen according to local curvature
6225  */
6226 //================================================================================
6227
6228 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*         e1,
6229                                               _LayerEdge*         e2,
6230                                               _EdgesOnShape&      eos1,
6231                                               _EdgesOnShape&      eos2,
6232                                               SMESH_MesherHelper& helper )
6233 {
6234   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6235   double norSize = plnNorm.SquareModulus();
6236   if ( norSize < std::numeric_limits<double>::min() )
6237     return; // parallel normals
6238
6239   // find closest points of skew _LayerEdge's
6240   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6241   gp_XYZ dir12 = src2 - src1;
6242   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6243   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6244   double  dot1 = perp2 * e1->_normal;
6245   double  dot2 = perp1 * e2->_normal;
6246   double    u1 =   ( perp2 * dir12 ) / dot1;
6247   double    u2 = - ( perp1 * dir12 ) / dot2;
6248   if ( u1 > 0 && u2 > 0 )
6249   {
6250     double ovl = ( u1 * e1->_normal * dir12 -
6251                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6252     if ( ovl > theSmoothThickToElemSizeRatio )
6253     {    
6254       e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6255       e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6256     }
6257   }
6258 }
6259
6260 //================================================================================
6261 /*!
6262  * \brief Fill data._collisionEdges
6263  */
6264 //================================================================================
6265
6266 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6267 {
6268   data._collisionEdges.clear();
6269
6270   // set the full thickness of the layers to LEs
6271   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6272   {
6273     _EdgesOnShape& eos = data._edgesOnShape[iS];
6274     if ( eos._edges.empty() ) continue;
6275     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6276
6277     for ( size_t i = 0; i < eos._edges.size(); ++i )
6278     {
6279       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6280       double maxLen = eos._edges[i]->_maxLen;
6281       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6282       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6283       eos._edges[i]->_maxLen = maxLen;
6284     }
6285   }
6286
6287   // make temporary quadrangles got by extrusion of
6288   // mesh edges along _LayerEdge._normal's
6289
6290   vector< const SMDS_MeshElement* > tmpFaces;
6291
6292   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6293   {
6294     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6295     if ( eos.ShapeType() != TopAbs_EDGE )
6296       continue;
6297     if ( eos._edges.empty() )
6298     {
6299       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6300       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6301       while ( smIt->more() )
6302         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6303           if ( eov->_edges.size() == 1 )
6304             edge[ bool( edge[0]) ] = eov->_edges[0];
6305
6306       if ( edge[1] )
6307       {
6308         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6309         tmpFaces.push_back( f );
6310       }
6311     }
6312     for ( size_t i = 0; i < eos._edges.size(); ++i )
6313     {
6314       _LayerEdge* edge = eos._edges[i];
6315       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6316       {
6317         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6318         if ( src2->GetPosition()->GetDim() > 0 &&
6319              src2->GetID() < edge->_nodes[0]->GetID() )
6320           continue; // avoid using same segment twice
6321
6322         // a _LayerEdge containg tgt2
6323         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6324
6325         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6326         tmpFaces.push_back( f );
6327       }
6328     }
6329   }
6330
6331   // Find _LayerEdge's intersecting tmpFaces.
6332
6333   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6334                                                             tmpFaces.end()));
6335   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6336     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6337
6338   double dist1, dist2, segLen, eps = 0.5;
6339   _CollisionEdges collEdges;
6340   vector< const SMDS_MeshElement* > suspectFaces;
6341   const double angle45 = Cos( 45. * M_PI / 180. );
6342
6343   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6344   {
6345     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6346     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6347       continue;
6348     // find sub-shapes whose VL can influence VL on eos
6349     set< TGeomID > neighborShapes;
6350     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6351     while ( const TopoDS_Shape* face = fIt->next() )
6352     {
6353       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6354       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6355       {
6356         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6357         while ( subIt->more() )
6358           neighborShapes.insert( subIt->next()->GetId() );
6359       }
6360     }
6361     if ( eos.ShapeType() == TopAbs_VERTEX )
6362     {
6363       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6364       while ( const TopoDS_Shape* edge = eIt->next() )
6365         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6366     }
6367     // find intersecting _LayerEdge's
6368     for ( size_t i = 0; i < eos._edges.size(); ++i )
6369     {
6370       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6371       _LayerEdge*   edge = eos._edges[i];
6372       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6373       segLen *= 1.2;
6374
6375       gp_Vec eSegDir0, eSegDir1;
6376       if ( edge->IsOnEdge() )
6377       {
6378         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6379         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6380         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6381       }
6382       suspectFaces.clear();
6383       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6384                                      SMDSAbs_Face, suspectFaces );
6385       collEdges._intEdges.clear();
6386       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6387       {
6388         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6389         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6390         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6391         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6392         if ( edge->IsOnEdge() ) {
6393           if ( edge->_2neibors->include( f->_le1 ) ||
6394                edge->_2neibors->include( f->_le2 )) continue;
6395         }
6396         else {
6397           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6398               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6399         }
6400         dist1 = dist2 = Precision::Infinite();
6401         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6402           dist1 = Precision::Infinite();
6403         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6404           dist2 = Precision::Infinite();
6405         if (( dist1 > segLen ) && ( dist2 > segLen ))
6406           continue;
6407
6408         if ( edge->IsOnEdge() )
6409         {
6410           // skip perpendicular EDGEs
6411           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6412           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6413                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6414                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6415                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6416           if ( !isParallel )
6417             continue;
6418         }
6419
6420         // either limit inflation of edges or remember them for updating _normal
6421         // double dot = edge->_normal * f->GetDir();
6422         // if ( dot > 0.1 )
6423         {
6424           collEdges._intEdges.push_back( f->_le1 );
6425           collEdges._intEdges.push_back( f->_le2 );
6426         }
6427         // else
6428         // {
6429         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6430         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6431         // }
6432       }
6433
6434       if ( !collEdges._intEdges.empty() )
6435       {
6436         collEdges._edge = edge;
6437         data._collisionEdges.push_back( collEdges );
6438       }
6439     }
6440   }
6441
6442   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6443     delete tmpFaces[i];
6444
6445   // restore the zero thickness
6446   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6447   {
6448     _EdgesOnShape& eos = data._edgesOnShape[iS];
6449     if ( eos._edges.empty() ) continue;
6450     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6451
6452     for ( size_t i = 0; i < eos._edges.size(); ++i )
6453     {
6454       eos._edges[i]->InvalidateStep( 1, eos );
6455       eos._edges[i]->_len = 0;
6456     }
6457   }
6458 }
6459
6460 //================================================================================
6461 /*!
6462  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6463  * _LayerEdge's on neighbor EDGE's
6464  */
6465 //================================================================================
6466
6467 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6468                                      SMESH_MesherHelper& helper,
6469                                      int                 stepNb,
6470                                      double              stepSize)
6471 {
6472   updateNormalsOfC1Vertices( data );
6473
6474   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6475     return false;
6476
6477   // map to store new _normal and _cosin for each intersected edge
6478   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6479   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6480   _LayerEdge zeroEdge;
6481   zeroEdge._normal.SetCoord( 0,0,0 );
6482   zeroEdge._maxLen = Precision::Infinite();
6483   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6484
6485   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6486
6487   double segLen, dist1, dist2, dist;
6488   vector< pair< _LayerEdge*, double > > intEdgesDist;
6489   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6490
6491   for ( int iter = 0; iter < 5; ++iter )
6492   {
6493     edge2newEdge.clear();
6494
6495     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6496     {
6497       _CollisionEdges& ce = data._collisionEdges[iE];
6498       _LayerEdge*   edge1 = ce._edge;
6499       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6500       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6501       if ( !eos1 ) continue;
6502
6503       // detect intersections
6504       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6505       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6506       double     eps = 0.5;
6507       intEdgesDist.clear();
6508       double minIntDist = Precision::Infinite();
6509       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6510       {
6511         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6512              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6513              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6514           continue;
6515         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6516         double fact = ( 1.1 + dot * dot );
6517         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6518         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6519         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6520         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6521         dist1 = dist2 = Precision::Infinite();
6522         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
6523              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6524           continue;
6525         dist = dist1;
6526         if ( dist > testLen || dist <= 0 )
6527         {
6528           dist = dist2;
6529           if ( dist > testLen || dist <= 0 )
6530             continue;
6531         }
6532         // choose a closest edge
6533         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6534         double d1 = intP.SquareDistance( pSrc0 );
6535         double d2 = intP.SquareDistance( pSrc1 );
6536         int iClose = i + ( d2 < d1 );
6537         _LayerEdge* edge2 = ce._intEdges[iClose];
6538         edge2->Unset( _LayerEdge::MARKED );
6539
6540         // choose a closest edge among neighbors
6541         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6542         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6543         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6544         {
6545           _LayerEdge * edgeJ = intEdgesDist[j].first;
6546           if ( edge2->IsNeiborOnEdge( edgeJ ))
6547           {
6548             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6549             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6550           }
6551         }
6552         intEdgesDist.push_back( make_pair( edge2, dist ));
6553         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6554         // {
6555         //   iClose = i + !( d2 < d1 );
6556         //   intEdges.push_back( ce._intEdges[iClose] );
6557         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6558         // }
6559         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6560       }
6561
6562       //ce._edge = 0;
6563
6564       // compute new _normals
6565       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6566       {
6567         _LayerEdge* edge2    = intEdgesDist[i].first;
6568         double       distWgt = edge1->_len / intEdgesDist[i].second;
6569         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6570         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
6571         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6572         edge2->Set( _LayerEdge::MARKED );
6573
6574         // get a new normal
6575         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6576
6577         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6578         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6579         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6580         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6581         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6582         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6583         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6584         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6585         newNormal.Normalize();
6586
6587         // get new cosin
6588         double newCos;
6589         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6590         if ( cos1 < theMinSmoothCosin )
6591         {
6592           newCos = cos2 * sgn1;
6593         }
6594         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6595         {
6596           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6597         }
6598         else
6599         {
6600           newCos = edge1->_cosin;
6601         }
6602
6603         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6604         e2neIt->second._normal += distWgt * newNormal;
6605         e2neIt->second._cosin   = newCos;
6606         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6607         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6608           e2neIt->second._normal += dir2;
6609         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6610         e2neIt->second._normal += distWgt * newNormal;
6611         e2neIt->second._cosin   = edge2->_cosin;
6612         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6613           e2neIt->second._normal += dir1;
6614       }
6615     }
6616
6617     if ( edge2newEdge.empty() )
6618       break; //return true;
6619
6620     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6621
6622     // Update data of edges depending on a new _normal
6623
6624     data.UnmarkEdges();
6625     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6626     {
6627       _LayerEdge*    edge = e2neIt->first;
6628       if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6629       _LayerEdge& newEdge = e2neIt->second;
6630       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6631
6632       // Check if a new _normal is OK:
6633       newEdge._normal.Normalize();
6634       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6635       {
6636         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6637         {
6638           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6639           edge->_maxLen = newEdge._maxLen;
6640           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6641         }
6642         continue; // the new _normal is bad
6643       }
6644       // the new _normal is OK
6645
6646       // find shapes that need smoothing due to change of _normal
6647       if ( edge->_cosin   < theMinSmoothCosin &&
6648            newEdge._cosin > theMinSmoothCosin )
6649       {
6650         if ( eos->_sWOL.IsNull() )
6651         {
6652           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6653           while ( fIt->more() )
6654             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6655         }
6656         else // edge inflates along a FACE
6657         {
6658           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6659           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6660           while ( const TopoDS_Shape* E = eIt->next() )
6661           {
6662             if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6663               continue;
6664             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6665             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6666             if ( angle < M_PI / 2 )
6667               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6668           }
6669         }
6670       }
6671
6672       double len = edge->_len;
6673       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6674       edge->SetNormal( newEdge._normal );
6675       edge->SetCosin( newEdge._cosin );
6676       edge->SetNewLength( len, *eos, helper );
6677       edge->Set( _LayerEdge::MARKED );
6678       edge->Set( _LayerEdge::NORMAL_UPDATED );
6679       edgesNoAnaSmooth.insert( eos );
6680     }
6681
6682     // Update normals and other dependent data of not intersecting _LayerEdge's
6683     // neighboring the intersecting ones
6684
6685     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6686     {
6687       _LayerEdge*   edge1 = e2neIt->first;
6688       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6689       if ( !edge1->Is( _LayerEdge::MARKED ))
6690         continue;
6691
6692       if ( edge1->IsOnEdge() )
6693       {
6694         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6695         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6696         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6697       }
6698
6699       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6700         continue;
6701       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6702       {
6703         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6704         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6705           continue; // j-th neighbor is also intersected
6706         _LayerEdge* prevEdge = edge1;
6707         const int nbSteps = 10;
6708         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6709         {
6710           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6711                neighbor->Is( _LayerEdge::MARKED ))
6712             break;
6713           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6714           if ( !eos ) continue;
6715           _LayerEdge* nextEdge = neighbor;
6716           if ( neighbor->_2neibors )
6717           {
6718             int iNext = 0;
6719             nextEdge = neighbor->_2neibors->_edges[iNext];
6720             if ( nextEdge == prevEdge )
6721               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6722           }
6723           double r = double(step-1)/nbSteps/(iter+1);
6724           if ( !nextEdge->_2neibors )
6725             r = Min( r, 0.5 );
6726
6727           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6728           newNorm.Normalize();
6729           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6730             break;
6731
6732           double len = neighbor->_len;
6733           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6734           neighbor->SetNormal( newNorm );
6735           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6736           if ( neighbor->_2neibors )
6737             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6738           neighbor->SetNewLength( len, *eos, helper );
6739           neighbor->Set( _LayerEdge::MARKED );
6740           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6741           edgesNoAnaSmooth.insert( eos );
6742
6743           if ( !neighbor->_2neibors )
6744             break; // neighbor is on VERTEX
6745
6746           // goto the next neighbor
6747           prevEdge = neighbor;
6748           neighbor = nextEdge;
6749         }
6750       }
6751     }
6752     dumpFunctionEnd();
6753   } // iterations
6754
6755   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6756
6757   return true;
6758 }
6759
6760 //================================================================================
6761 /*!
6762  * \brief Check if a new normal is OK
6763  */
6764 //================================================================================
6765
6766 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6767                                      _LayerEdge&   edge,
6768                                      const gp_XYZ& newNormal)
6769 {
6770   // check a min angle between the newNormal and surrounding faces
6771   vector<_Simplex> simplices;
6772   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6773   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6774   double newMinDot = 1, curMinDot = 1;
6775   for ( size_t i = 0; i < simplices.size(); ++i )
6776   {
6777     n1.Set( simplices[i]._nPrev );
6778     n2.Set( simplices[i]._nNext );
6779     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6780     double normLen2 = normFace.SquareModulus();
6781     if ( normLen2 < std::numeric_limits<double>::min() )
6782       continue;
6783     normFace /= Sqrt( normLen2 );
6784     newMinDot = Min( newNormal    * normFace, newMinDot );
6785     curMinDot = Min( edge._normal * normFace, curMinDot );
6786   }
6787   bool ok = true;
6788   if ( newMinDot < 0.5 )
6789   {
6790     ok = ( newMinDot >= curMinDot * 0.9 );
6791     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6792     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6793     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6794   }
6795
6796   return ok;
6797 }
6798
6799 //================================================================================
6800 /*!
6801  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6802  */
6803 //================================================================================
6804
6805 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6806                                                SMESH_MesherHelper& helper,
6807                                                const int           nbSteps,
6808                                                const double        stepSize )
6809 {
6810   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6811     return true; // no shapes needing smoothing
6812
6813   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6814   {
6815     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6816     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6817          !eos._hyp.ToSmooth() ||
6818          eos.ShapeType() != TopAbs_FACE ||
6819          eos._edges.empty() )
6820       continue;
6821
6822     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6823     if ( !toSmooth ) continue;
6824
6825     for ( size_t i = 0; i < eos._edges.size(); ++i )
6826     {
6827       _LayerEdge* edge = eos._edges[i];
6828       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6829         continue;
6830       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6831         continue;
6832
6833       const gp_XYZ& pPrev = edge->PrevPos();
6834       const gp_XYZ& pLast = edge->_pos.back();
6835       gp_XYZ      stepVec = pLast - pPrev;
6836       double realStepSize = stepVec.Modulus();
6837       if ( realStepSize < numeric_limits<double>::min() )
6838         continue;
6839
6840       edge->_lenFactor = realStepSize / stepSize;
6841       edge->_normal    = stepVec / realStepSize;
6842       edge->Set( _LayerEdge::NORMAL_UPDATED );
6843     }
6844   }
6845
6846   return true;
6847 }
6848
6849 //================================================================================
6850 /*!
6851  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6852  */
6853 //================================================================================
6854
6855 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6856 {
6857   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6858   {
6859     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6860     if ( eov._eosC1.empty() ||
6861          eov.ShapeType() != TopAbs_VERTEX ||
6862          eov._edges.empty() )
6863       continue;
6864
6865     gp_XYZ newNorm   = eov._edges[0]->_normal;
6866     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6867     bool normChanged = false;
6868
6869     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6870     {
6871       _EdgesOnShape*   eoe = eov._eosC1[i];
6872       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6873       const double    eLen = SMESH_Algo::EdgeLength( e );
6874       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6875       if ( oppV.IsSame( eov._shape ))
6876         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6877       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6878       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6879       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6880
6881       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6882       if ( curThickOpp + curThick < eLen )
6883         continue;
6884
6885       double wgt = 2. * curThick / eLen;
6886       newNorm += wgt * eovOpp->_edges[0]->_normal;
6887       normChanged = true;
6888     }
6889     if ( normChanged )
6890     {
6891       eov._edges[0]->SetNormal( newNorm.Normalized() );
6892       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6893     }
6894   }
6895 }
6896
6897 //================================================================================
6898 /*!
6899  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6900  */
6901 //================================================================================
6902
6903 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6904                                                   SMESH_MesherHelper& helper,
6905                                                   int                 stepNb )
6906 {
6907   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6908   bool isOK;
6909
6910   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6911   for ( ; id2face != data._convexFaces.end(); ++id2face )
6912   {
6913     _ConvexFace & convFace = (*id2face).second;
6914     if ( convFace._normalsFixed )
6915       continue; // already fixed
6916     if ( convFace.CheckPrisms() )
6917       continue; // nothing to fix
6918
6919     convFace._normalsFixed = true;
6920
6921     BRepAdaptor_Surface surface ( convFace._face, false );
6922     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6923
6924     // check if the convex FACE is of spherical shape
6925
6926     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6927     Bnd_B3d nodesBox;
6928     gp_Pnt  center;
6929
6930     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6931     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6932     {
6933       _EdgesOnShape& eos = *(id2eos->second);
6934       if ( eos.ShapeType() == TopAbs_VERTEX )
6935       {
6936         _LayerEdge* ledge = eos._edges[ 0 ];
6937         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6938           centersBox.Add( center );
6939       }
6940       for ( size_t i = 0; i < eos._edges.size(); ++i )
6941         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6942     }
6943     if ( centersBox.IsVoid() )
6944     {
6945       debugMsg( "Error: centersBox.IsVoid()" );
6946       return false;
6947     }
6948     const bool isSpherical =
6949       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6950
6951     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6952     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6953
6954     if ( isSpherical )
6955     {
6956       // set _LayerEdge::_normal as average of all normals
6957
6958       // WARNING: different density of nodes on EDGEs is not taken into account that
6959       // can lead to an improper new normal
6960
6961       gp_XYZ avgNormal( 0,0,0 );
6962       nbEdges = 0;
6963       id2eos = convFace._subIdToEOS.begin();
6964       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6965       {
6966         _EdgesOnShape& eos = *(id2eos->second);
6967         // set data of _CentralCurveOnEdge
6968         if ( eos.ShapeType() == TopAbs_EDGE )
6969         {
6970           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6971           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6972           if ( !eos._sWOL.IsNull() )
6973             ceCurve._adjFace.Nullify();
6974           else
6975             ceCurve._ledges.insert( ceCurve._ledges.end(),
6976                                     eos._edges.begin(), eos._edges.end());
6977         }
6978         // summarize normals
6979         for ( size_t i = 0; i < eos._edges.size(); ++i )
6980           avgNormal += eos._edges[ i ]->_normal;
6981       }
6982       double normSize = avgNormal.SquareModulus();
6983       if ( normSize < 1e-200 )
6984       {
6985         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6986         return false;
6987       }
6988       avgNormal /= Sqrt( normSize );
6989
6990       // compute new _LayerEdge::_cosin on EDGEs
6991       double avgCosin = 0;
6992       int     nbCosin = 0;
6993       gp_Vec inFaceDir;
6994       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6995       {
6996         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6997         if ( ceCurve._adjFace.IsNull() )
6998           continue;
6999         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7000         {
7001           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7002           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7003           if ( isOK )
7004           {
7005             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7006             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7007             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7008             nbCosin++;
7009           }
7010         }
7011       }
7012       if ( nbCosin > 0 )
7013         avgCosin /= nbCosin;
7014
7015       // set _LayerEdge::_normal = avgNormal
7016       id2eos = convFace._subIdToEOS.begin();
7017       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7018       {
7019         _EdgesOnShape& eos = *(id2eos->second);
7020         if ( eos.ShapeType() != TopAbs_EDGE )
7021           for ( size_t i = 0; i < eos._edges.size(); ++i )
7022             eos._edges[ i ]->_cosin = avgCosin;
7023
7024         for ( size_t i = 0; i < eos._edges.size(); ++i )
7025         {
7026           eos._edges[ i ]->SetNormal( avgNormal );
7027           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7028         }
7029       }
7030     }
7031     else // if ( isSpherical )
7032     {
7033       // We suppose that centers of curvature at all points of the FACE
7034       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7035       // having a common center of curvature we define the same new normal
7036       // as a sum of normals of _LayerEdge's on EDGEs among them.
7037
7038       // get all centers of curvature for each EDGE
7039
7040       helper.SetSubShape( convFace._face );
7041       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7042
7043       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7044       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7045       {
7046         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7047
7048         // set adjacent FACE
7049         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7050
7051         // get _LayerEdge's of the EDGE
7052         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7053         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7054         if ( !eos || eos->_edges.empty() )
7055         {
7056           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7057           for ( int iV = 0; iV < 2; ++iV )
7058           {
7059             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7060             TGeomID     vID = meshDS->ShapeToIndex( v );
7061             eos = data.GetShapeEdges( vID );
7062             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7063           }
7064           edgeLEdge    = &vertexLEdges[0];
7065           edgeLEdgeEnd = edgeLEdge + 2;
7066
7067           centerCurves[ iE ]._adjFace.Nullify();
7068         }
7069         else
7070         {
7071           if ( ! eos->_toSmooth )
7072             data.SortOnEdge( edge, eos->_edges );
7073           edgeLEdge    = &eos->_edges[ 0 ];
7074           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7075           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7076           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7077
7078           if ( ! eos->_sWOL.IsNull() )
7079             centerCurves[ iE ]._adjFace.Nullify();
7080         }
7081
7082         // Get curvature centers
7083
7084         centersBox.Clear();
7085
7086         if ( edgeLEdge[0]->IsOnEdge() &&
7087              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7088         { // 1st VERTEX
7089           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7090           centersBox.Add( center );
7091         }
7092         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7093           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7094           { // EDGE or VERTEXes
7095             centerCurves[ iE ].Append( center, *edgeLEdge );
7096             centersBox.Add( center );
7097           }
7098         if ( edgeLEdge[-1]->IsOnEdge() &&
7099              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7100         { // 2nd VERTEX
7101           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7102           centersBox.Add( center );
7103         }
7104         centerCurves[ iE ]._isDegenerated =
7105           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7106
7107       } // loop on EDGES of convFace._face to set up data of centerCurves
7108
7109       // Compute new normals for _LayerEdge's on EDGEs
7110
7111       double avgCosin = 0;
7112       int     nbCosin = 0;
7113       gp_Vec inFaceDir;
7114       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7115       {
7116         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7117         if ( ceCurve._isDegenerated )
7118           continue;
7119         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7120         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7121         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7122         {
7123           isOK = false;
7124           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7125           {
7126             if ( iE1 != iE2 )
7127               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7128           }
7129           if ( isOK && !ceCurve._adjFace.IsNull() )
7130           {
7131             // compute new _LayerEdge::_cosin
7132             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7133             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7134             if ( isOK )
7135             {
7136               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7137               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7138               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7139               nbCosin++;
7140             }
7141           }
7142         }
7143       }
7144       // set new normals to _LayerEdge's of NOT degenerated central curves
7145       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7146       {
7147         if ( centerCurves[ iE ]._isDegenerated )
7148           continue;
7149         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7150         {
7151           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7152           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7153         }
7154       }
7155       // set new normals to _LayerEdge's of     degenerated central curves
7156       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7157       {
7158         if ( !centerCurves[ iE ]._isDegenerated ||
7159              centerCurves[ iE ]._ledges.size() < 3 )
7160           continue;
7161         // new normal is an average of new normals at VERTEXes that
7162         // was computed on non-degenerated _CentralCurveOnEdge's
7163         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7164                            centerCurves[ iE ]._ledges.back ()->_normal );
7165         double sz = newNorm.Modulus();
7166         if ( sz < 1e-200 )
7167           continue;
7168         newNorm /= sz;
7169         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7170                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7171         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7172         {
7173           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7174           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7175           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7176         }
7177       }
7178
7179       // Find new normals for _LayerEdge's based on FACE
7180
7181       if ( nbCosin > 0 )
7182         avgCosin /= nbCosin;
7183       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7184       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7185       if ( id2eos != convFace._subIdToEOS.end() )
7186       {
7187         int iE = 0;
7188         gp_XYZ newNorm;
7189         _EdgesOnShape& eos = * ( id2eos->second );
7190         for ( size_t i = 0; i < eos._edges.size(); ++i )
7191         {
7192           _LayerEdge* ledge = eos._edges[ i ];
7193           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7194             continue;
7195           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7196           {
7197             iE = iE % centerCurves.size();
7198             if ( centerCurves[ iE ]._isDegenerated )
7199               continue;
7200             newNorm.SetCoord( 0,0,0 );
7201             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7202             {
7203               ledge->SetNormal( newNorm );
7204               ledge->_cosin  = avgCosin;
7205               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7206               break;
7207             }
7208           }
7209         }
7210       }
7211
7212     } // not a quasi-spherical FACE
7213
7214     // Update _LayerEdge's data according to a new normal
7215
7216     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7217                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7218
7219     id2eos = convFace._subIdToEOS.begin();
7220     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7221     {
7222       _EdgesOnShape& eos = * ( id2eos->second );
7223       for ( size_t i = 0; i < eos._edges.size(); ++i )
7224       {
7225         _LayerEdge* & ledge = eos._edges[ i ];
7226         double len = ledge->_len;
7227         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7228         ledge->SetCosin( ledge->_cosin );
7229         ledge->SetNewLength( len, eos, helper );
7230       }
7231       if ( eos.ShapeType() != TopAbs_FACE )
7232         for ( size_t i = 0; i < eos._edges.size(); ++i )
7233         {
7234           _LayerEdge* ledge = eos._edges[ i ];
7235           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7236           {
7237             _LayerEdge* neibor = ledge->_neibors[iN];
7238             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7239             {
7240               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7241               neibor->Set( _LayerEdge::MOVED );
7242               neibor->SetSmooLen( neibor->_len );
7243             }
7244           }
7245         }
7246     } // loop on sub-shapes of convFace._face
7247
7248     // Find FACEs adjacent to convFace._face that got necessity to smooth
7249     // as a result of normals modification
7250
7251     set< _EdgesOnShape* > adjFacesToSmooth;
7252     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7253     {
7254       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7255            centerCurves[ iE ]._adjFaceToSmooth )
7256         continue;
7257       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7258       {
7259         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7260         {
7261           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7262           break;
7263         }
7264       }
7265     }
7266     data.AddShapesToSmooth( adjFacesToSmooth );
7267
7268     dumpFunctionEnd();
7269
7270
7271   } // loop on data._convexFaces
7272
7273   return true;
7274 }
7275
7276 //================================================================================
7277 /*!
7278  * \brief Finds a center of curvature of a surface at a _LayerEdge
7279  */
7280 //================================================================================
7281
7282 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7283                                         BRepLProp_SLProps&  surfProp,
7284                                         SMESH_MesherHelper& helper,
7285                                         gp_Pnt &            center ) const
7286 {
7287   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7288   surfProp.SetParameters( uv.X(), uv.Y() );
7289   if ( !surfProp.IsCurvatureDefined() )
7290     return false;
7291
7292   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7293   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7294   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7295   if ( surfCurvatureMin > surfCurvatureMax )
7296     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7297   else
7298     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7299
7300   return true;
7301 }
7302
7303 //================================================================================
7304 /*!
7305  * \brief Check that prisms are not distorted
7306  */
7307 //================================================================================
7308
7309 bool _ConvexFace::CheckPrisms() const
7310 {
7311   double vol = 0;
7312   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7313   {
7314     const _LayerEdge* edge = _simplexTestEdges[i];
7315     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7316     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7317       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7318       {
7319         debugMsg( "Bad simplex of _simplexTestEdges ("
7320                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7321                   << " "<< edge->_simplices[j]._nPrev->GetID()
7322                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7323         return false;
7324       }
7325   }
7326   return true;
7327 }
7328
7329 //================================================================================
7330 /*!
7331  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7332  *        stored in this _CentralCurveOnEdge.
7333  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7334  *  \param [in,out] newNormal - current normal at this point, to be redefined
7335  *  \return bool - true if succeeded.
7336  */
7337 //================================================================================
7338
7339 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7340 {
7341   if ( this->_isDegenerated )
7342     return false;
7343
7344   // find two centers the given one lies between
7345
7346   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7347   {
7348     double sl2 = 1.001 * _segLength2[ i ];
7349
7350     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7351     if ( d1 > sl2 )
7352       continue;
7353     
7354     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7355     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7356       continue;
7357
7358     d1 = Sqrt( d1 );
7359     d2 = Sqrt( d2 );
7360     double r = d1 / ( d1 + d2 );
7361     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7362                    (      r ) * _ledges[ i+1 ]->_normal );
7363     norm.Normalize();
7364
7365     newNormal += norm;
7366     double sz = newNormal.Modulus();
7367     if ( sz < 1e-200 )
7368       break;
7369     newNormal /= sz;
7370     return true;
7371   }
7372   return false;
7373 }
7374
7375 //================================================================================
7376 /*!
7377  * \brief Set shape members
7378  */
7379 //================================================================================
7380
7381 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7382                                      const _ConvexFace&  convFace,
7383                                      _SolidData&         data,
7384                                      SMESH_MesherHelper& helper)
7385 {
7386   _edge = edge;
7387
7388   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7389   while ( const TopoDS_Shape* F = fIt->next())
7390     if ( !convFace._face.IsSame( *F ))
7391     {
7392       _adjFace = TopoDS::Face( *F );
7393       _adjFaceToSmooth = false;
7394       // _adjFace already in a smoothing queue ?
7395       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7396         _adjFaceToSmooth = eos->_toSmooth;
7397       break;
7398     }
7399 }
7400
7401 //================================================================================
7402 /*!
7403  * \brief Looks for intersection of it's last segment with faces
7404  *  \param distance - returns shortest distance from the last node to intersection
7405  */
7406 //================================================================================
7407
7408 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7409                                    double &                 distance,
7410                                    const double&            epsilon,
7411                                    _EdgesOnShape&           eos,
7412                                    const SMDS_MeshElement** intFace)
7413 {
7414   vector< const SMDS_MeshElement* > suspectFaces;
7415   double segLen;
7416   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7417   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7418
7419   bool segmentIntersected = false;
7420   distance = Precision::Infinite();
7421   int iFace = -1; // intersected face
7422   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7423   {
7424     const SMDS_MeshElement* face = suspectFaces[j];
7425     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7426          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7427       continue; // face sharing _LayerEdge node
7428     const int nbNodes = face->NbCornerNodes();
7429     bool intFound = false;
7430     double dist;
7431     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7432     if ( nbNodes == 3 )
7433     {
7434       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7435     }
7436     else
7437     {
7438       const SMDS_MeshNode* tria[3];
7439       tria[0] = *nIt++;
7440       tria[1] = *nIt++;
7441       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7442       {
7443         tria[2] = *nIt++;
7444         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7445         tria[1] = tria[2];
7446       }
7447     }
7448     if ( intFound )
7449     {
7450       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7451         segmentIntersected = true;
7452       if ( distance > dist )
7453         distance = dist, iFace = j;
7454     }
7455   }
7456   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7457
7458   distance -= segLen;
7459
7460   if ( segmentIntersected )
7461   {
7462 #ifdef __myDEBUG
7463     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7464     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7465     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7466          << ", intersection with face ("
7467          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7468          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7469          << ") distance = " << distance << endl;
7470 #endif
7471   }
7472
7473   return segmentIntersected;
7474 }
7475
7476 //================================================================================
7477 /*!
7478  * \brief Returns a point used to check orientation of _simplices
7479  */
7480 //================================================================================
7481
7482 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7483 {
7484   size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7485
7486   if ( !eos || eos->_sWOL.IsNull() )
7487     return _pos[ i ];
7488
7489   if ( eos->SWOLType() == TopAbs_EDGE )
7490   {
7491     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7492   }
7493   //else //  TopAbs_FACE
7494
7495   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7496 }
7497
7498 //================================================================================
7499 /*!
7500  * \brief Returns size and direction of the last segment
7501  */
7502 //================================================================================
7503
7504 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7505 {
7506   // find two non-coincident positions
7507   gp_XYZ orig = _pos.back();
7508   gp_XYZ vec;
7509   int iPrev = _pos.size() - 2;
7510   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7511   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7512   while ( iPrev >= 0 )
7513   {
7514     vec = orig - _pos[iPrev];
7515     if ( vec.SquareModulus() > tol*tol )
7516       break;
7517     else
7518       iPrev--;
7519   }
7520
7521   // make gp_Ax1
7522   gp_Ax1 segDir;
7523   if ( iPrev < 0 )
7524   {
7525     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7526     segDir.SetDirection( _normal );
7527     segLen = 0;
7528   }
7529   else
7530   {
7531     gp_Pnt pPrev = _pos[ iPrev ];
7532     if ( !eos._sWOL.IsNull() )
7533     {
7534       TopLoc_Location loc;
7535       if ( eos.SWOLType() == TopAbs_EDGE )
7536       {
7537         double f,l;
7538         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7539         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7540       }
7541       else
7542       {
7543         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7544         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7545       }
7546       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7547     }
7548     segDir.SetLocation( pPrev );
7549     segDir.SetDirection( vec );
7550     segLen = vec.Modulus();
7551   }
7552
7553   return segDir;
7554 }
7555
7556 //================================================================================
7557 /*!
7558  * \brief Return the last position of the target node on a FACE. 
7559  *  \param [in] F - the FACE this _LayerEdge is inflated along
7560  *  \return gp_XY - result UV
7561  */
7562 //================================================================================
7563
7564 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7565 {
7566   if ( F.IsSame( eos._sWOL )) // F is my FACE
7567     return gp_XY( _pos.back().X(), _pos.back().Y() );
7568
7569   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7570     return gp_XY( 1e100, 1e100 );
7571
7572   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7573   double f, l, u = _pos.back().X();
7574   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7575   if ( !C2d.IsNull() && f <= u && u <= l )
7576     return C2d->Value( u ).XY();
7577
7578   return gp_XY( 1e100, 1e100 );
7579 }
7580
7581 //================================================================================
7582 /*!
7583  * \brief Test intersection of the last segment with a given triangle
7584  *   using Moller-Trumbore algorithm
7585  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7586  */
7587 //================================================================================
7588
7589 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7590                                const gp_XYZ& vert0,
7591                                const gp_XYZ& vert1,
7592                                const gp_XYZ& vert2,
7593                                double&       t,
7594                                const double& EPSILON) const
7595 {
7596   const gp_Pnt& orig = lastSegment.Location();
7597   const gp_Dir& dir  = lastSegment.Direction();
7598
7599   /* calculate distance from vert0 to ray origin */
7600   //gp_XYZ tvec = orig.XYZ() - vert0;
7601
7602   //if ( tvec * dir > EPSILON )
7603     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7604     //return false;
7605
7606   gp_XYZ edge1 = vert1 - vert0;
7607   gp_XYZ edge2 = vert2 - vert0;
7608
7609   /* begin calculating determinant - also used to calculate U parameter */
7610   gp_XYZ pvec = dir.XYZ() ^ edge2;
7611
7612   /* if determinant is near zero, ray lies in plane of triangle */
7613   double det = edge1 * pvec;
7614
7615   const double ANGL_EPSILON = 1e-12;
7616   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7617     return false;
7618
7619   /* calculate distance from vert0 to ray origin */
7620   gp_XYZ tvec = orig.XYZ() - vert0;
7621
7622   /* calculate U parameter and test bounds */
7623   double u = ( tvec * pvec ) / det;
7624   //if (u < 0.0 || u > 1.0)
7625   if ( u < -EPSILON || u > 1.0 + EPSILON )
7626     return false;
7627
7628   /* prepare to test V parameter */
7629   gp_XYZ qvec = tvec ^ edge1;
7630
7631   /* calculate V parameter and test bounds */
7632   double v = (dir.XYZ() * qvec) / det;
7633   //if ( v < 0.0 || u + v > 1.0 )
7634   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7635     return false;
7636
7637   /* calculate t, ray intersects triangle */
7638   t = (edge2 * qvec) / det;
7639
7640   //return true;
7641   return t > 0.;
7642 }
7643
7644 //================================================================================
7645 /*!
7646  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7647  *        neighbor _LayerEdge's by it's own inflation vector.
7648  *  \param [in] eov - EOS of the VERTEX
7649  *  \param [in] eos - EOS of the FACE
7650  *  \param [in] step - inflation step
7651  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7652  */
7653 //================================================================================
7654
7655 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7656                                    const _EdgesOnShape*    eos,
7657                                    const int               step,
7658                                    vector< _LayerEdge* > & badSmooEdges )
7659 {
7660   // check if any of _neibors is in badSmooEdges
7661   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7662                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7663     return;
7664
7665   // get all edges to move
7666
7667   set< _LayerEdge* > edges;
7668
7669   // find a distance between _LayerEdge on VERTEX and its neighbors
7670   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7671   double dist2 = 0;
7672   for ( size_t i = 0; i < _neibors.size(); ++i )
7673   {
7674     _LayerEdge* nEdge = _neibors[i];
7675     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7676     {
7677       edges.insert( nEdge );
7678       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7679     }
7680   }
7681   // add _LayerEdge's close to curPosV
7682   size_t nbE;
7683   do {
7684     nbE = edges.size();
7685     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7686     {
7687       _LayerEdge* edgeF = *e;
7688       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7689       {
7690         _LayerEdge* nEdge = edgeF->_neibors[i];
7691         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7692              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7693           edges.insert( nEdge );
7694       }
7695     }
7696   }
7697   while ( nbE < edges.size() );
7698
7699   // move the target node of the got edges
7700
7701   gp_XYZ prevPosV = PrevPos();
7702   if ( eov->SWOLType() == TopAbs_EDGE )
7703   {
7704     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7705     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7706   }
7707   else if ( eov->SWOLType() == TopAbs_FACE )
7708   {
7709     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7710     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7711   }
7712
7713   SMDS_FacePosition* fPos;
7714   //double r = 1. - Min( 0.9, step / 10. );
7715   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7716   {
7717     _LayerEdge*       edgeF = *e;
7718     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7719     const gp_XYZ    newPosF = curPosV + prevVF;
7720     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7721     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7722     edgeF->_pos.back() = newPosF;
7723     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7724
7725     // set _curvature to make edgeF updated by putOnOffsetSurface()
7726     if ( !edgeF->_curvature )
7727       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7728       {
7729         edgeF->_curvature = new _Curvature;
7730         edgeF->_curvature->_r = 0;
7731         edgeF->_curvature->_k = 0;
7732         edgeF->_curvature->_h2lenRatio = 0;
7733         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7734       }
7735   }
7736   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7737   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7738   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7739   // {
7740   //   _LayerEdge*      edgeF = *e;
7741   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7742   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7743   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7744   //   edgeF->_pos.back() = newPosF;
7745   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7746   // }
7747
7748   // smooth _LayerEdge's around moved nodes
7749   //size_t nbBadBefore = badSmooEdges.size();
7750   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7751   {
7752     _LayerEdge* edgeF = *e;
7753     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7754       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7755         //&& !edges.count( edgeF->_neibors[j] ))
7756       {
7757         _LayerEdge* edgeFN = edgeF->_neibors[j];
7758         edgeFN->Unset( SMOOTHED );
7759         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7760         // if ( nbBad > 0 )
7761         // {
7762         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7763         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7764         //   int        nbBadAfter = edgeFN->_simplices.size();
7765         //   double vol;
7766         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7767         //   {
7768         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7769         //   }
7770         //   if ( nbBadAfter <= nbBad )
7771         //   {
7772         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7773         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7774         //     edgeF->_pos.back() = newPosF;
7775         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7776         //     nbBad = nbBadAfter;
7777         //   }
7778         // }
7779         if ( nbBad > 0 )
7780           badSmooEdges.push_back( edgeFN );
7781       }
7782   }
7783     // move a bit not smoothed around moved nodes
7784   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7785   //   {
7786   //   _LayerEdge*      edgeF = badSmooEdges[i];
7787   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7788   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7789   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7790   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7791   //   edgeF->_pos.back() = newPosF;
7792   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7793   // }
7794 }
7795
7796 //================================================================================
7797 /*!
7798  * \brief Perform smooth of _LayerEdge's based on EDGE's
7799  *  \retval bool - true if node has been moved
7800  */
7801 //================================================================================
7802
7803 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7804                               const TopoDS_Face&             F,
7805                               SMESH_MesherHelper&            helper)
7806 {
7807   ASSERT( IsOnEdge() );
7808
7809   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7810   SMESH_TNodeXYZ oldPos( tgtNode );
7811   double dist01, distNewOld;
7812   
7813   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7814   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7815   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7816
7817   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7818   double lenDelta = 0;
7819   if ( _curvature )
7820   {
7821     //lenDelta = _curvature->lenDelta( _len );
7822     lenDelta = _curvature->lenDeltaByDist( dist01 );
7823     newPos.ChangeCoord() += _normal * lenDelta;
7824   }
7825
7826   distNewOld = newPos.Distance( oldPos );
7827
7828   if ( F.IsNull() )
7829   {
7830     if ( _2neibors->_plnNorm )
7831     {
7832       // put newPos on the plane defined by source node and _plnNorm
7833       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7834       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7835       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7836     }
7837     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7838     _pos.back() = newPos.XYZ();
7839   }
7840   else
7841   {
7842     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7843     gp_XY uv( Precision::Infinite(), 0 );
7844     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7845     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7846
7847     newPos = surface->Value( uv );
7848     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7849   }
7850
7851   // commented for IPAL0052478
7852   // if ( _curvature && lenDelta < 0 )
7853   // {
7854   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7855   //   _len -= prevPos.Distance( oldPos );
7856   //   _len += prevPos.Distance( newPos );
7857   // }
7858   bool moved = distNewOld > dist01/50;
7859   //if ( moved )
7860   dumpMove( tgtNode ); // debug
7861
7862   return moved;
7863 }
7864
7865 //================================================================================
7866 /*!
7867  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7868  */
7869 //================================================================================
7870
7871 void _LayerEdge::SmoothWoCheck()
7872 {
7873   if ( Is( DIFFICULT ))
7874     return;
7875
7876   bool moved = Is( SMOOTHED );
7877   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7878     moved = _neibors[i]->Is( SMOOTHED );
7879   if ( !moved )
7880     return;
7881
7882   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7883
7884   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7885   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7886   _pos.back() = newPos;
7887
7888   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7889 }
7890
7891 //================================================================================
7892 /*!
7893  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7894  */
7895 //================================================================================
7896
7897 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7898 {
7899   if ( ! Is( NEAR_BOUNDARY ))
7900     return 0;
7901
7902   int nbBad = 0;
7903   double vol;
7904   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7905   {
7906     _LayerEdge* eN = _neibors[iN];
7907     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7908       continue;
7909     if ( needSmooth )
7910       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7911                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7912                        eN->_pos.size() != _pos.size() );
7913
7914     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7915     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7916     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7917       if ( eN->_nodes.size() > 1 &&
7918            eN->_simplices[i].Includes( _nodes.back() ) &&
7919            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7920       {
7921         ++nbBad;
7922         if ( badNeibors )
7923         {
7924           badNeibors->push_back( eN );
7925           debugMsg("Bad boundary simplex ( "
7926                    << " "<< eN->_nodes[0]->GetID()
7927                    << " "<< eN->_nodes.back()->GetID()
7928                    << " "<< eN->_simplices[i]._nPrev->GetID()
7929                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7930         }
7931         else
7932         {
7933           break;
7934         }
7935       }
7936   }
7937   return nbBad;
7938 }
7939
7940 //================================================================================
7941 /*!
7942  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7943  *  \retval int - nb of bad simplices around this _LayerEdge
7944  */
7945 //================================================================================
7946
7947 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7948 {
7949   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7950     return 0; // shape of simplices not changed
7951   if ( _simplices.size() < 2 )
7952     return 0; // _LayerEdge inflated along EDGE or FACE
7953
7954   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7955     findBest = true;
7956
7957   const gp_XYZ& curPos  = _pos.back();
7958   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7959
7960   // quality metrics (orientation) of tetras around _tgtNode
7961   int nbOkBefore = 0;
7962   double vol, minVolBefore = 1e100;
7963   for ( size_t i = 0; i < _simplices.size(); ++i )
7964   {
7965     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7966     minVolBefore = Min( minVolBefore, vol );
7967   }
7968   int nbBad = _simplices.size() - nbOkBefore;
7969
7970   bool bndNeedSmooth = false;
7971   if ( nbBad == 0 )
7972     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7973   if ( nbBad > 0 )
7974     Set( DISTORTED );
7975
7976   // evaluate min angle
7977   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7978   {
7979     size_t nbGoodAngles = _simplices.size();
7980     double angle;
7981     for ( size_t i = 0; i < _simplices.size(); ++i )
7982     {
7983       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7984         --nbGoodAngles;
7985     }
7986     if ( nbGoodAngles == _simplices.size() )
7987     {
7988       Unset( MOVED );
7989       return 0;
7990     }
7991   }
7992   if ( Is( ON_CONCAVE_FACE ))
7993     findBest = true;
7994
7995   if ( step % 2 == 0 )
7996     findBest = false;
7997
7998   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7999   {
8000     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8001       _smooFunction = _funs[ FUN_CENTROIDAL ];
8002     else
8003       _smooFunction = _funs[ FUN_LAPLACIAN ];
8004   }
8005
8006   // compute new position for the last _pos using different _funs
8007   gp_XYZ newPos;
8008   bool moved = false;
8009   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8010   {
8011     if ( iFun < 0 )
8012       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8013     else if ( _funs[ iFun ] == _smooFunction )
8014       continue; // _smooFunction again
8015     else if ( step > 1 )
8016       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8017     else
8018       break; // let "easy" functions improve elements around distorted ones
8019
8020     if ( _curvature )
8021     {
8022       double delta  = _curvature->lenDelta( _len );
8023       if ( delta > 0 )
8024         newPos += _normal * delta;
8025       else
8026       {
8027         double segLen = _normal * ( newPos - prevPos );
8028         if ( segLen + delta > 0 )
8029           newPos += _normal * delta;
8030       }
8031       // double segLenChange = _normal * ( curPos - newPos );
8032       // newPos += 0.5 * _normal * segLenChange;
8033     }
8034
8035     int nbOkAfter = 0;
8036     double minVolAfter = 1e100;
8037     for ( size_t i = 0; i < _simplices.size(); ++i )
8038     {
8039       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8040       minVolAfter = Min( minVolAfter, vol );
8041     }
8042     // get worse?
8043     if ( nbOkAfter < nbOkBefore )
8044       continue;
8045
8046     if (( findBest ) &&
8047         ( nbOkAfter == nbOkBefore ) &&
8048         ( minVolAfter <= minVolBefore ))
8049       continue;
8050
8051     nbBad        = _simplices.size() - nbOkAfter;
8052     minVolBefore = minVolAfter;
8053     nbOkBefore   = nbOkAfter;
8054     moved        = true;
8055
8056     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8057     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8058     _pos.back() = newPos;
8059
8060     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8061                   << (nbBad ? " --BAD" : ""));
8062
8063     if ( iFun > -1 )
8064     {
8065       continue; // look for a better function
8066     }
8067
8068     if ( !findBest )
8069       break;
8070
8071   } // loop on smoothing functions
8072
8073   if ( moved ) // notify _neibors
8074   {
8075     Set( SMOOTHED );
8076     for ( size_t i = 0; i < _neibors.size(); ++i )
8077       if ( !_neibors[i]->Is( MOVED ))
8078       {
8079         _neibors[i]->Set( MOVED );
8080         toSmooth.push_back( _neibors[i] );
8081       }
8082   }
8083
8084   return nbBad;
8085 }
8086
8087 //================================================================================
8088 /*!
8089  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8090  *  \retval int - nb of bad simplices around this _LayerEdge
8091  */
8092 //================================================================================
8093
8094 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8095 {
8096   if ( !_smooFunction )
8097     return 0; // _LayerEdge inflated along EDGE or FACE
8098   if ( Is( BLOCKED ))
8099     return 0; // not inflated
8100
8101   const gp_XYZ& curPos  = _pos.back();
8102   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8103
8104   // quality metrics (orientation) of tetras around _tgtNode
8105   int nbOkBefore = 0;
8106   double vol, minVolBefore = 1e100;
8107   for ( size_t i = 0; i < _simplices.size(); ++i )
8108   {
8109     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8110     minVolBefore = Min( minVolBefore, vol );
8111   }
8112   int nbBad = _simplices.size() - nbOkBefore;
8113
8114   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8115   {
8116     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8117       _smooFunction = _funs[ FUN_LAPLACIAN ];
8118     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8119       _smooFunction = _funs[ FUN_CENTROIDAL ];
8120   }
8121
8122   // compute new position for the last _pos using different _funs
8123   gp_XYZ newPos;
8124   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8125   {
8126     if ( iFun < 0 )
8127       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8128     else if ( _funs[ iFun ] == _smooFunction )
8129       continue; // _smooFunction again
8130     else if ( step > 1 )
8131       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8132     else
8133       break; // let "easy" functions improve elements around distorted ones
8134
8135     if ( _curvature )
8136     {
8137       double delta  = _curvature->lenDelta( _len );
8138       if ( delta > 0 )
8139         newPos += _normal * delta;
8140       else
8141       {
8142         double segLen = _normal * ( newPos - prevPos );
8143         if ( segLen + delta > 0 )
8144           newPos += _normal * delta;
8145       }
8146       // double segLenChange = _normal * ( curPos - newPos );
8147       // newPos += 0.5 * _normal * segLenChange;
8148     }
8149
8150     int nbOkAfter = 0;
8151     double minVolAfter = 1e100;
8152     for ( size_t i = 0; i < _simplices.size(); ++i )
8153     {
8154       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8155       minVolAfter = Min( minVolAfter, vol );
8156     }
8157     // get worse?
8158     if ( nbOkAfter < nbOkBefore )
8159       continue;
8160     if (( isConcaveFace || findBest ) &&
8161         ( nbOkAfter == nbOkBefore ) &&
8162         ( minVolAfter <= minVolBefore )
8163         )
8164       continue;
8165
8166     nbBad        = _simplices.size() - nbOkAfter;
8167     minVolBefore = minVolAfter;
8168     nbOkBefore   = nbOkAfter;
8169
8170     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8171     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8172     _pos.back() = newPos;
8173
8174     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8175                   << ( nbBad ? "--BAD" : ""));
8176
8177     // commented for IPAL0052478
8178     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8179     // _len += prevPos.Distance(newPos);
8180
8181     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8182     {
8183       //_smooFunction = _funs[ iFun ];
8184       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8185       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8186       // << " minVol: " << minVolAfter
8187       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8188       // << endl;
8189       continue; // look for a better function
8190     }
8191
8192     if ( !findBest )
8193       break;
8194
8195   } // loop on smoothing functions
8196
8197   return nbBad;
8198 }
8199
8200 //================================================================================
8201 /*!
8202  * \brief Chooses a smoothing technic giving a position most close to an initial one.
8203  *        For a correct result, _simplices must contain nodes lying on geometry.
8204  */
8205 //================================================================================
8206
8207 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8208                                      const TNode2Edge&     n2eMap)
8209 {
8210   if ( _smooFunction ) return;
8211
8212   // use smoothNefPolygon() near concaveVertices
8213   if ( !concaveVertices.empty() )
8214   {
8215     _smooFunction = _funs[ FUN_CENTROIDAL ];
8216
8217     Set( ON_CONCAVE_FACE );
8218
8219     for ( size_t i = 0; i < _simplices.size(); ++i )
8220     {
8221       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8222       {
8223         _smooFunction = _funs[ FUN_NEFPOLY ];
8224
8225         // set FUN_CENTROIDAL to neighbor edges
8226         for ( i = 0; i < _neibors.size(); ++i )
8227         {
8228           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8229           {
8230             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8231           }
8232         }
8233         return;
8234       }
8235     }
8236
8237     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8238     // // where the nodes are smoothed too far along a sphere thus creating
8239     // // inverted _simplices
8240     // double dist[theNbSmooFuns];
8241     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8242     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8243
8244     // double minDist = Precision::Infinite();
8245     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8246     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8247     // {
8248     //   gp_Pnt newP = (this->*_funs[i])();
8249     //   dist[i] = p.SquareDistance( newP );
8250     //   if ( dist[i]*coef[i] < minDist )
8251     //   {
8252     //     _smooFunction = _funs[i];
8253     //     minDist = dist[i]*coef[i];
8254     //   }
8255     // }
8256   }
8257   else
8258   {
8259     _smooFunction = _funs[ FUN_LAPLACIAN ];
8260   }
8261   // int minDim = 3;
8262   // for ( size_t i = 0; i < _simplices.size(); ++i )
8263   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8264   // if ( minDim == 0 )
8265   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8266   // else if ( minDim == 1 )
8267   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8268
8269
8270   // int iMin;
8271   // for ( int i = 0; i < FUN_NB; ++i )
8272   // {
8273   //   //cout << dist[i] << " ";
8274   //   if ( _smooFunction == _funs[i] ) {
8275   //     iMin = i;
8276   //     //debugMsg( fNames[i] );
8277   //     break;
8278   //   }
8279   // }
8280   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8281 }
8282
8283 //================================================================================
8284 /*!
8285  * \brief Returns a name of _SmooFunction
8286  */
8287 //================================================================================
8288
8289 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8290 {
8291   if ( !fun )
8292     fun = _smooFunction;
8293   for ( int i = 0; i < theNbSmooFuns; ++i )
8294     if ( fun == _funs[i] )
8295       return i;
8296
8297   return theNbSmooFuns;
8298 }
8299
8300 //================================================================================
8301 /*!
8302  * \brief Computes a new node position using Laplacian smoothing
8303  */
8304 //================================================================================
8305
8306 gp_XYZ _LayerEdge::smoothLaplacian()
8307 {
8308   gp_XYZ newPos (0,0,0);
8309   for ( size_t i = 0; i < _simplices.size(); ++i )
8310     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8311   newPos /= _simplices.size();
8312
8313   return newPos;
8314 }
8315
8316 //================================================================================
8317 /*!
8318  * \brief Computes a new node position using angular-based smoothing
8319  */
8320 //================================================================================
8321
8322 gp_XYZ _LayerEdge::smoothAngular()
8323 {
8324   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8325   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8326   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8327
8328   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8329   gp_XYZ pN( 0,0,0 );
8330   for ( size_t i = 0; i < _simplices.size(); ++i )
8331   {
8332     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8333     edgeDir.push_back( p - pPrev );
8334     edgeSize.push_back( edgeDir.back().Magnitude() );
8335     if ( edgeSize.back() < numeric_limits<double>::min() )
8336     {
8337       edgeDir.pop_back();
8338       edgeSize.pop_back();
8339     }
8340     else
8341     {
8342       edgeDir.back() /= edgeSize.back();
8343       points.push_back( p );
8344       pN += p;
8345     }
8346     pPrev = p;
8347   }
8348   edgeDir.push_back ( edgeDir[0] );
8349   edgeSize.push_back( edgeSize[0] );
8350   pN /= points.size();
8351
8352   gp_XYZ newPos(0,0,0);
8353   double sumSize = 0;
8354   for ( size_t i = 0; i < points.size(); ++i )
8355   {
8356     gp_Vec toN    = pN - points[i];
8357     double toNLen = toN.Magnitude();
8358     if ( toNLen < numeric_limits<double>::min() )
8359     {
8360       newPos += pN;
8361       continue;
8362     }
8363     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8364     double bisecLen = bisec.SquareMagnitude();
8365     if ( bisecLen < numeric_limits<double>::min() )
8366     {
8367       gp_Vec norm = edgeDir[i] ^ toN;
8368       bisec = norm ^ edgeDir[i];
8369       bisecLen = bisec.SquareMagnitude();
8370     }
8371     bisecLen = Sqrt( bisecLen );
8372     bisec /= bisecLen;
8373
8374 #if 1
8375     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8376     sumSize += bisecLen;
8377 #else
8378     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8379     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8380 #endif
8381     newPos += pNew;
8382   }
8383   newPos /= sumSize;
8384
8385   // project newPos to an average plane
8386
8387   gp_XYZ norm(0,0,0); // plane normal
8388   points.push_back( points[0] );
8389   for ( size_t i = 1; i < points.size(); ++i )
8390   {
8391     gp_XYZ vec1 = points[ i-1 ] - pN;
8392     gp_XYZ vec2 = points[ i   ] - pN;
8393     gp_XYZ cross = vec1 ^ vec2;
8394     try {
8395       cross.Normalize();
8396       if ( cross * norm < numeric_limits<double>::min() )
8397         norm += cross.Reversed();
8398       else
8399         norm += cross;
8400     }
8401     catch (Standard_Failure) { // if |cross| == 0.
8402     }
8403   }
8404   gp_XYZ vec = newPos - pN;
8405   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8406   newPos     = newPos - r * norm;
8407
8408   return newPos;
8409 }
8410
8411 //================================================================================
8412 /*!
8413  * \brief Computes a new node position using weigthed node positions
8414  */
8415 //================================================================================
8416
8417 gp_XYZ _LayerEdge::smoothLengthWeighted()
8418 {
8419   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8420   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8421
8422   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8423   for ( size_t i = 0; i < _simplices.size(); ++i )
8424   {
8425     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8426     edgeSize.push_back( ( p - pPrev ).Modulus() );
8427     if ( edgeSize.back() < numeric_limits<double>::min() )
8428     {
8429       edgeSize.pop_back();
8430     }
8431     else
8432     {
8433       points.push_back( p );
8434     }
8435     pPrev = p;
8436   }
8437   edgeSize.push_back( edgeSize[0] );
8438
8439   gp_XYZ newPos(0,0,0);
8440   double sumSize = 0;
8441   for ( size_t i = 0; i < points.size(); ++i )
8442   {
8443     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8444     sumSize += edgeSize[i] + edgeSize[i+1];
8445   }
8446   newPos /= sumSize;
8447   return newPos;
8448 }
8449
8450 //================================================================================
8451 /*!
8452  * \brief Computes a new node position using angular-based smoothing
8453  */
8454 //================================================================================
8455
8456 gp_XYZ _LayerEdge::smoothCentroidal()
8457 {
8458   gp_XYZ newPos(0,0,0);
8459   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8460   double sumSize = 0;
8461   for ( size_t i = 0; i < _simplices.size(); ++i )
8462   {
8463     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8464     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8465     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8466     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8467
8468     sumSize += size;
8469     newPos += gc * size;
8470   }
8471   newPos /= sumSize;
8472
8473   return newPos;
8474 }
8475
8476 //================================================================================
8477 /*!
8478  * \brief Computes a new node position located inside a Nef polygon
8479  */
8480 //================================================================================
8481
8482 gp_XYZ _LayerEdge::smoothNefPolygon()
8483 #ifdef OLD_NEF_POLYGON
8484 {
8485   gp_XYZ newPos(0,0,0);
8486
8487   // get a plane to seach a solution on
8488
8489   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8490   size_t i;
8491   const double tol = numeric_limits<double>::min();
8492   gp_XYZ center(0,0,0);
8493   for ( i = 0; i < _simplices.size(); ++i )
8494   {
8495     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8496                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8497     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8498   }
8499   vecs.back() = vecs[0];
8500   center /= _simplices.size();
8501
8502   gp_XYZ zAxis(0,0,0);
8503   for ( i = 0; i < _simplices.size(); ++i )
8504     zAxis += vecs[i] ^ vecs[i+1];
8505
8506   gp_XYZ yAxis;
8507   for ( i = 0; i < _simplices.size(); ++i )
8508   {
8509     yAxis = vecs[i];
8510     if ( yAxis.SquareModulus() > tol )
8511       break;
8512   }
8513   gp_XYZ xAxis = yAxis ^ zAxis;
8514   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8515   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8516   //                             p0.Distance( _simplices[2]._nPrev ));
8517   // gp_XYZ center = smoothLaplacian();
8518   // gp_XYZ xAxis, yAxis, zAxis;
8519   // for ( i = 0; i < _simplices.size(); ++i )
8520   // {
8521   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8522   //   if ( xAxis.SquareModulus() > tol*tol )
8523   //     break;
8524   // }
8525   // for ( i = 1; i < _simplices.size(); ++i )
8526   // {
8527   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8528   //   zAxis = xAxis ^ yAxis;
8529   //   if ( zAxis.SquareModulus() > tol*tol )
8530   //     break;
8531   // }
8532   // if ( i == _simplices.size() ) return newPos;
8533
8534   yAxis = zAxis ^ xAxis;
8535   xAxis /= xAxis.Modulus();
8536   yAxis /= yAxis.Modulus();
8537
8538   // get half-planes of _simplices
8539
8540   vector< _halfPlane > halfPlns( _simplices.size() );
8541   int nbHP = 0;
8542   for ( size_t i = 0; i < _simplices.size(); ++i )
8543   {
8544     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8545     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8546     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8547     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8548     gp_XY  vec12 = p2 - p1;
8549     double dist12 = vec12.Modulus();
8550     if ( dist12 < tol )
8551       continue;
8552     vec12 /= dist12;
8553     halfPlns[ nbHP ]._pos = p1;
8554     halfPlns[ nbHP ]._dir = vec12;
8555     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8556     ++nbHP;
8557   }
8558
8559   // intersect boundaries of half-planes, define state of intersection points
8560   // in relation to all half-planes and calculate internal point of a 2D polygon
8561
8562   double sumLen = 0;
8563   gp_XY newPos2D (0,0);
8564
8565   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8566   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8567   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8568
8569   vector< vector< TIntPntState > > allIntPnts( nbHP );
8570   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8571   {
8572     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8573     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8574
8575     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8576     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8577
8578     int nbNotOut = 0;
8579     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8580
8581     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8582     {
8583       if ( iHP1 == iHP2 ) continue;
8584
8585       TIntPntState & ips1 = intPnts1[ iHP2 ];
8586       if ( ips1.second == UNDEF )
8587       {
8588         // find an intersection point of boundaries of iHP1 and iHP2
8589
8590         if ( iHP2 == iPrev ) // intersection with neighbors is known
8591           ips1.first = halfPlns[ iHP1 ]._pos;
8592         else if ( iHP2 == iNext )
8593           ips1.first = halfPlns[ iHP2 ]._pos;
8594         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8595           ips1.second = NO_INT;
8596
8597         // classify the found intersection point
8598         if ( ips1.second != NO_INT )
8599         {
8600           ips1.second = NOT_OUT;
8601           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8602             if ( i != iHP1 && i != iHP2 &&
8603                  halfPlns[ i ].IsOut( ips1.first, tol ))
8604               ips1.second = IS_OUT;
8605         }
8606         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8607         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8608         TIntPntState & ips2 = intPnts2[ iHP1 ];
8609         ips2 = ips1;
8610       }
8611       if ( ips1.second == NOT_OUT )
8612       {
8613         ++nbNotOut;
8614         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8615       }
8616     }
8617
8618     // find a NOT_OUT segment of boundary which is located between
8619     // two NOT_OUT int points
8620
8621     if ( nbNotOut < 2 )
8622       continue; // no such a segment
8623
8624     if ( nbNotOut > 2 )
8625     {
8626       // sort points along the boundary
8627       map< double, TIntPntState* > ipsByParam;
8628       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8629       {
8630         TIntPntState & ips1 = intPnts1[ iHP2 ];
8631         if ( ips1.second != NO_INT )
8632         {
8633           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8634           double param = op * halfPlns[ iHP1 ]._dir;
8635           ipsByParam.insert( make_pair( param, & ips1 ));
8636         }
8637       }
8638       // look for two neighboring NOT_OUT points
8639       nbNotOut = 0;
8640       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8641       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8642       {
8643         TIntPntState & ips1 = *(u2ips->second);
8644         if ( ips1.second == NOT_OUT )
8645           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8646         else if ( nbNotOut >= 2 )
8647           break;
8648         else
8649           nbNotOut = 0;
8650       }
8651     }
8652
8653     if ( nbNotOut >= 2 )
8654     {
8655       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8656       sumLen += len;
8657
8658       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8659     }
8660   }
8661
8662   if ( sumLen > 0 )
8663   {
8664     newPos2D /= sumLen;
8665     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8666   }
8667   else
8668   {
8669     newPos = center;
8670   }
8671
8672   return newPos;
8673 }
8674 #else // OLD_NEF_POLYGON
8675 { ////////////////////////////////// NEW
8676   gp_XYZ newPos(0,0,0);
8677
8678   // get a plane to seach a solution on
8679
8680   size_t i;
8681   gp_XYZ center(0,0,0);
8682   for ( i = 0; i < _simplices.size(); ++i )
8683     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8684   center /= _simplices.size();
8685
8686   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8687   for ( i = 0; i < _simplices.size(); ++i )
8688     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8689   vecs.back() = vecs[0];
8690
8691   const double tol = numeric_limits<double>::min();
8692   gp_XYZ zAxis(0,0,0);
8693   for ( i = 0; i < _simplices.size(); ++i )
8694   {
8695     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8696     try {
8697       cross.Normalize();
8698       if ( cross * zAxis < tol )
8699         zAxis += cross.Reversed();
8700       else
8701         zAxis += cross;
8702     }
8703     catch (Standard_Failure) { // if |cross| == 0.
8704     }
8705   }
8706
8707   gp_XYZ yAxis;
8708   for ( i = 0; i < _simplices.size(); ++i )
8709   {
8710     yAxis = vecs[i];
8711     if ( yAxis.SquareModulus() > tol )
8712       break;
8713   }
8714   gp_XYZ xAxis = yAxis ^ zAxis;
8715   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8716   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8717   //                             p0.Distance( _simplices[2]._nPrev ));
8718   // gp_XYZ center = smoothLaplacian();
8719   // gp_XYZ xAxis, yAxis, zAxis;
8720   // for ( i = 0; i < _simplices.size(); ++i )
8721   // {
8722   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8723   //   if ( xAxis.SquareModulus() > tol*tol )
8724   //     break;
8725   // }
8726   // for ( i = 1; i < _simplices.size(); ++i )
8727   // {
8728   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8729   //   zAxis = xAxis ^ yAxis;
8730   //   if ( zAxis.SquareModulus() > tol*tol )
8731   //     break;
8732   // }
8733   // if ( i == _simplices.size() ) return newPos;
8734
8735   yAxis = zAxis ^ xAxis;
8736   xAxis /= xAxis.Modulus();
8737   yAxis /= yAxis.Modulus();
8738
8739   // get half-planes of _simplices
8740
8741   vector< _halfPlane > halfPlns( _simplices.size() );
8742   int nbHP = 0;
8743   for ( size_t i = 0; i < _simplices.size(); ++i )
8744   {
8745     const gp_XYZ& OP1 = vecs[ i   ];
8746     const gp_XYZ& OP2 = vecs[ i+1 ];
8747     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8748     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8749     gp_XY  vec12 = p2 - p1;
8750     double dist12 = vec12.Modulus();
8751     if ( dist12 < tol )
8752       continue;
8753     vec12 /= dist12;
8754     halfPlns[ nbHP ]._pos = p1;
8755     halfPlns[ nbHP ]._dir = vec12;
8756     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8757     ++nbHP;
8758   }
8759
8760   // intersect boundaries of half-planes, define state of intersection points
8761   // in relation to all half-planes and calculate internal point of a 2D polygon
8762
8763   double sumLen = 0;
8764   gp_XY newPos2D (0,0);
8765
8766   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8767   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8768   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8769
8770   vector< vector< TIntPntState > > allIntPnts( nbHP );
8771   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8772   {
8773     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8774     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8775
8776     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8777     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8778
8779     int nbNotOut = 0;
8780     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8781
8782     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8783     {
8784       if ( iHP1 == iHP2 ) continue;
8785
8786       TIntPntState & ips1 = intPnts1[ iHP2 ];
8787       if ( ips1.second == UNDEF )
8788       {
8789         // find an intersection point of boundaries of iHP1 and iHP2
8790
8791         if ( iHP2 == iPrev ) // intersection with neighbors is known
8792           ips1.first = halfPlns[ iHP1 ]._pos;
8793         else if ( iHP2 == iNext )
8794           ips1.first = halfPlns[ iHP2 ]._pos;
8795         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8796           ips1.second = NO_INT;
8797
8798         // classify the found intersection point
8799         if ( ips1.second != NO_INT )
8800         {
8801           ips1.second = NOT_OUT;
8802           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8803             if ( i != iHP1 && i != iHP2 &&
8804                  halfPlns[ i ].IsOut( ips1.first, tol ))
8805               ips1.second = IS_OUT;
8806         }
8807         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8808         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8809         TIntPntState & ips2 = intPnts2[ iHP1 ];
8810         ips2 = ips1;
8811       }
8812       if ( ips1.second == NOT_OUT )
8813       {
8814         ++nbNotOut;
8815         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8816       }
8817     }
8818
8819     // find a NOT_OUT segment of boundary which is located between
8820     // two NOT_OUT int points
8821
8822     if ( nbNotOut < 2 )
8823       continue; // no such a segment
8824
8825     if ( nbNotOut > 2 )
8826     {
8827       // sort points along the boundary
8828       map< double, TIntPntState* > ipsByParam;
8829       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8830       {
8831         TIntPntState & ips1 = intPnts1[ iHP2 ];
8832         if ( ips1.second != NO_INT )
8833         {
8834           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8835           double param = op * halfPlns[ iHP1 ]._dir;
8836           ipsByParam.insert( make_pair( param, & ips1 ));
8837         }
8838       }
8839       // look for two neighboring NOT_OUT points
8840       nbNotOut = 0;
8841       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8842       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8843       {
8844         TIntPntState & ips1 = *(u2ips->second);
8845         if ( ips1.second == NOT_OUT )
8846           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8847         else if ( nbNotOut >= 2 )
8848           break;
8849         else
8850           nbNotOut = 0;
8851       }
8852     }
8853
8854     if ( nbNotOut >= 2 )
8855     {
8856       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8857       sumLen += len;
8858
8859       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8860     }
8861   }
8862
8863   if ( sumLen > 0 )
8864   {
8865     newPos2D /= sumLen;
8866     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8867   }
8868   else
8869   {
8870     newPos = center;
8871   }
8872
8873   return newPos;
8874 }
8875 #endif // OLD_NEF_POLYGON
8876
8877 //================================================================================
8878 /*!
8879  * \brief Add a new segment to _LayerEdge during inflation
8880  */
8881 //================================================================================
8882
8883 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8884 {
8885   if ( Is( BLOCKED ))
8886     return;
8887
8888   if ( len > _maxLen )
8889   {
8890     len = _maxLen;
8891     Block( eos.GetData() );
8892   }
8893   const double lenDelta = len - _len;
8894   if ( lenDelta < len * 1e-3  )
8895   {
8896     Block( eos.GetData() );
8897     return;
8898   }
8899
8900   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8901   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8902   gp_XYZ newXYZ;
8903   if ( eos._hyp.IsOffsetMethod() )
8904   {
8905     newXYZ = oldXYZ;
8906     gp_Vec faceNorm;
8907     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8908     while ( faceIt->more() )
8909     {
8910       const SMDS_MeshElement* face = faceIt->next();
8911       if ( !eos.GetNormal( face, faceNorm ))
8912         continue;
8913
8914       // translate plane of a face
8915       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8916
8917       // find point of intersection of the face plane located at baryCenter
8918       // and _normal located at newXYZ
8919       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8920       double dot =  ( faceNorm.XYZ() * _normal );
8921       if ( dot < std::numeric_limits<double>::min() )
8922         dot = lenDelta * 1e-3;
8923       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8924       newXYZ += step * _normal;
8925     }
8926     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8927   }
8928   else
8929   {
8930     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8931   }
8932
8933   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8934   _pos.push_back( newXYZ );
8935
8936   if ( !eos._sWOL.IsNull() )
8937   {
8938     double distXYZ[4];
8939     bool uvOK = false;
8940     if ( eos.SWOLType() == TopAbs_EDGE )
8941     {
8942       double u = Precision::Infinite(); // to force projection w/o distance check
8943       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8944                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8945       _pos.back().SetCoord( u, 0, 0 );
8946       if ( _nodes.size() > 1 && uvOK )
8947       {
8948         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8949         pos->SetUParameter( u );
8950       }
8951     }
8952     else //  TopAbs_FACE
8953     {
8954       gp_XY uv( Precision::Infinite(), 0 );
8955       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8956                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8957       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8958       if ( _nodes.size() > 1 && uvOK )
8959       {
8960         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8961         pos->SetUParameter( uv.X() );
8962         pos->SetVParameter( uv.Y() );
8963       }
8964     }
8965     if ( uvOK )
8966     {
8967       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8968     }
8969     else
8970     {
8971       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8972       _pos.pop_back();
8973       Block( eos.GetData() );
8974       return;
8975     }
8976   }
8977
8978   _len = len;
8979
8980   // notify _neibors
8981   if ( eos.ShapeType() != TopAbs_FACE )
8982   {
8983     for ( size_t i = 0; i < _neibors.size(); ++i )
8984       //if (  _len > _neibors[i]->GetSmooLen() )
8985         _neibors[i]->Set( MOVED );
8986
8987     Set( MOVED );
8988   }
8989   dumpMove( n ); //debug
8990 }
8991
8992 //================================================================================
8993 /*!
8994  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8995  */
8996 //================================================================================
8997
8998 void _LayerEdge::Block( _SolidData& data )
8999 {
9000   //if ( Is( BLOCKED )) return;
9001   Set( BLOCKED );
9002
9003   _maxLen = _len;
9004   std::queue<_LayerEdge*> queue;
9005   queue.push( this );
9006
9007   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9008   while ( !queue.empty() )
9009   {
9010     _LayerEdge* edge = queue.front(); queue.pop();
9011     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9012     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9013     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9014     {
9015       _LayerEdge* neibor = edge->_neibors[iN];
9016       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9017         continue;
9018       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9019       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9020       double minDist = pSrc.SquareDistance( pSrcN );
9021       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9022       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9023       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9024       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9025       if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
9026       {
9027         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9028       }
9029       if ( neibor->_maxLen > newMaxLen )
9030       {
9031         neibor->_maxLen = newMaxLen;
9032         if ( neibor->_maxLen < neibor->_len )
9033         {
9034           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9035           while ( neibor->_len > neibor->_maxLen &&
9036                   neibor->NbSteps() > 1 )
9037             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9038           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9039           //neibor->Block( data );
9040         }
9041         queue.push( neibor );
9042       }
9043     }
9044   }
9045 }
9046
9047 //================================================================================
9048 /*!
9049  * \brief Remove last inflation step
9050  */
9051 //================================================================================
9052
9053 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9054 {
9055   if ( _pos.size() > curStep && _nodes.size() > 1 )
9056   {
9057     _pos.resize( curStep );
9058
9059     gp_Pnt      nXYZ = _pos.back();
9060     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9061     SMESH_TNodeXYZ curXYZ( n );
9062     if ( !eos._sWOL.IsNull() )
9063     {
9064       TopLoc_Location loc;
9065       if ( eos.SWOLType() == TopAbs_EDGE )
9066       {
9067         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9068         pos->SetUParameter( nXYZ.X() );
9069         double f,l;
9070         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9071         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9072       }
9073       else
9074       {
9075         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9076         pos->SetUParameter( nXYZ.X() );
9077         pos->SetVParameter( nXYZ.Y() );
9078         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9079         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9080       }
9081     }
9082     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9083     dumpMove( n );
9084
9085     if ( restoreLength )
9086     {
9087       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9088     }
9089   }
9090 }
9091
9092 //================================================================================
9093 /*!
9094  * \brief Return index of a _pos distant from _normal
9095  */
9096 //================================================================================
9097
9098 int _LayerEdge::GetSmoothedPos( const double tol )
9099 {
9100   int iSmoothed = 0;
9101   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9102   {
9103     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9104     if ( normDist > tol * tol )
9105       iSmoothed = i;
9106   }
9107   return iSmoothed;
9108 }
9109
9110 //================================================================================
9111 /*!
9112  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9113  */
9114 //================================================================================
9115
9116 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9117 {
9118   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9119     return;
9120
9121   // find the 1st smoothed _pos
9122   int iSmoothed = GetSmoothedPos( tol );
9123   if ( !iSmoothed ) return;
9124
9125   //if ( 1 || Is( DISTORTED ))
9126   {
9127     gp_XYZ normal = _normal;
9128     if ( Is( NORMAL_UPDATED ))
9129       for ( size_t i = 1; i < _pos.size(); ++i )
9130       {
9131         normal = _pos[i] - _pos[0];
9132         double size = normal.Modulus();
9133         if ( size > RealSmall() )
9134         {
9135           normal /= size;
9136           break;
9137         }
9138       }
9139     const double r = 0.2;
9140     for ( int iter = 0; iter < 50; ++iter )
9141     {
9142       double minDot = 1;
9143       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9144       {
9145         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9146         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9147         _pos[i] = newPos;
9148         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9149         double newLen = ( 1-r ) * midLen + r * segLen[i];
9150         const_cast< double& >( segLen[i] ) = newLen;
9151         // check angle between normal and (_pos[i+1], _pos[i] )
9152         gp_XYZ posDir = _pos[i+1] - _pos[i];
9153         double size   = posDir.SquareModulus();
9154         if ( size > RealSmall() )
9155           minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9156       }
9157       if ( minDot > 0.5 * 0.5 )
9158         break;
9159     }
9160   }
9161   // else
9162   // {
9163   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
9164   //   {
9165   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
9166   //       continue;
9167
9168   //     double     wgt = segLen[i] / segLen.back();
9169   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9170   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
9171   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
9172   //     _pos[i] = newPos;
9173   //   }
9174   // }
9175 }
9176
9177 //================================================================================
9178 /*!
9179  * \brief Create layers of prisms
9180  */
9181 //================================================================================
9182
9183 bool _ViscousBuilder::refine(_SolidData& data)
9184 {
9185   SMESH_MesherHelper& helper = data.GetHelper();
9186   helper.SetElementsOnShape(false);
9187
9188   Handle(Geom_Curve) curve;
9189   Handle(ShapeAnalysis_Surface) surface;
9190   TopoDS_Edge geomEdge;
9191   TopoDS_Face geomFace;
9192   TopLoc_Location loc;
9193   double f,l, u = 0;
9194   gp_XY uv;
9195   vector< gp_XYZ > pos3D;
9196   bool isOnEdge;
9197   TGeomID prevBaseId = -1;
9198   TNode2Edge* n2eMap = 0;
9199   TNode2Edge::iterator n2e;
9200
9201   // Create intermediate nodes on each _LayerEdge
9202
9203   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9204   {
9205     _EdgesOnShape& eos = data._edgesOnShape[iS];
9206     if ( eos._edges.empty() ) continue;
9207
9208     if ( eos._edges[0]->_nodes.size() < 2 )
9209       continue; // on _noShrinkShapes
9210
9211     // get data of a shrink shape
9212     isOnEdge = false;
9213     geomEdge.Nullify(); geomFace.Nullify();
9214     curve.Nullify(); surface.Nullify();
9215     if ( !eos._sWOL.IsNull() )
9216     {
9217       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9218       if ( isOnEdge )
9219       {
9220         geomEdge = TopoDS::Edge( eos._sWOL );
9221         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9222       }
9223       else
9224       {
9225         geomFace = TopoDS::Face( eos._sWOL );
9226         surface  = helper.GetSurface( geomFace );
9227       }
9228     }
9229     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9230     {
9231       geomFace = TopoDS::Face( eos._shape );
9232       surface  = helper.GetSurface( geomFace );
9233       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9234       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9235       {
9236         eos._eosC1[ i ]->_toSmooth = true;
9237         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9238           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9239       }
9240     }
9241
9242     vector< double > segLen;
9243     for ( size_t i = 0; i < eos._edges.size(); ++i )
9244     {
9245       _LayerEdge& edge = *eos._edges[i];
9246       if ( edge._pos.size() < 2 )
9247         continue;
9248
9249       // get accumulated length of segments
9250       segLen.resize( edge._pos.size() );
9251       segLen[0] = 0.0;
9252       if ( eos._sWOL.IsNull() )
9253       {
9254         bool useNormal = true;
9255         bool   usePos  = false;
9256         bool smoothed  = false;
9257         double   preci = 0.1 * edge._len;
9258         if ( eos._toSmooth && edge._pos.size() > 2 )
9259         {
9260           smoothed = edge.GetSmoothedPos( preci );
9261         }
9262         if ( smoothed )
9263         {
9264           if ( !surface.IsNull() &&
9265                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9266           {
9267             useNormal = usePos = false;
9268             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9269             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9270             {
9271               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9272               if ( surface->Gap() < 2. * edge._len )
9273                 segLen[j] = surface->Gap();
9274               else
9275                 useNormal = true;
9276             }
9277           }
9278         }
9279         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9280         {
9281 #ifndef __NODES_AT_POS
9282           useNormal = usePos = false;
9283           edge._pos[1] = edge._pos.back();
9284           edge._pos.resize( 2 );
9285           segLen.resize( 2 );
9286           segLen[ 1 ] = edge._len;
9287 #endif
9288         }
9289         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9290         {
9291           useNormal = usePos = false;
9292           _LayerEdge tmpEdge; // get original _normal
9293           tmpEdge._nodes.push_back( edge._nodes[0] );
9294           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9295             usePos = true;
9296           else
9297             for ( size_t j = 1; j < edge._pos.size(); ++j )
9298               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9299         }
9300         if ( useNormal )
9301         {
9302           for ( size_t j = 1; j < edge._pos.size(); ++j )
9303             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9304         }
9305         if ( usePos )
9306         {
9307           for ( size_t j = 1; j < edge._pos.size(); ++j )
9308             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9309         }
9310         else
9311         {
9312           bool swapped = ( edge._pos.size() > 2 );
9313           while ( swapped )
9314           {
9315             swapped = false;
9316             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9317               if ( segLen[j] > segLen.back() )
9318               {
9319                 segLen.erase( segLen.begin() + j );
9320                 edge._pos.erase( edge._pos.begin() + j );
9321                 --j;
9322               }
9323               else if ( segLen[j] < segLen[j-1] )
9324               {
9325                 std::swap( segLen[j], segLen[j-1] );
9326                 std::swap( edge._pos[j], edge._pos[j-1] );
9327                 swapped = true;
9328               }
9329           }
9330         }
9331         // smooth a path formed by edge._pos
9332 #ifndef __NODES_AT_POS
9333         if (( smoothed ) /*&&
9334             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9335           edge.SmoothPos( segLen, preci );
9336 #endif
9337       }
9338       else if ( eos._isRegularSWOL ) // usual SWOL
9339       {
9340         for ( size_t j = 1; j < edge._pos.size(); ++j )
9341           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9342       }
9343       else if ( !surface.IsNull() ) // SWOL surface with singularities
9344       {
9345         pos3D.resize( edge._pos.size() );
9346         for ( size_t j = 0; j < edge._pos.size(); ++j )
9347           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9348
9349         for ( size_t j = 1; j < edge._pos.size(); ++j )
9350           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9351       }
9352
9353       // allocate memory for new nodes if it is not yet refined
9354       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9355       if ( edge._nodes.size() == 2 )
9356       {
9357 #ifdef __NODES_AT_POS
9358         int nbNodes = edge._pos.size();
9359 #else
9360         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9361 #endif
9362         edge._nodes.resize( nbNodes, 0 );
9363         edge._nodes[1] = 0;
9364         edge._nodes.back() = tgtNode;
9365       }
9366       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9367       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9368       if ( baseShapeId != prevBaseId )
9369       {
9370         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9371         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9372         prevBaseId = baseShapeId;
9373       }
9374       _LayerEdge* edgeOnSameNode = 0;
9375       bool        useExistingPos = false;
9376       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9377       {
9378         edgeOnSameNode = n2e->second;
9379         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9380         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9381         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9382         if ( isOnEdge )
9383         {
9384           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9385           epos->SetUParameter( otherTgtPos.X() );
9386         }
9387         else
9388         {
9389           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9390           fpos->SetUParameter( otherTgtPos.X() );
9391           fpos->SetVParameter( otherTgtPos.Y() );
9392         }
9393       }
9394       // calculate height of the first layer
9395       double h0;
9396       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9397       const double f = eos._hyp.GetStretchFactor();
9398       const int    N = eos._hyp.GetNumberLayers();
9399       const double fPowN = pow( f, N );
9400       if ( fPowN - 1 <= numeric_limits<double>::min() )
9401         h0 = T / N;
9402       else
9403         h0 = T * ( f - 1 )/( fPowN - 1 );
9404
9405       const double zeroLen = std::numeric_limits<double>::min();
9406
9407       // create intermediate nodes
9408       double hSum = 0, hi = h0/f;
9409       size_t iSeg = 1;
9410       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9411       {
9412         // compute an intermediate position
9413         hi *= f;
9414         hSum += hi;
9415         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9416           ++iSeg;
9417         int iPrevSeg = iSeg-1;
9418         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9419           --iPrevSeg;
9420         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9421         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9422 #ifdef __NODES_AT_POS
9423         pos = edge._pos[ iStep ];
9424 #endif
9425         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9426         if ( !eos._sWOL.IsNull() )
9427         {
9428           // compute XYZ by parameters <pos>
9429           if ( isOnEdge )
9430           {
9431             u = pos.X();
9432             if ( !node )
9433               pos = curve->Value( u ).Transformed(loc);
9434           }
9435           else if ( eos._isRegularSWOL )
9436           {
9437             uv.SetCoord( pos.X(), pos.Y() );
9438             if ( !node )
9439               pos = surface->Value( pos.X(), pos.Y() );
9440           }
9441           else
9442           {
9443             uv.SetCoord( pos.X(), pos.Y() );
9444             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9445             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9446             if ( !node )
9447               pos = surface->Value( uv );
9448           }
9449         }
9450         // create or update the node
9451         if ( !node )
9452         {
9453           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9454           if ( !eos._sWOL.IsNull() )
9455           {
9456             if ( isOnEdge )
9457               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9458             else
9459               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9460           }
9461           else
9462           {
9463             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9464           }
9465         }
9466         else
9467         {
9468           if ( !eos._sWOL.IsNull() )
9469           {
9470             // make average pos from new and current parameters
9471             if ( isOnEdge )
9472             {
9473               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9474               if ( useExistingPos )
9475                 u = helper.GetNodeU( geomEdge, node );
9476               pos = curve->Value( u ).Transformed(loc);
9477
9478               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9479               epos->SetUParameter( u );
9480             }
9481             else
9482             {
9483               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9484               if ( useExistingPos )
9485                 uv = helper.GetNodeUV( geomFace, node );
9486               pos = surface->Value( uv );
9487
9488               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9489               fpos->SetUParameter( uv.X() );
9490               fpos->SetVParameter( uv.Y() );
9491             }
9492           }
9493           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9494         }
9495       } // loop on edge._nodes
9496
9497       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9498       {
9499         if ( isOnEdge )
9500           edge._pos.back().SetCoord( u, 0,0);
9501         else
9502           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9503
9504         if ( edgeOnSameNode )
9505           edgeOnSameNode->_pos.back() = edge._pos.back();
9506       }
9507
9508     } // loop on eos._edges to create nodes
9509
9510
9511     if ( !getMeshDS()->IsEmbeddedMode() )
9512       // Log node movement
9513       for ( size_t i = 0; i < eos._edges.size(); ++i )
9514       {
9515         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9516         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9517       }
9518   }
9519
9520
9521   // Create volumes
9522
9523   helper.SetElementsOnShape(true);
9524
9525   vector< vector<const SMDS_MeshNode*>* > nnVec;
9526   set< vector<const SMDS_MeshNode*>* >    nnSet;
9527   set< int >                       degenEdgeInd;
9528   vector<const SMDS_MeshElement*>     degenVols;
9529   vector<int>                       isRiskySWOL;
9530
9531   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9532   for ( ; exp.More(); exp.Next() )
9533   {
9534     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9535     if ( data._ignoreFaceIds.count( faceID ))
9536       continue;
9537     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9538     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9539     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9540     while ( fIt->more() )
9541     {
9542       const SMDS_MeshElement* face = fIt->next();
9543       const int            nbNodes = face->NbCornerNodes();
9544       nnVec.resize( nbNodes );
9545       nnSet.clear();
9546       degenEdgeInd.clear();
9547       isRiskySWOL.resize( nbNodes );
9548       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9549       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9550       for ( int iN = 0; iN < nbNodes; ++iN )
9551       {
9552         const SMDS_MeshNode* n = nIt->next();
9553         _LayerEdge*       edge = data._n2eMap[ n ];
9554         const int i = isReversedFace ? nbNodes-1-iN : iN;
9555         nnVec[ i ] = & edge->_nodes;
9556         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9557         minZ = std::min( minZ, nnVec[ i ]->size() );
9558         //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9559
9560         if ( helper.HasDegeneratedEdges() )
9561           nnSet.insert( nnVec[ i ]);
9562       }
9563
9564       if ( maxZ == 0 )
9565         continue;
9566       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9567         continue;
9568
9569       switch ( nbNodes )
9570       {
9571       case 3: // TRIA
9572       {
9573         // PENTA
9574         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9575           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9576                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9577
9578         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9579         {
9580           for ( int iN = 0; iN < nbNodes; ++iN )
9581             if ( nnVec[ iN ]->size() < iZ+1 )
9582               degenEdgeInd.insert( iN );
9583
9584           if ( degenEdgeInd.size() == 1 )  // PYRAM
9585           {
9586             int i2 = *degenEdgeInd.begin();
9587             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9588             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9589             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9590                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9591           }
9592           else  // TETRA
9593           {
9594             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9595             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9596                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9597                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9598                               (*nnVec[ i3 ])[ iZ ]);
9599           }
9600         }
9601         break; // TRIA
9602       }
9603       case 4: // QUAD
9604       {
9605         // HEX
9606         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9607           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9608                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9609                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9610                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9611
9612         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9613         {
9614           for ( int iN = 0; iN < nbNodes; ++iN )
9615             if ( nnVec[ iN ]->size() < iZ+1 )
9616               degenEdgeInd.insert( iN );
9617
9618           switch ( degenEdgeInd.size() )
9619           {
9620           case 2: // PENTA
9621           {
9622             int i2 = *degenEdgeInd.begin();
9623             int i3 = *degenEdgeInd.rbegin();
9624             bool ok = ( i3 - i2 == 1 );
9625             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9626             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9627             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9628
9629             const SMDS_MeshElement* vol =
9630               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9631                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9632             if ( !ok && vol )
9633               degenVols.push_back( vol );
9634           }
9635           break;
9636
9637           default: // degen HEX
9638           {
9639             const SMDS_MeshElement* vol =
9640               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9641                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9642                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9643                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9644                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9645                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9646                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9647                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9648             degenVols.push_back( vol );
9649           }
9650           }
9651         }
9652         break; // HEX
9653       }
9654       default:
9655         return error("Not supported type of element", data._index);
9656
9657       } // switch ( nbNodes )
9658     } // while ( fIt->more() )
9659   } // loop on FACEs
9660
9661   if ( !degenVols.empty() )
9662   {
9663     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9664     if ( !err || err->IsOK() )
9665     {
9666       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9667                                          "Degenerated volumes created" ));
9668       err->myBadElements.insert( err->myBadElements.end(),
9669                                  degenVols.begin(),degenVols.end() );
9670     }
9671   }
9672
9673   return true;
9674 }
9675
9676 //================================================================================
9677 /*!
9678  * \brief Shrink 2D mesh on faces to let space for inflated layers
9679  */
9680 //================================================================================
9681
9682 bool _ViscousBuilder::shrink(_SolidData& theData)
9683 {
9684   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
9685   // _LayerEdge's inflated along FACE or EDGE)
9686   map< TGeomID, list< _SolidData* > > f2sdMap;
9687   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9688   {
9689     _SolidData& data = _sdVec[i];
9690     TopTools_MapOfShape FFMap;
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         if ( &data == &theData && FFMap.Add( (*s2s).second ))
9698           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9699           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9700           // by StdMeshers_QuadToTriaAdaptor
9701           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9702           {
9703             SMESH_ProxyMesh::SubMesh* proxySub =
9704               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9705             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9706             while ( fIt->more() )
9707               proxySub->AddElement( fIt->next() );
9708             // as a result 3D algo will use elements from proxySub and not from smDS
9709           }
9710       }
9711   }
9712
9713   SMESH_MesherHelper helper( *_mesh );
9714   helper.ToFixNodeParameters( true );
9715
9716   // EDGEs to shrink
9717   map< TGeomID, _Shrinker1D > e2shrMap;
9718   vector< _EdgesOnShape* > subEOS;
9719   vector< _LayerEdge* > lEdges;
9720
9721   // loop on FACEs to srink mesh on
9722   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
9723   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9724   {
9725     list< _SolidData* > & dataList = f2sd->second;
9726     if ( dataList.front()->_n2eMap.empty() ||
9727          dataList.back() ->_n2eMap.empty() )
9728       continue; // not yet computed
9729     if ( dataList.front() != &theData &&
9730          dataList.back()  != &theData )
9731       continue;
9732
9733     _SolidData&      data = *dataList.front();
9734     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9735     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9736     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9737
9738     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
9739
9740     _shrinkedFaces.Add( F );
9741     helper.SetSubShape( F );
9742
9743     // ===========================
9744     // Prepare data for shrinking
9745     // ===========================
9746
9747     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
9748     // and hence all nodes on a FACE connected to 2d elements are to be smoothed
9749     vector < const SMDS_MeshNode* > smoothNodes;
9750     {
9751       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9752       while ( nIt->more() )
9753       {
9754         const SMDS_MeshNode* n = nIt->next();
9755         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
9756           smoothNodes.push_back( n );
9757       }
9758     }
9759     // Find out face orientation
9760     double refSign = 1;
9761     const set<TGeomID> ignoreShapes;
9762     bool isOkUV;
9763     if ( !smoothNodes.empty() )
9764     {
9765       vector<_Simplex> simplices;
9766       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9767       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
9768       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9769       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9770       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
9771         refSign = -1;
9772     }
9773
9774     // Find _LayerEdge's inflated along F
9775     subEOS.clear();
9776     lEdges.clear();
9777     {
9778       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9779                                                                 /*complexFirst=*/true); //!!!
9780       while ( subIt->more() )
9781       {
9782         const TGeomID subID = subIt->next()->GetId();
9783         if ( data._noShrinkShapes.count( subID ))
9784           continue;
9785         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9786         if ( !eos || eos->_sWOL.IsNull() ) continue;
9787
9788         subEOS.push_back( eos );
9789
9790         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9791         {
9792           lEdges.push_back( eos->_edges[ i ] );
9793           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9794         }
9795       }
9796     }
9797
9798     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9799     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9800     while ( fIt->more() )
9801       if ( const SMDS_MeshElement* f = fIt->next() )
9802         dumpChangeNodes( f );
9803     dumpFunctionEnd();
9804
9805     // Replace source nodes by target nodes in mesh faces to shrink
9806     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9807     const SMDS_MeshNode* nodes[20];
9808     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9809     {
9810       _EdgesOnShape& eos = * subEOS[ iS ];
9811       for ( size_t i = 0; i < eos._edges.size(); ++i )
9812       {
9813         _LayerEdge& edge = *eos._edges[i];
9814         const SMDS_MeshNode* srcNode = edge._nodes[0];
9815         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9816         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9817         while ( fIt->more() )
9818         {
9819           const SMDS_MeshElement* f = fIt->next();
9820           if ( !smDS->Contains( f ))
9821             continue;
9822           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9823           for ( int iN = 0; nIt->more(); ++iN )
9824           {
9825             const SMDS_MeshNode* n = nIt->next();
9826             nodes[iN] = ( n == srcNode ? tgtNode : n );
9827           }
9828           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9829           dumpChangeNodes( f );
9830         }
9831       }
9832     }
9833     dumpFunctionEnd();
9834
9835     // find out if a FACE is concave
9836     const bool isConcaveFace = isConcave( F, helper );
9837
9838     // Create _SmoothNode's on face F
9839     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9840     {
9841       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9842       const bool sortSimplices = isConcaveFace;
9843       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9844       {
9845         const SMDS_MeshNode* n = smoothNodes[i];
9846         nodesToSmooth[ i ]._node = n;
9847         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9848         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9849         // fix up incorrect uv of nodes on the FACE
9850         helper.GetNodeUV( F, n, 0, &isOkUV);
9851         dumpMove( n );
9852       }
9853       dumpFunctionEnd();
9854     }
9855     //if ( nodesToSmooth.empty() ) continue;
9856
9857     // Find EDGE's to shrink and set simpices to LayerEdge's
9858     set< _Shrinker1D* > eShri1D;
9859     {
9860       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9861       {
9862         _EdgesOnShape& eos = * subEOS[ iS ];
9863         if ( eos.SWOLType() == TopAbs_EDGE )
9864         {
9865           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9866           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9867           eShri1D.insert( & srinker );
9868           srinker.AddEdge( eos._edges[0], eos, helper );
9869           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9870           // restore params of nodes on EGDE if the EDGE has been already
9871           // srinked while srinking other FACE
9872           srinker.RestoreParams();
9873         }
9874         for ( size_t i = 0; i < eos._edges.size(); ++i )
9875         {
9876           _LayerEdge& edge = * eos._edges[i];
9877           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9878         }
9879       }
9880     }
9881
9882     bool toFixTria = false; // to improve quality of trias by diagonal swap
9883     if ( isConcaveFace )
9884     {
9885       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9886       if ( hasTria != hasQuad ) {
9887         toFixTria = hasTria;
9888       }
9889       else {
9890         set<int> nbNodesSet;
9891         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9892         while ( fIt->more() && nbNodesSet.size() < 2 )
9893           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9894         toFixTria = ( *nbNodesSet.begin() == 3 );
9895       }
9896     }
9897
9898     // ==================
9899     // Perform shrinking
9900     // ==================
9901
9902     bool shrinked = true;
9903     int nbBad, shriStep=0, smooStep=0;
9904     _SmoothNode::SmoothType smoothType
9905       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9906     SMESH_Comment errMsg;
9907     while ( shrinked )
9908     {
9909       shriStep++;
9910       // Move boundary nodes (actually just set new UV)
9911       // -----------------------------------------------
9912       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9913       shrinked = false;
9914       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9915       {
9916         _EdgesOnShape& eos = * subEOS[ iS ];
9917         for ( size_t i = 0; i < eos._edges.size(); ++i )
9918         {
9919           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9920         }
9921       }
9922       dumpFunctionEnd();
9923
9924       // Move nodes on EDGE's
9925       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9926       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9927       for ( ; shr != eShri1D.end(); ++shr )
9928         (*shr)->Compute( /*set3D=*/false, helper );
9929
9930       // Smoothing in 2D
9931       // -----------------
9932       int nbNoImpSteps = 0;
9933       bool       moved = true;
9934       nbBad = 1;
9935       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9936       {
9937         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9938
9939         int oldBadNb = nbBad;
9940         nbBad = 0;
9941         moved = false;
9942         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9943         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9944         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9945         {
9946           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9947                                             smooTy, /*set3D=*/isConcaveFace);
9948         }
9949         if ( nbBad < oldBadNb )
9950           nbNoImpSteps = 0;
9951         else
9952           nbNoImpSteps++;
9953
9954         dumpFunctionEnd();
9955       }
9956
9957       errMsg.clear();
9958       if ( nbBad > 0 )
9959         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9960       if ( shriStep > 200 )
9961         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9962       if ( !errMsg.empty() )
9963         break;
9964
9965       // Fix narrow triangles by swapping diagonals
9966       // ---------------------------------------
9967       if ( toFixTria )
9968       {
9969         set<const SMDS_MeshNode*> usedNodes;
9970         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9971
9972         // update working data
9973         set<const SMDS_MeshNode*>::iterator n;
9974         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9975         {
9976           n = usedNodes.find( nodesToSmooth[ i ]._node );
9977           if ( n != usedNodes.end())
9978           {
9979             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9980                                     nodesToSmooth[ i ]._simplices,
9981                                     ignoreShapes, NULL,
9982                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
9983             usedNodes.erase( n );
9984           }
9985         }
9986         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
9987         {
9988           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
9989           if ( n != usedNodes.end())
9990           {
9991             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
9992                                     lEdges[i]->_simplices,
9993                                     ignoreShapes );
9994             usedNodes.erase( n );
9995           }
9996         }
9997       }
9998       // TODO: check effect of this additional smooth
9999       // additional laplacian smooth to increase allowed shrink step
10000       // for ( int st = 1; st; --st )
10001       // {
10002       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10003       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10004       //   {
10005       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10006       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
10007       //   }
10008       // }
10009
10010     } // while ( shrinked )
10011
10012     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10013     {
10014       // remove faces
10015       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10016       {
10017         vector< const SMDS_MeshElement* > facesToRm;
10018         if ( psm )
10019         {
10020           facesToRm.reserve( psm->NbElements() );
10021           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10022             facesToRm.push_back( ite->next() );
10023
10024           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10025             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10026               psm->Clear();
10027         }
10028         for ( size_t i = 0; i < facesToRm.size(); ++i )
10029           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10030       }
10031       // remove nodes
10032       {
10033         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10034         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10035           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10036             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10037                                 subEOS[iS]->_edges[i]->_nodes.end() );
10038         }
10039         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10040         while ( itn->more() ) {
10041           const SMDS_MeshNode* n = itn->next();
10042           if ( !nodesToKeep.count( n ))
10043             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10044         }
10045       }
10046       // restore position and UV of target nodes
10047       gp_Pnt p;
10048       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10049         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10050         {
10051           _LayerEdge*       edge = subEOS[iS]->_edges[i];
10052           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10053           if ( edge->_pos.empty() ) continue;
10054           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10055           {
10056             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10057             pos->SetUParameter( edge->_pos[0].X() );
10058             pos->SetVParameter( edge->_pos[0].Y() );
10059             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10060           }
10061           else
10062           {
10063             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10064             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10065             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10066           }
10067           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10068           dumpMove( tgtNode );
10069         }
10070       // shrink EDGE sub-meshes and set proxy sub-meshes
10071       UVPtStructVec uvPtVec;
10072       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10073       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10074       {
10075         _Shrinker1D* shr = (*shrIt);
10076         shr->Compute( /*set3D=*/true, helper );
10077
10078         // set proxy mesh of EDGEs w/o layers
10079         map< double, const SMDS_MeshNode* > nodes;
10080         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10081         // remove refinement nodes
10082         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10083         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10084         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10085         if ( u2n->second == sn0 || u2n->second == sn1 )
10086         {
10087           while ( u2n->second != tn0 && u2n->second != tn1 )
10088             ++u2n;
10089           nodes.erase( nodes.begin(), u2n );
10090         }
10091         u2n = --nodes.end();
10092         if ( u2n->second == sn0 || u2n->second == sn1 )
10093         {
10094           while ( u2n->second != tn0 && u2n->second != tn1 )
10095             --u2n;
10096           nodes.erase( ++u2n, nodes.end() );
10097         }
10098         // set proxy sub-mesh
10099         uvPtVec.resize( nodes.size() );
10100         u2n = nodes.begin();
10101         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10102         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10103         {
10104           uvPtVec[ i ].node = u2n->second;
10105           uvPtVec[ i ].param = u2n->first;
10106           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10107         }
10108         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10109         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10110       }
10111
10112       // set proxy mesh of EDGEs with layers
10113       vector< _LayerEdge* > edges;
10114       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10115       {
10116         _EdgesOnShape& eos = * subEOS[ iS ];
10117         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10118
10119         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10120         data.SortOnEdge( E, eos._edges );
10121
10122         edges.clear();
10123         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10124           if ( !eov->_edges.empty() )
10125             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10126
10127         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10128
10129         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10130           if ( !eov->_edges.empty() )
10131             edges.push_back( eov->_edges[0] ); // on last VERTEX
10132
10133         uvPtVec.resize( edges.size() );
10134         for ( size_t i = 0; i < edges.size(); ++i )
10135         {
10136           uvPtVec[ i ].node = edges[i]->_nodes.back();
10137           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10138           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10139         }
10140         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10141         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10142         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10143       }
10144       // temporary clear the FACE sub-mesh from faces made by refine()
10145       vector< const SMDS_MeshElement* > elems;
10146       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10147       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10148         elems.push_back( ite->next() );
10149       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10150         elems.push_back( ite->next() );
10151       smDS->Clear();
10152
10153       // compute the mesh on the FACE
10154       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10155       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10156
10157       // re-fill proxy sub-meshes of the FACE
10158       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10159         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10160           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10161             psm->AddElement( ite->next() );
10162
10163       // re-fill smDS
10164       for ( size_t i = 0; i < elems.size(); ++i )
10165         smDS->AddElement( elems[i] );
10166
10167       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10168         return error( errMsg );
10169
10170     } // end of re-meshing in case of failed smoothing
10171     else
10172     {
10173       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10174       bool isStructuredFixed = false;
10175       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10176         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10177       if ( !isStructuredFixed )
10178       {
10179         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10180           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10181
10182         for ( int st = 3; st; --st )
10183         {
10184           switch( st ) {
10185           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10186           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10187           case 3: smoothType = _SmoothNode::ANGULAR; break;
10188           }
10189           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10190           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10191           {
10192             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10193                                      smoothType,/*set3D=*/st==1 );
10194           }
10195           dumpFunctionEnd();
10196         }
10197       }
10198       if ( !getMeshDS()->IsEmbeddedMode() )
10199         // Log node movement
10200         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10201         {
10202           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10203           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10204         }
10205     }
10206
10207     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10208     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10209
10210   } // loop on FACES to srink mesh on
10211
10212
10213   // Replace source nodes by target nodes in shrinked mesh edges
10214
10215   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10216   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10217     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10218
10219   return true;
10220 }
10221
10222 //================================================================================
10223 /*!
10224  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10225  */
10226 //================================================================================
10227
10228 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10229                                            _EdgesOnShape&         eos,
10230                                            SMESH_MesherHelper&    helper,
10231                                            const SMESHDS_SubMesh* faceSubMesh)
10232 {
10233   const SMDS_MeshNode* srcNode = edge._nodes[0];
10234   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10235
10236   if ( eos.SWOLType() == TopAbs_FACE )
10237   {
10238     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10239     {
10240       edge._pos.clear();
10241       return srcNode == tgtNode;
10242     }
10243     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10244     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10245     gp_Vec2d uvDir( srcUV, tgtUV );
10246     double uvLen = uvDir.Magnitude();
10247     uvDir /= uvLen;
10248     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10249     edge._len = uvLen;
10250
10251     edge._pos.resize(1);
10252     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10253
10254     // set UV of source node to target node
10255     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10256     pos->SetUParameter( srcUV.X() );
10257     pos->SetVParameter( srcUV.Y() );
10258   }
10259   else // _sWOL is TopAbs_EDGE
10260   {
10261     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10262     {
10263       edge._pos.clear();
10264       return srcNode == tgtNode;
10265     }
10266     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10267     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10268     if ( !edgeSM || edgeSM->NbElements() == 0 )
10269       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10270
10271     const SMDS_MeshNode* n2 = 0;
10272     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10273     while ( eIt->more() && !n2 )
10274     {
10275       const SMDS_MeshElement* e = eIt->next();
10276       if ( !edgeSM->Contains(e)) continue;
10277       n2 = e->GetNode( 0 );
10278       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10279     }
10280     if ( !n2 )
10281       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10282
10283     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10284     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10285     double u2   = helper.GetNodeU( E, n2, srcNode );
10286
10287     edge._pos.clear();
10288
10289     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10290     {
10291       // tgtNode is located so that it does not make faces with wrong orientation
10292       return true;
10293     }
10294     edge._pos.resize(1);
10295     edge._pos[0].SetCoord( U_TGT, uTgt );
10296     edge._pos[0].SetCoord( U_SRC, uSrc );
10297     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10298
10299     edge._simplices.resize( 1 );
10300     edge._simplices[0]._nPrev = n2;
10301
10302     // set U of source node to the target node
10303     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10304     pos->SetUParameter( uSrc );
10305   }
10306   return true;
10307 }
10308
10309 //================================================================================
10310 /*!
10311  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10312  */
10313 //================================================================================
10314
10315 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10316 {
10317   if ( edge._nodes.size() == 1 )
10318   {
10319     edge._pos.clear();
10320     edge._len = 0;
10321
10322     const SMDS_MeshNode* srcNode = edge._nodes[0];
10323     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10324     if ( S.IsNull() ) return;
10325
10326     gp_Pnt p;
10327
10328     switch ( S.ShapeType() )
10329     {
10330     case TopAbs_EDGE:
10331     {
10332       double f,l;
10333       TopLoc_Location loc;
10334       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10335       if ( curve.IsNull() ) return;
10336       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10337       p = curve->Value( ePos->GetUParameter() );
10338       break;
10339     }
10340     case TopAbs_VERTEX:
10341     {
10342       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10343       break;
10344     }
10345     default: return;
10346     }
10347     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10348     dumpMove( srcNode );
10349   }
10350 }
10351
10352 //================================================================================
10353 /*!
10354  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10355  */
10356 //================================================================================
10357
10358 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10359                                   SMESH_MesherHelper&         helper,
10360                                   const bool                  is2D,
10361                                   const int                   step,
10362                                   set<const SMDS_MeshNode*> * involvedNodes)
10363 {
10364   SMESH::Controls::AspectRatio qualifier;
10365   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10366   const double maxAspectRatio = is2D ? 4. : 2;
10367   _NodeCoordHelper xyz( F, helper, is2D );
10368
10369   // find bad triangles
10370
10371   vector< const SMDS_MeshElement* > badTrias;
10372   vector< double >                  badAspects;
10373   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10374   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10375   while ( fIt->more() )
10376   {
10377     const SMDS_MeshElement * f = fIt->next();
10378     if ( f->NbCornerNodes() != 3 ) continue;
10379     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10380     double aspect = qualifier.GetValue( points );
10381     if ( aspect > maxAspectRatio )
10382     {
10383       badTrias.push_back( f );
10384       badAspects.push_back( aspect );
10385     }
10386   }
10387   if ( step == 1 )
10388   {
10389     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10390     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10391     while ( fIt->more() )
10392     {
10393       const SMDS_MeshElement * f = fIt->next();
10394       if ( f->NbCornerNodes() == 3 )
10395         dumpChangeNodes( f );
10396     }
10397     dumpFunctionEnd();
10398   }
10399   if ( badTrias.empty() )
10400     return;
10401
10402   // find couples of faces to swap diagonal
10403
10404   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10405   vector< T2Trias > triaCouples; 
10406
10407   TIDSortedElemSet involvedFaces, emptySet;
10408   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10409   {
10410     T2Trias trias    [3];
10411     double  aspRatio [3];
10412     int i1, i2, i3;
10413
10414     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10415       continue;
10416     for ( int iP = 0; iP < 3; ++iP )
10417       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10418
10419     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10420     int bestCouple = -1;
10421     for ( int iSide = 0; iSide < 3; ++iSide )
10422     {
10423       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10424       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10425       trias [iSide].first  = badTrias[iTia];
10426       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10427                                                              & i1, & i2 );
10428       if (( ! trias[iSide].second ) ||
10429           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10430           ( ! sm->Contains( trias[iSide].second )))
10431         continue;
10432
10433       // aspect ratio of an adjacent tria
10434       for ( int iP = 0; iP < 3; ++iP )
10435         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10436       double aspectInit = qualifier.GetValue( points2 );
10437
10438       // arrange nodes as after diag-swaping
10439       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10440         i3 = helper.WrapIndex( i1-1, 3 );
10441       else
10442         i3 = helper.WrapIndex( i1+1, 3 );
10443       points1 = points;
10444       points1( 1+ iSide ) = points2( 1+ i3 );
10445       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10446
10447       // aspect ratio after diag-swaping
10448       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10449       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10450         continue;
10451
10452       // prevent inversion of a triangle
10453       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10454       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10455       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10456         continue;
10457
10458       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10459         bestCouple = iSide;
10460     }
10461
10462     if ( bestCouple >= 0 )
10463     {
10464       triaCouples.push_back( trias[bestCouple] );
10465       involvedFaces.insert ( trias[bestCouple].second );
10466     }
10467     else
10468     {
10469       involvedFaces.erase( badTrias[iTia] );
10470     }
10471   }
10472   if ( triaCouples.empty() )
10473     return;
10474
10475   // swap diagonals
10476
10477   SMESH_MeshEditor editor( helper.GetMesh() );
10478   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10479   for ( size_t i = 0; i < triaCouples.size(); ++i )
10480   {
10481     dumpChangeNodes( triaCouples[i].first );
10482     dumpChangeNodes( triaCouples[i].second );
10483     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10484   }
10485
10486   if ( involvedNodes )
10487     for ( size_t i = 0; i < triaCouples.size(); ++i )
10488     {
10489       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10490                              triaCouples[i].first->end_nodes() );
10491       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10492                              triaCouples[i].second->end_nodes() );
10493     }
10494
10495   // just for debug dump resulting triangles
10496   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10497   for ( size_t i = 0; i < triaCouples.size(); ++i )
10498   {
10499     dumpChangeNodes( triaCouples[i].first );
10500     dumpChangeNodes( triaCouples[i].second );
10501   }
10502 }
10503
10504 //================================================================================
10505 /*!
10506  * \brief Move target node to it's final position on the FACE during shrinking
10507  */
10508 //================================================================================
10509
10510 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10511                                  const TopoDS_Face&    F,
10512                                  _EdgesOnShape&        eos,
10513                                  SMESH_MesherHelper&   helper )
10514 {
10515   if ( _pos.empty() )
10516     return false; // already at the target position
10517
10518   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10519
10520   if ( eos.SWOLType() == TopAbs_FACE )
10521   {
10522     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10523     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10524     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10525     const double uvLen = tgtUV.Distance( curUV );
10526     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10527
10528     // Select shrinking step such that not to make faces with wrong orientation.
10529     double stepSize = 1e100;
10530     for ( size_t i = 0; i < _simplices.size(); ++i )
10531     {
10532       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10533       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10534       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10535       gp_XY dirN = uvN2 - uvN1;
10536       double det = uvDir.Crossed( dirN );
10537       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10538       gp_XY dirN2Cur = curUV - uvN1;
10539       double step = dirN.Crossed( dirN2Cur ) / det;
10540       if ( step > 0 )
10541         stepSize = Min( step, stepSize );
10542     }
10543     gp_Pnt2d newUV;
10544     if ( uvLen <= stepSize )
10545     {
10546       newUV = tgtUV;
10547       _pos.clear();
10548     }
10549     else if ( stepSize > 0 )
10550     {
10551       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10552     }
10553     else
10554     {
10555       return true;
10556     }
10557     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10558     pos->SetUParameter( newUV.X() );
10559     pos->SetVParameter( newUV.Y() );
10560
10561 #ifdef __myDEBUG
10562     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10563     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10564     dumpMove( tgtNode );
10565 #endif
10566   }
10567   else // _sWOL is TopAbs_EDGE
10568   {
10569     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10570     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10571     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10572
10573     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10574     const double uSrc   = _pos[0].Coord( U_SRC );
10575     const double lenTgt = _pos[0].Coord( LEN_TGT );
10576
10577     double newU = _pos[0].Coord( U_TGT );
10578     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10579     {
10580       _pos.clear();
10581     }
10582     else
10583     {
10584       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10585     }
10586     tgtPos->SetUParameter( newU );
10587 #ifdef __myDEBUG
10588     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10589     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10590     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10591     dumpMove( tgtNode );
10592 #endif
10593   }
10594
10595   return true;
10596 }
10597
10598 //================================================================================
10599 /*!
10600  * \brief Perform smooth on the FACE
10601  *  \retval bool - true if the node has been moved
10602  */
10603 //================================================================================
10604
10605 bool _SmoothNode::Smooth(int&                  nbBad,
10606                          Handle(Geom_Surface)& surface,
10607                          SMESH_MesherHelper&   helper,
10608                          const double          refSign,
10609                          SmoothType            how,
10610                          bool                  set3D)
10611 {
10612   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10613
10614   // get uv of surrounding nodes
10615   vector<gp_XY> uv( _simplices.size() );
10616   for ( size_t i = 0; i < _simplices.size(); ++i )
10617     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10618
10619   // compute new UV for the node
10620   gp_XY newPos (0,0);
10621   if ( how == TFI && _simplices.size() == 4 )
10622   {
10623     gp_XY corners[4];
10624     for ( size_t i = 0; i < _simplices.size(); ++i )
10625       if ( _simplices[i]._nOpp )
10626         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10627       else
10628         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10629
10630     newPos = helper.calcTFI ( 0.5, 0.5,
10631                               corners[0], corners[1], corners[2], corners[3],
10632                               uv[1], uv[2], uv[3], uv[0] );
10633   }
10634   else if ( how == ANGULAR )
10635   {
10636     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10637   }
10638   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10639   {
10640     // average centers of diagonals wieghted with their reciprocal lengths
10641     if ( _simplices.size() == 4 )
10642     {
10643       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10644       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10645       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10646     }
10647     else
10648     {
10649       double sumWeight = 0;
10650       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10651       for ( int i = 0; i < nb; ++i )
10652       {
10653         int iFrom = i + 2;
10654         int iTo   = i + _simplices.size() - 1;
10655         for ( int j = iFrom; j < iTo; ++j )
10656         {
10657           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10658           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10659           sumWeight += w;
10660           newPos += w * ( uv[i]+uv[i2] );
10661         }
10662       }
10663       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10664     }
10665   }
10666   else
10667   {
10668     // Laplacian smooth
10669     for ( size_t i = 0; i < _simplices.size(); ++i )
10670       newPos += uv[i];
10671     newPos /= _simplices.size();
10672   }
10673
10674   // count quality metrics (orientation) of triangles around the node
10675   int nbOkBefore = 0;
10676   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10677   for ( size_t i = 0; i < _simplices.size(); ++i )
10678     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10679
10680   int nbOkAfter = 0;
10681   for ( size_t i = 0; i < _simplices.size(); ++i )
10682     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10683
10684   if ( nbOkAfter < nbOkBefore )
10685   {
10686     nbBad += _simplices.size() - nbOkBefore;
10687     return false;
10688   }
10689
10690   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10691   pos->SetUParameter( newPos.X() );
10692   pos->SetVParameter( newPos.Y() );
10693
10694 #ifdef __myDEBUG
10695   set3D = true;
10696 #endif
10697   if ( set3D )
10698   {
10699     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10700     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10701     dumpMove( _node );
10702   }
10703
10704   nbBad += _simplices.size() - nbOkAfter;
10705   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10706 }
10707
10708 //================================================================================
10709 /*!
10710  * \brief Computes new UV using angle based smoothing technic
10711  */
10712 //================================================================================
10713
10714 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10715                                      const gp_XY&   uvToFix,
10716                                      const double   refSign)
10717 {
10718   uv.push_back( uv.front() );
10719
10720   vector< gp_XY >  edgeDir ( uv.size() );
10721   vector< double > edgeSize( uv.size() );
10722   for ( size_t i = 1; i < edgeDir.size(); ++i )
10723   {
10724     edgeDir [i-1] = uv[i] - uv[i-1];
10725     edgeSize[i-1] = edgeDir[i-1].Modulus();
10726     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10727       edgeDir[i-1].SetX( 100 );
10728     else
10729       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10730   }
10731   edgeDir.back()  = edgeDir.front();
10732   edgeSize.back() = edgeSize.front();
10733
10734   gp_XY  newPos(0,0);
10735   //int    nbEdges = 0;
10736   double sumSize = 0;
10737   for ( size_t i = 1; i < edgeDir.size(); ++i )
10738   {
10739     if ( edgeDir[i-1].X() > 1. ) continue;
10740     int i1 = i-1;
10741     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10742     if ( i == edgeDir.size() ) break;
10743     gp_XY p = uv[i];
10744     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10745     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10746     gp_XY bisec = norm1 + norm2;
10747     double bisecSize = bisec.Modulus();
10748     if ( bisecSize < numeric_limits<double>::min() )
10749     {
10750       bisec = -edgeDir[i1] + edgeDir[i];
10751       bisecSize = bisec.Modulus();
10752     }
10753     bisec /= bisecSize;
10754
10755     gp_XY  dirToN  = uvToFix - p;
10756     double distToN = dirToN.Modulus();
10757     if ( bisec * dirToN < 0 )
10758       distToN = -distToN;
10759
10760     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10761     //++nbEdges;
10762     sumSize += edgeSize[i1] + edgeSize[i];
10763   }
10764   newPos /= /*nbEdges * */sumSize;
10765   return newPos;
10766 }
10767
10768 //================================================================================
10769 /*!
10770  * \brief Delete _SolidData
10771  */
10772 //================================================================================
10773
10774 _SolidData::~_SolidData()
10775 {
10776   TNode2Edge::iterator n2e = _n2eMap.begin();
10777   for ( ; n2e != _n2eMap.end(); ++n2e )
10778   {
10779     _LayerEdge* & e = n2e->second;
10780     if ( e )
10781     {
10782       delete e->_curvature;
10783       if ( e->_2neibors )
10784         delete e->_2neibors->_plnNorm;
10785       delete e->_2neibors;
10786     }
10787     delete e;
10788     e = 0;
10789   }
10790   _n2eMap.clear();
10791
10792   delete _helper;
10793   _helper = 0;
10794 }
10795
10796 //================================================================================
10797 /*!
10798  * \brief Keep a _LayerEdge inflated along the EDGE
10799  */
10800 //================================================================================
10801
10802 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10803                            _EdgesOnShape&      eos,
10804                            SMESH_MesherHelper& helper )
10805 {
10806   // init
10807   if ( _nodes.empty() )
10808   {
10809     _edges[0] = _edges[1] = 0;
10810     _done = false;
10811   }
10812   // check _LayerEdge
10813   if ( e == _edges[0] || e == _edges[1] )
10814     return;
10815   if ( eos.SWOLType() != TopAbs_EDGE )
10816     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10817   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10818     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10819
10820   // store _LayerEdge
10821   _geomEdge = TopoDS::Edge( eos._sWOL );
10822   double f,l;
10823   BRep_Tool::Range( _geomEdge, f,l );
10824   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10825   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10826
10827   // Update _nodes
10828
10829   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10830   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10831
10832   if ( _nodes.empty() )
10833   {
10834     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10835     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10836       return;
10837     TopLoc_Location loc;
10838     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10839     GeomAdaptor_Curve aCurve(C, f,l);
10840     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10841
10842     int nbExpectNodes = eSubMesh->NbNodes();
10843     _initU  .reserve( nbExpectNodes );
10844     _normPar.reserve( nbExpectNodes );
10845     _nodes  .reserve( nbExpectNodes );
10846     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10847     while ( nIt->more() )
10848     {
10849       const SMDS_MeshNode* node = nIt->next();
10850       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10851            node == tgtNode0 || node == tgtNode1 )
10852         continue; // refinement nodes
10853       _nodes.push_back( node );
10854       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10855       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10856       _normPar.push_back(  len / totLen );
10857     }
10858   }
10859   else
10860   {
10861     // remove target node of the _LayerEdge from _nodes
10862     size_t nbFound = 0;
10863     for ( size_t i = 0; i < _nodes.size(); ++i )
10864       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10865         _nodes[i] = 0, nbFound++;
10866     if ( nbFound == _nodes.size() )
10867       _nodes.clear();
10868   }
10869 }
10870
10871 //================================================================================
10872 /*!
10873  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10874  */
10875 //================================================================================
10876
10877 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10878 {
10879   if ( _done || _nodes.empty())
10880     return;
10881   const _LayerEdge* e = _edges[0];
10882   if ( !e ) e = _edges[1];
10883   if ( !e ) return;
10884
10885   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
10886             ( !_edges[1] || _edges[1]->_pos.empty() ));
10887
10888   double f,l;
10889   if ( set3D || _done )
10890   {
10891     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10892     GeomAdaptor_Curve aCurve(C, f,l);
10893
10894     if ( _edges[0] )
10895       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10896     if ( _edges[1] )
10897       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10898     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10899
10900     for ( size_t i = 0; i < _nodes.size(); ++i )
10901     {
10902       if ( !_nodes[i] ) continue;
10903       double len = totLen * _normPar[i];
10904       GCPnts_AbscissaPoint discret( aCurve, len, f );
10905       if ( !discret.IsDone() )
10906         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10907       double u = discret.Parameter();
10908       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10909       pos->SetUParameter( u );
10910       gp_Pnt p = C->Value( u );
10911       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10912     }
10913   }
10914   else
10915   {
10916     BRep_Tool::Range( _geomEdge, f,l );
10917     if ( _edges[0] )
10918       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10919     if ( _edges[1] )
10920       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10921     
10922     for ( size_t i = 0; i < _nodes.size(); ++i )
10923     {
10924       if ( !_nodes[i] ) continue;
10925       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10926       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10927       pos->SetUParameter( u );
10928     }
10929   }
10930 }
10931
10932 //================================================================================
10933 /*!
10934  * \brief Restore initial parameters of nodes on EDGE
10935  */
10936 //================================================================================
10937
10938 void _Shrinker1D::RestoreParams()
10939 {
10940   if ( _done )
10941     for ( size_t i = 0; i < _nodes.size(); ++i )
10942     {
10943       if ( !_nodes[i] ) continue;
10944       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10945       pos->SetUParameter( _initU[i] );
10946     }
10947   _done = false;
10948 }
10949
10950 //================================================================================
10951 /*!
10952  * \brief Replace source nodes by target nodes in shrinked mesh edges
10953  */
10954 //================================================================================
10955
10956 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10957 {
10958   const SMDS_MeshNode* nodes[3];
10959   for ( int i = 0; i < 2; ++i )
10960   {
10961     if ( !_edges[i] ) continue;
10962
10963     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
10964     if ( !eSubMesh ) return;
10965     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
10966     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
10967     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10968     while ( eIt->more() )
10969     {
10970       const SMDS_MeshElement* e = eIt->next();
10971       if ( !eSubMesh->Contains( e ))
10972           continue;
10973       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
10974       for ( int iN = 0; iN < e->NbNodes(); ++iN )
10975       {
10976         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
10977         nodes[iN] = ( n == srcNode ? tgtNode : n );
10978       }
10979       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
10980     }
10981   }
10982 }
10983
10984 //================================================================================
10985 /*!
10986  * \brief Creates 2D and 1D elements on boundaries of new prisms
10987  */
10988 //================================================================================
10989
10990 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
10991 {
10992   SMESH_MesherHelper helper( *_mesh );
10993
10994   vector< const SMDS_MeshNode* > faceNodes;
10995
10996   //for ( size_t i = 0; i < _sdVec.size(); ++i )
10997   {
10998     //_SolidData& data = _sdVec[i];
10999     TopTools_IndexedMapOfShape geomEdges;
11000     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11001     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11002     {
11003       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11004       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
11005         continue;
11006
11007       // Get _LayerEdge's based on E
11008
11009       map< double, const SMDS_MeshNode* > u2nodes;
11010       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11011         continue;
11012
11013       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11014       TNode2Edge & n2eMap = data._n2eMap;
11015       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11016       {
11017         //check if 2D elements are needed on E
11018         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11019         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11020         ledges.push_back( n2e->second );
11021         u2n++;
11022         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11023           continue; // no layers on E
11024         ledges.push_back( n2eMap[ u2n->second ]);
11025
11026         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11027         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11028         int nbSharedPyram = 0;
11029         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11030         while ( vIt->more() )
11031         {
11032           const SMDS_MeshElement* v = vIt->next();
11033           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11034         }
11035         if ( nbSharedPyram > 1 )
11036           continue; // not free border of the pyramid
11037
11038         faceNodes.clear();
11039         faceNodes.push_back( ledges[0]->_nodes[0] );
11040         faceNodes.push_back( ledges[1]->_nodes[0] );
11041         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11042         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11043
11044         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11045           continue; // faces already created
11046       }
11047       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11048         ledges.push_back( n2eMap[ u2n->second ]);
11049
11050       // Find out orientation and type of face to create
11051
11052       bool reverse = false, isOnFace;
11053       
11054       map< TGeomID, TopoDS_Shape >::iterator e2f =
11055         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
11056       TopoDS_Shape F;
11057       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11058       {
11059         F = e2f->second.Oriented( TopAbs_FORWARD );
11060         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11061         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11062           reverse = !reverse, F.Reverse();
11063         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11064           reverse = !reverse;
11065       }
11066       else
11067       {
11068         // find FACE with layers sharing E
11069         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
11070         while ( fIt->more() && F.IsNull() )
11071         {
11072           const TopoDS_Shape* pF = fIt->next();
11073           if ( helper.IsSubShape( *pF, data._solid) &&
11074                !data._ignoreFaceIds.count( e2f->first ))
11075             F = *pF;
11076         }
11077       }
11078       // Find the sub-mesh to add new faces
11079       SMESHDS_SubMesh* sm = 0;
11080       if ( isOnFace )
11081         sm = getMeshDS()->MeshElements( F );
11082       else
11083         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11084       if ( !sm )
11085         return error("error in addBoundaryElements()", data._index);
11086
11087       // Make faces
11088       const int dj1 = reverse ? 0 : 1;
11089       const int dj2 = reverse ? 1 : 0;
11090       for ( size_t j = 1; j < ledges.size(); ++j )
11091       {
11092         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11093         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11094         if ( nn1.size() == nn2.size() )
11095         {
11096           if ( isOnFace )
11097             for ( size_t z = 1; z < nn1.size(); ++z )
11098               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11099           else
11100             for ( size_t z = 1; z < nn1.size(); ++z )
11101               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11102         }
11103         else if ( nn1.size() == 1 )
11104         {
11105           if ( isOnFace )
11106             for ( size_t z = 1; z < nn2.size(); ++z )
11107               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11108           else
11109             for ( size_t z = 1; z < nn2.size(); ++z )
11110               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11111         }
11112         else
11113         {
11114           if ( isOnFace )
11115             for ( size_t z = 1; z < nn1.size(); ++z )
11116               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11117           else
11118             for ( size_t z = 1; z < nn1.size(); ++z )
11119               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11120         }
11121       }
11122
11123       // Make edges
11124       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11125       {
11126         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11127         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11128         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11129         {
11130           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11131           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
11132             continue;
11133           helper.SetSubShape( eos->_sWOL );
11134           helper.SetElementsOnShape( true );
11135           for ( size_t z = 1; z < nn.size(); ++z )
11136             helper.AddEdge( nn[z-1], nn[z] );
11137         }
11138       }
11139
11140     } // loop on EDGE's
11141   } // loop on _SolidData's
11142
11143   return true;
11144 }