Salome HOME
23239: [CEA 1739] Regression : crash trying to create mesh
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2015  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 "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
46
47 #include <Adaptor3d_HSurface.hxx>
48 #include <BRepAdaptor_Curve2d.hxx>
49 #include <BRepAdaptor_Surface.hxx>
50 #include <BRepLProp_SLProps.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B2d.hxx>
53 #include <Bnd_B3d.hxx>
54 #include <ElCLib.hxx>
55 #include <GCPnts_AbscissaPoint.hxx>
56 #include <Geom2d_Circle.hxx>
57 #include <Geom2d_Line.hxx>
58 #include <Geom2d_TrimmedCurve.hxx>
59 #include <GeomAdaptor_Curve.hxx>
60 #include <GeomLib.hxx>
61 #include <Geom_Circle.hxx>
62 #include <Geom_Curve.hxx>
63 #include <Geom_Line.hxx>
64 #include <Geom_TrimmedCurve.hxx>
65 #include <Precision.hxx>
66 #include <Standard_ErrorHandler.hxx>
67 #include <Standard_Failure.hxx>
68 #include <TColStd_Array1OfReal.hxx>
69 #include <TopExp.hxx>
70 #include <TopExp_Explorer.hxx>
71 #include <TopTools_IndexedMapOfShape.hxx>
72 #include <TopTools_ListOfShape.hxx>
73 #include <TopTools_MapOfShape.hxx>
74 #include <TopoDS.hxx>
75 #include <TopoDS_Edge.hxx>
76 #include <TopoDS_Face.hxx>
77 #include <TopoDS_Vertex.hxx>
78 #include <gp_Ax1.hxx>
79 #include <gp_Cone.hxx>
80 #include <gp_Sphere.hxx>
81 #include <gp_Vec.hxx>
82 #include <gp_XY.hxx>
83
84 #include <list>
85 #include <string>
86 #include <cmath>
87 #include <limits>
88
89 #ifdef _DEBUG_
90 //#define __myDEBUG
91 //#define __NOT_INVALIDATE_BAD_SMOOTH
92 #endif
93
94 using namespace std;
95
96 //================================================================================
97 namespace VISCOUS_3D
98 {
99   typedef int TGeomID;
100
101   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
102
103   const double theMinSmoothCosin = 0.1;
104   const double theSmoothThickToElemSizeRatio = 0.3;
105
106   // what part of thickness is allowed till intersection
107   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
108   const double theThickToIntersection = 1.5;
109
110   bool needSmoothing( double cosin, double tgtThick, double elemSize )
111   {
112     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
113   }
114
115   /*!
116    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
117    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
118    */
119   struct _MeshOfSolid : public SMESH_ProxyMesh,
120                         public SMESH_subMeshEventListenerData
121   {
122     bool                  _n2nMapComputed;
123     SMESH_ComputeErrorPtr _warning;
124
125     _MeshOfSolid( SMESH_Mesh* mesh)
126       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
127     {
128       SMESH_ProxyMesh::setMesh( *mesh );
129     }
130
131     // returns submesh for a geom face
132     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
133     {
134       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
135       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
136     }
137     void setNode2Node(const SMDS_MeshNode*                 srcNode,
138                       const SMDS_MeshNode*                 proxyNode,
139                       const SMESH_ProxyMesh::SubMesh* subMesh)
140     {
141       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
142     }
143   };
144   //--------------------------------------------------------------------------------
145   /*!
146    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
147    * It is used to clear an inferior dim sub-meshes modified by viscous layers
148    */
149   class _ShrinkShapeListener : SMESH_subMeshEventListener
150   {
151     _ShrinkShapeListener()
152       : SMESH_subMeshEventListener(/*isDeletable=*/false,
153                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
154   public:
155     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
156     virtual void ProcessEvent(const int                       event,
157                               const int                       eventType,
158                               SMESH_subMesh*                  solidSM,
159                               SMESH_subMeshEventListenerData* data,
160                               const SMESH_Hypothesis*         hyp)
161     {
162       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
163       {
164         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
165       }
166     }
167   };
168   //--------------------------------------------------------------------------------
169   /*!
170    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
171    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
172    * delete the data as soon as it has been used
173    */
174   class _ViscousListener : SMESH_subMeshEventListener
175   {
176     _ViscousListener():
177       SMESH_subMeshEventListener(/*isDeletable=*/false,
178                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
179     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
180   public:
181     virtual void ProcessEvent(const int                       event,
182                               const int                       eventType,
183                               SMESH_subMesh*                  subMesh,
184                               SMESH_subMeshEventListenerData* data,
185                               const SMESH_Hypothesis*         hyp)
186     {
187       if ( SMESH_subMesh::COMPUTE_EVENT       == eventType &&
188            SMESH_subMesh::CHECK_COMPUTE_STATE != event)
189       {
190         // delete SMESH_ProxyMesh containing temporary faces
191         subMesh->DeleteEventListener( this );
192       }
193     }
194     // Finds or creates proxy mesh of the solid
195     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
196                                       const TopoDS_Shape& solid,
197                                       bool                toCreate=false)
198     {
199       if ( !mesh ) return 0;
200       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
201       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
202       if ( !data && toCreate )
203       {
204         data = new _MeshOfSolid(mesh);
205         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
206         sm->SetEventListener( Get(), data, sm );
207       }
208       return data;
209     }
210     // Removes proxy mesh of the solid
211     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
212     {
213       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
214     }
215   };
216   
217   //================================================================================
218   /*!
219    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
220    * the main shape when sub-mesh of the main shape is cleared,
221    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
222    * is cleared
223    */
224   //================================================================================
225
226   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
227   {
228     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
229     SMESH_subMeshEventListenerData* data =
230       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
231     if ( data )
232     {
233       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
234            data->mySubMeshes.end())
235         data->mySubMeshes.push_back( sub );
236     }
237     else
238     {
239       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
240       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
241     }
242   }
243   struct _SolidData;
244   //--------------------------------------------------------------------------------
245   /*!
246    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
247    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
248    * The class is used to check validity of face or volumes around a smoothed node;
249    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
250    */
251   struct _Simplex
252   {
253     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
254     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
255     _Simplex(const SMDS_MeshNode* nPrev=0,
256              const SMDS_MeshNode* nNext=0,
257              const SMDS_MeshNode* nOpp=0)
258       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
259     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt, double& vol) const
260     {
261       const double M[3][3] =
262         {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
263          { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
264          { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
265       vol = ( + M[0][0]*M[1][1]*M[2][2]
266               + M[0][1]*M[1][2]*M[2][0]
267               + M[0][2]*M[1][0]*M[2][1]
268               - M[0][0]*M[1][2]*M[2][1]
269               - M[0][1]*M[1][0]*M[2][2]
270               - M[0][2]*M[1][1]*M[2][0]);
271       return vol > 1e-100;
272     }
273     bool IsForward(const gp_XY&         tgtUV,
274                    const SMDS_MeshNode* smoothedNode,
275                    const TopoDS_Face&   face,
276                    SMESH_MesherHelper&  helper,
277                    const double         refSign) const
278     {
279       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
280       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
281       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
282       double d = v1 ^ v2;
283       return d*refSign > 1e-100;
284     }
285     bool IsNeighbour(const _Simplex& other) const
286     {
287       return _nPrev == other._nNext || _nNext == other._nPrev;
288     }
289     static void GetSimplices( const SMDS_MeshNode* node,
290                               vector<_Simplex>&   simplices,
291                               const set<TGeomID>& ingnoreShapes,
292                               const _SolidData*   dataToCheckOri = 0,
293                               const bool          toSort = false);
294     static void SortSimplices(vector<_Simplex>& simplices);
295   };
296   //--------------------------------------------------------------------------------
297   /*!
298    * Structure used to take into account surface curvature while smoothing
299    */
300   struct _Curvature
301   {
302     double _r; // radius
303     double _k; // factor to correct node smoothed position
304     double _h2lenRatio; // avgNormProj / (2*avgDist)
305   public:
306     static _Curvature* New( double avgNormProj, double avgDist )
307     {
308       _Curvature* c = 0;
309       if ( fabs( avgNormProj / avgDist ) > 1./200 )
310       {
311         c = new _Curvature;
312         c->_r = avgDist * avgDist / avgNormProj;
313         c->_k = avgDist * avgDist / c->_r / c->_r;
314         //c->_k = avgNormProj / c->_r;
315         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
316         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
317       }
318       return c;
319     }
320     double lenDelta(double len) const { return _k * ( _r + len ); }
321     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
322   };
323   //--------------------------------------------------------------------------------
324
325   struct _2NearEdges;
326   struct _LayerEdge;
327   struct _EdgesOnShape;
328   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
329
330   //--------------------------------------------------------------------------------
331   /*!
332    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
333    * and a node of the most internal layer (_nodes.back())
334    */
335   struct _LayerEdge
336   {
337     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
338
339     vector< const SMDS_MeshNode*> _nodes;
340
341     gp_XYZ              _normal; // to solid surface
342     vector<gp_XYZ>      _pos; // points computed during inflation
343     double              _len; // length achived with the last inflation step
344     double              _cosin; // of angle (_normal ^ surface)
345     double              _lenFactor; // to compute _len taking _cosin into account
346
347     // face or edge w/o layer along or near which _LayerEdge is inflated
348     //TopoDS_Shape*       _sWOL;
349     // simplices connected to the source node (_nodes[0]);
350     // used for smoothing and quality check of _LayerEdge's based on the FACE
351     vector<_Simplex>    _simplices;
352     PSmooFun            _smooFunction; // smoothing function
353     // data for smoothing of _LayerEdge's based on the EDGE
354     _2NearEdges*        _2neibors;
355
356     _Curvature*         _curvature;
357     // TODO:: detele _Curvature, _plnNorm
358
359     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
360     bool SetNewLength2d( Handle(Geom_Surface)& surface,
361                          const TopoDS_Face&    F,
362                          _EdgesOnShape&        eos,
363                          SMESH_MesherHelper&   helper );
364     void SetDataByNeighbors( const SMDS_MeshNode* n1,
365                              const SMDS_MeshNode* n2,
366                              const _EdgesOnShape& eos,
367                              SMESH_MesherHelper&  helper);
368     void InvalidateStep( int curStep, const _EdgesOnShape& eos, bool restoreLength=false );
369     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
370                             const TNode2Edge&     n2eMap);
371     int  Smooth(const int step, const bool isConcaveFace, const bool findBest);
372     bool SmoothOnEdge(Handle(Geom_Surface)& surface,
373                       const TopoDS_Face&    F,
374                       SMESH_MesherHelper&   helper);
375     bool FindIntersection( SMESH_ElementSearcher&   searcher,
376                            double &                 distance,
377                            const double&            epsilon,
378                            _EdgesOnShape&           eos,
379                            const SMDS_MeshElement** face = 0);
380     bool SegTriaInter( const gp_Ax1&        lastSegment,
381                        const SMDS_MeshNode* n0,
382                        const SMDS_MeshNode* n1,
383                        const SMDS_MeshNode* n2,
384                        double&              dist,
385                        const double&        epsilon) const;
386     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
387     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
388     bool   IsOnEdge() const { return _2neibors; }
389     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
390     void   SetCosin( double cosin );
391     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
392
393     gp_XYZ smoothLaplacian();
394     gp_XYZ smoothAngular();
395     gp_XYZ smoothLengthWeighted();
396     gp_XYZ smoothCentroidal();
397     gp_XYZ smoothNefPolygon();
398
399     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
400     static const int theNbSmooFuns = FUN_NB;
401     static PSmooFun _funs[theNbSmooFuns];
402     static const char* _funNames[theNbSmooFuns+1];
403     int smooFunID( PSmooFun fun=0) const;
404   };
405   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
406                                                             &_LayerEdge::smoothLengthWeighted,
407                                                             &_LayerEdge::smoothCentroidal,
408                                                             &_LayerEdge::smoothNefPolygon,
409                                                             &_LayerEdge::smoothAngular };
410   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
411                                                          "LengthWeighted",
412                                                          "Centroidal",
413                                                          "NefPolygon",
414                                                          "Angular",
415                                                          "None"};
416   struct _LayerEdgeCmp
417   {
418     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
419     {
420       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
421       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
422     }
423   };
424   //--------------------------------------------------------------------------------
425   /*!
426    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
427    */
428   struct _halfPlane
429   {
430     gp_XY _pos, _dir, _inNorm;
431     bool IsOut( const gp_XY p, const double tol ) const
432     {
433       return _inNorm * ( p - _pos ) < -tol;
434     }
435     bool FindInterestion( const _halfPlane& hp, gp_XY & intPnt )
436     {
437       const double eps = 1e-10;
438       double D = _dir.Crossed( hp._dir );
439       if ( fabs(D) < std::numeric_limits<double>::min())
440         return false;
441       gp_XY vec21 = _pos - hp._pos; 
442       double u = hp._dir.Crossed( vec21 ) / D; 
443       intPnt = _pos + _dir * u;
444       return true;
445     }
446   };
447   //--------------------------------------------------------------------------------
448   /*!
449    * Structure used to smooth a _LayerEdge based on an EDGE.
450    */
451   struct _2NearEdges
452   {
453     double               _wgt  [2]; // weights of _nodes
454     _LayerEdge*          _edges[2];
455
456      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
457     gp_XYZ*              _plnNorm;
458
459     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
460     const SMDS_MeshNode* tgtNode(bool is2nd) {
461       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
462     }
463     const SMDS_MeshNode* srcNode(bool is2nd) {
464       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
465     }
466     void reverse() {
467       std::swap( _wgt  [0], _wgt  [1] );
468       std::swap( _edges[0], _edges[1] );
469     }
470   };
471
472
473   //--------------------------------------------------------------------------------
474   /*!
475    * \brief Layers parameters got by averaging several hypotheses
476    */
477   struct AverageHyp
478   {
479     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
480       :_nbLayers(0), _nbHyps(0), _thickness(0), _stretchFactor(0), _method(0)
481     {
482       Add( hyp );
483     }
484     void Add( const StdMeshers_ViscousLayers* hyp )
485     {
486       if ( hyp )
487       {
488         _nbHyps++;
489         _nbLayers       = hyp->GetNumberLayers();
490         //_thickness     += hyp->GetTotalThickness();
491         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
492         _stretchFactor += hyp->GetStretchFactor();
493         _method         = hyp->GetMethod();
494       }
495     }
496     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
497     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
498     int    GetNumberLayers()   const { return _nbLayers; }
499     int    GetMethod()         const { return _method; }
500
501     bool   UseSurfaceNormal()  const
502     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
503     bool   ToSmooth()          const
504     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
505     bool   IsOffsetMethod()    const
506     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
507
508   private:
509     int     _nbLayers, _nbHyps, _method;
510     double  _thickness, _stretchFactor;
511   };
512
513   //--------------------------------------------------------------------------------
514   /*!
515    * \brief _LayerEdge's on a shape and other shape data
516    */
517   struct _EdgesOnShape
518   {
519     vector< _LayerEdge* > _edges;
520
521     TopoDS_Shape          _shape;
522     TGeomID               _shapeID;
523     SMESH_subMesh *       _subMesh;
524     // face or edge w/o layer along or near which _edges are inflated
525     TopoDS_Shape          _sWOL;
526     // averaged StdMeshers_ViscousLayers parameters
527     AverageHyp            _hyp;
528     bool                  _toSmooth;
529
530     vector< gp_XYZ >      _faceNormals; // if _shape is FACE
531     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
532
533     TopAbs_ShapeEnum ShapeType() const
534     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
535     TopAbs_ShapeEnum SWOLType() const
536     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
537     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
538   };
539
540   //--------------------------------------------------------------------------------
541   /*!
542    * \brief Convex FACE whose radius of curvature is less than the thickness of 
543    *        layers. It is used to detect distortion of prisms based on a convex
544    *        FACE and to update normals to enable further increasing the thickness
545    */
546   struct _ConvexFace
547   {
548     TopoDS_Face                     _face;
549
550     // edges whose _simplices are used to detect prism destorsion
551     vector< _LayerEdge* >           _simplexTestEdges;
552
553     // map a sub-shape to _SolidData::_edgesOnShape
554     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
555
556     bool                            _normalsFixed;
557
558     bool GetCenterOfCurvature( _LayerEdge*         ledge,
559                                BRepLProp_SLProps&  surfProp,
560                                SMESH_MesherHelper& helper,
561                                gp_Pnt &            center ) const;
562     bool CheckPrisms() const;
563   };
564
565   //--------------------------------------------------------------------------------
566   /*!
567    * \brief Data of a SOLID
568    */
569   struct _SolidData
570   {
571     typedef const StdMeshers_ViscousLayers* THyp;
572     TopoDS_Shape                    _solid;
573     TGeomID                         _index; // SOLID id
574     _MeshOfSolid*                   _proxyMesh;
575     list< THyp >                    _hyps;
576     list< TopoDS_Shape >            _hypShapes;
577     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
578     set< TGeomID >                  _reversedFaceIds;
579     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
580
581     double                          _stepSize, _stepSizeCoeff, _geomSize;
582     const SMDS_MeshNode*            _stepSizeNodes[2];
583
584     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
585
586     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
587     map< TGeomID, TNode2Edge* >     _s2neMap;
588     // _LayerEdge's with underlying shapes
589     vector< _EdgesOnShape >         _edgesOnShape;
590
591     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
592     //        layers and a FACE w/o layers
593     // value: the shape (FACE or EDGE) to shrink mesh on.
594     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
595     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
596
597     // Convex FACEs whose radius of curvature is less than the thickness of layers
598     map< TGeomID, _ConvexFace >      _convexFaces;
599
600     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
601     // the adjacent SOLID
602     set< TGeomID >                   _noShrinkShapes;
603
604     int                              _nbShapesToSmooth;
605
606     // <EDGE to smooth on> to <it's curve> -- for analytic smooth
607     map< TGeomID,Handle(Geom_Curve)> _edge2curve;
608
609     set< TGeomID >                   _concaveFaces;
610
611     double                           _maxThickness; // of all _hyps
612     double                           _minThickness; // of all _hyps
613
614     double                           _epsilon; // precision for SegTriaInter()
615
616     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
617                _MeshOfSolid*       m=0)
618       :_solid(s), _proxyMesh(m) {}
619     ~_SolidData();
620
621     Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&    E,
622                                        _EdgesOnShape&        eos,
623                                        SMESH_MesherHelper&   helper);
624
625     void SortOnEdge( const TopoDS_Edge&     E,
626                      vector< _LayerEdge* >& edges,
627                      SMESH_MesherHelper&    helper);
628
629     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
630
631     _ConvexFace* GetConvexFace( const TGeomID faceID )
632     {
633       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
634       return id2face == _convexFaces.end() ? 0 : & id2face->second;
635     }
636     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
637     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
638     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
639     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
640
641     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape );
642
643     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
644   };
645   //--------------------------------------------------------------------------------
646   /*!
647    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
648    */
649   struct _CentralCurveOnEdge
650   {
651     bool                  _isDegenerated;
652     vector< gp_Pnt >      _curvaCenters;
653     vector< _LayerEdge* > _ledges;
654     vector< gp_XYZ >      _normals; // new normal for each of _ledges
655     vector< double >      _segLength2;
656
657     TopoDS_Edge           _edge;
658     TopoDS_Face           _adjFace;
659     bool                  _adjFaceToSmooth;
660
661     void Append( const gp_Pnt& center, _LayerEdge* ledge )
662     {
663       if ( _curvaCenters.size() > 0 )
664         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
665       _curvaCenters.push_back( center );
666       _ledges.push_back( ledge );
667       _normals.push_back( ledge->_normal );
668     }
669     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
670     void SetShapes( const TopoDS_Edge&  edge,
671                     const _ConvexFace&  convFace,
672                     _SolidData&         data,
673                     SMESH_MesherHelper& helper);
674   };
675   //--------------------------------------------------------------------------------
676   /*!
677    * \brief Data of node on a shrinked FACE
678    */
679   struct _SmoothNode
680   {
681     const SMDS_MeshNode*         _node;
682     vector<_Simplex>             _simplices; // for quality check
683
684     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
685
686     bool Smooth(int&                  badNb,
687                 Handle(Geom_Surface)& surface,
688                 SMESH_MesherHelper&   helper,
689                 const double          refSign,
690                 SmoothType            how,
691                 bool                  set3D);
692
693     gp_XY computeAngularPos(vector<gp_XY>& uv,
694                             const gp_XY&   uvToFix,
695                             const double   refSign );
696   };
697   //--------------------------------------------------------------------------------
698   /*!
699    * \brief Builder of viscous layers
700    */
701   class _ViscousBuilder
702   {
703   public:
704     _ViscousBuilder();
705     // does it's job
706     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
707                                   const TopoDS_Shape& shape);
708     // check validity of hypotheses
709     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
710                                            const TopoDS_Shape& shape );
711
712     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
713     void RestoreListeners();
714
715     // computes SMESH_ProxyMesh::SubMesh::_n2n;
716     bool MakeN2NMap( _MeshOfSolid* pm );
717
718   private:
719
720     bool findSolidsWithLayers();
721     bool findFacesWithLayers(const bool onlyWith=false);
722     void getIgnoreFaces(const TopoDS_Shape&             solid,
723                         const StdMeshers_ViscousLayers* hyp,
724                         const TopoDS_Shape&             hypShape,
725                         set<TGeomID>&                   ignoreFaces);
726     bool makeLayer(_SolidData& data);
727     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
728     bool setEdgeData(_LayerEdge& edge, _EdgesOnShape& eos, const set<TGeomID>& subIds,
729                      SMESH_MesherHelper& helper, _SolidData& data);
730     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
731                          const TopoDS_Face&   face,
732                          SMESH_MesherHelper&  helper,
733                          bool&                isOK,
734                          bool                 shiftInside=false);
735     bool getFaceNormalAtSingularity(const gp_XY&        uv,
736                                     const TopoDS_Face&  face,
737                                     SMESH_MesherHelper& helper,
738                                     gp_Dir&             normal );
739     gp_XYZ getWeigthedNormal( const SMDS_MeshNode*             n,
740                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
741                               int                              nbFaces );
742     bool findNeiborsOnEdge(const _LayerEdge*     edge,
743                            const SMDS_MeshNode*& n1,
744                            const SMDS_MeshNode*& n2,
745                            _EdgesOnShape&        eos,
746                            _SolidData&           data);
747     void findSimplexTestEdges( _SolidData&                    data,
748                                vector< vector<_LayerEdge*> >& edgesByGeom);
749     void computeGeomSize( _SolidData& data );
750     bool findShapesToSmooth( _SolidData& data);
751     void limitStepSizeByCurvature( _SolidData&  data );
752     void limitStepSize( _SolidData&             data,
753                         const SMDS_MeshElement* face,
754                         const _LayerEdge*       maxCosinEdge );
755     void limitStepSize( _SolidData& data, const double minSize);
756     bool inflate(_SolidData& data);
757     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
758     bool smoothAnalyticEdge( _SolidData&           data,
759                              _EdgesOnShape&        eos,
760                              Handle(Geom_Surface)& surface,
761                              const TopoDS_Face&    F,
762                              SMESH_MesherHelper&   helper);
763     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb );
764     bool updateNormalsOfConvexFaces( _SolidData&         data,
765                                      SMESH_MesherHelper& helper,
766                                      int                 stepNb );
767     bool refine(_SolidData& data);
768     bool shrink();
769     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
770                               SMESH_MesherHelper& helper,
771                               const SMESHDS_SubMesh* faceSubMesh );
772     void restoreNoShrink( _LayerEdge& edge ) const;
773     void fixBadFaces(const TopoDS_Face&          F,
774                      SMESH_MesherHelper&         helper,
775                      const bool                  is2D,
776                      const int                   step,
777                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
778     bool addBoundaryElements();
779
780     bool error( const string& text, int solidID=-1 );
781     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
782
783     // debug
784     void makeGroupOfLE();
785
786     SMESH_Mesh*           _mesh;
787     SMESH_ComputeErrorPtr _error;
788
789     vector< _SolidData >  _sdVec;
790     int                   _tmpFaceID;
791   };
792   //--------------------------------------------------------------------------------
793   /*!
794    * \brief Shrinker of nodes on the EDGE
795    */
796   class _Shrinker1D
797   {
798     TopoDS_Edge                   _geomEdge;
799     vector<double>                _initU;
800     vector<double>                _normPar;
801     vector<const SMDS_MeshNode*>  _nodes;
802     const _LayerEdge*             _edges[2];
803     bool                          _done;
804   public:
805     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
806     void Compute(bool set3D, SMESH_MesherHelper& helper);
807     void RestoreParams();
808     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
809   };
810   //--------------------------------------------------------------------------------
811   /*!
812    * \brief Class of temporary mesh face.
813    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
814    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
815    */
816   struct _TmpMeshFace : public SMDS_MeshElement
817   {
818     vector<const SMDS_MeshNode* > _nn;
819     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id, int faceID=-1):
820       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); }
821     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
822     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
823     virtual vtkIdType GetVtkType() const                      { return -1; }
824     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
825     virtual SMDSAbs_GeometryType GetGeomType() const
826     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
827     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
828     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
829   };
830   //--------------------------------------------------------------------------------
831   /*!
832    * \brief Class of temporary mesh face storing _LayerEdge it's based on
833    */
834   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
835   {
836     _LayerEdge *_le1, *_le2;
837     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
838       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
839     {
840       _nn[0]=_le1->_nodes[0];
841       _nn[1]=_le1->_nodes.back();
842       _nn[2]=_le2->_nodes.back();
843       _nn[3]=_le2->_nodes[0];
844     }
845   };
846   //--------------------------------------------------------------------------------
847   /*!
848    * \brief Retriever of node coordinates either directly or from a surface by node UV.
849    * \warning Location of a surface is ignored
850    */
851   struct _NodeCoordHelper
852   {
853     SMESH_MesherHelper&        _helper;
854     const TopoDS_Face&         _face;
855     Handle(Geom_Surface)       _surface;
856     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
857
858     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
859       : _helper( helper ), _face( F )
860     {
861       if ( is2D )
862       {
863         TopLoc_Location loc;
864         _surface = BRep_Tool::Surface( _face, loc );
865       }
866       if ( _surface.IsNull() )
867         _fun = & _NodeCoordHelper::direct;
868       else
869         _fun = & _NodeCoordHelper::byUV;
870     }
871     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
872
873   private:
874     gp_XYZ direct(const SMDS_MeshNode* n) const
875     {
876       return SMESH_TNodeXYZ( n );
877     }
878     gp_XYZ byUV  (const SMDS_MeshNode* n) const
879     {
880       gp_XY uv = _helper.GetNodeUV( _face, n );
881       return _surface->Value( uv.X(), uv.Y() ).XYZ();
882     }
883   };
884
885 } // namespace VISCOUS_3D
886
887
888
889 //================================================================================
890 // StdMeshers_ViscousLayers hypothesis
891 //
892 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
893   :SMESH_Hypothesis(hypId, studyId, gen),
894    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
895    _method( SURF_OFFSET_SMOOTH )
896 {
897   _name = StdMeshers_ViscousLayers::GetHypType();
898   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
899 } // --------------------------------------------------------------------------------
900 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
901 {
902   if ( faceIds != _shapeIds )
903     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
904   if ( _isToIgnoreShapes != toIgnore )
905     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
906 } // --------------------------------------------------------------------------------
907 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
908 {
909   if ( thickness != _thickness )
910     _thickness = thickness, NotifySubMeshesHypothesisModification();
911 } // --------------------------------------------------------------------------------
912 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
913 {
914   if ( _nbLayers != nb )
915     _nbLayers = nb, NotifySubMeshesHypothesisModification();
916 } // --------------------------------------------------------------------------------
917 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
918 {
919   if ( _stretchFactor != factor )
920     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
921 } // --------------------------------------------------------------------------------
922 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
923 {
924   if ( _method != method )
925     _method = method, NotifySubMeshesHypothesisModification();
926 } // --------------------------------------------------------------------------------
927 SMESH_ProxyMesh::Ptr
928 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
929                                   const TopoDS_Shape& theShape,
930                                   const bool          toMakeN2NMap) const
931 {
932   using namespace VISCOUS_3D;
933   _ViscousBuilder bulder;
934   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
935   if ( err && !err->IsOK() )
936     return SMESH_ProxyMesh::Ptr();
937
938   vector<SMESH_ProxyMesh::Ptr> components;
939   TopExp_Explorer exp( theShape, TopAbs_SOLID );
940   for ( ; exp.More(); exp.Next() )
941   {
942     if ( _MeshOfSolid* pm =
943          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
944     {
945       if ( toMakeN2NMap && !pm->_n2nMapComputed )
946         if ( !bulder.MakeN2NMap( pm ))
947           return SMESH_ProxyMesh::Ptr();
948       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
949       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
950
951       if ( pm->_warning && !pm->_warning->IsOK() )
952       {
953         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
954         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
955         if ( !smError || smError->IsOK() )
956           smError = pm->_warning;
957       }
958     }
959     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
960   }
961   switch ( components.size() )
962   {
963   case 0: break;
964
965   case 1: return components[0];
966
967   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
968   }
969   return SMESH_ProxyMesh::Ptr();
970 } // --------------------------------------------------------------------------------
971 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
972 {
973   save << " " << _nbLayers
974        << " " << _thickness
975        << " " << _stretchFactor
976        << " " << _shapeIds.size();
977   for ( size_t i = 0; i < _shapeIds.size(); ++i )
978     save << " " << _shapeIds[i];
979   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
980   save << " " << _method;
981   return save;
982 } // --------------------------------------------------------------------------------
983 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
984 {
985   int nbFaces, faceID, shapeToTreat, method;
986   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
987   while ( _shapeIds.size() < nbFaces && load >> faceID )
988     _shapeIds.push_back( faceID );
989   if ( load >> shapeToTreat ) {
990     _isToIgnoreShapes = !shapeToTreat;
991     if ( load >> method )
992       _method = (ExtrusionMethod) method;
993   }
994   else {
995     _isToIgnoreShapes = true; // old behavior
996   }
997   return load;
998 } // --------------------------------------------------------------------------------
999 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1000                                                    const TopoDS_Shape& theShape)
1001 {
1002   // TODO
1003   return false;
1004 } // --------------------------------------------------------------------------------
1005 SMESH_ComputeErrorPtr
1006 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1007                                           const TopoDS_Shape&                  theShape,
1008                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1009 {
1010   VISCOUS_3D::_ViscousBuilder bulder;
1011   SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
1012   if ( err && !err->IsOK() )
1013     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1014   else
1015     theStatus = SMESH_Hypothesis::HYP_OK;
1016
1017   return err;
1018 }
1019 // --------------------------------------------------------------------------------
1020 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1021 {
1022   bool isIn =
1023     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1024   return IsToIgnoreShapes() ? !isIn : isIn;
1025 }
1026 // END StdMeshers_ViscousLayers hypothesis
1027 //================================================================================
1028
1029 namespace VISCOUS_3D
1030 {
1031   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1032   {
1033     gp_Vec dir;
1034     double f,l;
1035     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1036     gp_Pnt p = BRep_Tool::Pnt( fromV );
1037     double distF = p.SquareDistance( c->Value( f ));
1038     double distL = p.SquareDistance( c->Value( l ));
1039     c->D1(( distF < distL ? f : l), p, dir );
1040     if ( distL < distF ) dir.Reverse();
1041     return dir.XYZ();
1042   }
1043   //--------------------------------------------------------------------------------
1044   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1045                      SMESH_MesherHelper& helper)
1046   {
1047     gp_Vec dir;
1048     double f,l; gp_Pnt p;
1049     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1050     if ( c.IsNull() ) return gp_XYZ( 1e100, 1e100, 1e100 );
1051     double u = helper.GetNodeU( E, atNode );
1052     c->D1( u, p, dir );
1053     return dir.XYZ();
1054   }
1055   //--------------------------------------------------------------------------------
1056   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1057                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1058                      double* cosin=0);
1059   //--------------------------------------------------------------------------------
1060   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1061                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1062   {
1063     double f,l;
1064     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1065     if ( c.IsNull() )
1066     {
1067       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1068       return getFaceDir( F, v, node, helper, ok );
1069     }
1070     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1071     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1072     gp_Pnt p; gp_Vec du, dv, norm;
1073     surface->D1( uv.X(),uv.Y(), p, du,dv );
1074     norm = du ^ dv;
1075
1076     double u = helper.GetNodeU( fromE, node, 0, &ok );
1077     c->D1( u, p, du );
1078     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1079     if ( o == TopAbs_REVERSED )
1080       du.Reverse();
1081
1082     gp_Vec dir = norm ^ du;
1083
1084     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1085          helper.IsClosedEdge( fromE ))
1086     {
1087       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1088       else                        c->D1( f, p, dv );
1089       if ( o == TopAbs_REVERSED )
1090         dv.Reverse();
1091       gp_Vec dir2 = norm ^ dv;
1092       dir = dir.Normalized() + dir2.Normalized();
1093     }
1094     return dir.XYZ();
1095   }
1096   //--------------------------------------------------------------------------------
1097   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1098                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1099                      bool& ok, double* cosin)
1100   {
1101     TopoDS_Face faceFrw = F;
1102     faceFrw.Orientation( TopAbs_FORWARD );
1103     double f,l; TopLoc_Location loc;
1104     TopoDS_Edge edges[2]; // sharing a vertex
1105     int nbEdges = 0;
1106     {
1107       TopoDS_Vertex VV[2];
1108       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1109       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1110       {
1111         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1112         if ( SMESH_Algo::isDegenerated( e )) continue;
1113         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1114         if ( VV[1].IsSame( fromV )) {
1115           nbEdges += edges[ 0 ].IsNull();
1116           edges[ 0 ] = e;
1117         }
1118         else if ( VV[0].IsSame( fromV )) {
1119           nbEdges += edges[ 1 ].IsNull();
1120           edges[ 1 ] = e;
1121         }
1122       }
1123     }
1124     gp_XYZ dir(0,0,0), edgeDir[2];
1125     if ( nbEdges == 2 )
1126     {
1127       // get dirs of edges going fromV
1128       ok = true;
1129       for ( size_t i = 0; i < nbEdges && ok; ++i )
1130       {
1131         edgeDir[i] = getEdgeDir( edges[i], fromV );
1132         double size2 = edgeDir[i].SquareModulus();
1133         if (( ok = size2 > numeric_limits<double>::min() ))
1134           edgeDir[i] /= sqrt( size2 );
1135       }
1136       if ( !ok ) return dir;
1137
1138       // get angle between the 2 edges
1139       gp_Vec faceNormal;
1140       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1141       if ( Abs( angle ) < 5 * M_PI/180 )
1142       {
1143         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1144       }
1145       else
1146       {
1147         dir = edgeDir[0] + edgeDir[1];
1148         if ( angle < 0 )
1149           dir.Reverse();
1150       }
1151       if ( cosin ) {
1152         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1153         *cosin = Cos( angle );
1154       }
1155     }
1156     else if ( nbEdges == 1 )
1157     {
1158       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1159       if ( cosin ) *cosin = 1.;
1160     }
1161     else
1162     {
1163       ok = false;
1164     }
1165
1166     return dir;
1167   }
1168
1169   //================================================================================
1170   /*!
1171    * \brief Finds concave VERTEXes of a FACE
1172    */
1173   //================================================================================
1174
1175   bool getConcaveVertices( const TopoDS_Face&  F,
1176                            SMESH_MesherHelper& helper,
1177                            set< TGeomID >*     vertices = 0)
1178   {
1179     // check angles at VERTEXes
1180     TError error;
1181     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1182     for ( size_t iW = 0; iW < wires.size(); ++iW )
1183     {
1184       const int nbEdges = wires[iW]->NbEdges();
1185       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1186         continue;
1187       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1188       {
1189         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1190         int iE2 = ( iE1 + 1 ) % nbEdges;
1191         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1192           iE2 = ( iE2 + 1 ) % nbEdges;
1193         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1194         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1195                                         wires[iW]->Edge( iE2 ), F, V );
1196         if ( angle < -5. * M_PI / 180. )
1197         {
1198           if ( !vertices )
1199             return true;
1200           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1201         }
1202       }
1203     }
1204     return vertices ? !vertices->empty() : false;
1205   }
1206
1207   //================================================================================
1208   /*!
1209    * \brief Returns true if a FACE is bound by a concave EDGE
1210    */
1211   //================================================================================
1212
1213   bool isConcave( const TopoDS_Face&  F,
1214                   SMESH_MesherHelper& helper,
1215                   set< TGeomID >*     vertices = 0 )
1216   {
1217     bool isConcv = false;
1218     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1219     //   return true;
1220     gp_Vec2d drv1, drv2;
1221     gp_Pnt2d p;
1222     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1223     for ( ; eExp.More(); eExp.Next() )
1224     {
1225       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1226       if ( SMESH_Algo::isDegenerated( E )) continue;
1227       // check if 2D curve is concave
1228       BRepAdaptor_Curve2d curve( E, F );
1229       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1230       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1231       curve.Intervals( intervals, GeomAbs_C2 );
1232       bool isConvex = true;
1233       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1234       {
1235         double u1 = intervals( i );
1236         double u2 = intervals( i+1 );
1237         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1238         double cross = drv2 ^ drv1;
1239         if ( E.Orientation() == TopAbs_REVERSED )
1240           cross = -cross;
1241         isConvex = ( cross > 0.1 ); //-1e-9 );
1242       }
1243       if ( !isConvex )
1244       {
1245         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1246         isConcv = true;
1247         if ( vertices )
1248           break;
1249         else
1250           return true;
1251       }
1252     }
1253
1254     // check angles at VERTEXes
1255     if ( getConcaveVertices( F, helper, vertices ))
1256       isConcv = true;
1257
1258     return isConcv;
1259   }
1260
1261   //================================================================================
1262   /*!
1263    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1264    *  \param [in] face - the mesh face to treat
1265    *  \param [in] nodeOnEdge - a node on the EDGE
1266    *  \param [out] faceSize - the computed distance
1267    *  \return bool - true if faceSize computed
1268    */
1269   //================================================================================
1270
1271   bool getDistFromEdge( const SMDS_MeshElement* face,
1272                         const SMDS_MeshNode*    nodeOnEdge,
1273                         double &                faceSize )
1274   {
1275     faceSize = Precision::Infinite();
1276     bool done = false;
1277
1278     int nbN  = face->NbCornerNodes();
1279     int iOnE = face->GetNodeIndex( nodeOnEdge );
1280     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1281                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1282     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1283                                       face->GetNode( iNext[1] ) };
1284     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1285     double segLen = -1.;
1286     // look for two neighbor not in-FACE nodes of face
1287     for ( int i = 0; i < 2; ++i )
1288     {
1289       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1290            nNext[i]->GetID() < nodeOnEdge->GetID() )
1291       {
1292         // look for an in-FACE node
1293         for ( int iN = 0; iN < nbN; ++iN )
1294         {
1295           if ( iN == iOnE || iN == iNext[i] )
1296             continue;
1297           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1298           gp_XYZ v = pInFace - segEnd;
1299           if ( segLen < 0 )
1300           {
1301             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1302             segLen = segVec.Modulus();
1303           }
1304           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1305           faceSize = Min( faceSize, distToSeg );
1306           done = true;
1307         }
1308         segLen = -1;
1309       }
1310     }
1311     return done;
1312   }
1313   //================================================================================
1314   /*!
1315    * \brief Return direction of axis or revolution of a surface
1316    */
1317   //================================================================================
1318
1319   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1320                           gp_Dir &                 axis )
1321   {
1322     switch ( surface.GetType() ) {
1323     case GeomAbs_Cone:
1324     {
1325       gp_Cone cone = surface.Cone();
1326       axis = cone.Axis().Direction();
1327       break;
1328     }
1329     case GeomAbs_Sphere:
1330     {
1331       gp_Sphere sphere = surface.Sphere();
1332       axis = sphere.Position().Direction();
1333       break;
1334     }
1335     case GeomAbs_SurfaceOfRevolution:
1336     {
1337       axis = surface.AxeOfRevolution().Direction();
1338       break;
1339     }
1340     //case GeomAbs_SurfaceOfExtrusion:
1341     case GeomAbs_OffsetSurface:
1342     {
1343       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1344       return getRovolutionAxis( base->Surface(), axis );
1345     }
1346     default: return false;
1347     }
1348     return true;
1349   }
1350
1351   //--------------------------------------------------------------------------------
1352   // DEBUG. Dump intermediate node positions into a python script
1353   // HOWTO use: run python commands written in a console to see
1354   //  construction steps of viscous layers
1355 #ifdef __myDEBUG
1356   ofstream* py;
1357   int       theNbPyFunc;
1358   struct PyDump {
1359     PyDump(SMESH_Mesh& m) {
1360       int tag = 3 + m.GetId();
1361       const char* fname = "/tmp/viscous.py";
1362       cout << "execfile('"<<fname<<"')"<<endl;
1363       py = new ofstream(fname);
1364       *py << "import SMESH" << endl
1365           << "from salome.smesh import smeshBuilder" << endl
1366           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1367           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1368           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1369       theNbPyFunc = 0;
1370     }
1371     void Finish() {
1372       if (py) {
1373         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1374           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1375         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1376           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1377       }
1378       delete py; py=0;
1379     }
1380     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1381   };
1382 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1383 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1384 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1385 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1386   void _dumpFunction(const string& fun, int ln)
1387   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1388   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1389   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1390                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1391   void _dumpCmd(const string& txt, int ln)
1392   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1393   void dumpFunctionEnd()
1394   { if (py) *py<< "  return"<< endl; }
1395   void dumpChangeNodes( const SMDS_MeshElement* f )
1396   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1397       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1398       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1399 #define debugMsg( txt ) { cout << txt << " (line: " << __LINE__ << ")" << endl; }
1400 #else
1401   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1402 #define dumpFunction(f) f
1403 #define dumpMove(n)
1404 #define dumpMoveComm(n,txt)
1405 #define dumpCmd(txt)
1406 #define dumpFunctionEnd()
1407 #define dumpChangeNodes(f)
1408 #define debugMsg( txt ) {}
1409 #endif
1410 }
1411
1412 using namespace VISCOUS_3D;
1413
1414 //================================================================================
1415 /*!
1416  * \brief Constructor of _ViscousBuilder
1417  */
1418 //================================================================================
1419
1420 _ViscousBuilder::_ViscousBuilder()
1421 {
1422   _error = SMESH_ComputeError::New(COMPERR_OK);
1423   _tmpFaceID = 0;
1424 }
1425
1426 //================================================================================
1427 /*!
1428  * \brief Stores error description and returns false
1429  */
1430 //================================================================================
1431
1432 bool _ViscousBuilder::error(const string& text, int solidId )
1433 {
1434   const string prefix = string("Viscous layers builder: ");
1435   _error->myName    = COMPERR_ALGO_FAILED;
1436   _error->myComment = prefix + text;
1437   if ( _mesh )
1438   {
1439     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1440     if ( !sm && !_sdVec.empty() )
1441       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1442     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1443     {
1444       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1445       if ( smError && smError->myAlgo )
1446         _error->myAlgo = smError->myAlgo;
1447       smError = _error;
1448       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1449     }
1450     // set KO to all solids
1451     for ( size_t i = 0; i < _sdVec.size(); ++i )
1452     {
1453       if ( _sdVec[i]._index == solidId )
1454         continue;
1455       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1456       if ( !sm->IsEmpty() )
1457         continue;
1458       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1459       if ( !smError || smError->IsOK() )
1460       {
1461         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1462         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1463       }
1464     }
1465   }
1466   makeGroupOfLE(); // debug
1467
1468   return false;
1469 }
1470
1471 //================================================================================
1472 /*!
1473  * \brief At study restoration, restore event listeners used to clear an inferior
1474  *  dim sub-mesh modified by viscous layers
1475  */
1476 //================================================================================
1477
1478 void _ViscousBuilder::RestoreListeners()
1479 {
1480   // TODO
1481 }
1482
1483 //================================================================================
1484 /*!
1485  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1486  */
1487 //================================================================================
1488
1489 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1490 {
1491   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1492   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1493   for ( ; fExp.More(); fExp.Next() )
1494   {
1495     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1496     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1497
1498     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1499       continue;
1500     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1501       continue;
1502
1503     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1504       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1505
1506     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1507     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1508     while( prxIt->more() )
1509     {
1510       const SMDS_MeshElement* fSrc = srcIt->next();
1511       const SMDS_MeshElement* fPrx = prxIt->next();
1512       if ( fSrc->NbNodes() != fPrx->NbNodes())
1513         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1514       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1515         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1516     }
1517   }
1518   pm->_n2nMapComputed = true;
1519   return true;
1520 }
1521
1522 //================================================================================
1523 /*!
1524  * \brief Does its job
1525  */
1526 //================================================================================
1527
1528 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1529                                                const TopoDS_Shape& theShape)
1530 {
1531   // TODO: set priority of solids during Gen::Compute()
1532
1533   _mesh = & theMesh;
1534
1535   // check if proxy mesh already computed
1536   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1537   if ( !exp.More() )
1538     return error("No SOLID's in theShape"), _error;
1539
1540   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1541     return SMESH_ComputeErrorPtr(); // everything already computed
1542
1543   PyDump debugDump( theMesh );
1544
1545   // TODO: ignore already computed SOLIDs 
1546   if ( !findSolidsWithLayers())
1547     return _error;
1548
1549   if ( !findFacesWithLayers() )
1550     return _error;
1551
1552   for ( size_t i = 0; i < _sdVec.size(); ++i )
1553   {
1554     if ( ! makeLayer(_sdVec[i]) )
1555       return _error;
1556
1557     if ( _sdVec[i]._n2eMap.size() == 0 )
1558       continue;
1559     
1560     if ( ! inflate(_sdVec[i]) )
1561       return _error;
1562
1563     if ( ! refine(_sdVec[i]) )
1564       return _error;
1565   }
1566   if ( !shrink() )
1567     return _error;
1568
1569   addBoundaryElements();
1570
1571   makeGroupOfLE(); // debug
1572   debugDump.Finish();
1573
1574   return _error;
1575 }
1576
1577 //================================================================================
1578 /*!
1579  * \brief Check validity of hypotheses
1580  */
1581 //================================================================================
1582
1583 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1584                                                         const TopoDS_Shape& shape )
1585 {
1586   _mesh = & mesh;
1587
1588   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1589     return SMESH_ComputeErrorPtr(); // everything already computed
1590
1591
1592   findSolidsWithLayers();
1593   bool ok = findFacesWithLayers( true );
1594
1595   // remove _MeshOfSolid's of _SolidData's
1596   for ( size_t i = 0; i < _sdVec.size(); ++i )
1597     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1598
1599   if ( !ok )
1600     return _error;
1601
1602   return SMESH_ComputeErrorPtr();
1603 }
1604
1605 //================================================================================
1606 /*!
1607  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1608  */
1609 //================================================================================
1610
1611 bool _ViscousBuilder::findSolidsWithLayers()
1612 {
1613   // get all solids
1614   TopTools_IndexedMapOfShape allSolids;
1615   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1616   _sdVec.reserve( allSolids.Extent());
1617
1618   SMESH_Gen* gen = _mesh->GetGen();
1619   SMESH_HypoFilter filter;
1620   for ( int i = 1; i <= allSolids.Extent(); ++i )
1621   {
1622     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1623     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1624     if ( !algo ) continue;
1625     // TODO: check if algo is hidden
1626     const list <const SMESHDS_Hypothesis *> & allHyps =
1627       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1628     _SolidData* soData = 0;
1629     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1630     const StdMeshers_ViscousLayers* viscHyp = 0;
1631     for ( ; hyp != allHyps.end(); ++hyp )
1632       if ( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp ))
1633       {
1634         TopoDS_Shape hypShape;
1635         filter.Init( filter.Is( viscHyp ));
1636         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1637
1638         if ( !soData )
1639         {
1640           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1641                                                                     allSolids(i),
1642                                                                     /*toCreate=*/true);
1643           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1644           soData = & _sdVec.back();
1645           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1646         }
1647         soData->_hyps.push_back( viscHyp );
1648         soData->_hypShapes.push_back( hypShape );
1649       }
1650   }
1651   if ( _sdVec.empty() )
1652     return error
1653       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1654
1655   return true;
1656 }
1657
1658 //================================================================================
1659 /*!
1660  * \brief 
1661  */
1662 //================================================================================
1663
1664 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1665 {
1666   SMESH_MesherHelper helper( *_mesh );
1667   TopExp_Explorer exp;
1668   TopTools_IndexedMapOfShape solids;
1669
1670   // collect all faces-to-ignore defined by hyp
1671   for ( size_t i = 0; i < _sdVec.size(); ++i )
1672   {
1673     solids.Add( _sdVec[i]._solid );
1674
1675     // get faces-to-ignore defined by each hyp
1676     typedef const StdMeshers_ViscousLayers* THyp;
1677     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1678     list< TFacesOfHyp > ignoreFacesOfHyps;
1679     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
1680     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1681     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1682     {
1683       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1684       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1685     }
1686
1687     // fill _SolidData::_face2hyp and check compatibility of hypotheses
1688     const int nbHyps = _sdVec[i]._hyps.size();
1689     if ( nbHyps > 1 )
1690     {
1691       // check if two hypotheses define different parameters for the same FACE
1692       list< TFacesOfHyp >::iterator igFacesOfHyp;
1693       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
1694       {
1695         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
1696         THyp hyp = 0;
1697         igFacesOfHyp = ignoreFacesOfHyps.begin();
1698         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1699           if ( ! igFacesOfHyp->first.count( faceID ))
1700           {
1701             if ( hyp )
1702               return error(SMESH_Comment("Several hypotheses define "
1703                                          "Viscous Layers on the face #") << faceID );
1704             hyp = igFacesOfHyp->second;
1705           }
1706         if ( hyp )
1707           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
1708         else
1709           _sdVec[i]._ignoreFaceIds.insert( faceID );
1710       }
1711
1712       // check if two hypotheses define different number of viscous layers for
1713       // adjacent faces of a solid
1714       set< int > nbLayersSet;
1715       igFacesOfHyp = ignoreFacesOfHyps.begin();
1716       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1717       {
1718         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
1719       }
1720       if ( nbLayersSet.size() > 1 )
1721       {
1722         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
1723         {
1724           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
1725           THyp hyp1 = 0, hyp2 = 0;
1726           while( const TopoDS_Shape* face = fIt->next() )
1727           {
1728             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
1729             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
1730             if ( f2h != _sdVec[i]._face2hyp.end() )
1731             {
1732               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
1733             }
1734           }
1735           if ( hyp1 && hyp2 &&
1736                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
1737           {
1738             return error("Two hypotheses define different number of "
1739                          "viscous layers on adjacent faces");
1740           }
1741         }
1742       }
1743     } // if ( nbHyps > 1 )
1744     else
1745     {
1746       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
1747     }
1748   } // loop on _sdVec
1749
1750   if ( onlyWith ) // is called to check hypotheses compatibility only
1751     return true;
1752
1753   // fill _SolidData::_reversedFaceIds
1754   for ( size_t i = 0; i < _sdVec.size(); ++i )
1755   {
1756     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1757     for ( ; exp.More(); exp.Next() )
1758     {
1759       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1760       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
1761       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
1762           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
1763           helper.IsReversedSubMesh( face ))
1764       {
1765         _sdVec[i]._reversedFaceIds.insert( faceID );
1766       }
1767     }
1768   }
1769
1770   // Find faces to shrink mesh on (solution 2 in issue 0020832);
1771   TopTools_IndexedMapOfShape shapes;
1772   for ( size_t i = 0; i < _sdVec.size(); ++i )
1773   {
1774     shapes.Clear();
1775     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1776     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1777     {
1778       const TopoDS_Shape& edge = shapes(iE);
1779       // find 2 faces sharing an edge
1780       TopoDS_Shape FF[2];
1781       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1782       while ( fIt->more())
1783       {
1784         const TopoDS_Shape* f = fIt->next();
1785         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1786           FF[ int( !FF[0].IsNull()) ] = *f;
1787       }
1788       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1789       // check presence of layers on them
1790       int ignore[2];
1791       for ( int j = 0; j < 2; ++j )
1792         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1793       if ( ignore[0] == ignore[1] )
1794         continue; // nothing interesting
1795       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1796       // check presence of layers on fWOL within an adjacent SOLID
1797       bool collision = false;
1798       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1799       while ( const TopoDS_Shape* solid = sIt->next() )
1800         if ( !solid->IsSame( _sdVec[i]._solid ))
1801         {
1802           int iSolid = solids.FindIndex( *solid );
1803           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
1804           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1805           {
1806             //_sdVec[i]._noShrinkShapes.insert( iFace );
1807             //fWOL.Nullify();
1808             collision = true;
1809           }
1810         }
1811       // add edge to maps
1812       if ( !fWOL.IsNull())
1813       {
1814         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1815         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1816         if ( collision )
1817         {
1818           // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
1819           // on the edge but shrink won't be performed
1820           _sdVec[i]._noShrinkShapes.insert( edgeInd );
1821         }
1822       }
1823     }
1824   }
1825   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1826   // the algo of the SOLID sharing the FACE does not support it
1827   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1828   for ( size_t i = 0; i < _sdVec.size(); ++i )
1829   {
1830     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1831     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1832     {
1833       const TopoDS_Shape& fWOL = e2f->second;
1834       const TGeomID     edgeID = e2f->first;
1835       bool notShrinkFace = false;
1836       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1837       while ( soIt->more() )
1838       {
1839         const TopoDS_Shape* solid = soIt->next();
1840         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1841         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1842         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1843         notShrinkFace = true;
1844         size_t iSolid = 0;
1845         for ( ; iSolid < _sdVec.size(); ++iSolid )
1846         {
1847           if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
1848             if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
1849               notShrinkFace = false;
1850             break;
1851           }
1852         }
1853         if ( notShrinkFace )
1854         {
1855           _sdVec[i]._noShrinkShapes.insert( edgeID );
1856
1857           // add VERTEXes of the edge in _noShrinkShapes
1858           TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
1859           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
1860             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
1861
1862           // check if there is a collision with to-shrink-from EDGEs in iSolid
1863           if ( iSolid == _sdVec.size() )
1864             continue; // no VL in the solid
1865           shapes.Clear();
1866           TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
1867           for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1868           {
1869             const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
1870             const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
1871             if ( eID == edgeID ||
1872                  !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
1873                  _sdVec[i]._noShrinkShapes.count( eID ))
1874               continue;
1875             for ( int is1st = 0; is1st < 2; ++is1st )
1876             {
1877               TopoDS_Vertex V = helper.IthVertex( is1st, E );
1878               if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
1879               {
1880                 // _sdVec[i]._noShrinkShapes.insert( eID );
1881                 // V = helper.IthVertex( !is1st, E );
1882                 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
1883                 //iE = 0; // re-start the loop on EDGEs of fWOL
1884                 return error("No way to make a conformal mesh with "
1885                              "the given set of faces with layers", _sdVec[i]._index);
1886               }
1887             }
1888           }
1889         }
1890
1891       } // while ( soIt->more() )
1892     } // loop on _sdVec[i]._shrinkShape2Shape
1893   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
1894
1895   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1896
1897   for ( size_t i = 0; i < _sdVec.size(); ++i )
1898   {
1899     shapes.Clear();
1900     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1901     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1902     {
1903       const TopoDS_Shape& vertex = shapes(iV);
1904       // find faces WOL sharing the vertex
1905       vector< TopoDS_Shape > facesWOL;
1906       int totalNbFaces = 0;
1907       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1908       while ( fIt->more())
1909       {
1910         const TopoDS_Shape* f = fIt->next();
1911         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1912         {
1913           totalNbFaces++;
1914           const int fID = getMeshDS()->ShapeToIndex( *f );
1915           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
1916                !_sdVec[i]._noShrinkShapes.count( fID )*/)
1917             facesWOL.push_back( *f );
1918         }
1919       }
1920       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1921         continue; // no layers at this vertex or no WOL
1922       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1923       switch ( facesWOL.size() )
1924       {
1925       case 1:
1926       {
1927         helper.SetSubShape( facesWOL[0] );
1928         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1929         {
1930           TopoDS_Shape seamEdge;
1931           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1932           while ( eIt->more() && seamEdge.IsNull() )
1933           {
1934             const TopoDS_Shape* e = eIt->next();
1935             if ( helper.IsRealSeam( *e ) )
1936               seamEdge = *e;
1937           }
1938           if ( !seamEdge.IsNull() )
1939           {
1940             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1941             break;
1942           }
1943         }
1944         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1945         break;
1946       }
1947       case 2:
1948       {
1949         // find an edge shared by 2 faces
1950         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1951         while ( eIt->more())
1952         {
1953           const TopoDS_Shape* e = eIt->next();
1954           if ( helper.IsSubShape( *e, facesWOL[0]) &&
1955                helper.IsSubShape( *e, facesWOL[1]))
1956           {
1957             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1958           }
1959         }
1960         break;
1961       }
1962       default:
1963         return error("Not yet supported case", _sdVec[i]._index);
1964       }
1965     }
1966   }
1967
1968   // add FACEs of other SOLIDs to _ignoreFaceIds
1969   for ( size_t i = 0; i < _sdVec.size(); ++i )
1970   {
1971     shapes.Clear();
1972     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1973
1974     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1975     {
1976       if ( !shapes.Contains( exp.Current() ))
1977         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1978     }
1979   }
1980
1981   return true;
1982 }
1983
1984 //================================================================================
1985 /*!
1986  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
1987  */
1988 //================================================================================
1989
1990 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
1991                                      const StdMeshers_ViscousLayers* hyp,
1992                                      const TopoDS_Shape&             hypShape,
1993                                      set<TGeomID>&                   ignoreFaceIds)
1994 {
1995   TopExp_Explorer exp;
1996
1997   vector<TGeomID> ids = hyp->GetBndShapes();
1998   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1999   {
2000     for ( size_t ii = 0; ii < ids.size(); ++ii )
2001     {
2002       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2003       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2004         ignoreFaceIds.insert( ids[ii] );
2005     }
2006   }
2007   else // FACEs with layers are given
2008   {
2009     exp.Init( solid, TopAbs_FACE );
2010     for ( ; exp.More(); exp.Next() )
2011     {
2012       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2013       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2014         ignoreFaceIds.insert( faceInd );
2015     }
2016   }
2017
2018   // ignore internal FACEs if inlets and outlets are specified
2019   if ( hyp->IsToIgnoreShapes() )
2020   {
2021     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2022     TopExp::MapShapesAndAncestors( hypShape,
2023                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2024
2025     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2026     {
2027       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2028       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2029         continue;
2030
2031       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2032       if ( nbSolids > 1 )
2033         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2034     }
2035   }
2036 }
2037
2038 //================================================================================
2039 /*!
2040  * \brief Create the inner surface of the viscous layer and prepare data for infation
2041  */
2042 //================================================================================
2043
2044 bool _ViscousBuilder::makeLayer(_SolidData& data)
2045 {
2046   // get all sub-shapes to make layers on
2047   set<TGeomID> subIds, faceIds;
2048   subIds = data._noShrinkShapes;
2049   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2050   for ( ; exp.More(); exp.Next() )
2051   {
2052     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2053     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2054     {
2055       faceIds.insert( fSubM->GetId() );
2056       SMESH_subMeshIteratorPtr subIt = fSubM->getDependsOnIterator(/*includeSelf=*/true);
2057       while ( subIt->more() )
2058         subIds.insert( subIt->next()->GetId() );
2059     }
2060   }
2061
2062   // make a map to find new nodes on sub-shapes shared with other SOLID
2063   map< TGeomID, TNode2Edge* >::iterator s2ne;
2064   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2065   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2066   {
2067     TGeomID shapeInd = s2s->first;
2068     for ( size_t i = 0; i < _sdVec.size(); ++i )
2069     {
2070       if ( _sdVec[i]._index == data._index ) continue;
2071       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2072       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2073            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2074       {
2075         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2076         break;
2077       }
2078     }
2079   }
2080
2081   // Create temporary faces and _LayerEdge's
2082
2083   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2084
2085   data._stepSize = Precision::Infinite();
2086   data._stepSizeNodes[0] = 0;
2087
2088   SMESH_MesherHelper helper( *_mesh );
2089   helper.SetSubShape( data._solid );
2090   helper.SetElementsOnShape( true );
2091
2092   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2093   TNode2Edge::iterator n2e2;
2094
2095   // collect _LayerEdge's of shapes they are based on
2096   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2097   const int nbShapes = getMeshDS()->MaxShapeIndex();
2098   edgesByGeom.resize( nbShapes+1 );
2099
2100   // set data of _EdgesOnShape's
2101   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2102   {
2103     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2104     while ( smIt->more() )
2105     {
2106       sm = smIt->next();
2107       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2108            !faceIds.count( sm->GetId() ))
2109         continue;
2110       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2111     }
2112   }
2113   // make _LayerEdge's
2114   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2115   {
2116     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2117     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2118     SMESH_ProxyMesh::SubMesh* proxySub =
2119       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2120
2121     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2122     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2123
2124     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2125     while ( eIt->more() )
2126     {
2127       const SMDS_MeshElement* face = eIt->next();
2128       double          faceMaxCosin = -1;
2129       _LayerEdge*     maxCosinEdge = 0;
2130       int             nbDegenNodes = 0;
2131
2132       newNodes.resize( face->NbCornerNodes() );
2133       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2134       {
2135         const SMDS_MeshNode* n = face->GetNode( i );
2136         const int      shapeID = n->getshapeId();
2137         const bool onDegenShap = helper.IsDegenShape( shapeID );
2138         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2139         if ( onDegenShap )
2140         {
2141           if ( onDegenEdge )
2142           {
2143             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2144             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2145             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2146             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2147               n = vN;
2148               nbDegenNodes++;
2149             }
2150           }
2151           else
2152           {
2153             nbDegenNodes++;
2154           }
2155         }
2156         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2157         if ( !(*n2e).second )
2158         {
2159           // add a _LayerEdge
2160           _LayerEdge* edge = new _LayerEdge();
2161           edge->_nodes.push_back( n );
2162           n2e->second = edge;
2163           edgesByGeom[ shapeID ]._edges.push_back( edge );
2164           const bool noShrink = data._noShrinkShapes.count( shapeID );
2165
2166           SMESH_TNodeXYZ xyz( n );
2167
2168           // set edge data or find already refined _LayerEdge and get data from it
2169           if (( !noShrink                                                     ) &&
2170               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2171               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2172               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2173           {
2174             _LayerEdge* foundEdge = (*n2e2).second;
2175             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2176             foundEdge->_pos.push_back( lastPos );
2177             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2178             const_cast< SMDS_MeshNode* >
2179               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2180           }
2181           else
2182           {
2183             if ( !noShrink )
2184             {
2185               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2186             }
2187             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], subIds, helper, data ))
2188               return false;
2189           }
2190           dumpMove(edge->_nodes.back());
2191
2192           if ( edge->_cosin > faceMaxCosin )
2193           {
2194             faceMaxCosin = edge->_cosin;
2195             maxCosinEdge = edge;
2196           }
2197         }
2198         newNodes[ i ] = n2e->second->_nodes.back();
2199
2200         if ( onDegenEdge )
2201           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2202       }
2203       if ( newNodes.size() - nbDegenNodes < 2 )
2204         continue;
2205
2206       // create a temporary face
2207       const SMDS_MeshElement* newFace =
2208         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId() );
2209       proxySub->AddElement( newFace );
2210
2211       // compute inflation step size by min size of element on a convex surface
2212       if ( faceMaxCosin > theMinSmoothCosin )
2213         limitStepSize( data, face, maxCosinEdge );
2214
2215     } // loop on 2D elements on a FACE
2216   } // loop on FACEs of a SOLID
2217
2218   data._epsilon = 1e-7;
2219   if ( data._stepSize < 1. )
2220     data._epsilon *= data._stepSize;
2221
2222   if ( !findShapesToSmooth( data ))
2223     return false;
2224
2225   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2226   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2227
2228   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2229   TNode2Edge::iterator n2e;
2230   const SMDS_MeshNode* nn[2];
2231   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2232   {
2233     _EdgesOnShape& eos = data._edgesOnShape[iS];
2234     vector< _LayerEdge* >& localEdges = eos._edges;
2235     for ( size_t i = 0; i < localEdges.size(); ++i )
2236     {
2237       _LayerEdge* edge = localEdges[i];
2238       if ( edge->IsOnEdge() )
2239       {
2240         // get neighbor nodes
2241         bool hasData = ( edge->_2neibors->_edges[0] );
2242         if ( hasData ) // _LayerEdge is a copy of another one
2243         {
2244           nn[0] = edge->_2neibors->srcNode(0);
2245           nn[1] = edge->_2neibors->srcNode(1);
2246         }
2247         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2248         {
2249           return false;
2250         }
2251         // set neighbor _LayerEdge's
2252         for ( int j = 0; j < 2; ++j )
2253         {
2254           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2255             return error("_LayerEdge not found by src node", data._index);
2256           edge->_2neibors->_edges[j] = n2e->second;
2257         }
2258         if ( !hasData )
2259           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2260       }
2261
2262       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2263       {
2264         _Simplex& s = edge->_simplices[j];
2265         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2266         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2267       }
2268
2269       // For an _LayerEdge on a degenerated EDGE, copy some data from
2270       // a corresponding _LayerEdge on a VERTEX
2271       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2272       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2273       {
2274         // Generally we should not get here
2275         if ( eos.ShapeType() != TopAbs_EDGE )
2276           continue;
2277         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2278         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2279         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2280           continue;
2281         const _LayerEdge* vEdge = n2e->second;
2282         edge->_normal    = vEdge->_normal;
2283         edge->_lenFactor = vEdge->_lenFactor;
2284         edge->_cosin     = vEdge->_cosin;
2285       }
2286     }
2287   }
2288
2289   // fix _LayerEdge::_2neibors on EDGEs to smooth
2290   map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2291   for ( ; e2c != data._edge2curve.end(); ++e2c )
2292     if ( !e2c->second.IsNull() )
2293     {
2294       if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2295         data.Sort2NeiborsOnEdge( eos->_edges );
2296     }
2297
2298   dumpFunctionEnd();
2299   return true;
2300 }
2301
2302 //================================================================================
2303 /*!
2304  * \brief Compute inflation step size by min size of element on a convex surface
2305  */
2306 //================================================================================
2307
2308 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2309                                      const SMDS_MeshElement* face,
2310                                      const _LayerEdge*       maxCosinEdge )
2311 {
2312   int iN = 0;
2313   double minSize = 10 * data._stepSize;
2314   const int nbNodes = face->NbCornerNodes();
2315   for ( int i = 0; i < nbNodes; ++i )
2316   {
2317     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2318     const SMDS_MeshNode*  curN = face->GetNode( i );
2319     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2320          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2321     {
2322       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2323       if ( dist < minSize )
2324         minSize = dist, iN = i;
2325     }
2326   }
2327   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2328   if ( newStep < data._stepSize )
2329   {
2330     data._stepSize = newStep;
2331     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2332     data._stepSizeNodes[0] = face->GetNode( iN );
2333     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2334   }
2335 }
2336
2337 //================================================================================
2338 /*!
2339  * \brief Compute inflation step size by min size of element on a convex surface
2340  */
2341 //================================================================================
2342
2343 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2344 {
2345   if ( minSize < data._stepSize )
2346   {
2347     data._stepSize = minSize;
2348     if ( data._stepSizeNodes[0] )
2349     {
2350       double dist =
2351         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2352       data._stepSizeCoeff = data._stepSize / dist;
2353     }
2354   }
2355 }
2356
2357 //================================================================================
2358 /*!
2359  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2360  */
2361 //================================================================================
2362
2363 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2364 {
2365   const int nbTestPnt = 5; // on a FACE sub-shape
2366
2367   BRepLProp_SLProps surfProp( 2, 1e-6 );
2368   SMESH_MesherHelper helper( *_mesh );
2369
2370   data._convexFaces.clear();
2371
2372   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2373   {
2374     _EdgesOnShape& eof = data._edgesOnShape[iS];
2375     if ( eof.ShapeType() != TopAbs_FACE ||
2376          data._ignoreFaceIds.count( eof._shapeID ))
2377       continue;
2378
2379     TopoDS_Face        F = TopoDS::Face( eof._shape );
2380     SMESH_subMesh *   sm = eof._subMesh;
2381     const TGeomID faceID = eof._shapeID;
2382
2383     BRepAdaptor_Surface surface( F, false );
2384     surfProp.SetSurface( surface );
2385
2386     bool isTooCurved = false;
2387
2388     _ConvexFace cnvFace;
2389     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2390     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2391     while ( smIt->more() )
2392     {
2393       sm = smIt->next();
2394       const TGeomID subID = sm->GetId();
2395       // find _LayerEdge's of a sub-shape
2396       _EdgesOnShape* eos;
2397       if (( eos = data.GetShapeEdges( subID )))
2398         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2399       else
2400         continue;
2401       // check concavity and curvature and limit data._stepSize
2402       const double minCurvature =
2403         1. / ( eos->_hyp.GetTotalThickness() * ( 1+theThickToIntersection ));
2404       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2405       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2406       {
2407         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2408         surfProp.SetParameters( uv.X(), uv.Y() );
2409         if ( !surfProp.IsCurvatureDefined() )
2410           continue;
2411         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2412         {
2413           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2414           isTooCurved = true;
2415         }
2416         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2417         {
2418           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2419           isTooCurved = true;
2420         }
2421       }
2422     } // loop on sub-shapes of the FACE
2423
2424     if ( !isTooCurved ) continue;
2425
2426     _ConvexFace & convFace =
2427       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2428
2429     convFace._face = F;
2430     convFace._normalsFixed = false;
2431
2432     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2433     // prism distortion.
2434     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2435     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2436     {
2437       // there are _LayerEdge's on the FACE it-self;
2438       // select _LayerEdge's near EDGEs
2439       _EdgesOnShape& eos = * id2eos->second;
2440       for ( size_t i = 0; i < eos._edges.size(); ++i )
2441       {
2442         _LayerEdge* ledge = eos._edges[ i ];
2443         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2444           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2445           {
2446             convFace._simplexTestEdges.push_back( ledge );
2447             break;
2448           }
2449       }
2450     }
2451     else
2452     {
2453       // where there are no _LayerEdge's on a _ConvexFace,
2454       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2455       // so that collision of viscous internal faces is not detected by check of
2456       // intersection of _LayerEdge's with the viscous internal faces.
2457
2458       set< const SMDS_MeshNode* > usedNodes;
2459
2460       // look for _LayerEdge's with null _sWOL
2461       id2eos = convFace._subIdToEOS.begin();
2462       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2463       {
2464         _EdgesOnShape& eos = * id2eos->second;
2465         if ( !eos._sWOL.IsNull() )
2466           continue;
2467         for ( size_t i = 0; i < eos._edges.size(); ++i )
2468         {
2469           _LayerEdge* ledge = eos._edges[ i ];
2470           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2471           if ( !usedNodes.insert( srcNode ).second ) continue;
2472
2473           _Simplex::GetSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
2474           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2475           {
2476             usedNodes.insert( ledge->_simplices[i]._nPrev );
2477             usedNodes.insert( ledge->_simplices[i]._nNext );
2478           }
2479           convFace._simplexTestEdges.push_back( ledge );
2480         }
2481       }
2482     }
2483   } // loop on FACEs of data._solid
2484 }
2485
2486 //================================================================================
2487 /*!
2488  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2489  */
2490 //================================================================================
2491
2492 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2493 {
2494   // define allowed thickness
2495   computeGeomSize( data ); // compute data._geomSize
2496
2497   data._maxThickness = 0;
2498   data._minThickness = 1e100;
2499   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2500   for ( ; hyp != data._hyps.end(); ++hyp )
2501   {
2502     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2503     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2504   }
2505   const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2506
2507   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2508   // boundry inclined to the shape at a sharp angle
2509
2510   //list< TGeomID > shapesToSmooth;
2511   TopTools_MapOfShape edgesOfSmooFaces;
2512
2513   SMESH_MesherHelper helper( *_mesh );
2514   bool ok = true;
2515
2516   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2517   data._nbShapesToSmooth = 0;
2518
2519   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2520   {
2521     _EdgesOnShape& eos = edgesByGeom[iS];
2522     eos._toSmooth = false;
2523     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2524       continue;
2525
2526     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2527     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2528     {
2529       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2530       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2531       if ( eE.empty() ) continue;
2532       // TopLoc_Location loc;
2533       // Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( S ), loc );
2534       // bool isPlane = GeomLib_IsPlanarSurface( surface ).IsPlanar();
2535       //if ( eE[0]->_sWOL.IsNull() )
2536       {
2537         double faceSize;
2538         for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2539           if ( eE[i]->_cosin > theMinSmoothCosin )
2540           {
2541             SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2542             while ( fIt->more() && !eos._toSmooth )
2543             {
2544               const SMDS_MeshElement* face = fIt->next();
2545               if ( getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2546                 eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2547             }
2548           }
2549       }
2550       // else
2551       // {
2552       //   const TopoDS_Face& F1 = TopoDS::Face( S );
2553       //   const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
2554       //   const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
2555       //   for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2556       //   {
2557       //     gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
2558       //     gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
2559       //     double angle = dir1.Angle(  );
2560       //     double cosin = cos( angle );
2561       //     eos._toSmooth = ( cosin > theMinSmoothCosin );
2562       //   }
2563       // }
2564     }
2565     if ( eos._toSmooth )
2566     {
2567       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2568         edgesOfSmooFaces.Add( eExp.Current() );
2569
2570       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2571     }
2572     data._nbShapesToSmooth += eos._toSmooth;
2573
2574   }  // check FACEs
2575
2576   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2577   {
2578     _EdgesOnShape& eos = edgesByGeom[iS];
2579     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2580     if ( !eos._hyp.ToSmooth() ) continue;
2581
2582     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2583     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2584       continue;
2585
2586     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2587     {
2588       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2589       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2590       if ( eV.empty() ) continue;
2591       gp_Vec  eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2592       double angle = eDir.Angle( eV[0]->_normal );
2593       double cosin = Cos( angle );
2594       double cosinAbs = Abs( cosin );
2595       if ( cosinAbs > theMinSmoothCosin )
2596       {
2597         // always smooth analytic EDGEs
2598         eos._toSmooth = ! data.CurveForSmooth( E, eos, helper ).IsNull();
2599
2600         // compare tgtThick with the length of an end segment
2601         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2602         while ( eIt->more() && !eos._toSmooth )
2603         {
2604           const SMDS_MeshElement* endSeg = eIt->next();
2605           if ( endSeg->getshapeId() == iS )
2606           {
2607             double segLen =
2608               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2609             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2610           }
2611         }
2612       }
2613     }
2614     data._nbShapesToSmooth += eos._toSmooth;
2615
2616   } // check EDGEs
2617
2618   // Reset _cosin if no smooth is allowed by the user
2619   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2620   {
2621     _EdgesOnShape& eos = edgesByGeom[iS];
2622     if ( eos._edges.empty() ) continue;
2623
2624     if ( !eos._hyp.ToSmooth() )
2625       for ( size_t i = 0; i < eos._edges.size(); ++i )
2626         eos._edges[i]->SetCosin( 0 );
2627   }
2628
2629
2630   // int nbShapes = 0;
2631   // for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2632   // {
2633   //   nbShapes += ( edgesByGeom[iS]._edges.size() > 0 );
2634   // }
2635   // data._edgesOnShape.reserve( nbShapes );
2636
2637   // // first we put _LayerEdge's on shapes to smooth (EGDEs go first)
2638   // vector< _LayerEdge* > edges;
2639   // list< TGeomID >::iterator gIt = shapesToSmooth.begin();
2640   // for ( ; gIt != shapesToSmooth.end(); ++gIt )
2641   // {
2642   //   _EdgesOnShape& eos = edgesByGeom[ *gIt ];
2643   //   if ( eos._edges.empty() ) continue;
2644   //   eos._edges.swap( edges ); // avoid copying array
2645   //   eos._toSmooth = true;
2646   //   data._edgesOnShape.push_back( eos );
2647   //   data._edgesOnShape.back()._edges.swap( edges );
2648   // }
2649
2650   // // then the rest _LayerEdge's
2651   // for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2652   // {
2653   //   _EdgesOnShape& eos = edgesByGeom[ *gIt ];
2654   //   if ( eos._edges.empty() ) continue;
2655   //   eos._edges.swap( edges ); // avoid copying array
2656   //   eos._toSmooth = false;
2657   //   data._edgesOnShape.push_back( eos );
2658   //   data._edgesOnShape.back()._edges.swap( edges );
2659   // }
2660
2661   return ok;
2662 }
2663
2664 //================================================================================
2665 /*!
2666  * \brief initialize data of _EdgesOnShape
2667  */
2668 //================================================================================
2669
2670 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
2671                                     SMESH_subMesh* sm,
2672                                     _SolidData&    data )
2673 {
2674   if ( !eos._shape.IsNull() ||
2675        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
2676     return;
2677
2678   SMESH_MesherHelper helper( *_mesh );
2679
2680   eos._subMesh = sm;
2681   eos._shapeID = sm->GetId();
2682   eos._shape   = sm->GetSubShape();
2683   if ( eos.ShapeType() == TopAbs_FACE )
2684     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
2685   eos._toSmooth = false;
2686
2687   // set _SWOL
2688   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
2689     data._shrinkShape2Shape.find( eos._shapeID );
2690   if ( s2s != data._shrinkShape2Shape.end() )
2691     eos._sWOL = s2s->second;
2692
2693   // set _hyp
2694   if ( data._hyps.size() == 1 )
2695   {
2696     eos._hyp = data._hyps.back();
2697   }
2698   else
2699   {
2700     // compute average StdMeshers_ViscousLayers parameters
2701     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
2702     if ( eos.ShapeType() == TopAbs_FACE )
2703     {
2704       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
2705         eos._hyp = f2hyp->second;
2706     }
2707     else
2708     {
2709       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
2710       while ( const TopoDS_Shape* face = fIt->next() )
2711       {
2712         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2713         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
2714           eos._hyp.Add( f2hyp->second );
2715       }
2716     }
2717   }
2718
2719   // set _faceNormals
2720   if ( ! eos._hyp.UseSurfaceNormal() )
2721   {
2722     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
2723     {
2724       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2725       eos._faceNormals.resize( smDS->NbElements() );
2726
2727       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2728       for ( int iF = 0; eIt->more(); ++iF )
2729       {
2730         const SMDS_MeshElement* face = eIt->next();
2731         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
2732           eos._faceNormals[iF].SetCoord( 0,0,0 );
2733       }
2734
2735       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
2736         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
2737           eos._faceNormals[iF].Reverse();
2738     }
2739     else // find EOS of adjacent FACEs
2740     {
2741       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
2742       while ( const TopoDS_Shape* face = fIt->next() )
2743       {
2744         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2745         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
2746         if ( eos._faceEOS.back()->_shape.IsNull() )
2747           // avoid using uninitialised _shapeID in GetNormal()
2748           eos._faceEOS.back()->_shapeID = faceID;
2749       }
2750     }
2751   }
2752 }
2753
2754 //================================================================================
2755 /*!
2756  * \brief Returns normal of a face
2757  */
2758 //================================================================================
2759
2760 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
2761 {
2762   bool ok = false;
2763   const _EdgesOnShape* eos = 0;
2764
2765   if ( face->getshapeId() == _shapeID )
2766   {
2767     eos = this;
2768   }
2769   else
2770   {
2771     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
2772       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
2773         eos = _faceEOS[ iF ];
2774   }
2775
2776   if (( eos ) &&
2777       ( ok = ( face->getIdInShape() < eos->_faceNormals.size() )))
2778   {
2779     norm = eos->_faceNormals[ face->getIdInShape() ];
2780   }
2781   else if ( !eos )
2782   {
2783     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
2784               << " on _shape #" << _shapeID );
2785   }
2786   return ok;
2787 }
2788
2789
2790 //================================================================================
2791 /*!
2792  * \brief Set data of _LayerEdge needed for smoothing
2793  *  \param subIds - ids of sub-shapes of a SOLID to take into account faces from
2794  */
2795 //================================================================================
2796
2797 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
2798                                   _EdgesOnShape&      eos,
2799                                   const set<TGeomID>& subIds,
2800                                   SMESH_MesherHelper& helper,
2801                                   _SolidData&         data)
2802 {
2803   const SMDS_MeshNode* node = edge._nodes[0]; // source node
2804
2805   edge._len       = 0;
2806   edge._2neibors  = 0;
2807   edge._curvature = 0;
2808
2809   // --------------------------
2810   // Compute _normal and _cosin
2811   // --------------------------
2812
2813   edge._cosin = 0;
2814   edge._normal.SetCoord(0,0,0);
2815
2816   int totalNbFaces = 0;
2817   TopoDS_Face F;
2818   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
2819   gp_Vec geomNorm;
2820   bool normOK = true;
2821
2822   const bool onShrinkShape = !eos._sWOL.IsNull();
2823   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
2824                               ( eos.ShapeType() != TopAbs_FACE && !onShrinkShape ));
2825
2826   // get geom FACEs the node lies on
2827   //if ( useGeometry )
2828   {
2829     set<TGeomID> faceIds;
2830     if  ( eos.ShapeType() == TopAbs_FACE )
2831     {
2832       faceIds.insert( eos._shapeID );
2833     }
2834     else
2835     {
2836       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2837       while ( fIt->more() )
2838         faceIds.insert( fIt->next()->getshapeId() );
2839     }
2840     set<TGeomID>::iterator id = faceIds.begin();
2841     for ( ; id != faceIds.end(); ++id )
2842     {
2843       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
2844       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
2845         continue;
2846       F = TopoDS::Face( s );
2847       face2Norm[ totalNbFaces ].first = F;
2848       totalNbFaces++;
2849     }
2850   }
2851
2852   // find _normal
2853   if ( useGeometry )
2854   {
2855     if ( onShrinkShape ) // one of faces the node is on has no layers
2856     {
2857       if ( eos.SWOLType() == TopAbs_EDGE )
2858       {
2859         // inflate from VERTEX along EDGE
2860         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
2861       }
2862       else if ( eos.ShapeType() == TopAbs_VERTEX )
2863       {
2864         // inflate from VERTEX along FACE
2865         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
2866                                    node, helper, normOK, &edge._cosin);
2867       }
2868       else
2869       {
2870         // inflate from EDGE along FACE
2871         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
2872                                    node, helper, normOK);
2873       }
2874     }
2875
2876     // layers are on all faces of SOLID the node is on
2877     else
2878     {
2879       int nbOkNorms = 0;
2880       for ( int iF = 0; iF < totalNbFaces; ++iF )
2881       {
2882         F = TopoDS::Face( face2Norm[ iF ].first );
2883         geomNorm = getFaceNormal( node, F, helper, normOK );
2884         if ( !normOK ) continue;
2885         nbOkNorms++;
2886
2887         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2888           geomNorm.Reverse();
2889         face2Norm[ iF ].second = geomNorm.XYZ();
2890         edge._normal += geomNorm.XYZ();
2891       }
2892       if ( nbOkNorms == 0 )
2893         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
2894
2895       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
2896       {
2897         // opposite normals, re-get normals at shifted positions (IPAL 52426)
2898         edge._normal.SetCoord( 0,0,0 );
2899         for ( int iF = 0; iF < totalNbFaces; ++iF )
2900         {
2901           const TopoDS_Face& F = face2Norm[iF].first;
2902           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
2903           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2904             geomNorm.Reverse();
2905           if ( normOK )
2906             face2Norm[ iF ].second = geomNorm.XYZ();
2907           edge._normal += face2Norm[ iF ].second;
2908         }
2909       }
2910
2911       if ( totalNbFaces < 3 )
2912       {
2913         //edge._normal /= totalNbFaces;
2914       }
2915       else
2916       {
2917         edge._normal = getWeigthedNormal( node, face2Norm, totalNbFaces );
2918       }
2919     }
2920   }
2921   else // !useGeometry - get _normal using surrounding mesh faces
2922   {
2923     set<TGeomID> faceIds;
2924
2925     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2926     while ( fIt->more() )
2927     {
2928       const SMDS_MeshElement* face = fIt->next();
2929       if ( eos.GetNormal( face, geomNorm ))
2930       {
2931         if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
2932           continue; // use only one mesh face on FACE
2933         edge._normal += geomNorm.XYZ();
2934         totalNbFaces++;
2935       }
2936     }
2937   }
2938
2939   // compute _cosin
2940   //if ( eos._hyp.UseSurfaceNormal() )
2941   {
2942     switch ( eos.ShapeType() )
2943     {
2944     case TopAbs_FACE: {
2945       edge._cosin = 0;
2946       break;
2947     }
2948     case TopAbs_EDGE: {
2949       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
2950       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
2951       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
2952       edge._cosin      = Cos( angle );
2953       //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
2954       break;
2955     }
2956     case TopAbs_VERTEX: {
2957       if ( eos.SWOLType() != TopAbs_FACE ) { // else _cosin is set by getFaceDir()
2958         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
2959         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
2960         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
2961         edge._cosin      = Cos( angle );
2962         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
2963           for ( int iF = totalNbFaces-2; iF >=0; --iF )
2964           {
2965             F = face2Norm[ iF ].first;
2966             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
2967             if ( normOK ) {
2968               double angle = inFaceDir.Angle( edge._normal );
2969               edge._cosin = Max( edge._cosin, Cos( angle ));
2970             }
2971           }
2972       }
2973       //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2974       break;
2975     }
2976     default:
2977       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2978     }
2979   }
2980
2981   double normSize = edge._normal.SquareModulus();
2982   if ( normSize < numeric_limits<double>::min() )
2983     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2984
2985   edge._normal /= sqrt( normSize );
2986
2987   // TODO: if ( !normOK ) then get normal by mesh faces
2988
2989   // Set the rest data
2990   // --------------------
2991   if ( onShrinkShape )
2992   {
2993     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2994     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2995       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2996
2997     // set initial position which is parameters on _sWOL in this case
2998     if ( eos.SWOLType() == TopAbs_EDGE )
2999     {
3000       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3001       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3002       if ( edge._nodes.size() > 1 )
3003         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3004     }
3005     else // TopAbs_FACE
3006     {
3007       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3008       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3009       if ( edge._nodes.size() > 1 )
3010         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3011     }
3012   }
3013   else
3014   {
3015     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3016
3017     if ( eos.ShapeType() == TopAbs_FACE )
3018     {
3019       _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3020     }
3021   }
3022
3023   // Set neighbour nodes for a _LayerEdge based on EDGE
3024
3025   if ( eos.ShapeType() == TopAbs_EDGE /*||
3026        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3027   {
3028     edge._2neibors = new _2NearEdges;
3029     // target node instead of source ones will be set later
3030     // if ( ! findNeiborsOnEdge( &edge,
3031     //                           edge._2neibors->_nodes[0],
3032     //                           edge._2neibors->_nodes[1], eos,
3033     //                           data))
3034     //   return false;
3035     // edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
3036     //                          edge._2neibors->_nodes[1],
3037     //                          helper);
3038   }
3039
3040   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3041
3042   return true;
3043 }
3044
3045 //================================================================================
3046 /*!
3047  * \brief Return normal to a FACE at a node
3048  *  \param [in] n - node
3049  *  \param [in] face - FACE
3050  *  \param [in] helper - helper
3051  *  \param [out] isOK - true or false
3052  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3053  *  \return gp_XYZ - normal
3054  */
3055 //================================================================================
3056
3057 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3058                                       const TopoDS_Face&   face,
3059                                       SMESH_MesherHelper&  helper,
3060                                       bool&                isOK,
3061                                       bool                 shiftInside)
3062 {
3063   gp_XY uv;
3064   if ( shiftInside )
3065   {
3066     // get a shifted position
3067     gp_Pnt p = SMESH_TNodeXYZ( node );
3068     gp_XYZ shift( 0,0,0 );
3069     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3070     switch ( S.ShapeType() ) {
3071     case TopAbs_VERTEX:
3072     {
3073       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3074       break;
3075     }
3076     case TopAbs_EDGE:
3077     {
3078       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3079       break;
3080     }
3081     default:
3082       isOK = false;
3083     }
3084     if ( isOK )
3085       shift.Normalize();
3086     p.Translate( shift * 1e-5 );
3087
3088     TopLoc_Location loc;
3089     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3090
3091     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3092     
3093     projector.Perform( p );
3094     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3095     {
3096       isOK = false;
3097       return p.XYZ();
3098     }
3099     Quantity_Parameter U,V;
3100     projector.LowerDistanceParameters(U,V);
3101     uv.SetCoord( U,V );
3102   }
3103   else
3104   {
3105     uv = helper.GetNodeUV( face, node, 0, &isOK );
3106   }
3107
3108   gp_Dir normal;
3109   isOK = false;
3110
3111   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3112
3113   if ( !shiftInside &&
3114        helper.IsDegenShape( node->getshapeId() ) &&
3115        getFaceNormalAtSingularity( uv, face, helper, normal ))
3116   {
3117     isOK = true;
3118     return normal.XYZ();
3119   }
3120
3121   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3122   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3123
3124   if ( pointKind == IMPOSSIBLE &&
3125        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3126   {
3127     // probably NormEstim() failed due to a too high tolerance
3128     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3129     isOK = ( pointKind < IMPOSSIBLE );
3130   }
3131   if ( pointKind < IMPOSSIBLE )
3132   {
3133     if ( pointKind != REGULAR &&
3134          !shiftInside &&
3135          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3136     {
3137       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3138       if ( normShift * normal.XYZ() < 0. )
3139         normal = normShift;
3140     }
3141     isOK = true;
3142   }
3143
3144   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3145   {
3146     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3147
3148     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3149     while ( fIt->more() )
3150     {
3151       const SMDS_MeshElement* f = fIt->next();
3152       if ( f->getshapeId() == faceID )
3153       {
3154         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3155         if ( isOK )
3156         {
3157           TopoDS_Face ff = face;
3158           ff.Orientation( TopAbs_FORWARD );
3159           if ( helper.IsReversedSubMesh( ff ))
3160             normal.Reverse();
3161           break;
3162         }
3163       }
3164     }
3165   }
3166   return normal.XYZ();
3167 }
3168
3169 //================================================================================
3170 /*!
3171  * \brief Try to get normal at a singularity of a surface basing on it's nature
3172  */
3173 //================================================================================
3174
3175 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3176                                                   const TopoDS_Face&  face,
3177                                                   SMESH_MesherHelper& helper,
3178                                                   gp_Dir&             normal )
3179 {
3180   BRepAdaptor_Surface surface( face );
3181   gp_Dir axis;
3182   if ( !getRovolutionAxis( surface, axis ))
3183     return false;
3184
3185   double f,l, d, du, dv;
3186   f = surface.FirstUParameter();
3187   l = surface.LastUParameter();
3188   d = ( uv.X() - f ) / ( l - f );
3189   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3190   f = surface.FirstVParameter();
3191   l = surface.LastVParameter();
3192   d = ( uv.Y() - f ) / ( l - f );
3193   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3194
3195   gp_Dir refDir;
3196   gp_Pnt2d testUV = uv;
3197   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3198   double tol = 1e-5;
3199   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3200   for ( int iLoop = 0; true ; ++iLoop )
3201   {
3202     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3203     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3204       break;
3205     if ( iLoop > 20 )
3206       return false;
3207     tol /= 10.;
3208   }
3209
3210   if ( axis * refDir < 0. )
3211     axis.Reverse();
3212
3213   normal = axis;
3214
3215   return true;
3216 }
3217
3218 //================================================================================
3219 /*!
3220  * \brief Return a normal at a node weighted with angles taken by FACEs
3221  *  \param [in] n - the node
3222  *  \param [in] fId2Normal - FACE ids and normals
3223  *  \param [in] nbFaces - nb of FACEs meeting at the node
3224  *  \return gp_XYZ - computed normal
3225  */
3226 //================================================================================
3227
3228 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode*             n,
3229                                            std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
3230                                            int                              nbFaces )
3231 {
3232   gp_XYZ resNorm(0,0,0);
3233   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
3234   if ( V.ShapeType() != TopAbs_VERTEX )
3235   {
3236     for ( int i = 0; i < nbFaces; ++i )
3237       resNorm += fId2Normal[i].second;
3238     return resNorm;
3239   }
3240
3241   // exclude equal normals
3242   int nbUniqNorms = nbFaces;
3243   for ( int i = 0; i < nbFaces; ++i ) {
3244     for ( int j = i+1; j < nbFaces; ++j )
3245       if ( fId2Normal[i].second.IsEqual( fId2Normal[j].second, 0.1 ))
3246       {
3247         fId2Normal[i].second.SetCoord( 0,0,0 );
3248         --nbUniqNorms;
3249         break;
3250       }
3251   }
3252   for ( int i = 0; i < nbFaces; ++i )
3253     resNorm += fId2Normal[i].second;
3254
3255   // assure that resNorm is visible by every FACE (IPAL0052675)
3256   if ( nbUniqNorms > 3 )
3257   {
3258     bool change = false;
3259     for ( int nbAttempts = 0; nbAttempts < nbFaces; ++nbAttempts)
3260     {
3261       for ( int i = 0; i < nbFaces; ++i )
3262         if ( resNorm * fId2Normal[i].second < 0.5 )
3263         {
3264           resNorm += fId2Normal[i].second;
3265           change = true;
3266         }
3267       if ( !change ) break;
3268     }
3269   }
3270
3271   // double angles[30];
3272   // for ( int i = 0; i < nbFaces; ++i )
3273   // {
3274   //   const TopoDS_Face& F = fId2Normal[i].first;
3275
3276   //   // look for two EDGEs shared by F and other FACEs within fId2Normal
3277   //   TopoDS_Edge ee[2];
3278   //   int nbE = 0;
3279   //   PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3280   //   while ( const TopoDS_Shape* E = eIt->next() )
3281   //   {
3282   //     if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
3283   //       continue;
3284   //     bool isSharedEdge = false;
3285   //     for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
3286   //     {
3287   //       if ( i == j ) continue;
3288   //       const TopoDS_Shape& otherF = fId2Normal[j].first;
3289   //       isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
3290   //     }
3291   //     if ( !isSharedEdge )
3292   //       continue;
3293   //     ee[ nbE ] = TopoDS::Edge( *E );
3294   //     ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
3295   //     if ( ++nbE == 2 )
3296   //       break;
3297   //   }
3298
3299   //   // get an angle between the two EDGEs
3300   //   angles[i] = 0;
3301   //   if ( nbE < 1 ) continue;
3302   //   if ( nbE == 1 )
3303   //   {
3304   //     ee[ 1 ] == ee[ 0 ];
3305   //   }
3306   //   else
3307   //   {
3308   //     if ( !V.IsSame( SMESH_MesherHelper::IthVertex( 0, ee[ 1 ] )))
3309   //       std::swap( ee[0], ee[1] );
3310   //   }
3311   //   angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F, TopoDS::Vertex( V ));
3312   // }
3313
3314   // // compute a weighted normal
3315   // double sumAngle = 0;
3316   // for ( int i = 0; i < nbFaces; ++i )
3317   // {
3318   //   angles[i] = ( angles[i] > 2*M_PI )  ?  0  :  M_PI - angles[i];
3319   //   sumAngle += angles[i];
3320   // }
3321   // for ( int i = 0; i < nbFaces; ++i )
3322   //   resNorm += angles[i] / sumAngle * fId2Normal[i].second;
3323
3324   return resNorm;
3325 }
3326
3327 //================================================================================
3328 /*!
3329  * \brief Find 2 neigbor nodes of a node on EDGE
3330  */
3331 //================================================================================
3332
3333 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
3334                                         const SMDS_MeshNode*& n1,
3335                                         const SMDS_MeshNode*& n2,
3336                                         _EdgesOnShape&        eos,
3337                                         _SolidData&           data)
3338 {
3339   const SMDS_MeshNode* node = edge->_nodes[0];
3340   const int        shapeInd = eos._shapeID;
3341   SMESHDS_SubMesh*   edgeSM = 0;
3342   if ( eos.ShapeType() == TopAbs_EDGE )
3343   {
3344     edgeSM = eos._subMesh->GetSubMeshDS();
3345     if ( !edgeSM || edgeSM->NbElements() == 0 )
3346       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
3347   }
3348   int iN = 0;
3349   n2 = 0;
3350   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
3351   while ( eIt->more() && !n2 )
3352   {
3353     const SMDS_MeshElement* e = eIt->next();
3354     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
3355     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
3356     if ( edgeSM )
3357     {
3358       if (!edgeSM->Contains(e)) continue;
3359     }
3360     else
3361     {
3362       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
3363       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
3364     }
3365     ( iN++ ? n2 : n1 ) = nNeibor;
3366   }
3367   if ( !n2 )
3368     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
3369   return true;
3370 }
3371
3372 //================================================================================
3373 /*!
3374  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
3375  */
3376 //================================================================================
3377
3378 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
3379                                      const SMDS_MeshNode* n2,
3380                                      const _EdgesOnShape& eos,
3381                                      SMESH_MesherHelper&  helper)
3382 {
3383   if ( eos.ShapeType() != TopAbs_EDGE )
3384     return;
3385
3386   gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
3387   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
3388   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
3389
3390   // Set _curvature
3391
3392   double      sumLen = vec1.Modulus() + vec2.Modulus();
3393   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
3394   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
3395   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
3396   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
3397   if ( _curvature ) delete _curvature;
3398   _curvature = _Curvature::New( avgNormProj, avgLen );
3399   // if ( _curvature )
3400   //   debugMsg( _nodes[0]->GetID()
3401   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
3402   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
3403   //             << _curvature->lenDelta(0) );
3404
3405   // Set _plnNorm
3406
3407   if ( eos._sWOL.IsNull() )
3408   {
3409     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
3410     // if ( SMESH_Algo::isDegenerated( E ))
3411     //   return;
3412     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
3413     gp_XYZ plnNorm = dirE ^ _normal;
3414     double proj0   = plnNorm * vec1;
3415     double proj1   = plnNorm * vec2;
3416     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
3417     {
3418       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
3419       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
3420     }
3421   }
3422 }
3423
3424 //================================================================================
3425 /*!
3426  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
3427  * this and other _LayerEdge's are inflated along a FACE or an EDGE
3428  */
3429 //================================================================================
3430
3431 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
3432                          _EdgesOnShape&      eos,
3433                          SMESH_MesherHelper& helper )
3434 {
3435   _nodes     = other._nodes;
3436   _normal    = other._normal;
3437   _len       = 0;
3438   _lenFactor = other._lenFactor;
3439   _cosin     = other._cosin;
3440   _2neibors  = other._2neibors;
3441   _curvature = 0; std::swap( _curvature, other._curvature );
3442   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
3443
3444   gp_XYZ lastPos( 0,0,0 );
3445   if ( eos.SWOLType() == TopAbs_EDGE )
3446   {
3447     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
3448     _pos.push_back( gp_XYZ( u, 0, 0));
3449
3450     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
3451     lastPos.SetX( u );
3452   }
3453   else // TopAbs_FACE
3454   {
3455     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
3456     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3457
3458     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
3459     lastPos.SetX( uv.X() );
3460     lastPos.SetY( uv.Y() );
3461   }
3462   return lastPos;
3463 }
3464
3465 //================================================================================
3466 /*!
3467  * \brief Set _cosin and _lenFactor
3468  */
3469 //================================================================================
3470
3471 void _LayerEdge::SetCosin( double cosin )
3472 {
3473   _cosin = cosin;
3474   cosin = Abs( _cosin );
3475   _lenFactor = ( /*0.1 < cosin &&*/ cosin < 1-1e-12 ) ?  1./sqrt(1-cosin*cosin) : 1.0;
3476 }
3477
3478 //================================================================================
3479 /*!
3480  * \brief Fills a vector<_Simplex > 
3481  */
3482 //================================================================================
3483
3484 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
3485                              vector<_Simplex>&    simplices,
3486                              const set<TGeomID>&  ingnoreShapes,
3487                              const _SolidData*    dataToCheckOri,
3488                              const bool           toSort)
3489 {
3490   simplices.clear();
3491   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3492   while ( fIt->more() )
3493   {
3494     const SMDS_MeshElement* f = fIt->next();
3495     const TGeomID    shapeInd = f->getshapeId();
3496     if ( ingnoreShapes.count( shapeInd )) continue;
3497     const int nbNodes = f->NbCornerNodes();
3498     const int  srcInd = f->GetNodeIndex( node );
3499     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
3500     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
3501     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
3502     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
3503       std::swap( nPrev, nNext );
3504     simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
3505   }
3506
3507   if ( toSort )
3508     SortSimplices( simplices );
3509 }
3510
3511 //================================================================================
3512 /*!
3513  * \brief Set neighbor simplices side by side
3514  */
3515 //================================================================================
3516
3517 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
3518 {
3519   vector<_Simplex> sortedSimplices( simplices.size() );
3520   sortedSimplices[0] = simplices[0];
3521   int nbFound = 0;
3522   for ( size_t i = 1; i < simplices.size(); ++i )
3523   {
3524     for ( size_t j = 1; j < simplices.size(); ++j )
3525       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
3526       {
3527         sortedSimplices[i] = simplices[j];
3528         nbFound++;
3529         break;
3530       }
3531   }
3532   if ( nbFound == simplices.size() - 1 )
3533     simplices.swap( sortedSimplices );
3534 }
3535
3536 //================================================================================
3537 /*!
3538  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
3539  */
3540 //================================================================================
3541
3542 void _ViscousBuilder::makeGroupOfLE()
3543 {
3544 #ifdef _DEBUG_
3545   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3546   {
3547     if ( _sdVec[i]._n2eMap.empty() ) continue;
3548
3549     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
3550     TNode2Edge::iterator n2e;
3551     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
3552     {
3553       _LayerEdge* le = n2e->second;
3554       for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
3555         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
3556                 << ", " << le->_nodes[iN]->GetID() <<"])");
3557     }
3558     dumpFunctionEnd();
3559
3560     dumpFunction( SMESH_Comment("makeNormals") << i );
3561     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
3562     {
3563       _LayerEdge* edge = n2e->second;
3564       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
3565       nXYZ += edge->_normal * _sdVec[i]._stepSize;
3566       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
3567               << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
3568     }
3569     dumpFunctionEnd();
3570
3571     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
3572     dumpCmd( "faceId1 = mesh.NbElements()" );
3573     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
3574     for ( ; fExp.More(); fExp.Next() )
3575     {
3576       if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
3577       {
3578         if ( sm->NbElements() == 0 ) continue;
3579         SMDS_ElemIteratorPtr fIt = sm->GetElements();
3580         while ( fIt->more())
3581         {
3582           const SMDS_MeshElement* e = fIt->next();
3583           SMESH_Comment cmd("mesh.AddFace([");
3584           for ( int j=0; j < e->NbCornerNodes(); ++j )
3585             cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
3586           dumpCmd( cmd );
3587         }
3588       }
3589     }
3590     dumpCmd( "faceId2 = mesh.NbElements()" );
3591     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
3592              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
3593              << "'%s-%s' % (faceId1+1, faceId2))");
3594     dumpFunctionEnd();
3595   }
3596 #endif
3597 }
3598
3599 //================================================================================
3600 /*!
3601  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
3602  */
3603 //================================================================================
3604
3605 void _ViscousBuilder::computeGeomSize( _SolidData& data )
3606 {
3607   data._geomSize = Precision::Infinite();
3608   double intersecDist;
3609   auto_ptr<SMESH_ElementSearcher> searcher
3610     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
3611                                            data._proxyMesh->GetFaces( data._solid )) );
3612
3613   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
3614   {
3615     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
3616     if ( eos._edges.empty() || eos.ShapeType() == TopAbs_EDGE )
3617       continue;
3618     for ( size_t i = 0; i < eos._edges.size(); ++i )
3619     {
3620       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos );
3621       if ( data._geomSize > intersecDist && intersecDist > 0 )
3622         data._geomSize = intersecDist;
3623     }
3624   }
3625 }
3626
3627 //================================================================================
3628 /*!
3629  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
3630  */
3631 //================================================================================
3632
3633 bool _ViscousBuilder::inflate(_SolidData& data)
3634 {
3635   SMESH_MesherHelper helper( *_mesh );
3636
3637   // Limit inflation step size by geometry size found by itersecting
3638   // normals of _LayerEdge's with mesh faces
3639   if ( data._stepSize > 0.3 * data._geomSize )
3640     limitStepSize( data, 0.3 * data._geomSize );
3641
3642   const double tgtThick = data._maxThickness;
3643   if ( data._stepSize > data._minThickness )
3644     limitStepSize( data, data._minThickness );
3645
3646   if ( data._stepSize < 1. )
3647     data._epsilon = data._stepSize * 1e-7;
3648
3649   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
3650
3651   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
3652
3653   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
3654   int nbSteps = 0, nbRepeats = 0;
3655   while ( avgThick < 0.99 )
3656   {
3657     // new target length
3658     curThick += data._stepSize;
3659     if ( curThick > tgtThick )
3660     {
3661       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
3662       nbRepeats++;
3663     }
3664
3665     // Elongate _LayerEdge's
3666     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
3667     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
3668     {
3669       _EdgesOnShape& eos = data._edgesOnShape[iS];
3670       if ( eos._edges.empty() ) continue;
3671
3672       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
3673       for ( size_t i = 0; i < eos._edges.size(); ++i )
3674       {
3675         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
3676       }
3677     }
3678     dumpFunctionEnd();
3679
3680     if ( !updateNormals( data, helper, nbSteps ))
3681       return false;
3682
3683     // Improve and check quality
3684     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
3685     {
3686       if ( nbSteps > 0 )
3687       {
3688 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
3689         debugMsg("NOT INVALIDATED STEP!");
3690         return error("Smoothing failed", data._index);
3691 #endif
3692         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
3693         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
3694         {
3695           _EdgesOnShape& eos = data._edgesOnShape[iS];
3696           for ( size_t i = 0; i < eos._edges.size(); ++i )
3697             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
3698         }
3699         dumpFunctionEnd();
3700       }
3701       break; // no more inflating possible
3702     }
3703     nbSteps++;
3704
3705     // Evaluate achieved thickness
3706     avgThick = 0;
3707     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
3708     {
3709       _EdgesOnShape& eos = data._edgesOnShape[iS];
3710       if ( eos._edges.empty() ) continue;
3711
3712       const double shapeTgtThick = eos._hyp.GetTotalThickness();
3713       for ( size_t i = 0; i < eos._edges.size(); ++i )
3714       {
3715         avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
3716       }
3717     }
3718     avgThick /= data._n2eMap.size();
3719     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
3720
3721     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
3722     {
3723       debugMsg( "-- Stop inflation since "
3724                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
3725                 << tgtThick * avgThick << " ) * " << safeFactor );
3726       break;
3727     }
3728     // new step size
3729     limitStepSize( data, 0.25 * distToIntersection );
3730     if ( data._stepSizeNodes[0] )
3731       data._stepSize = data._stepSizeCoeff *
3732         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
3733
3734   } // while ( avgThick < 0.99 )
3735
3736   if (nbSteps == 0 )
3737     return error("failed at the very first inflation step", data._index);
3738
3739   if ( avgThick < 0.99 )
3740   {
3741     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
3742     {
3743       data._proxyMesh->_warning.reset
3744         ( new SMESH_ComputeError (COMPERR_WARNING,
3745                                   SMESH_Comment("Thickness ") << tgtThick <<
3746                                   " of viscous layers not reached,"
3747                                   " average reached thickness is " << avgThick*tgtThick));
3748     }
3749   }
3750
3751   // Restore position of src nodes moved by infaltion on _noShrinkShapes
3752   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
3753   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
3754   {
3755     _EdgesOnShape& eos = data._edgesOnShape[iS];
3756     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
3757       for ( size_t i = 0; i < eos._edges.size(); ++i )
3758       {
3759         restoreNoShrink( *eos._edges[ i ] );
3760       }
3761   }
3762   dumpFunctionEnd();
3763
3764   return true;
3765 }
3766
3767 //================================================================================
3768 /*!
3769  * \brief Improve quality of layer inner surface and check intersection
3770  */
3771 //================================================================================
3772
3773 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
3774                                      const int   nbSteps,
3775                                      double &    distToIntersection)
3776 {
3777   if ( data._nbShapesToSmooth == 0 )
3778     return true; // no shapes needing smoothing
3779
3780   bool moved, improved;
3781   vector< _LayerEdge* > badSmooEdges;
3782
3783   SMESH_MesherHelper helper(*_mesh);
3784   Handle(Geom_Surface) surface;
3785   TopoDS_Face F;
3786
3787   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
3788   {
3789     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
3790
3791     for ( int iS = 0; iS < data._edgesOnShape.size(); ++iS )
3792     {
3793       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
3794       if ( !eos._toSmooth ||
3795            eos.ShapeType() != shapeType ||
3796            eos._edges.empty() )
3797         continue;
3798
3799       // already smoothed?
3800       bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
3801       if ( !toSmooth ) continue;
3802
3803       if ( !eos._hyp.ToSmooth() )
3804       {
3805         // smooth disabled by the user; check validy only
3806         if ( !isFace ) continue;
3807         double vol;
3808         for ( size_t i = 0; i < eos._edges.size(); ++i )
3809         {
3810           _LayerEdge* edge = eos._edges[i];
3811           const gp_XYZ& curPos (  );
3812           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
3813             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0],
3814                                                  &edge->_pos.back(), vol ))
3815               return false;
3816         }
3817         continue; // goto to the next EDGE or FACE
3818       }
3819
3820       // prepare data
3821       if ( eos.SWOLType() == TopAbs_FACE )
3822       {
3823         if ( !F.IsSame( eos._sWOL )) {
3824           F = TopoDS::Face( eos._sWOL );
3825           helper.SetSubShape( F );
3826           surface = BRep_Tool::Surface( F );
3827         }
3828       }
3829       else
3830       {
3831         F.Nullify(); surface.Nullify();
3832       }
3833       const TGeomID sInd = eos._shapeID;
3834
3835       // perform smoothing
3836
3837       if ( eos.ShapeType() == TopAbs_EDGE )
3838       {
3839         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
3840
3841         // try a simple solution on an analytic EDGE
3842         if ( !smoothAnalyticEdge( data, eos, surface, F, helper ))
3843         {
3844           // smooth on EDGE's
3845           int step = 0;
3846           do {
3847             moved = false;
3848             for ( size_t i = 0; i < eos._edges.size(); ++i )
3849             {
3850               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
3851             }
3852             dumpCmd( SMESH_Comment("# end step ")<<step);
3853           }
3854           while ( moved && step++ < 5 );
3855         }
3856         dumpFunctionEnd();
3857       }
3858       else
3859       {
3860         // smooth on FACE's
3861
3862         const bool isConcaveFace = data._concaveFaces.count( sInd );
3863
3864         int step = 0, stepLimit = 5, badNb = 0;
3865         while (( ++step <= stepLimit ) || improved )
3866         {
3867           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
3868                        <<"_InfStep"<<nbSteps<<"_"<<step); // debug
3869           int oldBadNb = badNb;
3870           badSmooEdges.clear();
3871
3872           if ( step % 2 ) {
3873             for ( size_t i = 0; i < eos._edges.size(); ++i )  // iterate forward
3874               if ( eos._edges[i]->Smooth( step, isConcaveFace, false ))
3875                 badSmooEdges.push_back( eos._edges[i] );
3876           }
3877
3878           else {
3879             for ( int i = eos._edges.size()-1; i >= 0; --i ) // iterate backward
3880               if ( eos._edges[i]->Smooth( step, isConcaveFace, false ))
3881                 badSmooEdges.push_back( eos._edges[i] );
3882           }
3883           badNb = badSmooEdges.size();
3884           improved = ( badNb < oldBadNb );
3885
3886           if ( !badSmooEdges.empty() && step >= stepLimit / 2 )
3887           {
3888             // look for the best smooth of _LayerEdge's neighboring badSmooEdges
3889             vector<_Simplex> simplices;
3890             for ( size_t i = 0; i < badSmooEdges.size(); ++i )
3891             {
3892               _LayerEdge* ledge = badSmooEdges[i];
3893               _Simplex::GetSimplices( ledge->_nodes[0], simplices, data._ignoreFaceIds );
3894               for ( size_t iS = 0; iS < simplices.size(); ++iS )
3895               {
3896                 TNode2Edge::iterator n2e = data._n2eMap.find( simplices[iS]._nNext );
3897                 if ( n2e != data._n2eMap.end()) {
3898                   _LayerEdge* ledge2 = n2e->second;
3899                   if ( ledge2->_nodes[0]->getshapeId() == sInd )
3900                     ledge2->Smooth( step, isConcaveFace, /*findBest=*/true );
3901                 }
3902               }
3903             }
3904           }
3905           // issue 22576 -- no bad faces but still there are intersections to fix
3906           // if ( improved && badNb == 0 )
3907           //   stepLimit = step + 3;
3908
3909           dumpFunctionEnd();
3910         }
3911         if ( badNb > 0 )
3912         {
3913 #ifdef __myDEBUG
3914           double vol = 0;
3915           for ( int i = 0; i < eos._edges.size(); ++i )
3916           {
3917             _LayerEdge* edge = eos._edges[i];
3918             SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
3919             for ( size_t j = 0; j < edge->_simplices.size(); ++j )
3920               if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
3921               {
3922                 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
3923                      << " "<< edge->_simplices[j]._nPrev->GetID()
3924                      << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
3925                 return false;
3926               }
3927           }
3928 #endif
3929           return false;
3930         }
3931       } // // smooth on FACE's
3932     } // loop on shapes
3933   } // smooth on [ EDGEs, FACEs ]
3934
3935   // Check orientation of simplices of _ConvexFace::_simplexTestEdges
3936   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
3937   for ( ; id2face != data._convexFaces.end(); ++id2face )
3938   {
3939     _ConvexFace & convFace = (*id2face).second;
3940     if ( !convFace._simplexTestEdges.empty() &&
3941          convFace._simplexTestEdges[0]->_nodes[0]->GetPosition()->GetDim() == 2 )
3942       continue; // _simplexTestEdges are based on FACE -- already checked while smoothing
3943
3944     if ( !convFace.CheckPrisms() )
3945       return false;
3946   }
3947
3948   // Check if the last segments of _LayerEdge intersects 2D elements;
3949   // checked elements are either temporary faces or faces on surfaces w/o the layers
3950
3951   auto_ptr<SMESH_ElementSearcher> searcher
3952     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
3953                                            data._proxyMesh->GetFaces( data._solid )) );
3954
3955   distToIntersection = Precision::Infinite();
3956   double dist;
3957   const SMDS_MeshElement* intFace = 0;
3958   const SMDS_MeshElement* closestFace = 0;
3959   _LayerEdge* le = 0;
3960   for ( int iS = 0; iS < data._edgesOnShape.size(); ++iS )
3961   {
3962     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
3963     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
3964       continue;
3965     for ( size_t i = 0; i < eos._edges.size(); ++i )
3966     {
3967       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
3968         return false;
3969       if ( distToIntersection > dist )
3970       {
3971         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
3972         // lying on this _ConvexFace
3973         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
3974           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
3975             continue;
3976
3977         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
3978         // ( avoid limiting the thickness on the case of issue 22576)
3979         if ( intFace->getshapeId() == eos._shapeID  )
3980           continue;
3981
3982         distToIntersection = dist;
3983         le = eos._edges[i];
3984         closestFace = intFace;
3985       }
3986     }
3987   }
3988 #ifdef __myDEBUG
3989   if ( closestFace )
3990   {
3991     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
3992     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
3993          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
3994          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3995          << ") distance = " << distToIntersection<< endl;
3996   }
3997 #endif
3998
3999   return true;
4000 }
4001
4002 //================================================================================
4003 /*!
4004  * \brief Return a curve of the EDGE to be used for smoothing and arrange
4005  *        _LayerEdge's to be in a consequent order
4006  */
4007 //================================================================================
4008
4009 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
4010                                                _EdgesOnShape&        eos,
4011                                                SMESH_MesherHelper&   helper)
4012 {
4013   const TGeomID eIndex = eos._shapeID;
4014
4015   map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
4016
4017   if ( i2curve == _edge2curve.end() )
4018   {
4019     // sort _LayerEdge's by position on the EDGE
4020     SortOnEdge( E, eos._edges, helper );
4021
4022     SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
4023
4024     TopLoc_Location loc; double f,l;
4025
4026     Handle(Geom_Line)   line;
4027     Handle(Geom_Circle) circle;
4028     bool isLine, isCirc;
4029     if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
4030     {
4031       // check if the EDGE is a line
4032       Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
4033       if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
4034         curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
4035
4036       line   = Handle(Geom_Line)::DownCast( curve );
4037       circle = Handle(Geom_Circle)::DownCast( curve );
4038       isLine = (!line.IsNull());
4039       isCirc = (!circle.IsNull());
4040
4041       if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
4042       {
4043         // Bnd_B3d bndBox;
4044         // SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
4045         // while ( nIt->more() )
4046         //   bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
4047         // gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
4048
4049         // gp_Pnt p0, p1;
4050         // if ( eos._edges.size() > 1 ) {
4051         //   p0 = SMESH_TNodeXYZ( eos._edges[0]->_nodes[0] );
4052         //   p1 = SMESH_TNodeXYZ( eos._edges[1]->_nodes[0] );
4053         // }
4054         // else {
4055         //   p0 = curve->Value( f );
4056         //   p1 = curve->Value( l );
4057         // }
4058         // const double lineTol = 1e-2 * p0.Distance( p1 );
4059         // for ( int i = 0; i < 3 && !isLine; ++i )
4060         //   isLine = ( size.Coord( i+1 ) <= lineTol ); ////////// <--- WRONG
4061
4062         isLine = SMESH_Algo::IsStraight( E );
4063
4064         if ( isLine )
4065           line = new Geom_Line( gp::OX() ); // only type does matter
4066       }
4067       if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
4068       {
4069         // TODO
4070       }
4071     }
4072     else //////////////////////////////////////////////////////////////////////// 2D case
4073     {
4074       const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
4075
4076       // check if the EDGE is a line
4077       Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
4078       if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
4079         curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
4080
4081       Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
4082       Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
4083       isLine = (!line2d.IsNull());
4084       isCirc = (!circle2d.IsNull());
4085
4086       if ( !isLine && !isCirc) // Check if the EDGE is close to a line
4087       {
4088         Bnd_B2d bndBox;
4089         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
4090         while ( nIt->more() )
4091           bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
4092         gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
4093
4094         const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
4095         for ( int i = 0; i < 2 && !isLine; ++i )
4096           isLine = ( size.Coord( i+1 ) <= lineTol );
4097       }
4098       if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
4099       {
4100         // TODO
4101       }
4102       if ( isLine )
4103       {
4104         line = new Geom_Line( gp::OX() ); // only type does matter
4105       }
4106       else if ( isCirc )
4107       {
4108         gp_Pnt2d p = circle2d->Location();
4109         gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
4110         circle = new Geom_Circle( ax, 1.); // only center position does matter
4111       }
4112     }
4113
4114     Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
4115     if ( isLine )
4116       res = line;
4117     else if ( isCirc )
4118       res = circle;
4119
4120     return res;
4121   }
4122   return i2curve->second;
4123 }
4124
4125 //================================================================================
4126 /*!
4127  * \brief Sort _LayerEdge's by a parameter on a given EDGE
4128  */
4129 //================================================================================
4130
4131 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
4132                              vector< _LayerEdge* >& edges,
4133                              SMESH_MesherHelper&    helper)
4134 {
4135   map< double, _LayerEdge* > u2edge;
4136   for ( size_t i = 0; i < edges.size(); ++i )
4137     u2edge.insert( make_pair( helper.GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
4138
4139   ASSERT( u2edge.size() == edges.size() );
4140   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
4141   for ( int i = 0; i < edges.size(); ++i, ++u2e )
4142     edges[i] = u2e->second;
4143
4144   Sort2NeiborsOnEdge( edges );
4145 }
4146
4147 //================================================================================
4148 /*!
4149  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
4150  */
4151 //================================================================================
4152
4153 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
4154 {
4155   for ( size_t i = 0; i < edges.size()-1; ++i )
4156     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
4157       edges[i]->_2neibors->reverse();
4158
4159   const size_t iLast = edges.size() - 1;
4160   if ( edges.size() > 1 &&
4161        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
4162     edges[iLast]->_2neibors->reverse();
4163 }
4164
4165 //================================================================================
4166 /*!
4167  * \brief Return _EdgesOnShape* corresponding to the shape
4168  */
4169 //================================================================================
4170
4171 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
4172 {
4173   if ( shapeID < _edgesOnShape.size() &&
4174        _edgesOnShape[ shapeID ]._shapeID == shapeID )
4175     return & _edgesOnShape[ shapeID ];
4176
4177   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
4178     if ( _edgesOnShape[i]._shapeID == shapeID )
4179       return & _edgesOnShape[i];
4180
4181   return 0;
4182 }
4183
4184 //================================================================================
4185 /*!
4186  * \brief Return _EdgesOnShape* corresponding to the shape
4187  */
4188 //================================================================================
4189
4190 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
4191 {
4192   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
4193   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
4194 }
4195
4196 //================================================================================
4197 /*!
4198  * \brief Prepare data of the _LayerEdge for smoothing on FACE
4199  */
4200 //================================================================================
4201
4202 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes )
4203 {
4204   set< TGeomID > vertices;
4205   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
4206   if ( isConcave( TopoDS::Face( eof->_shape ), helper, &vertices ))
4207     _concaveFaces.insert( eof->_shapeID );
4208
4209   for ( size_t i = 0; i < eof->_edges.size(); ++i )
4210     eof->_edges[i]->_smooFunction = 0;
4211
4212   for ( size_t i = 0; i < eof->_edges.size(); ++i )
4213   {
4214     _LayerEdge* edge = eof->_edges[i];
4215     _Simplex::GetSimplices
4216       ( edge->_nodes[0], edge->_simplices, _ignoreFaceIds, this, /*sort=*/true );
4217
4218     edge->ChooseSmooFunction( vertices, _n2eMap );
4219
4220     double avgNormProj = 0, avgLen = 0;
4221     for ( size_t i = 0; i < edge->_simplices.size(); ++i )
4222     {
4223       _Simplex& s = edge->_simplices[i];
4224
4225       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
4226       avgNormProj += edge->_normal * vec;
4227       avgLen      += vec.Modulus();
4228       if ( substituteSrcNodes )
4229       {
4230         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
4231         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
4232       }
4233     }
4234     avgNormProj /= edge->_simplices.size();
4235     avgLen      /= edge->_simplices.size();
4236     edge->_curvature = _Curvature::New( avgNormProj, avgLen );
4237   }
4238 }
4239
4240 //================================================================================
4241 /*!
4242  * \brief Add faces for smoothing
4243  */
4244 //================================================================================
4245
4246 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosSet )
4247 {
4248   set< _EdgesOnShape * >::const_iterator eos = eosSet.begin();
4249   for ( ; eos != eosSet.end(); ++eos )
4250   {
4251     if ( !*eos || (*eos)->_toSmooth ) continue;
4252
4253     (*eos)->_toSmooth = true;
4254
4255     if ( (*eos)->ShapeType() == TopAbs_FACE )
4256     {
4257       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/true );
4258     }
4259   }
4260 }
4261
4262 //================================================================================
4263 /*!
4264  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
4265  */
4266 //================================================================================
4267
4268 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
4269                                           _EdgesOnShape&        eos,
4270                                           Handle(Geom_Surface)& surface,
4271                                           const TopoDS_Face&    F,
4272                                           SMESH_MesherHelper&   helper)
4273 {
4274   const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
4275
4276   Handle(Geom_Curve) curve = data.CurveForSmooth( E, eos, helper );
4277   if ( curve.IsNull() ) return false;
4278
4279   const size_t iFrom = 0, iTo = eos._edges.size();
4280
4281   // compute a relative length of segments
4282   vector< double > len( iTo-iFrom+1 );
4283   {
4284     double curLen, prevLen = len[0] = 1.0;
4285     for ( int i = iFrom; i < iTo; ++i )
4286     {
4287       curLen = prevLen * eos._edges[i]->_2neibors->_wgt[0] / eos._edges[i]->_2neibors->_wgt[1];
4288       len[i-iFrom+1] = len[i-iFrom] + curLen;
4289       prevLen = curLen;
4290     }
4291   }
4292
4293   if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
4294   {
4295     if ( F.IsNull() ) // 3D
4296     {
4297       SMESH_TNodeXYZ p0( eos._edges[iFrom]->_2neibors->tgtNode(0));
4298       SMESH_TNodeXYZ p1( eos._edges[iTo-1]->_2neibors->tgtNode(1));
4299       for ( int i = iFrom; i < iTo; ++i )
4300       {
4301         double r = len[i-iFrom] / len.back();
4302         gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
4303         eos._edges[i]->_pos.back() = newPos;
4304         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( eos._edges[i]->_nodes.back() );
4305         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4306         dumpMove( tgtNode );
4307       }
4308     }
4309     else
4310     {
4311       // gp_XY uv0 = helper.GetNodeUV( F, eos._edges[iFrom]->_2neibors->tgtNode(0));
4312       // gp_XY uv1 = helper.GetNodeUV( F, eos._edges[iTo-1]->_2neibors->tgtNode(1));
4313       _LayerEdge* e0 = eos._edges[iFrom]->_2neibors->_edges[0];
4314       _LayerEdge* e1 = eos._edges[iTo-1]->_2neibors->_edges[1];
4315       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
4316       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
4317       if ( eos._edges[iFrom]->_2neibors->tgtNode(0) ==
4318            eos._edges[iTo-1]->_2neibors->tgtNode(1) ) // closed edge
4319       {
4320         int iPeriodic = helper.GetPeriodicIndex();
4321         if ( iPeriodic == 1 || iPeriodic == 2 )
4322         {
4323           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
4324           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
4325             std::swap( uv0, uv1 );
4326         }
4327       }
4328       const gp_XY rangeUV = uv1 - uv0;
4329       for ( int i = iFrom; i < iTo; ++i )
4330       {
4331         double r = len[i-iFrom] / len.back();
4332         gp_XY newUV = uv0 + r * rangeUV;
4333         eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
4334
4335         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
4336         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( eos._edges[i]->_nodes.back() );
4337         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4338         dumpMove( tgtNode );
4339
4340         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4341         pos->SetUParameter( newUV.X() );
4342         pos->SetVParameter( newUV.Y() );
4343       }
4344     }
4345     return true;
4346   }
4347
4348   if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
4349   {
4350     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
4351     gp_Pnt center3D = circle->Location();
4352
4353     if ( F.IsNull() ) // 3D
4354     {
4355       if ( eos._edges[iFrom]->_2neibors->tgtNode(0) ==
4356            eos._edges[iTo-1]->_2neibors->tgtNode(1) )
4357         return true; // closed EDGE - nothing to do
4358
4359       return false; // TODO ???
4360     }
4361     else // 2D
4362     {
4363       const gp_XY center( center3D.X(), center3D.Y() );
4364
4365       _LayerEdge* e0 = eos._edges[iFrom]->_2neibors->_edges[0];
4366       _LayerEdge* eM = eos._edges[iFrom];
4367       _LayerEdge* e1 = eos._edges[iTo-1]->_2neibors->_edges[1];
4368       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
4369       gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
4370       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
4371       gp_Vec2d vec0( center, uv0 );
4372       gp_Vec2d vecM( center, uvM );
4373       gp_Vec2d vec1( center, uv1 );
4374       double uLast = vec0.Angle( vec1 ); // -PI - +PI
4375       double uMidl = vec0.Angle( vecM );
4376       if ( uLast * uMidl <= 0. )
4377         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
4378       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
4379
4380       gp_Ax2d   axis( center, vec0 );
4381       gp_Circ2d circ( axis, radius );
4382       for ( int i = iFrom; i < iTo; ++i )
4383       {
4384         double    newU = uLast * len[i-iFrom] / len.back();
4385         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
4386         eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
4387
4388         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
4389         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( eos._edges[i]->_nodes.back() );
4390         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4391         dumpMove( tgtNode );
4392
4393         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4394         pos->SetUParameter( newUV.X() );
4395         pos->SetVParameter( newUV.Y() );
4396       }
4397     }
4398     return true;
4399   }
4400
4401   return false;
4402 }
4403
4404 //================================================================================
4405 /*!
4406  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
4407  * _LayerEdge's on neighbor EDGE's
4408  */
4409 //================================================================================
4410
4411 bool _ViscousBuilder::updateNormals( _SolidData&         data,
4412                                      SMESH_MesherHelper& helper,
4413                                      int                 stepNb )
4414 {
4415   if ( stepNb > 0 )
4416     return updateNormalsOfConvexFaces( data, helper, stepNb );
4417
4418   // make temporary quadrangles got by extrusion of
4419   // mesh edges along _LayerEdge._normal's
4420
4421   vector< const SMDS_MeshElement* > tmpFaces;
4422   {
4423     set< SMESH_TLink > extrudedLinks; // contains target nodes
4424     vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
4425
4426     dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
4427     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4428     {
4429       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4430       if ( eos.ShapeType() != TopAbs_EDGE || !eos._sWOL.IsNull() )
4431         continue;
4432       for ( size_t i = 0; i < eos._edges.size(); ++i )
4433       {
4434         _LayerEdge* edge = eos._edges[i];
4435         const SMDS_MeshNode* tgt1 = edge->_nodes.back();
4436         for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
4437         {
4438           const SMDS_MeshNode* tgt2 = edge->_2neibors->tgtNode(j);
4439           pair< set< SMESH_TLink >::iterator, bool > link_isnew =
4440             extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
4441           if ( !link_isnew.second )
4442           {
4443             extrudedLinks.erase( link_isnew.first );
4444             continue; // already extruded and will no more encounter
4445           }
4446           // a _LayerEdge containg tgt2
4447           _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
4448
4449           _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
4450           tmpFaces.push_back( f );
4451
4452           dumpCmd(SMESH_Comment("mesh.AddFace([ ")
4453                   <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
4454                   <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
4455         }
4456       }
4457     }
4458     dumpFunctionEnd();
4459   }
4460   // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
4461   // Perform two loops on _LayerEdge on EDGE's:
4462   // 1) to find and fix intersection
4463   // 2) to check that no new intersection appears as result of 1)
4464
4465   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
4466                                                             tmpFaces.end()));
4467   auto_ptr<SMESH_ElementSearcher> searcher
4468     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
4469
4470   // 1) Find intersections
4471   double dist;
4472   const SMDS_MeshElement* face;
4473   typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
4474   TLEdge2LEdgeSet edge2CloseEdge;
4475
4476   const double eps = data._epsilon * data._epsilon;
4477   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4478   {
4479     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4480     if (( eos.ShapeType() != TopAbs_EDGE ) && 
4481         ( eos._sWOL.IsNull() || eos.SWOLType() != TopAbs_FACE ))
4482       continue;
4483     for ( size_t i = 0; i < eos._edges.size(); ++i )
4484     {
4485       _LayerEdge* edge = eos._edges[i];
4486       if ( edge->FindIntersection( *searcher, dist, eps, eos, &face ))
4487       {
4488         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) face;
4489         set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
4490         ee.insert( f->_le1 );
4491         ee.insert( f->_le2 );
4492         if ( f->_le1->IsOnEdge() && data.GetShapeEdges( f->_le1 )->_sWOL.IsNull() )
4493           edge2CloseEdge[ f->_le1 ].insert( edge );
4494         if ( f->_le2->IsOnEdge() && data.GetShapeEdges( f->_le2 )->_sWOL.IsNull() )
4495           edge2CloseEdge[ f->_le2 ].insert( edge );
4496       }
4497     }
4498   }
4499
4500   // Set _LayerEdge._normal
4501
4502   if ( !edge2CloseEdge.empty() )
4503   {
4504     dumpFunction(SMESH_Comment("updateNormals")<<data._index);
4505
4506     set< _EdgesOnShape* > shapesToSmooth;
4507
4508     // vector to store new _normal and _cosin for each edge in edge2CloseEdge
4509     vector< pair< _LayerEdge*, _LayerEdge > > edge2newEdge( edge2CloseEdge.size() );
4510
4511     TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
4512     for ( size_t iE = 0; e2ee != edge2CloseEdge.end(); ++e2ee, ++iE )
4513     {
4514       _LayerEdge* edge1 = e2ee->first;
4515       _LayerEdge* edge2 = 0;
4516       set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
4517
4518       edge2newEdge[ iE ].first = NULL;
4519
4520       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
4521       if ( !eos1 ) continue;
4522
4523       // find EDGEs the edges reside
4524       // TopoDS_Edge E1, E2;
4525       // TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
4526       // if ( S.ShapeType() != TopAbs_EDGE )
4527       //   continue; // TODO: find EDGE by VERTEX
4528       // E1 = TopoDS::Edge( S );
4529       set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
4530       for ( ; !edge2 && eIt != ee.end(); ++eIt )
4531       {
4532         if ( eos1->_sWOL == data.GetShapeEdges( *eIt  )->_sWOL )
4533           edge2 = *eIt;
4534       }
4535       if ( !edge2 ) continue;
4536
4537       edge2newEdge[ iE ].first = edge1;
4538       _LayerEdge& newEdge = edge2newEdge[ iE ].second;
4539       // while ( E2.IsNull() && eIt != ee.end())
4540       // {
4541       //   _LayerEdge* e2 = *eIt++;
4542       //   TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
4543       //   if ( S.ShapeType() == TopAbs_EDGE )
4544       //     E2 = TopoDS::Edge( S ), edge2 = e2;
4545       // }
4546       // if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
4547
4548       // find 3 FACEs sharing 2 EDGEs
4549
4550       // TopoDS_Face FF1[2], FF2[2];
4551       // PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
4552       // while ( fIt->more() && FF1[1].IsNull() )
4553       // {
4554       //   const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
4555       //   if ( helper.IsSubShape( *F, data._solid))
4556       //     FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
4557       // }
4558       // fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
4559       // while ( fIt->more() && FF2[1].IsNull())
4560       // {
4561       //   const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
4562       //   if ( helper.IsSubShape( *F, data._solid))
4563       //     FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
4564       // }
4565       // // exclude a FACE common to E1 and E2 (put it to FFn[1] )
4566       // if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
4567       //   std::swap( FF1[0], FF1[1] );
4568       // if ( FF2[0].IsSame( FF1[0]) )
4569       //   std::swap( FF2[0], FF2[1] );
4570       // if ( FF1[0].IsNull() || FF2[0].IsNull() )
4571       //   continue;
4572
4573       // get a new normal for edge1
4574       //bool ok;
4575       gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
4576       // if ( edge1->_cosin < 0 )
4577       //   dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
4578       // if ( edge2->_cosin < 0 )
4579       //   dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
4580
4581       double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
4582       double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
4583       double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
4584       newEdge._normal = ( wgt1 * dir1 + wgt2 * dir2 ).XYZ();
4585       newEdge._normal.Normalize();
4586
4587       // cout << edge1->_nodes[0]->GetID() << " "
4588       //      << edge2->_nodes[0]->GetID() << " NORM: "
4589       //      << newEdge._normal.X() << ", " << newEdge._normal.Y() << ", " << newEdge._normal.Z() << endl;
4590
4591       // get new cosin
4592       if ( cos1 < theMinSmoothCosin )
4593       {
4594         newEdge._cosin = edge2->_cosin;
4595       }
4596       else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
4597       {
4598         // gp_Vec dirInFace;
4599         // if ( edge1->_cosin < 0 )
4600         //   dirInFace = dir1;
4601         // else
4602         //   dirInFace = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
4603         // double angle = dirInFace.Angle( edge1->_normal ); // [0,PI]
4604         // edge1->SetCosin( Cos( angle ));
4605         //newEdge._cosin = 0; // ???????????
4606         newEdge._cosin = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
4607       }
4608       else
4609       {
4610         newEdge._cosin = edge1->_cosin;
4611       }
4612
4613       // find shapes that need smoothing due to change of _normal
4614       if ( edge1->_cosin  < theMinSmoothCosin &&
4615            newEdge._cosin > theMinSmoothCosin )
4616       {
4617         if ( eos1->_sWOL.IsNull() )
4618         {
4619           SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
4620           while ( fIt->more() )
4621             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
4622           //limitStepSize( data, fIt->next(), edge1->_cosin ); // too late
4623         }
4624         else // edge1 inflates along a FACE
4625         {
4626           TopoDS_Shape V = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
4627           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
4628           while ( const TopoDS_Shape* E = eIt->next() )
4629           {
4630             if ( !helper.IsSubShape( *E, /*FACE=*/eos1->_sWOL ))
4631               continue;
4632             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
4633             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
4634             if ( angle < M_PI / 2 )
4635               shapesToSmooth.insert( data.GetShapeEdges( *E ));
4636           }
4637         }
4638       }
4639     }
4640
4641     data.AddShapesToSmooth( shapesToSmooth );
4642
4643     // Update data of edges depending on a new _normal
4644
4645     for ( size_t iE = 0; iE < edge2newEdge.size(); ++iE )
4646     {
4647       _LayerEdge*   edge1 = edge2newEdge[ iE ].first;
4648       _LayerEdge& newEdge = edge2newEdge[ iE ].second;
4649       if ( !edge1 ) continue;
4650       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
4651       if ( !eos1 ) continue;
4652
4653       edge1->_normal = newEdge._normal;
4654       edge1->SetCosin( newEdge._cosin );
4655       edge1->InvalidateStep( 1, *eos1 );
4656       edge1->_len = 0;
4657       edge1->SetNewLength( data._stepSize, *eos1, helper );
4658       if ( edge1->IsOnEdge() )
4659       {
4660         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
4661         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
4662         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
4663       }
4664
4665       // Update normals and other dependent data of not intersecting _LayerEdge's
4666       // neighboring the intersecting ones
4667
4668       if ( !edge1->_2neibors )
4669         continue;
4670       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
4671       {
4672         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
4673         if ( edge2CloseEdge.count ( neighbor ))
4674           continue; // j-th neighbor is also intersected
4675         _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
4676         if ( !eos ) continue;
4677         _LayerEdge* prevEdge = edge1;
4678         const int nbSteps = 10;
4679         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
4680         {
4681           if ( !neighbor->_2neibors )
4682             break; // neighbor is on VERTEX
4683           int iNext = 0;
4684           _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
4685           if ( nextEdge == prevEdge )
4686             nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
4687           double r = double(step-1)/nbSteps;
4688           if ( !nextEdge->_2neibors )
4689             r = 0.5;
4690
4691           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
4692           newNorm.Normalize();
4693
4694           neighbor->_normal = newNorm;
4695           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
4696           neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
4697
4698           neighbor->InvalidateStep( 1, *eos );
4699           neighbor->_len = 0;
4700           neighbor->SetNewLength( data._stepSize, *eos, helper );
4701
4702           // goto the next neighbor
4703           prevEdge = neighbor;
4704           neighbor = nextEdge;
4705         }
4706       }
4707     }
4708     dumpFunctionEnd();
4709   }
4710   // 2) Check absence of intersections
4711   // TODO?
4712
4713   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
4714     delete tmpFaces[i];
4715
4716   return true;
4717 }
4718
4719 //================================================================================
4720 /*!
4721  * \brief Modify normals of _LayerEdge's on _ConvexFace's
4722  */
4723 //================================================================================
4724
4725 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
4726                                                   SMESH_MesherHelper& helper,
4727                                                   int                 stepNb )
4728 {
4729   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
4730   bool isOK;
4731
4732   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
4733   for ( ; id2face != data._convexFaces.end(); ++id2face )
4734   {
4735     _ConvexFace & convFace = (*id2face).second;
4736     if ( convFace._normalsFixed )
4737       continue; // already fixed
4738     if ( convFace.CheckPrisms() )
4739       continue; // nothing to fix
4740
4741     convFace._normalsFixed = true;
4742
4743     BRepAdaptor_Surface surface ( convFace._face, false );
4744     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
4745
4746     // check if the convex FACE is of spherical shape
4747
4748     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
4749     Bnd_B3d nodesBox;
4750     gp_Pnt  center;
4751
4752     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
4753     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
4754     {
4755       _EdgesOnShape& eos = *(id2eos->second);
4756       if ( eos.ShapeType() == TopAbs_VERTEX )
4757       {
4758         _LayerEdge* ledge = eos._edges[ 0 ];
4759         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
4760           centersBox.Add( center );
4761       }
4762       for ( size_t i = 0; i < eos._edges.size(); ++i )
4763         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
4764     }
4765     if ( centersBox.IsVoid() )
4766     {
4767       debugMsg( "Error: centersBox.IsVoid()" );
4768       return false;
4769     }
4770     const bool isSpherical =
4771       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
4772
4773     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
4774     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
4775
4776     if ( isSpherical )
4777     {
4778       // set _LayerEdge::_normal as average of all normals
4779
4780       // WARNING: different density of nodes on EDGEs is not taken into account that
4781       // can lead to an improper new normal
4782
4783       gp_XYZ avgNormal( 0,0,0 );
4784       nbEdges = 0;
4785       id2eos = convFace._subIdToEOS.begin();
4786       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
4787       {
4788         _EdgesOnShape& eos = *(id2eos->second);
4789         // set data of _CentralCurveOnEdge
4790         if ( eos.ShapeType() == TopAbs_EDGE )
4791         {
4792           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
4793           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
4794           if ( !eos._sWOL.IsNull() )
4795             ceCurve._adjFace.Nullify();
4796           else
4797             ceCurve._ledges.insert( ceCurve._ledges.end(),
4798                                     eos._edges.begin(), eos._edges.end());
4799         }
4800         // summarize normals
4801         for ( size_t i = 0; i < eos._edges.size(); ++i )
4802           avgNormal += eos._edges[ i ]->_normal;
4803       }
4804       double normSize = avgNormal.SquareModulus();
4805       if ( normSize < 1e-200 )
4806       {
4807         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
4808         return false;
4809       }
4810       avgNormal /= Sqrt( normSize );
4811
4812       // compute new _LayerEdge::_cosin on EDGEs
4813       double avgCosin = 0;
4814       int     nbCosin = 0;
4815       gp_Vec inFaceDir;
4816       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4817       {
4818         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
4819         if ( ceCurve._adjFace.IsNull() )
4820           continue;
4821         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
4822         {
4823           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
4824           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
4825           if ( isOK )
4826           {
4827             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
4828             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
4829             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
4830             nbCosin++;
4831           }
4832         }
4833       }
4834       if ( nbCosin > 0 )
4835         avgCosin /= nbCosin;
4836
4837       // set _LayerEdge::_normal = avgNormal
4838       id2eos = convFace._subIdToEOS.begin();
4839       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
4840       {
4841         _EdgesOnShape& eos = *(id2eos->second);
4842         if ( eos.ShapeType() != TopAbs_EDGE )
4843           for ( size_t i = 0; i < eos._edges.size(); ++i )
4844             eos._edges[ i ]->_cosin = avgCosin;
4845
4846         for ( size_t i = 0; i < eos._edges.size(); ++i )
4847           eos._edges[ i ]->_normal = avgNormal;
4848       }
4849     }
4850     else // if ( isSpherical )
4851     {
4852       // We suppose that centers of curvature at all points of the FACE
4853       // lie on some curve, let's call it "central curve". For all _LayerEdge's
4854       // having a common center of curvature we define the same new normal
4855       // as a sum of normals of _LayerEdge's on EDGEs among them.
4856
4857       // get all centers of curvature for each EDGE
4858
4859       helper.SetSubShape( convFace._face );
4860       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
4861
4862       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
4863       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
4864       {
4865         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
4866
4867         // set adjacent FACE
4868         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
4869
4870         // get _LayerEdge's of the EDGE
4871         TGeomID edgeID = meshDS->ShapeToIndex( edge );
4872         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
4873         if ( !eos || eos->_edges.empty() )
4874         {
4875           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
4876           for ( int iV = 0; iV < 2; ++iV )
4877           {
4878             TopoDS_Vertex v = helper.IthVertex( iV, edge );
4879             TGeomID     vID = meshDS->ShapeToIndex( v );
4880             eos = data.GetShapeEdges( vID );
4881             vertexLEdges[ iV ] = eos->_edges[ 0 ];
4882           }
4883           edgeLEdge    = &vertexLEdges[0];
4884           edgeLEdgeEnd = edgeLEdge + 2;
4885
4886           centerCurves[ iE ]._adjFace.Nullify();
4887         }
4888         else
4889         {
4890           if ( ! eos->_toSmooth )
4891             data.SortOnEdge( edge, eos->_edges, helper );
4892           edgeLEdge    = &eos->_edges[ 0 ];
4893           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
4894           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
4895           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
4896
4897           if ( ! eos->_sWOL.IsNull() )
4898             centerCurves[ iE ]._adjFace.Nullify();
4899         }
4900
4901         // Get curvature centers
4902
4903         centersBox.Clear();
4904
4905         if ( edgeLEdge[0]->IsOnEdge() &&
4906              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
4907         { // 1st VERTEX
4908           centerCurves[ iE ].Append( center, vertexLEdges[0] );
4909           centersBox.Add( center );
4910         }
4911         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
4912           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
4913           { // EDGE or VERTEXes
4914             centerCurves[ iE ].Append( center, *edgeLEdge );
4915             centersBox.Add( center );
4916           }
4917         if ( edgeLEdge[-1]->IsOnEdge() &&
4918              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
4919         { // 2nd VERTEX
4920           centerCurves[ iE ].Append( center, vertexLEdges[1] );
4921           centersBox.Add( center );
4922         }
4923         centerCurves[ iE ]._isDegenerated =
4924           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
4925
4926       } // loop on EDGES of convFace._face to set up data of centerCurves
4927
4928       // Compute new normals for _LayerEdge's on EDGEs
4929
4930       double avgCosin = 0;
4931       int     nbCosin = 0;
4932       gp_Vec inFaceDir;
4933       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
4934       {
4935         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
4936         if ( ceCurve._isDegenerated )
4937           continue;
4938         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
4939         vector< gp_XYZ > &   newNormals = ceCurve._normals;
4940         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
4941         {
4942           isOK = false;
4943           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
4944           {
4945             if ( iE1 != iE2 )
4946               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
4947           }
4948           if ( isOK && !ceCurve._adjFace.IsNull() )
4949           {
4950             // compute new _LayerEdge::_cosin
4951             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
4952             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
4953             if ( isOK )
4954             {
4955               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
4956               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
4957               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
4958               nbCosin++;
4959             }
4960           }
4961         }
4962       }
4963       // set new normals to _LayerEdge's of NOT degenerated central curves
4964       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4965       {
4966         if ( centerCurves[ iE ]._isDegenerated )
4967           continue;
4968         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
4969           centerCurves[ iE ]._ledges[ iLE ]->_normal = centerCurves[ iE ]._normals[ iLE ];
4970       }
4971       // set new normals to _LayerEdge's of     degenerated central curves
4972       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4973       {
4974         if ( !centerCurves[ iE ]._isDegenerated ||
4975              centerCurves[ iE ]._ledges.size() < 3 )
4976           continue;
4977         // new normal is an average of new normals at VERTEXes that
4978         // was computed on non-degenerated _CentralCurveOnEdge's
4979         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
4980                            centerCurves[ iE ]._ledges.back ()->_normal );
4981         double sz = newNorm.Modulus();
4982         if ( sz < 1e-200 )
4983           continue;
4984         newNorm /= sz;
4985         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
4986                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
4987         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
4988         {
4989           centerCurves[ iE ]._ledges[ iLE ]->_normal = newNorm;
4990           centerCurves[ iE ]._ledges[ iLE ]->_cosin  = newCosin;
4991         }
4992       }
4993
4994       // Find new normals for _LayerEdge's based on FACE
4995
4996       if ( nbCosin > 0 )
4997         avgCosin /= nbCosin;
4998       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
4999       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
5000       if ( id2eos != convFace._subIdToEOS.end() )
5001       {
5002         int iE = 0;
5003         gp_XYZ newNorm;
5004         _EdgesOnShape& eos = * ( id2eos->second );
5005         for ( size_t i = 0; i < eos._edges.size(); ++i )
5006         {
5007           _LayerEdge* ledge = eos._edges[ i ];
5008           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
5009             continue;
5010           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
5011           {
5012             iE = iE % centerCurves.size();
5013             if ( centerCurves[ iE ]._isDegenerated )
5014               continue;
5015             newNorm.SetCoord( 0,0,0 );
5016             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
5017             {
5018               ledge->_normal = newNorm;
5019               ledge->_cosin  = avgCosin;
5020               break;
5021             }
5022           }
5023         }
5024       }
5025
5026     } // not a quasi-spherical FACE
5027
5028     // Update _LayerEdge's data according to a new normal
5029
5030     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
5031                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
5032
5033     id2eos = convFace._subIdToEOS.begin();
5034     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
5035     {
5036       _EdgesOnShape& eos = * ( id2eos->second );
5037       for ( size_t i = 0; i < eos._edges.size(); ++i )
5038       {
5039         _LayerEdge* & ledge = eos._edges[ i ];
5040         double len = ledge->_len;
5041         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
5042         ledge->SetCosin( ledge->_cosin );
5043         ledge->SetNewLength( len, eos, helper );
5044       }
5045
5046     } // loop on sub-shapes of convFace._face
5047
5048     // Find FACEs adjacent to convFace._face that got necessity to smooth
5049     // as a result of normals modification
5050
5051     set< _EdgesOnShape* > adjFacesToSmooth;
5052     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
5053     {
5054       if ( centerCurves[ iE ]._adjFace.IsNull() ||
5055            centerCurves[ iE ]._adjFaceToSmooth )
5056         continue;
5057       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
5058       {
5059         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
5060         {
5061           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
5062           break;
5063         }
5064       }
5065     }
5066     data.AddShapesToSmooth( adjFacesToSmooth );
5067
5068     dumpFunctionEnd();
5069
5070
5071   } // loop on data._convexFaces
5072
5073   return true;
5074 }
5075
5076 //================================================================================
5077 /*!
5078  * \brief Finds a center of curvature of a surface at a _LayerEdge
5079  */
5080 //================================================================================
5081
5082 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
5083                                         BRepLProp_SLProps&  surfProp,
5084                                         SMESH_MesherHelper& helper,
5085                                         gp_Pnt &            center ) const
5086 {
5087   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
5088   surfProp.SetParameters( uv.X(), uv.Y() );
5089   if ( !surfProp.IsCurvatureDefined() )
5090     return false;
5091
5092   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
5093   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
5094   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
5095   if ( surfCurvatureMin > surfCurvatureMax )
5096     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
5097   else
5098     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
5099
5100   return true;
5101 }
5102
5103 //================================================================================
5104 /*!
5105  * \brief Check that prisms are not distorted
5106  */
5107 //================================================================================
5108
5109 bool _ConvexFace::CheckPrisms() const
5110 {
5111   double vol = 0;
5112   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
5113   {
5114     const _LayerEdge* edge = _simplexTestEdges[i];
5115     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
5116     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5117       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
5118       {
5119         debugMsg( "Bad simplex of _simplexTestEdges ("
5120                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
5121                   << " "<< edge->_simplices[j]._nPrev->GetID()
5122                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5123         return false;
5124       }
5125   }
5126   return true;
5127 }
5128
5129 //================================================================================
5130 /*!
5131  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
5132  *        stored in this _CentralCurveOnEdge.
5133  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
5134  *  \param [in,out] newNormal - current normal at this point, to be redefined
5135  *  \return bool - true if succeeded.
5136  */
5137 //================================================================================
5138
5139 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
5140 {
5141   if ( this->_isDegenerated )
5142     return false;
5143
5144   // find two centers the given one lies between
5145
5146   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
5147   {
5148     double sl2 = 1.001 * _segLength2[ i ];
5149
5150     double d1 = center.SquareDistance( _curvaCenters[ i ]);
5151     if ( d1 > sl2 )
5152       continue;
5153     
5154     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
5155     if ( d2 > sl2 || d2 + d1 < 1e-100 )
5156       continue;
5157
5158     d1 = Sqrt( d1 );
5159     d2 = Sqrt( d2 );
5160     double r = d1 / ( d1 + d2 );
5161     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
5162                    (      r ) * _ledges[ i+1 ]->_normal );
5163     norm.Normalize();
5164
5165     newNormal += norm;
5166     double sz = newNormal.Modulus();
5167     if ( sz < 1e-200 )
5168       break;
5169     newNormal /= sz;
5170     return true;
5171   }
5172   return false;
5173 }
5174
5175 //================================================================================
5176 /*!
5177  * \brief Set shape members
5178  */
5179 //================================================================================
5180
5181 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
5182                                      const _ConvexFace&  convFace,
5183                                      _SolidData&         data,
5184                                      SMESH_MesherHelper& helper)
5185 {
5186   _edge = edge;
5187
5188   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
5189   while ( const TopoDS_Shape* F = fIt->next())
5190     if ( !convFace._face.IsSame( *F ))
5191     {
5192       _adjFace = TopoDS::Face( *F );
5193       _adjFaceToSmooth = false;
5194       // _adjFace already in a smoothing queue ?
5195       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
5196         _adjFaceToSmooth = eos->_toSmooth;
5197       break;
5198     }
5199 }
5200
5201 //================================================================================
5202 /*!
5203  * \brief Looks for intersection of it's last segment with faces
5204  *  \param distance - returns shortest distance from the last node to intersection
5205  */
5206 //================================================================================
5207
5208 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
5209                                    double &                 distance,
5210                                    const double&            epsilon,
5211                                    _EdgesOnShape&           eos,
5212                                    const SMDS_MeshElement** face)
5213 {
5214   vector< const SMDS_MeshElement* > suspectFaces;
5215   double segLen;
5216   gp_Ax1 lastSegment = LastSegment( segLen, eos );
5217   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
5218
5219   bool segmentIntersected = false;
5220   distance = Precision::Infinite();
5221   int iFace = -1; // intersected face
5222   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
5223   {
5224     const SMDS_MeshElement* face = suspectFaces[j];
5225     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
5226          face->GetNodeIndex( _nodes[0]     ) >= 0 )
5227       continue; // face sharing _LayerEdge node
5228     const int nbNodes = face->NbCornerNodes();
5229     bool intFound = false;
5230     double dist;
5231     SMDS_MeshElement::iterator nIt = face->begin_nodes();
5232     if ( nbNodes == 3 )
5233     {
5234       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
5235     }
5236     else
5237     {
5238       const SMDS_MeshNode* tria[3];
5239       tria[0] = *nIt++;
5240       tria[1] = *nIt++;
5241       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
5242       {
5243         tria[2] = *nIt++;
5244         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
5245         tria[1] = tria[2];
5246       }
5247     }
5248     if ( intFound )
5249     {
5250       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
5251         segmentIntersected = true;
5252       if ( distance > dist )
5253         distance = dist, iFace = j;
5254     }
5255   }
5256   if ( iFace != -1 && face ) *face = suspectFaces[iFace];
5257
5258   if ( segmentIntersected )
5259   {
5260 #ifdef __myDEBUG
5261     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
5262     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
5263     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
5264          << ", intersection with face ("
5265          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5266          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
5267          << ") distance = " << distance - segLen<< endl;
5268 #endif
5269   }
5270
5271   distance -= segLen;
5272
5273   return segmentIntersected;
5274 }
5275
5276 //================================================================================
5277 /*!
5278  * \brief Returns size and direction of the last segment
5279  */
5280 //================================================================================
5281
5282 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
5283 {
5284   // find two non-coincident positions
5285   gp_XYZ orig = _pos.back();
5286   gp_XYZ dir;
5287   int iPrev = _pos.size() - 2;
5288   const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
5289   while ( iPrev >= 0 )
5290   {
5291     dir = orig - _pos[iPrev];
5292     if ( dir.SquareModulus() > tol*tol )
5293       break;
5294     else
5295       iPrev--;
5296   }
5297
5298   // make gp_Ax1
5299   gp_Ax1 segDir;
5300   if ( iPrev < 0 )
5301   {
5302     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
5303     segDir.SetDirection( _normal );
5304     segLen = 0;
5305   }
5306   else
5307   {
5308     gp_Pnt pPrev = _pos[ iPrev ];
5309     if ( !eos._sWOL.IsNull() )
5310     {
5311       TopLoc_Location loc;
5312       if ( eos.SWOLType() == TopAbs_EDGE )
5313       {
5314         double f,l;
5315         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
5316         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
5317       }
5318       else
5319       {
5320         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
5321         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
5322       }
5323       dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
5324     }
5325     segDir.SetLocation( pPrev );
5326     segDir.SetDirection( dir );
5327     segLen = dir.Modulus();
5328   }
5329
5330   return segDir;
5331 }
5332
5333 //================================================================================
5334 /*!
5335  * \brief Return the last position of the target node on a FACE. 
5336  *  \param [in] F - the FACE this _LayerEdge is inflated along
5337  *  \return gp_XY - result UV
5338  */
5339 //================================================================================
5340
5341 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
5342 {
5343   if ( F.IsSame( eos._sWOL )) // F is my FACE
5344     return gp_XY( _pos.back().X(), _pos.back().Y() );
5345
5346   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
5347     return gp_XY( 1e100, 1e100 );
5348
5349   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
5350   double f, l, u = _pos.back().X();
5351   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
5352   if ( !C2d.IsNull() && f <= u && u <= l )
5353     return C2d->Value( u ).XY();
5354
5355   return gp_XY( 1e100, 1e100 );
5356 }
5357
5358 //================================================================================
5359 /*!
5360  * \brief Test intersection of the last segment with a given triangle
5361  *   using Moller-Trumbore algorithm
5362  * Intersection is detected if distance to intersection is less than _LayerEdge._len
5363  */
5364 //================================================================================
5365
5366 bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
5367                                const SMDS_MeshNode* n0,
5368                                const SMDS_MeshNode* n1,
5369                                const SMDS_MeshNode* n2,
5370                                double&              t,
5371                                const double&        EPSILON) const
5372 {
5373   //const double EPSILON = 1e-6;
5374
5375   const gp_Pnt& orig = lastSegment.Location();
5376   const gp_Dir& dir  = lastSegment.Direction();
5377
5378   SMESH_TNodeXYZ vert0( n0 );
5379   SMESH_TNodeXYZ vert1( n1 );
5380   SMESH_TNodeXYZ vert2( n2 );
5381
5382   /* calculate distance from vert0 to ray origin */
5383   gp_XYZ tvec = orig.XYZ() - vert0;
5384
5385   //if ( tvec * dir > EPSILON )
5386     // intersected face is at back side of the temporary face this _LayerEdge belongs to
5387     //return false;
5388
5389   gp_XYZ edge1 = vert1 - vert0;
5390   gp_XYZ edge2 = vert2 - vert0;
5391
5392   /* begin calculating determinant - also used to calculate U parameter */
5393   gp_XYZ pvec = dir.XYZ() ^ edge2;
5394
5395   /* if determinant is near zero, ray lies in plane of triangle */
5396   double det = edge1 * pvec;
5397
5398   if (det > -EPSILON && det < EPSILON)
5399     return false;
5400
5401   /* calculate U parameter and test bounds */
5402   double u = ( tvec * pvec ) / det;
5403   //if (u < 0.0 || u > 1.0)
5404   if (u < -EPSILON || u > 1.0 + EPSILON)
5405     return false;
5406
5407   /* prepare to test V parameter */
5408   gp_XYZ qvec = tvec ^ edge1;
5409
5410   /* calculate V parameter and test bounds */
5411   double v = (dir.XYZ() * qvec) / det;
5412   //if ( v < 0.0 || u + v > 1.0 )
5413   if ( v < -EPSILON || u + v > 1.0 + EPSILON)
5414     return false;
5415
5416   /* calculate t, ray intersects triangle */
5417   t = (edge2 * qvec) / det;
5418
5419   //return true;
5420   return t > 0.;
5421 }
5422
5423 //================================================================================
5424 /*!
5425  * \brief Perform smooth of _LayerEdge's based on EDGE's
5426  *  \retval bool - true if node has been moved
5427  */
5428 //================================================================================
5429
5430 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
5431                               const TopoDS_Face&    F,
5432                               SMESH_MesherHelper&   helper)
5433 {
5434   ASSERT( IsOnEdge() );
5435
5436   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
5437   SMESH_TNodeXYZ oldPos( tgtNode );
5438   double dist01, distNewOld;
5439   
5440   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
5441   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
5442   dist01 = p0.Distance( _2neibors->tgtNode(1) );
5443
5444   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
5445   double lenDelta = 0;
5446   if ( _curvature )
5447   {
5448     //lenDelta = _curvature->lenDelta( _len );
5449     lenDelta = _curvature->lenDeltaByDist( dist01 );
5450     newPos.ChangeCoord() += _normal * lenDelta;
5451   }
5452
5453   distNewOld = newPos.Distance( oldPos );
5454
5455   if ( F.IsNull() )
5456   {
5457     if ( _2neibors->_plnNorm )
5458     {
5459       // put newPos on the plane defined by source node and _plnNorm
5460       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
5461       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
5462       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
5463     }
5464     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5465     _pos.back() = newPos.XYZ();
5466   }
5467   else
5468   {
5469     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5470     gp_XY uv( Precision::Infinite(), 0 );
5471     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
5472     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
5473
5474     newPos = surface->Value( uv.X(), uv.Y() );
5475     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5476   }
5477
5478   // commented for IPAL0052478
5479   // if ( _curvature && lenDelta < 0 )
5480   // {
5481   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
5482   //   _len -= prevPos.Distance( oldPos );
5483   //   _len += prevPos.Distance( newPos );
5484   // }
5485   bool moved = distNewOld > dist01/50;
5486   //if ( moved )
5487   dumpMove( tgtNode ); // debug
5488
5489   return moved;
5490 }
5491
5492 //================================================================================
5493 /*!
5494  * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
5495  *  \retval bool - true if _tgtNode has been moved
5496  */
5497 //================================================================================
5498
5499 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, const bool findBest )
5500 {
5501   if ( _simplices.size() < 2 )
5502     return 0; // _LayerEdge inflated along EDGE or FACE
5503
5504   const gp_XYZ& curPos ( _pos.back() );
5505   const gp_XYZ& prevPos( _pos[ _pos.size()-2 ]);
5506
5507   // quality metrics (orientation) of tetras around _tgtNode
5508   int nbOkBefore = 0;
5509   double vol, minVolBefore = 1e100;
5510   for ( size_t i = 0; i < _simplices.size(); ++i )
5511   {
5512     nbOkBefore += _simplices[i].IsForward( _nodes[0], &curPos, vol );
5513     minVolBefore = Min( minVolBefore, vol );
5514   }
5515   int nbBad = _simplices.size() - nbOkBefore;
5516
5517   // compute new position for the last _pos using different _funs
5518   gp_XYZ newPos;
5519   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
5520   {
5521     if ( iFun < 0 )
5522       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
5523     else if ( _funs[ iFun ] == _smooFunction )
5524       continue; // _smooFunction again
5525     else if ( step > 0 )
5526       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
5527     else
5528       break; // let "easy" functions improve elements around distorted ones
5529
5530     if ( _curvature )
5531     {
5532       double delta  = _curvature->lenDelta( _len );
5533       if ( delta > 0 )
5534         newPos += _normal * delta;
5535       else
5536       {
5537         double segLen = _normal * ( newPos - prevPos );
5538         if ( segLen + delta > 0 )
5539           newPos += _normal * delta;
5540       }
5541       // double segLenChange = _normal * ( curPos - newPos );
5542       // newPos += 0.5 * _normal * segLenChange;
5543     }
5544
5545     int nbOkAfter = 0;
5546     double minVolAfter = 1e100;
5547     for ( size_t i = 0; i < _simplices.size(); ++i )
5548     {
5549       nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos, vol );
5550       minVolAfter = Min( minVolAfter, vol );
5551     }
5552     // get worse?
5553     if ( nbOkAfter < nbOkBefore )
5554       continue;
5555     if (( isConcaveFace || findBest ) &&
5556         ( nbOkAfter == nbOkBefore ) &&
5557         //( iFun > -1 || nbOkAfter < _simplices.size() ) &&
5558         ( minVolAfter <= minVolBefore ))
5559       continue;
5560
5561     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
5562
5563     // commented for IPAL0052478
5564     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
5565     // _len += prevPos.Distance(newPos);
5566
5567     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
5568     _pos.back() = newPos;
5569     dumpMoveComm( n, _funNames[ iFun < 0 ? smooFunID() : iFun ]);
5570
5571     nbBad = _simplices.size() - nbOkAfter;
5572
5573     if ( iFun > -1 )
5574     {
5575       //_smooFunction = _funs[ iFun ];
5576       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
5577       // << "\t nbBad: " << _simplices.size() - nbOkAfter
5578       // << " minVol: " << minVolAfter
5579       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
5580       // << endl;
5581       minVolBefore = minVolAfter;
5582       nbOkBefore = nbOkAfter;
5583       continue; // look for a better function
5584     }
5585
5586     if ( !findBest )
5587       break;
5588
5589   } // loop on smoothing functions
5590
5591   return nbBad;
5592 }
5593
5594 //================================================================================
5595 /*!
5596  * \brief Chooses a smoothing technic giving a position most close to an initial one.
5597  *        For a correct result, _simplices must contain nodes lying on geometry.
5598  */
5599 //================================================================================
5600
5601 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
5602                                      const TNode2Edge&     n2eMap)
5603 {
5604   if ( _smooFunction ) return;
5605
5606   // use smoothNefPolygon() near concaveVertices
5607   if ( !concaveVertices.empty() )
5608   {
5609     for ( size_t i = 0; i < _simplices.size(); ++i )
5610     {
5611       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
5612       {
5613         _smooFunction = _funs[ FUN_NEFPOLY ];
5614
5615         // set FUN_CENTROIDAL to neighbor edges
5616         TNode2Edge::const_iterator n2e;
5617         for ( i = 0; i < _simplices.size(); ++i )
5618         {
5619           if (( _simplices[i]._nPrev->GetPosition()->GetDim() == 2 ) &&
5620               (( n2e = n2eMap.find( _simplices[i]._nPrev )) != n2eMap.end() ))
5621           {
5622             n2e->second->_smooFunction = _funs[ FUN_CENTROIDAL ];
5623           }
5624         }
5625         return;
5626       }
5627     }
5628     //}
5629
5630     // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
5631     // where the nodes are smoothed too far along a sphere thus creating
5632     // inverted _simplices
5633     double dist[theNbSmooFuns];
5634     //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
5635     double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
5636
5637     double minDist = Precision::Infinite();
5638     gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
5639     for ( int i = 0; i < FUN_NEFPOLY; ++i )
5640     {
5641       gp_Pnt newP = (this->*_funs[i])();
5642       dist[i] = p.SquareDistance( newP );
5643       if ( dist[i]*coef[i] < minDist )
5644       {
5645         _smooFunction = _funs[i];
5646         minDist = dist[i]*coef[i];
5647       }
5648     }
5649   }
5650   else
5651   {
5652     _smooFunction = _funs[ FUN_LAPLACIAN ];
5653   }
5654   // int minDim = 3;
5655   // for ( size_t i = 0; i < _simplices.size(); ++i )
5656   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
5657   // if ( minDim == 0 )
5658   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
5659   // else if ( minDim == 1 )
5660   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
5661
5662
5663   // int iMin;
5664   // for ( int i = 0; i < FUN_NB; ++i )
5665   // {
5666   //   //cout << dist[i] << " ";
5667   //   if ( _smooFunction == _funs[i] ) {
5668   //     iMin = i;
5669   //     //debugMsg( fNames[i] );
5670   //     break;
5671   //   }
5672   // }
5673   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
5674 }
5675
5676 //================================================================================
5677 /*!
5678  * \brief Returns a name of _SmooFunction
5679  */
5680 //================================================================================
5681
5682 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
5683 {
5684   if ( !fun )
5685     fun = _smooFunction;
5686   for ( int i = 0; i < theNbSmooFuns; ++i )
5687     if ( fun == _funs[i] )
5688       return i;
5689
5690   return theNbSmooFuns;
5691 }
5692
5693 //================================================================================
5694 /*!
5695  * \brief Computes a new node position using Laplacian smoothing
5696  */
5697 //================================================================================
5698
5699 gp_XYZ _LayerEdge::smoothLaplacian()
5700 {
5701   gp_XYZ newPos (0,0,0);
5702   for ( size_t i = 0; i < _simplices.size(); ++i )
5703     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
5704   newPos /= _simplices.size();
5705
5706   return newPos;
5707 }
5708
5709 //================================================================================
5710 /*!
5711  * \brief Computes a new node position using angular-based smoothing
5712  */
5713 //================================================================================
5714
5715 gp_XYZ _LayerEdge::smoothAngular()
5716 {
5717   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1);
5718   vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
5719   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
5720
5721   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
5722   gp_XYZ pN( 0,0,0 );
5723   for ( size_t i = 0; i < _simplices.size(); ++i )
5724   {
5725     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5726     edgeDir.push_back( p - pPrev );
5727     edgeSize.push_back( edgeDir.back().Magnitude() );
5728     //double edgeSize = edgeDir.back().Magnitude();
5729     if ( edgeSize.back() < numeric_limits<double>::min() )
5730     {
5731       edgeDir.pop_back();
5732       edgeSize.pop_back();
5733     }
5734     else
5735     {
5736       edgeDir.back() /= edgeSize.back();
5737       points.push_back( p );
5738       pN += p;
5739     }
5740     pPrev = p;
5741   }
5742   edgeDir.push_back ( edgeDir[0] );
5743   edgeSize.push_back( edgeSize[0] );
5744   pN /= points.size();
5745
5746   gp_XYZ newPos(0,0,0);
5747   //gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
5748   double sumSize = 0;
5749   for ( size_t i = 0; i < points.size(); ++i )
5750   {
5751     gp_Vec toN( pN - points[i]);
5752     double toNLen = toN.Magnitude();
5753     if ( toNLen < numeric_limits<double>::min() )
5754     {
5755       newPos += pN;
5756       continue;
5757     }
5758     gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
5759     double bisecLen = bisec.SquareMagnitude();
5760     if ( bisecLen < numeric_limits<double>::min() )
5761     {
5762       gp_Vec norm = edgeDir[i] ^ toN;
5763       bisec = norm ^ edgeDir[i];
5764       bisecLen = bisec.SquareMagnitude();
5765     }
5766     bisecLen = Sqrt( bisecLen );
5767     bisec /= bisecLen;
5768
5769 #if 1
5770     //bisecLen = 1.;
5771     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
5772     sumSize += bisecLen;
5773 #else
5774     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
5775     sumSize += ( edgeSize[i] + edgeSize[i+1] );
5776 #endif
5777     newPos += pNew;
5778   }
5779   newPos /= sumSize;
5780
5781   return newPos;
5782 }
5783
5784 //================================================================================
5785 /*!
5786  * \brief Computes a new node position using weigthed node positions
5787  */
5788 //================================================================================
5789
5790 gp_XYZ _LayerEdge::smoothLengthWeighted()
5791 {
5792   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
5793   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
5794
5795   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
5796   for ( size_t i = 0; i < _simplices.size(); ++i )
5797   {
5798     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5799     edgeSize.push_back( ( p - pPrev ).Modulus() );
5800     if ( edgeSize.back() < numeric_limits<double>::min() )
5801     {
5802       edgeSize.pop_back();
5803     }
5804     else
5805     {
5806       points.push_back( p );
5807     }
5808     pPrev = p;
5809   }
5810   edgeSize.push_back( edgeSize[0] );
5811
5812   gp_XYZ newPos(0,0,0);
5813   double sumSize = 0;
5814   for ( size_t i = 0; i < points.size(); ++i )
5815   {
5816     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
5817     sumSize += edgeSize[i] + edgeSize[i+1];
5818   }
5819   newPos /= sumSize;
5820   return newPos;
5821 }
5822
5823 //================================================================================
5824 /*!
5825  * \brief Computes a new node position using angular-based smoothing
5826  */
5827 //================================================================================
5828
5829 gp_XYZ _LayerEdge::smoothCentroidal()
5830 {
5831   gp_XYZ newPos(0,0,0);
5832   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
5833   double sumSize = 0;
5834   for ( size_t i = 0; i < _simplices.size(); ++i )
5835   {
5836     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5837     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
5838     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
5839     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
5840
5841     sumSize += size;
5842     newPos += gc * size;
5843   }
5844   newPos /= sumSize;
5845
5846   return newPos;
5847 }
5848
5849 //================================================================================
5850 /*!
5851  * \brief Computes a new node position located inside a Nef polygon
5852  */
5853 //================================================================================
5854
5855 gp_XYZ _LayerEdge::smoothNefPolygon()
5856 {
5857   gp_XYZ newPos(0,0,0);
5858
5859   // get a plane to seach a solution on
5860
5861   vector< gp_XYZ > vecs( _simplices.size() + 1 );
5862   size_t i;
5863   const double tol = numeric_limits<double>::min();
5864   gp_XYZ center(0,0,0);
5865   for ( i = 0; i < _simplices.size(); ++i )
5866   {
5867     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
5868                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
5869     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
5870   }
5871   vecs.back() = vecs[0];
5872   center /= _simplices.size();
5873
5874   gp_XYZ zAxis(0,0,0);
5875   for ( i = 0; i < _simplices.size(); ++i )
5876     zAxis += vecs[i] ^ vecs[i+1];
5877
5878   gp_XYZ yAxis;
5879   for ( i = 0; i < _simplices.size(); ++i )
5880   {
5881     yAxis = vecs[i];
5882     if ( yAxis.SquareModulus() > tol )
5883       break;
5884   }
5885   gp_XYZ xAxis = yAxis ^ zAxis;
5886   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
5887   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
5888   //                             p0.Distance( _simplices[2]._nPrev ));
5889   // gp_XYZ center = smoothLaplacian();
5890   // gp_XYZ xAxis, yAxis, zAxis;
5891   // for ( i = 0; i < _simplices.size(); ++i )
5892   // {
5893   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5894   //   if ( xAxis.SquareModulus() > tol*tol )
5895   //     break;
5896   // }
5897   // for ( i = 1; i < _simplices.size(); ++i )
5898   // {
5899   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5900   //   zAxis = xAxis ^ yAxis;
5901   //   if ( zAxis.SquareModulus() > tol*tol )
5902   //     break;
5903   // }
5904   // if ( i == _simplices.size() ) return newPos;
5905
5906   yAxis = zAxis ^ xAxis;
5907   xAxis /= xAxis.Modulus();
5908   yAxis /= yAxis.Modulus();
5909
5910   // get half-planes of _simplices
5911
5912   vector< _halfPlane > halfPlns( _simplices.size() );
5913   int nbHP = 0;
5914   for ( size_t i = 0; i < _simplices.size(); ++i )
5915   {
5916     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5917     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
5918     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
5919     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
5920     gp_XY  vec12 = p2 - p1;
5921     double dist12 = vec12.Modulus();
5922     if ( dist12 < tol )
5923       continue;
5924     vec12 /= dist12;
5925     halfPlns[ nbHP ]._pos = p1;
5926     halfPlns[ nbHP ]._dir = vec12;
5927     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
5928     ++nbHP;
5929   }
5930
5931   // intersect boundaries of half-planes, define state of intersection points
5932   // in relation to all half-planes and calculate internal point of a 2D polygon
5933
5934   double sumLen = 0;
5935   gp_XY newPos2D (0,0);
5936
5937   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
5938   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
5939   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
5940
5941   vector< vector< TIntPntState > > allIntPnts( nbHP );
5942   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
5943   {
5944     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
5945     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
5946
5947     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
5948     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
5949
5950     int nbNotOut = 0;
5951     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
5952
5953     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
5954     {
5955       if ( iHP1 == iHP2 ) continue;
5956
5957       TIntPntState & ips1 = intPnts1[ iHP2 ];
5958       if ( ips1.second == UNDEF )
5959       {
5960         // find an intersection point of boundaries of iHP1 and iHP2
5961
5962         if ( iHP2 == iPrev ) // intersection with neighbors is known
5963           ips1.first = halfPlns[ iHP1 ]._pos;
5964         else if ( iHP2 == iNext )
5965           ips1.first = halfPlns[ iHP2 ]._pos;
5966         else if ( !halfPlns[ iHP1 ].FindInterestion( halfPlns[ iHP2 ], ips1.first ))
5967           ips1.second = NO_INT;
5968
5969         // classify the found intersection point
5970         if ( ips1.second != NO_INT )
5971         {
5972           ips1.second = NOT_OUT;
5973           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
5974             if ( i != iHP1 && i != iHP2 &&
5975                  halfPlns[ i ].IsOut( ips1.first, tol ))
5976               ips1.second = IS_OUT;
5977         }
5978         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
5979         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
5980         TIntPntState & ips2 = intPnts2[ iHP1 ];
5981         ips2 = ips1;
5982       }
5983       if ( ips1.second == NOT_OUT )
5984       {
5985         ++nbNotOut;
5986         segEnds[ bool(segEnds[0]) ] = & ips1.first;
5987       }
5988     }
5989
5990     // find a NOT_OUT segment of boundary which is located between
5991     // two NOT_OUT int points
5992
5993     if ( nbNotOut < 2 )
5994       continue; // no such a segment
5995
5996     if ( nbNotOut > 2 )
5997     {
5998       // sort points along the boundary
5999       map< double, TIntPntState* > ipsByParam;
6000       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
6001       {
6002         TIntPntState & ips1 = intPnts1[ iHP2 ];
6003         if ( ips1.second != NO_INT )
6004         {
6005           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
6006           double param = op * halfPlns[ iHP1 ]._dir;
6007           ipsByParam.insert( make_pair( param, & ips1 ));
6008         }
6009       }
6010       // look for two neighboring NOT_OUT points
6011       nbNotOut = 0;
6012       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
6013       for ( ; u2ips != ipsByParam.end(); ++u2ips )
6014       {
6015         TIntPntState & ips1 = *(u2ips->second);
6016         if ( ips1.second == NOT_OUT )
6017           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
6018         else if ( nbNotOut >= 2 )
6019           break;
6020         else
6021           nbNotOut = 0;
6022       }
6023     }
6024
6025     if ( nbNotOut >= 2 )
6026     {
6027       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
6028       sumLen += len;
6029
6030       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
6031     }
6032   }
6033
6034   if ( sumLen > 0 )
6035   {
6036     newPos2D /= sumLen;
6037     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
6038   }
6039   else
6040   {
6041     newPos = center;
6042   }
6043
6044   return newPos;
6045 }
6046
6047 //================================================================================
6048 /*!
6049  * \brief Add a new segment to _LayerEdge during inflation
6050  */
6051 //================================================================================
6052
6053 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
6054 {
6055   if ( _len - len > -1e-6 )
6056   {
6057     //_pos.push_back( _pos.back() );
6058     return;
6059   }
6060
6061   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
6062   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
6063   gp_XYZ newXYZ;
6064   if ( eos._hyp.IsOffsetMethod() )
6065   {
6066     newXYZ = oldXYZ;
6067     gp_Vec faceNorm;
6068     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
6069     while ( faceIt->more() )
6070     {
6071       const SMDS_MeshElement* face = faceIt->next();
6072       if ( !eos.GetNormal( face, faceNorm ))
6073         continue;
6074
6075       // translate plane of a face
6076       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * ( len - _len );
6077
6078       // find point of intersection of the face plane located at baryCenter
6079       // and _normal located at newXYZ
6080       double d    = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
6081       double dot  = ( faceNorm.XYZ() * _normal );
6082       if ( dot < std::numeric_limits<double>::min() )
6083         dot = ( len - _len ) * 1e-3;
6084       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
6085       newXYZ += step * _normal;
6086     }
6087   }
6088   else
6089   {
6090     newXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
6091   }
6092   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
6093
6094   _pos.push_back( newXYZ );
6095   _len = len;
6096
6097   if ( !eos._sWOL.IsNull() )
6098   {
6099     double distXYZ[4];
6100     if ( eos.SWOLType() == TopAbs_EDGE )
6101     {
6102       double u = Precision::Infinite(); // to force projection w/o distance check
6103       helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
6104       _pos.back().SetCoord( u, 0, 0 );
6105       if ( _nodes.size() > 1 )
6106       {
6107         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
6108         pos->SetUParameter( u );
6109       }
6110     }
6111     else //  TopAbs_FACE
6112     {
6113       gp_XY uv( Precision::Infinite(), 0 );
6114       helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
6115       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
6116       if ( _nodes.size() > 1 )
6117       {
6118         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
6119         pos->SetUParameter( uv.X() );
6120         pos->SetVParameter( uv.Y() );
6121       }
6122     }
6123     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
6124   }
6125   dumpMove( n ); //debug
6126 }
6127
6128 //================================================================================
6129 /*!
6130  * \brief Remove last inflation step
6131  */
6132 //================================================================================
6133
6134 void _LayerEdge::InvalidateStep( int curStep, const _EdgesOnShape& eos, bool restoreLength )
6135 {
6136   if ( _pos.size() > curStep )
6137   {
6138     if ( restoreLength )
6139       _len -= ( _pos[ curStep-1 ] - _pos.back() ).Modulus();
6140
6141     _pos.resize( curStep );
6142     gp_Pnt nXYZ = _pos.back();
6143     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
6144     if ( !eos._sWOL.IsNull() )
6145     {
6146       TopLoc_Location loc;
6147       if ( eos.SWOLType() == TopAbs_EDGE )
6148       {
6149         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
6150         pos->SetUParameter( nXYZ.X() );
6151         double f,l;
6152         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
6153         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
6154       }
6155       else
6156       {
6157         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
6158         pos->SetUParameter( nXYZ.X() );
6159         pos->SetVParameter( nXYZ.Y() );
6160         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
6161         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
6162       }
6163     }
6164     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
6165     dumpMove( n );
6166   }
6167 }
6168
6169 //================================================================================
6170 /*!
6171  * \brief Create layers of prisms
6172  */
6173 //================================================================================
6174
6175 bool _ViscousBuilder::refine(_SolidData& data)
6176 {
6177   SMESH_MesherHelper helper( *_mesh );
6178   helper.SetSubShape( data._solid );
6179   helper.SetElementsOnShape(false);
6180
6181   Handle(Geom_Curve) curve;
6182   Handle(Geom_Surface) surface;
6183   TopoDS_Edge geomEdge;
6184   TopoDS_Face geomFace;
6185   TopoDS_Shape prevSWOL;
6186   TopLoc_Location loc;
6187   double f,l, u;
6188   gp_XY uv;
6189   bool isOnEdge;
6190   TGeomID prevBaseId = -1;
6191   TNode2Edge* n2eMap = 0;
6192   TNode2Edge::iterator n2e;
6193
6194   // Create intermediate nodes on each _LayerEdge
6195
6196   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6197   {
6198     _EdgesOnShape& eos = data._edgesOnShape[iS];
6199     if ( eos._edges.empty() ) continue;
6200
6201     if ( eos._edges[0]->_nodes.size() < 2 )
6202       continue; // on _noShrinkShapes
6203
6204     for ( size_t i = 0; i < eos._edges.size(); ++i )
6205     {
6206       _LayerEdge& edge = *eos._edges[i];
6207
6208       // get accumulated length of segments
6209       vector< double > segLen( edge._pos.size() );
6210       segLen[0] = 0.0;
6211       for ( size_t j = 1; j < edge._pos.size(); ++j )
6212         segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
6213
6214       // allocate memory for new nodes if it is not yet refined
6215       const SMDS_MeshNode* tgtNode = edge._nodes.back();
6216       if ( edge._nodes.size() == 2 )
6217       {
6218         edge._nodes.resize( eos._hyp.GetNumberLayers() + 1, 0 );
6219         edge._nodes[1] = 0;
6220         edge._nodes.back() = tgtNode;
6221       }
6222       // get data of a shrink shape
6223       if ( !eos._sWOL.IsNull() && eos._sWOL != prevSWOL )
6224       {
6225         isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
6226         if ( isOnEdge )
6227         {
6228           geomEdge = TopoDS::Edge( eos._sWOL );
6229           curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
6230         }
6231         else
6232         {
6233           geomFace = TopoDS::Face( eos._sWOL );
6234           surface  = BRep_Tool::Surface( geomFace, loc );
6235         }
6236         prevSWOL = eos._sWOL;
6237       }
6238       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
6239       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
6240       if ( baseShapeId != prevBaseId )
6241       {
6242         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
6243         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
6244         prevBaseId = baseShapeId;
6245       }
6246       _LayerEdge* edgeOnSameNode = 0;
6247       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
6248       {
6249         edgeOnSameNode = n2e->second;
6250         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
6251         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
6252         if ( isOnEdge )
6253         {
6254           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
6255           epos->SetUParameter( otherTgtPos.X() );
6256         }
6257         else
6258         {
6259           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
6260           fpos->SetUParameter( otherTgtPos.X() );
6261           fpos->SetVParameter( otherTgtPos.Y() );
6262         }
6263       }
6264       // calculate height of the first layer
6265       double h0;
6266       const double T = segLen.back(); //data._hyp.GetTotalThickness();
6267       const double f = eos._hyp.GetStretchFactor();
6268       const int    N = eos._hyp.GetNumberLayers();
6269       const double fPowN = pow( f, N );
6270       if ( fPowN - 1 <= numeric_limits<double>::min() )
6271         h0 = T / N;
6272       else
6273         h0 = T * ( f - 1 )/( fPowN - 1 );
6274
6275       const double zeroLen = std::numeric_limits<double>::min();
6276
6277       // create intermediate nodes
6278       double hSum = 0, hi = h0/f;
6279       size_t iSeg = 1;
6280       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
6281       {
6282         // compute an intermediate position
6283         hi *= f;
6284         hSum += hi;
6285         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
6286           ++iSeg;
6287         int iPrevSeg = iSeg-1;
6288         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
6289           --iPrevSeg;
6290         double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
6291         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
6292
6293         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
6294         if ( !eos._sWOL.IsNull() )
6295         {
6296           // compute XYZ by parameters <pos>
6297           if ( isOnEdge )
6298           {
6299             u = pos.X();
6300             if ( !node )
6301               pos = curve->Value( u ).Transformed(loc);
6302           }
6303           else
6304           {
6305             uv.SetCoord( pos.X(), pos.Y() );
6306             if ( !node )
6307               pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
6308           }
6309         }
6310         // create or update the node
6311         if ( !node )
6312         {
6313           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
6314           if ( !eos._sWOL.IsNull() )
6315           {
6316             if ( isOnEdge )
6317               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
6318             else
6319               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
6320           }
6321           else
6322           {
6323             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
6324           }
6325         }
6326         else
6327         {
6328           if ( !eos._sWOL.IsNull() )
6329           {
6330             // make average pos from new and current parameters
6331             if ( isOnEdge )
6332             {
6333               u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
6334               pos = curve->Value( u ).Transformed(loc);
6335
6336               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
6337               epos->SetUParameter( u );
6338             }
6339             else
6340             {
6341               uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
6342               pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
6343
6344               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
6345               fpos->SetUParameter( uv.X() );
6346               fpos->SetVParameter( uv.Y() );
6347             }
6348           }
6349           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
6350         }
6351       } // loop on edge._nodes
6352
6353       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
6354       {
6355         if ( isOnEdge )
6356           edge._pos.back().SetCoord( u, 0,0);
6357         else
6358           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
6359
6360         if ( edgeOnSameNode )
6361           edgeOnSameNode->_pos.back() = edge._pos.back();
6362       }
6363
6364     } // loop on eos._edges to create nodes
6365
6366
6367     if ( !getMeshDS()->IsEmbeddedMode() )
6368       // Log node movement
6369       for ( size_t i = 0; i < eos._edges.size(); ++i )
6370       {
6371         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
6372         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
6373       }
6374   }
6375
6376
6377   // Create volumes
6378
6379   helper.SetElementsOnShape(true);
6380
6381   vector< vector<const SMDS_MeshNode*>* > nnVec;
6382   set< vector<const SMDS_MeshNode*>* >    nnSet;
6383   set< int > degenEdgeInd;
6384   vector<const SMDS_MeshElement*> degenVols;
6385
6386   TopExp_Explorer exp( data._solid, TopAbs_FACE );
6387   for ( ; exp.More(); exp.Next() )
6388   {
6389     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
6390     if ( data._ignoreFaceIds.count( faceID ))
6391       continue;
6392     const bool isReversedFace = data._reversedFaceIds.count( faceID );
6393     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
6394     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
6395     while ( fIt->more() )
6396     {
6397       const SMDS_MeshElement* face = fIt->next();
6398       const int            nbNodes = face->NbCornerNodes();
6399       nnVec.resize( nbNodes );
6400       nnSet.clear();
6401       degenEdgeInd.clear();
6402       int nbZ = 0;
6403       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
6404       for ( int iN = 0; iN < nbNodes; ++iN )
6405       {
6406         const SMDS_MeshNode* n = nIt->next();
6407         const int i = isReversedFace ? nbNodes-1-iN : iN;
6408         nnVec[ i ] = & data._n2eMap[ n ]->_nodes;
6409         if ( nnVec[ i ]->size() < 2 )
6410           degenEdgeInd.insert( iN );
6411         else
6412           nbZ = nnVec[ i ]->size();
6413
6414         if ( helper.HasDegeneratedEdges() )
6415           nnSet.insert( nnVec[ i ]);
6416       }
6417       if ( nbZ == 0 )
6418         continue;
6419       if ( 0 < nnSet.size() && nnSet.size() < 3 )
6420         continue;
6421
6422       switch ( nbNodes )
6423       {
6424       case 3:
6425         switch ( degenEdgeInd.size() )
6426         {
6427         case 0: // PENTA
6428         {
6429           for ( int iZ = 1; iZ < nbZ; ++iZ )
6430             helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
6431                               (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
6432           break;
6433         }
6434         case 1: // PYRAM
6435         {
6436           int i2 = *degenEdgeInd.begin();
6437           int i0 = helper.WrapIndex( i2 - 1, nbNodes );
6438           int i1 = helper.WrapIndex( i2 + 1, nbNodes );
6439           for ( int iZ = 1; iZ < nbZ; ++iZ )
6440             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
6441                               (*nnVec[i1])[iZ],   (*nnVec[i0])[iZ],   (*nnVec[i2])[0]);
6442           break;
6443         }
6444         case 2: // TETRA
6445         {
6446           int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
6447           for ( int iZ = 1; iZ < nbZ; ++iZ )
6448             helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
6449                               (*nnVec[i3])[iZ]);
6450           break;
6451         }
6452         }
6453         break;
6454
6455       case 4:
6456         switch ( degenEdgeInd.size() )
6457         {
6458         case 0: // HEX
6459         {
6460           for ( int iZ = 1; iZ < nbZ; ++iZ )
6461             helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
6462                               (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
6463                               (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
6464                               (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
6465           break;
6466         }
6467         case 2: // PENTA?
6468         {
6469           int i2 = *degenEdgeInd.begin();
6470           int i3 = *degenEdgeInd.rbegin();
6471           bool ok = ( i3 - i2 == 1 );
6472           if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
6473           int i0 = helper.WrapIndex( i3 + 1, nbNodes );
6474           int i1 = helper.WrapIndex( i0 + 1, nbNodes );
6475           for ( int iZ = 1; iZ < nbZ; ++iZ )
6476           {
6477             const SMDS_MeshElement* vol =
6478               helper.AddVolume( (*nnVec[i3])[0], (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
6479                                 (*nnVec[i2])[0], (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
6480             if ( !ok && vol )
6481               degenVols.push_back( vol );
6482           }
6483           break;
6484         }
6485         case 3: // degen HEX
6486         {
6487           const SMDS_MeshNode* nn[8];
6488           for ( int iZ = 1; iZ < nbZ; ++iZ )
6489           {
6490             const SMDS_MeshElement* vol =
6491               helper.AddVolume( nnVec[0]->size() > 1 ? (*nnVec[0])[iZ-1] : (*nnVec[0])[0],
6492                                 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ-1] : (*nnVec[1])[0],
6493                                 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ-1] : (*nnVec[2])[0],
6494                                 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ-1] : (*nnVec[3])[0],
6495                                 nnVec[0]->size() > 1 ? (*nnVec[0])[iZ]   : (*nnVec[0])[0],
6496                                 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ]   : (*nnVec[1])[0],
6497                                 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ]   : (*nnVec[2])[0],
6498                                 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ]   : (*nnVec[3])[0]);
6499             degenVols.push_back( vol );
6500           }
6501         }
6502         break;
6503         }
6504         break;
6505
6506       default:
6507         return error("Not supported type of element", data._index);
6508
6509       } // switch ( nbNodes )
6510     } // while ( fIt->more() )
6511   } // loop on FACEs
6512
6513   if ( !degenVols.empty() )
6514   {
6515     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
6516     if ( !err || err->IsOK() )
6517     {
6518       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
6519                                          "Degenerated volumes created" ));
6520       err->myBadElements.insert( err->myBadElements.end(),
6521                                  degenVols.begin(),degenVols.end() );
6522     }
6523   }
6524
6525   return true;
6526 }
6527
6528 //================================================================================
6529 /*!
6530  * \brief Shrink 2D mesh on faces to let space for inflated layers
6531  */
6532 //================================================================================
6533
6534 bool _ViscousBuilder::shrink()
6535 {
6536   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
6537   // inflated along FACE or EDGE)
6538   map< TGeomID, _SolidData* > f2sdMap;
6539   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
6540   {
6541     _SolidData& data = _sdVec[i];
6542     TopTools_MapOfShape FFMap;
6543     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
6544     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
6545       if ( s2s->second.ShapeType() == TopAbs_FACE )
6546       {
6547         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
6548
6549         if ( FFMap.Add( (*s2s).second ))
6550           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
6551           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
6552           // by StdMeshers_QuadToTriaAdaptor
6553           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
6554           {
6555             SMESH_ProxyMesh::SubMesh* proxySub =
6556               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
6557             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6558             while ( fIt->more() )
6559               proxySub->AddElement( fIt->next() );
6560             // as a result 3D algo will use elements from proxySub and not from smDS
6561           }
6562       }
6563   }
6564
6565   SMESH_MesherHelper helper( *_mesh );
6566   helper.ToFixNodeParameters( true );
6567
6568   // EDGE's to shrink
6569   map< TGeomID, _Shrinker1D > e2shrMap;
6570   vector< _EdgesOnShape* > subEOS;
6571   vector< _LayerEdge* > lEdges;
6572
6573   // loop on FACES to srink mesh on
6574   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
6575   for ( ; f2sd != f2sdMap.end(); ++f2sd )
6576   {
6577     _SolidData&      data = *f2sd->second;
6578     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
6579     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
6580     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
6581
6582     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
6583
6584     helper.SetSubShape(F);
6585
6586     // ===========================
6587     // Prepare data for shrinking
6588     // ===========================
6589
6590     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
6591     // and thus all nodes on a FACE connected to 2d elements are to be smoothed
6592     vector < const SMDS_MeshNode* > smoothNodes;
6593     {
6594       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
6595       while ( nIt->more() )
6596       {
6597         const SMDS_MeshNode* n = nIt->next();
6598         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
6599           smoothNodes.push_back( n );
6600       }
6601     }
6602     // Find out face orientation
6603     double refSign = 1;
6604     const set<TGeomID> ignoreShapes;
6605     bool isOkUV;
6606     if ( !smoothNodes.empty() )
6607     {
6608       vector<_Simplex> simplices;
6609       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
6610       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
6611       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
6612       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
6613       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
6614         refSign = -1;
6615     }
6616
6617     // Find _LayerEdge's inflated along F
6618     subEOS.clear();
6619     lEdges.clear();
6620     {
6621       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
6622                                                                 /*complexFirst=*/true); //!!!
6623       while ( subIt->more() )
6624       {
6625         const TGeomID subID = subIt->next()->GetId();
6626         if ( data._noShrinkShapes.count( subID ))
6627           continue;
6628         _EdgesOnShape* eos = data.GetShapeEdges( subID );
6629         if ( !eos || eos->_sWOL.IsNull() ) continue;
6630
6631         subEOS.push_back( eos );
6632
6633         for ( size_t i = 0; i < eos->_edges.size(); ++i )
6634         {
6635           lEdges.push_back( eos->_edges[ i ] );
6636           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
6637         }
6638       }
6639     }
6640
6641     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
6642     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6643     while ( fIt->more() )
6644       if ( const SMDS_MeshElement* f = fIt->next() )
6645         dumpChangeNodes( f );
6646     dumpFunctionEnd();
6647
6648     // Replace source nodes by target nodes in mesh faces to shrink
6649     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
6650     const SMDS_MeshNode* nodes[20];
6651     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
6652     {
6653       _EdgesOnShape& eos = * subEOS[ iS ];
6654       for ( size_t i = 0; i < eos._edges.size(); ++i )
6655       {
6656         _LayerEdge& edge = *eos._edges[i];
6657         const SMDS_MeshNode* srcNode = edge._nodes[0];
6658         const SMDS_MeshNode* tgtNode = edge._nodes.back();
6659         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
6660         while ( fIt->more() )
6661         {
6662           const SMDS_MeshElement* f = fIt->next();
6663           if ( !smDS->Contains( f ))
6664             continue;
6665           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
6666           for ( int iN = 0; nIt->more(); ++iN )
6667           {
6668             const SMDS_MeshNode* n = nIt->next();
6669             nodes[iN] = ( n == srcNode ? tgtNode : n );
6670           }
6671           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
6672           dumpChangeNodes( f );
6673         }
6674       }
6675     }
6676     dumpFunctionEnd();
6677
6678     // find out if a FACE is concave
6679     const bool isConcaveFace = isConcave( F, helper );
6680
6681     // Create _SmoothNode's on face F
6682     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
6683     {
6684       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
6685       const bool sortSimplices = isConcaveFace;
6686       for ( size_t i = 0; i < smoothNodes.size(); ++i )
6687       {
6688         const SMDS_MeshNode* n = smoothNodes[i];
6689         nodesToSmooth[ i ]._node = n;
6690         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
6691         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
6692         // fix up incorrect uv of nodes on the FACE
6693         helper.GetNodeUV( F, n, 0, &isOkUV);
6694         dumpMove( n );
6695       }
6696       dumpFunctionEnd();
6697     }
6698     //if ( nodesToSmooth.empty() ) continue;
6699
6700     // Find EDGE's to shrink and set simpices to LayerEdge's
6701     set< _Shrinker1D* > eShri1D;
6702     {
6703       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
6704       {
6705         _EdgesOnShape& eos = * subEOS[ iS ];
6706         if ( eos.SWOLType() == TopAbs_EDGE )
6707         {
6708           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
6709           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
6710           eShri1D.insert( & srinker );
6711           srinker.AddEdge( eos._edges[0], eos, helper );
6712           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
6713           // restore params of nodes on EGDE if the EDGE has been already
6714           // srinked while srinking other FACE
6715           srinker.RestoreParams();
6716         }
6717         for ( size_t i = 0; i < eos._edges.size(); ++i )
6718         {
6719           _LayerEdge& edge = * eos._edges[i];
6720           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
6721         }
6722       }
6723     }
6724
6725     bool toFixTria = false; // to improve quality of trias by diagonal swap
6726     if ( isConcaveFace )
6727     {
6728       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
6729       if ( hasTria != hasQuad ) {
6730         toFixTria = hasTria;
6731       }
6732       else {
6733         set<int> nbNodesSet;
6734         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6735         while ( fIt->more() && nbNodesSet.size() < 2 )
6736           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
6737         toFixTria = ( *nbNodesSet.begin() == 3 );
6738       }
6739     }
6740
6741     // ==================
6742     // Perform shrinking
6743     // ==================
6744
6745     bool shrinked = true;
6746     int badNb, shriStep=0, smooStep=0;
6747     _SmoothNode::SmoothType smoothType
6748       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
6749     while ( shrinked )
6750     {
6751       shriStep++;
6752       // Move boundary nodes (actually just set new UV)
6753       // -----------------------------------------------
6754       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
6755       shrinked = false;
6756       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
6757       {
6758         _EdgesOnShape& eos = * subEOS[ iS ];
6759         for ( size_t i = 0; i < eos._edges.size(); ++i )
6760         {
6761           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
6762         }
6763       }
6764       dumpFunctionEnd();
6765
6766       // Move nodes on EDGE's
6767       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
6768       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
6769       for ( ; shr != eShri1D.end(); ++shr )
6770         (*shr)->Compute( /*set3D=*/false, helper );
6771
6772       // Smoothing in 2D
6773       // -----------------
6774       int nbNoImpSteps = 0;
6775       bool       moved = true;
6776       badNb = 1;
6777       while (( nbNoImpSteps < 5 && badNb > 0) && moved)
6778       {
6779         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6780
6781         int oldBadNb = badNb;
6782         badNb = 0;
6783         moved = false;
6784         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
6785         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
6786         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6787         {
6788           moved |= nodesToSmooth[i].Smooth( badNb, surface, helper, refSign,
6789                                             smooTy, /*set3D=*/isConcaveFace);
6790         }
6791         if ( badNb < oldBadNb )
6792           nbNoImpSteps = 0;
6793         else
6794           nbNoImpSteps++;
6795
6796         dumpFunctionEnd();
6797       }
6798       if ( badNb > 0 )
6799         return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
6800       if ( shriStep > 200 )
6801         return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
6802
6803       // Fix narrow triangles by swapping diagonals
6804       // ---------------------------------------
6805       if ( toFixTria )
6806       {
6807         set<const SMDS_MeshNode*> usedNodes;
6808         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
6809
6810         // update working data
6811         set<const SMDS_MeshNode*>::iterator n;
6812         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
6813         {
6814           n = usedNodes.find( nodesToSmooth[ i ]._node );
6815           if ( n != usedNodes.end())
6816           {
6817             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
6818                                     nodesToSmooth[ i ]._simplices,
6819                                     ignoreShapes, NULL,
6820                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
6821             usedNodes.erase( n );
6822           }
6823         }
6824         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
6825         {
6826           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
6827           if ( n != usedNodes.end())
6828           {
6829             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
6830                                     lEdges[i]->_simplices,
6831                                     ignoreShapes );
6832             usedNodes.erase( n );
6833           }
6834         }
6835       }
6836       // TODO: check effect of this additional smooth
6837       // additional laplacian smooth to increase allowed shrink step
6838       // for ( int st = 1; st; --st )
6839       // {
6840       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6841       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6842       //   {
6843       //     nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6844       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
6845       //   }
6846       // }
6847     } // while ( shrinked )
6848
6849     // No wrongly shaped faces remain; final smooth. Set node XYZ.
6850     bool isStructuredFixed = false;
6851     if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
6852       isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
6853     if ( !isStructuredFixed )
6854     {
6855       if ( isConcaveFace ) // fix narrow faces by swapping diagonals
6856         fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
6857
6858       for ( int st = 3; st; --st )
6859       {
6860         switch( st ) {
6861         case 1: smoothType = _SmoothNode::LAPLACIAN; break;
6862         case 2: smoothType = _SmoothNode::LAPLACIAN; break;
6863         case 3: smoothType = _SmoothNode::ANGULAR; break;
6864         }
6865         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6866         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6867         {
6868           nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6869                                    smoothType,/*set3D=*/st==1 );
6870         }
6871         dumpFunctionEnd();
6872       }
6873     }
6874     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
6875     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
6876
6877     if ( !getMeshDS()->IsEmbeddedMode() )
6878       // Log node movement
6879       for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6880       {
6881         SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
6882         getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
6883       }
6884
6885   } // loop on FACES to srink mesh on
6886
6887
6888   // Replace source nodes by target nodes in shrinked mesh edges
6889
6890   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
6891   for ( ; e2shr != e2shrMap.end(); ++e2shr )
6892     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
6893
6894   return true;
6895 }
6896
6897 //================================================================================
6898 /*!
6899  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
6900  */
6901 //================================================================================
6902
6903 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
6904                                            _EdgesOnShape&         eos,
6905                                            SMESH_MesherHelper&    helper,
6906                                            const SMESHDS_SubMesh* faceSubMesh)
6907 {
6908   const SMDS_MeshNode* srcNode = edge._nodes[0];
6909   const SMDS_MeshNode* tgtNode = edge._nodes.back();
6910
6911   if ( eos.SWOLType() == TopAbs_FACE )
6912   {
6913     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
6914     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
6915     gp_Vec2d uvDir( srcUV, tgtUV );
6916     double uvLen = uvDir.Magnitude();
6917     uvDir /= uvLen;
6918     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
6919     edge._len = uvLen;
6920
6921     edge._pos.resize(1);
6922     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
6923
6924     // set UV of source node to target node
6925     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
6926     pos->SetUParameter( srcUV.X() );
6927     pos->SetVParameter( srcUV.Y() );
6928   }
6929   else // _sWOL is TopAbs_EDGE
6930   {
6931     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
6932     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
6933     if ( !edgeSM || edgeSM->NbElements() == 0 )
6934       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
6935
6936     const SMDS_MeshNode* n2 = 0;
6937     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
6938     while ( eIt->more() && !n2 )
6939     {
6940       const SMDS_MeshElement* e = eIt->next();
6941       if ( !edgeSM->Contains(e)) continue;
6942       n2 = e->GetNode( 0 );
6943       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
6944     }
6945     if ( !n2 )
6946       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
6947
6948     double uSrc = helper.GetNodeU( E, srcNode, n2 );
6949     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
6950     double u2   = helper.GetNodeU( E, n2, srcNode );
6951
6952     edge._pos.clear();
6953
6954     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
6955     {
6956       // tgtNode is located so that it does not make faces with wrong orientation
6957       return true;
6958     }
6959     edge._pos.resize(1);
6960     edge._pos[0].SetCoord( U_TGT, uTgt );
6961     edge._pos[0].SetCoord( U_SRC, uSrc );
6962     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
6963
6964     edge._simplices.resize( 1 );
6965     edge._simplices[0]._nPrev = n2;
6966
6967     // set U of source node to the target node
6968     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
6969     pos->SetUParameter( uSrc );
6970   }
6971   return true;
6972 }
6973
6974 //================================================================================
6975 /*!
6976  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
6977  */
6978 //================================================================================
6979
6980 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
6981 {
6982   if ( edge._nodes.size() == 1 )
6983   {
6984     edge._pos.clear();
6985     edge._len = 0;
6986
6987     const SMDS_MeshNode* srcNode = edge._nodes[0];
6988     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
6989     if ( S.IsNull() ) return;
6990
6991     gp_Pnt p;
6992
6993     switch ( S.ShapeType() )
6994     {
6995     case TopAbs_EDGE:
6996     {
6997       double f,l;
6998       TopLoc_Location loc;
6999       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
7000       if ( curve.IsNull() ) return;
7001       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
7002       p = curve->Value( ePos->GetUParameter() );
7003       break;
7004     }
7005     case TopAbs_VERTEX:
7006     {
7007       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
7008       break;
7009     }
7010     default: return;
7011     }
7012     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
7013     dumpMove( srcNode );
7014   }
7015 }
7016
7017 //================================================================================
7018 /*!
7019  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
7020  */
7021 //================================================================================
7022
7023 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
7024                                   SMESH_MesherHelper&         helper,
7025                                   const bool                  is2D,
7026                                   const int                   step,
7027                                   set<const SMDS_MeshNode*> * involvedNodes)
7028 {
7029   SMESH::Controls::AspectRatio qualifier;
7030   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
7031   const double maxAspectRatio = is2D ? 4. : 2;
7032   _NodeCoordHelper xyz( F, helper, is2D );
7033
7034   // find bad triangles
7035
7036   vector< const SMDS_MeshElement* > badTrias;
7037   vector< double >                  badAspects;
7038   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
7039   SMDS_ElemIteratorPtr fIt = sm->GetElements();
7040   while ( fIt->more() )
7041   {
7042     const SMDS_MeshElement * f = fIt->next();
7043     if ( f->NbCornerNodes() != 3 ) continue;
7044     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
7045     double aspect = qualifier.GetValue( points );
7046     if ( aspect > maxAspectRatio )
7047     {
7048       badTrias.push_back( f );
7049       badAspects.push_back( aspect );
7050     }
7051   }
7052   if ( step == 1 )
7053   {
7054     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
7055     SMDS_ElemIteratorPtr fIt = sm->GetElements();
7056     while ( fIt->more() )
7057     {
7058       const SMDS_MeshElement * f = fIt->next();
7059       if ( f->NbCornerNodes() == 3 )
7060         dumpChangeNodes( f );
7061     }
7062     dumpFunctionEnd();
7063   }
7064   if ( badTrias.empty() )
7065     return;
7066
7067   // find couples of faces to swap diagonal
7068
7069   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
7070   vector< T2Trias > triaCouples; 
7071
7072   TIDSortedElemSet involvedFaces, emptySet;
7073   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
7074   {
7075     T2Trias trias    [3];
7076     double  aspRatio [3];
7077     int i1, i2, i3;
7078
7079     if ( !involvedFaces.insert( badTrias[iTia] ).second )
7080       continue;
7081     for ( int iP = 0; iP < 3; ++iP )
7082       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
7083
7084     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
7085     int bestCouple = -1;
7086     for ( int iSide = 0; iSide < 3; ++iSide )
7087     {
7088       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
7089       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
7090       trias [iSide].first  = badTrias[iTia];
7091       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
7092                                                              & i1, & i2 );
7093       if (( ! trias[iSide].second ) ||
7094           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
7095           ( ! sm->Contains( trias[iSide].second )))
7096         continue;
7097
7098       // aspect ratio of an adjacent tria
7099       for ( int iP = 0; iP < 3; ++iP )
7100         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
7101       double aspectInit = qualifier.GetValue( points2 );
7102
7103       // arrange nodes as after diag-swaping
7104       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
7105         i3 = helper.WrapIndex( i1-1, 3 );
7106       else
7107         i3 = helper.WrapIndex( i1+1, 3 );
7108       points1 = points;
7109       points1( 1+ iSide ) = points2( 1+ i3 );
7110       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
7111
7112       // aspect ratio after diag-swaping
7113       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
7114       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
7115         continue;
7116
7117       // prevent inversion of a triangle
7118       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
7119       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
7120       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
7121         continue;
7122
7123       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
7124         bestCouple = iSide;
7125     }
7126
7127     if ( bestCouple >= 0 )
7128     {
7129       triaCouples.push_back( trias[bestCouple] );
7130       involvedFaces.insert ( trias[bestCouple].second );
7131     }
7132     else
7133     {
7134       involvedFaces.erase( badTrias[iTia] );
7135     }
7136   }
7137   if ( triaCouples.empty() )
7138     return;
7139
7140   // swap diagonals
7141
7142   SMESH_MeshEditor editor( helper.GetMesh() );
7143   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
7144   for ( size_t i = 0; i < triaCouples.size(); ++i )
7145   {
7146     dumpChangeNodes( triaCouples[i].first );
7147     dumpChangeNodes( triaCouples[i].second );
7148     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
7149   }
7150
7151   if ( involvedNodes )
7152     for ( size_t i = 0; i < triaCouples.size(); ++i )
7153     {
7154       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
7155                              triaCouples[i].first->end_nodes() );
7156       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
7157                              triaCouples[i].second->end_nodes() );
7158     }
7159
7160   // just for debug dump resulting triangles
7161   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
7162   for ( size_t i = 0; i < triaCouples.size(); ++i )
7163   {
7164     dumpChangeNodes( triaCouples[i].first );
7165     dumpChangeNodes( triaCouples[i].second );
7166   }
7167 }
7168
7169 //================================================================================
7170 /*!
7171  * \brief Move target node to it's final position on the FACE during shrinking
7172  */
7173 //================================================================================
7174
7175 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
7176                                  const TopoDS_Face&    F,
7177                                  _EdgesOnShape&        eos,
7178                                  SMESH_MesherHelper&   helper )
7179 {
7180   if ( _pos.empty() )
7181     return false; // already at the target position
7182
7183   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
7184
7185   if ( eos.SWOLType() == TopAbs_FACE )
7186   {
7187     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
7188     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
7189     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
7190     const double uvLen = tgtUV.Distance( curUV );
7191     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
7192
7193     // Select shrinking step such that not to make faces with wrong orientation.
7194     double stepSize = 1e100;
7195     for ( size_t i = 0; i < _simplices.size(); ++i )
7196     {
7197       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
7198       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
7199       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
7200       gp_XY dirN = uvN2 - uvN1;
7201       double det = uvDir.Crossed( dirN );
7202       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
7203       gp_XY dirN2Cur = curUV - uvN1;
7204       double step = dirN.Crossed( dirN2Cur ) / det;
7205       if ( step > 0 )
7206         stepSize = Min( step, stepSize );
7207     }
7208     gp_Pnt2d newUV;
7209     if ( uvLen <= stepSize )
7210     {
7211       newUV = tgtUV;
7212       _pos.clear();
7213     }
7214     else if ( stepSize > 0 )
7215     {
7216       newUV = curUV + uvDir.XY() * stepSize * kSafe;
7217     }
7218     else
7219     {
7220       return true;
7221     }
7222     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
7223     pos->SetUParameter( newUV.X() );
7224     pos->SetVParameter( newUV.Y() );
7225
7226 #ifdef __myDEBUG
7227     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
7228     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
7229     dumpMove( tgtNode );
7230 #endif
7231   }
7232   else // _sWOL is TopAbs_EDGE
7233   {
7234     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
7235     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
7236     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
7237
7238     const double u2     = helper.GetNodeU( E, n2, tgtNode );
7239     const double uSrc   = _pos[0].Coord( U_SRC );
7240     const double lenTgt = _pos[0].Coord( LEN_TGT );
7241
7242     double newU = _pos[0].Coord( U_TGT );
7243     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
7244     {
7245       _pos.clear();
7246     }
7247     else
7248     {
7249       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
7250     }
7251     tgtPos->SetUParameter( newU );
7252 #ifdef __myDEBUG
7253     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
7254     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
7255     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
7256     dumpMove( tgtNode );
7257 #endif
7258   }
7259   return true;
7260 }
7261
7262 //================================================================================
7263 /*!
7264  * \brief Perform smooth on the FACE
7265  *  \retval bool - true if the node has been moved
7266  */
7267 //================================================================================
7268
7269 bool _SmoothNode::Smooth(int&                  badNb,
7270                          Handle(Geom_Surface)& surface,
7271                          SMESH_MesherHelper&   helper,
7272                          const double          refSign,
7273                          SmoothType            how,
7274                          bool                  set3D)
7275 {
7276   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
7277
7278   // get uv of surrounding nodes
7279   vector<gp_XY> uv( _simplices.size() );
7280   for ( size_t i = 0; i < _simplices.size(); ++i )
7281     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
7282
7283   // compute new UV for the node
7284   gp_XY newPos (0,0);
7285   if ( how == TFI && _simplices.size() == 4 )
7286   {
7287     gp_XY corners[4];
7288     for ( size_t i = 0; i < _simplices.size(); ++i )
7289       if ( _simplices[i]._nOpp )
7290         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
7291       else
7292         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
7293
7294     newPos = helper.calcTFI ( 0.5, 0.5,
7295                               corners[0], corners[1], corners[2], corners[3],
7296                               uv[1], uv[2], uv[3], uv[0] );
7297   }
7298   else if ( how == ANGULAR )
7299   {
7300     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
7301   }
7302   else if ( how == CENTROIDAL && _simplices.size() > 3 )
7303   {
7304     // average centers of diagonals wieghted with their reciprocal lengths
7305     if ( _simplices.size() == 4 )
7306     {
7307       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
7308       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
7309       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
7310     }
7311     else
7312     {
7313       double sumWeight = 0;
7314       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
7315       for ( int i = 0; i < nb; ++i )
7316       {
7317         int iFrom = i + 2;
7318         int iTo   = i + _simplices.size() - 1;
7319         for ( int j = iFrom; j < iTo; ++j )
7320         {
7321           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
7322           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
7323           sumWeight += w;
7324           newPos += w * ( uv[i]+uv[i2] );
7325         }
7326       }
7327       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
7328     }
7329   }
7330   else
7331   {
7332     // Laplacian smooth
7333     for ( size_t i = 0; i < _simplices.size(); ++i )
7334       newPos += uv[i];
7335     newPos /= _simplices.size();
7336   }
7337
7338   // count quality metrics (orientation) of triangles around the node
7339   int nbOkBefore = 0;
7340   gp_XY tgtUV = helper.GetNodeUV( face, _node );
7341   for ( size_t i = 0; i < _simplices.size(); ++i )
7342     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
7343
7344   int nbOkAfter = 0;
7345   for ( size_t i = 0; i < _simplices.size(); ++i )
7346     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
7347
7348   if ( nbOkAfter < nbOkBefore )
7349   {
7350     badNb += _simplices.size() - nbOkBefore;
7351     return false;
7352   }
7353
7354   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
7355   pos->SetUParameter( newPos.X() );
7356   pos->SetVParameter( newPos.Y() );
7357
7358 #ifdef __myDEBUG
7359   set3D = true;
7360 #endif
7361   if ( set3D )
7362   {
7363     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
7364     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
7365     dumpMove( _node );
7366   }
7367
7368   badNb += _simplices.size() - nbOkAfter;
7369   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
7370 }
7371
7372 //================================================================================
7373 /*!
7374  * \brief Computes new UV using angle based smoothing technic
7375  */
7376 //================================================================================
7377
7378 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
7379                                      const gp_XY&   uvToFix,
7380                                      const double   refSign)
7381 {
7382   uv.push_back( uv.front() );
7383
7384   vector< gp_XY >  edgeDir ( uv.size() );
7385   vector< double > edgeSize( uv.size() );
7386   for ( size_t i = 1; i < edgeDir.size(); ++i )
7387   {
7388     edgeDir [i-1] = uv[i] - uv[i-1];
7389     edgeSize[i-1] = edgeDir[i-1].Modulus();
7390     if ( edgeSize[i-1] < numeric_limits<double>::min() )
7391       edgeDir[i-1].SetX( 100 );
7392     else
7393       edgeDir[i-1] /= edgeSize[i-1] * refSign;
7394   }
7395   edgeDir.back()  = edgeDir.front();
7396   edgeSize.back() = edgeSize.front();
7397
7398   gp_XY  newPos(0,0);
7399   //int    nbEdges = 0;
7400   double sumSize = 0;
7401   for ( size_t i = 1; i < edgeDir.size(); ++i )
7402   {
7403     if ( edgeDir[i-1].X() > 1. ) continue;
7404     int i1 = i-1;
7405     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
7406     if ( i == edgeDir.size() ) break;
7407     gp_XY p = uv[i];
7408     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
7409     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
7410     gp_XY bisec = norm1 + norm2;
7411     double bisecSize = bisec.Modulus();
7412     if ( bisecSize < numeric_limits<double>::min() )
7413     {
7414       bisec = -edgeDir[i1] + edgeDir[i];
7415       bisecSize = bisec.Modulus();
7416     }
7417     bisec /= bisecSize;
7418
7419     gp_XY  dirToN  = uvToFix - p;
7420     double distToN = dirToN.Modulus();
7421     if ( bisec * dirToN < 0 )
7422       distToN = -distToN;
7423
7424     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
7425     //++nbEdges;
7426     sumSize += edgeSize[i1] + edgeSize[i];
7427   }
7428   newPos /= /*nbEdges * */sumSize;
7429   return newPos;
7430 }
7431
7432 //================================================================================
7433 /*!
7434  * \brief Delete _SolidData
7435  */
7436 //================================================================================
7437
7438 _SolidData::~_SolidData()
7439 {
7440   TNode2Edge::iterator n2e = _n2eMap.begin();
7441   for ( ; n2e != _n2eMap.end(); ++n2e )
7442   {
7443     _LayerEdge* & e = n2e->second;
7444     if ( e && e->_2neibors )
7445       delete e->_2neibors;
7446     delete e;
7447     e = NULL;
7448   }
7449   _n2eMap.clear();
7450 }
7451 //================================================================================
7452 /*!
7453  * \brief Keep a _LayerEdge inflated along the EDGE
7454  */
7455 //================================================================================
7456
7457 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
7458                            _EdgesOnShape&      eos,
7459                            SMESH_MesherHelper& helper )
7460 {
7461   // init
7462   if ( _nodes.empty() )
7463   {
7464     _edges[0] = _edges[1] = 0;
7465     _done = false;
7466   }
7467   // check _LayerEdge
7468   if ( e == _edges[0] || e == _edges[1] )
7469     return;
7470   if ( eos.SWOLType() != TopAbs_EDGE )
7471     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
7472   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
7473     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
7474
7475   // store _LayerEdge
7476   _geomEdge = TopoDS::Edge( eos._sWOL );
7477   double f,l;
7478   BRep_Tool::Range( _geomEdge, f,l );
7479   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
7480   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
7481
7482   // Update _nodes
7483
7484   const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
7485   const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
7486
7487   if ( _nodes.empty() )
7488   {
7489     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
7490     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
7491       return;
7492     TopLoc_Location loc;
7493     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
7494     GeomAdaptor_Curve aCurve(C, f,l);
7495     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
7496
7497     int nbExpectNodes = eSubMesh->NbNodes();
7498     _initU  .reserve( nbExpectNodes );
7499     _normPar.reserve( nbExpectNodes );
7500     _nodes  .reserve( nbExpectNodes );
7501     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
7502     while ( nIt->more() )
7503     {
7504       const SMDS_MeshNode* node = nIt->next();
7505       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
7506            node == tgtNode0 || node == tgtNode1 )
7507         continue; // refinement nodes
7508       _nodes.push_back( node );
7509       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
7510       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
7511       _normPar.push_back(  len / totLen );
7512     }
7513   }
7514   else
7515   {
7516     // remove target node of the _LayerEdge from _nodes
7517     int nbFound = 0;
7518     for ( size_t i = 0; i < _nodes.size(); ++i )
7519       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
7520         _nodes[i] = 0, nbFound++;
7521     if ( nbFound == _nodes.size() )
7522       _nodes.clear();
7523   }
7524 }
7525
7526 //================================================================================
7527 /*!
7528  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
7529  */
7530 //================================================================================
7531
7532 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
7533 {
7534   if ( _done || _nodes.empty())
7535     return;
7536   const _LayerEdge* e = _edges[0];
7537   if ( !e ) e = _edges[1];
7538   if ( !e ) return;
7539
7540   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
7541             ( !_edges[1] || _edges[1]->_pos.empty() ));
7542
7543   double f,l;
7544   if ( set3D || _done )
7545   {
7546     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
7547     GeomAdaptor_Curve aCurve(C, f,l);
7548
7549     if ( _edges[0] )
7550       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
7551     if ( _edges[1] )
7552       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
7553     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
7554
7555     for ( size_t i = 0; i < _nodes.size(); ++i )
7556     {
7557       if ( !_nodes[i] ) continue;
7558       double len = totLen * _normPar[i];
7559       GCPnts_AbscissaPoint discret( aCurve, len, f );
7560       if ( !discret.IsDone() )
7561         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
7562       double u = discret.Parameter();
7563       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7564       pos->SetUParameter( u );
7565       gp_Pnt p = C->Value( u );
7566       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
7567     }
7568   }
7569   else
7570   {
7571     BRep_Tool::Range( _geomEdge, f,l );
7572     if ( _edges[0] )
7573       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
7574     if ( _edges[1] )
7575       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
7576     
7577     for ( size_t i = 0; i < _nodes.size(); ++i )
7578     {
7579       if ( !_nodes[i] ) continue;
7580       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
7581       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7582       pos->SetUParameter( u );
7583     }
7584   }
7585 }
7586
7587 //================================================================================
7588 /*!
7589  * \brief Restore initial parameters of nodes on EDGE
7590  */
7591 //================================================================================
7592
7593 void _Shrinker1D::RestoreParams()
7594 {
7595   if ( _done )
7596     for ( size_t i = 0; i < _nodes.size(); ++i )
7597     {
7598       if ( !_nodes[i] ) continue;
7599       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7600       pos->SetUParameter( _initU[i] );
7601     }
7602   _done = false;
7603 }
7604
7605 //================================================================================
7606 /*!
7607  * \brief Replace source nodes by target nodes in shrinked mesh edges
7608  */
7609 //================================================================================
7610
7611 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
7612 {
7613   const SMDS_MeshNode* nodes[3];
7614   for ( int i = 0; i < 2; ++i )
7615   {
7616     if ( !_edges[i] ) continue;
7617
7618     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
7619     if ( !eSubMesh ) return;
7620     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
7621     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
7622     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
7623     while ( eIt->more() )
7624     {
7625       const SMDS_MeshElement* e = eIt->next();
7626       if ( !eSubMesh->Contains( e ))
7627           continue;
7628       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
7629       for ( int iN = 0; iN < e->NbNodes(); ++iN )
7630       {
7631         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
7632         nodes[iN] = ( n == srcNode ? tgtNode : n );
7633       }
7634       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
7635     }
7636   }
7637 }
7638
7639 //================================================================================
7640 /*!
7641  * \brief Creates 2D and 1D elements on boundaries of new prisms
7642  */
7643 //================================================================================
7644
7645 bool _ViscousBuilder::addBoundaryElements()
7646 {
7647   SMESH_MesherHelper helper( *_mesh );
7648
7649   vector< const SMDS_MeshNode* > faceNodes;
7650
7651   for ( size_t i = 0; i < _sdVec.size(); ++i )
7652   {
7653     _SolidData& data = _sdVec[i];
7654     TopTools_IndexedMapOfShape geomEdges;
7655     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
7656     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
7657     {
7658       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
7659       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
7660         continue;
7661
7662       // Get _LayerEdge's based on E
7663
7664       map< double, const SMDS_MeshNode* > u2nodes;
7665       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
7666         continue;
7667
7668       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
7669       TNode2Edge & n2eMap = data._n2eMap;
7670       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
7671       {
7672         //check if 2D elements are needed on E
7673         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
7674         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
7675         ledges.push_back( n2e->second );
7676         u2n++;
7677         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
7678           continue; // no layers on E
7679         ledges.push_back( n2eMap[ u2n->second ]);
7680
7681         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
7682         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
7683         int nbSharedPyram = 0;
7684         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
7685         while ( vIt->more() )
7686         {
7687           const SMDS_MeshElement* v = vIt->next();
7688           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
7689         }
7690         if ( nbSharedPyram > 1 )
7691           continue; // not free border of the pyramid
7692
7693         faceNodes.clear();
7694         faceNodes.push_back( ledges[0]->_nodes[0] );
7695         faceNodes.push_back( ledges[1]->_nodes[0] );
7696         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
7697         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
7698
7699         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
7700           continue; // faces already created
7701       }
7702       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
7703         ledges.push_back( n2eMap[ u2n->second ]);
7704
7705       // Find out orientation and type of face to create
7706
7707       bool reverse = false, isOnFace;
7708       
7709       map< TGeomID, TopoDS_Shape >::iterator e2f =
7710         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
7711       TopoDS_Shape F;
7712       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
7713       {
7714         F = e2f->second.Oriented( TopAbs_FORWARD );
7715         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
7716         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
7717           reverse = !reverse, F.Reverse();
7718         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
7719           reverse = !reverse;
7720       }
7721       else
7722       {
7723         // find FACE with layers sharing E
7724         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
7725         while ( fIt->more() && F.IsNull() )
7726         {
7727           const TopoDS_Shape* pF = fIt->next();
7728           if ( helper.IsSubShape( *pF, data._solid) &&
7729                !data._ignoreFaceIds.count( e2f->first ))
7730             F = *pF;
7731         }
7732       }
7733       // Find the sub-mesh to add new faces
7734       SMESHDS_SubMesh* sm = 0;
7735       if ( isOnFace )
7736         sm = getMeshDS()->MeshElements( F );
7737       else
7738         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
7739       if ( !sm )
7740         return error("error in addBoundaryElements()", data._index);
7741
7742       // Make faces
7743       const int dj1 = reverse ? 0 : 1;
7744       const int dj2 = reverse ? 1 : 0;
7745       for ( size_t j = 1; j < ledges.size(); ++j )
7746       {
7747         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
7748         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
7749         if ( nn1.size() == nn2.size() )
7750         {
7751           if ( isOnFace )
7752             for ( size_t z = 1; z < nn1.size(); ++z )
7753               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
7754           else
7755             for ( size_t z = 1; z < nn1.size(); ++z )
7756               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
7757         }
7758         else if ( nn1.size() == 1 )
7759         {
7760           if ( isOnFace )
7761             for ( size_t z = 1; z < nn2.size(); ++z )
7762               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
7763           else
7764             for ( size_t z = 1; z < nn2.size(); ++z )
7765               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
7766         }
7767         else
7768         {
7769           if ( isOnFace )
7770             for ( size_t z = 1; z < nn1.size(); ++z )
7771               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
7772           else
7773             for ( size_t z = 1; z < nn1.size(); ++z )
7774               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
7775         }
7776       }
7777
7778       // Make edges
7779       for ( int isFirst = 0; isFirst < 2; ++isFirst )
7780       {
7781         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
7782         _EdgesOnShape* eos = data.GetShapeEdges( edge );
7783         if ( eos && eos->SWOLType() == TopAbs_EDGE )
7784         {
7785           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
7786           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
7787             continue;
7788           helper.SetSubShape( eos->_sWOL );
7789           helper.SetElementsOnShape( true );
7790           for ( size_t z = 1; z < nn.size(); ++z )
7791             helper.AddEdge( nn[z-1], nn[z] );
7792         }
7793       }
7794
7795     } // loop on EDGE's
7796   } // loop on _SolidData's
7797
7798   return true;
7799 }