Salome HOME
b2f6855b01c065ec0245b23b6a550c94e1552f25
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2014  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 <BRepAdaptor_Curve2d.hxx>
48 #include <BRepAdaptor_Surface.hxx>
49 #include <BRepLProp_SLProps.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B2d.hxx>
52 #include <Bnd_B3d.hxx>
53 #include <ElCLib.hxx>
54 #include <GCPnts_AbscissaPoint.hxx>
55 #include <Geom2d_Circle.hxx>
56 #include <Geom2d_Line.hxx>
57 #include <Geom2d_TrimmedCurve.hxx>
58 #include <GeomAdaptor_Curve.hxx>
59 #include <GeomLib.hxx>
60 #include <Geom_Circle.hxx>
61 #include <Geom_Curve.hxx>
62 #include <Geom_Line.hxx>
63 #include <Geom_TrimmedCurve.hxx>
64 #include <Precision.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_Failure.hxx>
67 #include <TColStd_Array1OfReal.hxx>
68 #include <TopExp.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopTools_IndexedMapOfShape.hxx>
71 #include <TopTools_ListOfShape.hxx>
72 #include <TopTools_MapOfShape.hxx>
73 #include <TopoDS.hxx>
74 #include <TopoDS_Edge.hxx>
75 #include <TopoDS_Face.hxx>
76 #include <TopoDS_Vertex.hxx>
77 #include <gp_Ax1.hxx>
78 #include <gp_Vec.hxx>
79 #include <gp_XY.hxx>
80
81 #include <list>
82 #include <string>
83 #include <cmath>
84 #include <limits>
85
86 //#define __myDEBUG
87
88 using namespace std;
89
90 //================================================================================
91 namespace VISCOUS_3D
92 {
93   typedef int TGeomID;
94
95   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
96
97   /*!
98    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
99    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
100    */
101   struct _MeshOfSolid : public SMESH_ProxyMesh,
102                         public SMESH_subMeshEventListenerData
103   {
104     bool _n2nMapComputed;
105
106     _MeshOfSolid( SMESH_Mesh* mesh)
107       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
108     {
109       SMESH_ProxyMesh::setMesh( *mesh );
110     }
111
112     // returns submesh for a geom face
113     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
114     {
115       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
116       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
117     }
118     void setNode2Node(const SMDS_MeshNode*                 srcNode,
119                       const SMDS_MeshNode*                 proxyNode,
120                       const SMESH_ProxyMesh::SubMesh* subMesh)
121     {
122       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
123     }
124   };
125   //--------------------------------------------------------------------------------
126   /*!
127    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
128    * It is used to clear an inferior dim sub-meshes modified by viscous layers
129    */
130   class _ShrinkShapeListener : SMESH_subMeshEventListener
131   {
132     _ShrinkShapeListener()
133       : SMESH_subMeshEventListener(/*isDeletable=*/false,
134                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
135   public:
136     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
137     virtual void ProcessEvent(const int                       event,
138                               const int                       eventType,
139                               SMESH_subMesh*                  solidSM,
140                               SMESH_subMeshEventListenerData* data,
141                               const SMESH_Hypothesis*         hyp)
142     {
143       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
144       {
145         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
146       }
147     }
148   };
149   //--------------------------------------------------------------------------------
150   /*!
151    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
152    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
153    * delete the data as soon as it has been used
154    */
155   class _ViscousListener : SMESH_subMeshEventListener
156   {
157     _ViscousListener():
158       SMESH_subMeshEventListener(/*isDeletable=*/false,
159                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
160     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
161   public:
162     virtual void ProcessEvent(const int                       event,
163                               const int                       eventType,
164                               SMESH_subMesh*                  subMesh,
165                               SMESH_subMeshEventListenerData* data,
166                               const SMESH_Hypothesis*         hyp)
167     {
168       if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
169       {
170         // delete SMESH_ProxyMesh containing temporary faces
171         subMesh->DeleteEventListener( this );
172       }
173     }
174     // Finds or creates proxy mesh of the solid
175     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
176                                       const TopoDS_Shape& solid,
177                                       bool                toCreate=false)
178     {
179       if ( !mesh ) return 0;
180       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
181       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
182       if ( !data && toCreate )
183       {
184         data = new _MeshOfSolid(mesh);
185         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
186         sm->SetEventListener( Get(), data, sm );
187       }
188       return data;
189     }
190     // Removes proxy mesh of the solid
191     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
192     {
193       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
194     }
195   };
196   
197   //================================================================================
198   /*!
199    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
200    * the main shape when sub-mesh of the main shape is cleared,
201    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
202    * is cleared
203    */
204   //================================================================================
205
206   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
207   {
208     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
209     SMESH_subMeshEventListenerData* data =
210       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
211     if ( data )
212     {
213       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
214            data->mySubMeshes.end())
215         data->mySubMeshes.push_back( sub );
216     }
217     else
218     {
219       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
220       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
221     }
222   }
223   //--------------------------------------------------------------------------------
224   /*!
225    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
226    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
227    * The class is used to check validity of face or volumes around a smoothed node;
228    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
229    */
230   struct _Simplex
231   {
232     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
233     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
234     _Simplex(const SMDS_MeshNode* nPrev=0,
235              const SMDS_MeshNode* nNext=0,
236              const SMDS_MeshNode* nOpp=0)
237       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
238     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
239     {
240       const double M[3][3] =
241         {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
242          { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
243          { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
244       double determinant = ( + M[0][0]*M[1][1]*M[2][2]
245                              + M[0][1]*M[1][2]*M[2][0]
246                              + M[0][2]*M[1][0]*M[2][1]
247                              - M[0][0]*M[1][2]*M[2][1]
248                              - M[0][1]*M[1][0]*M[2][2]
249                              - M[0][2]*M[1][1]*M[2][0]);
250       return determinant > 1e-100;
251     }
252     bool IsForward(const gp_XY&         tgtUV,
253                    const SMDS_MeshNode* smoothedNode,
254                    const TopoDS_Face&   face,
255                    SMESH_MesherHelper&  helper,
256                    const double         refSign) const
257     {
258       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
259       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
260       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
261       double d = v1 ^ v2;
262       return d*refSign > 1e-100;
263     }
264     bool IsNeighbour(const _Simplex& other) const
265     {
266       return _nPrev == other._nNext || _nNext == other._nPrev;
267     }
268   };
269   //--------------------------------------------------------------------------------
270   /*!
271    * Structure used to take into account surface curvature while smoothing
272    */
273   struct _Curvature
274   {
275     double _r; // radius
276     double _k; // factor to correct node smoothed position
277     double _h2lenRatio; // avgNormProj / (2*avgDist)
278   public:
279     static _Curvature* New( double avgNormProj, double avgDist )
280     {
281       _Curvature* c = 0;
282       if ( fabs( avgNormProj / avgDist ) > 1./200 )
283       {
284         c = new _Curvature;
285         c->_r = avgDist * avgDist / avgNormProj;
286         c->_k = avgDist * avgDist / c->_r / c->_r;
287         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
288         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
289       }
290       return c;
291     }
292     double lenDelta(double len) const { return _k * ( _r + len ); }
293     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
294   };
295   struct _LayerEdge;
296   //--------------------------------------------------------------------------------
297   /*!
298    * Structure used to smooth a _LayerEdge (master) based on an EDGE.
299    */
300   struct _2NearEdges
301   {
302     // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
303     const SMDS_MeshNode* _nodes[2];
304     // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
305     //gp_XYZ               _vec[2];
306     double               _wgt[2]; // weights of _nodes
307     _LayerEdge*          _edges[2];
308
309      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
310     gp_XYZ*              _plnNorm;
311
312     _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
313     void reverse() {
314       std::swap( _nodes[0], _nodes[1] );
315       std::swap( _wgt[0], _wgt[1] );
316     }
317   };
318   //--------------------------------------------------------------------------------
319   /*!
320    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
321    * and a node of the most internal layer (_nodes.back())
322    */
323   struct _LayerEdge
324   {
325     vector< const SMDS_MeshNode*> _nodes;
326
327     gp_XYZ              _normal; // to solid surface
328     vector<gp_XYZ>      _pos; // points computed during inflation
329     double              _len; // length achived with the last inflation step
330     double              _cosin; // of angle (_normal ^ surface)
331     double              _lenFactor; // to compute _len taking _cosin into account
332
333     // face or edge w/o layer along or near which _LayerEdge is inflated
334     TopoDS_Shape        _sWOL;
335     // simplices connected to the source node (_nodes[0]);
336     // used for smoothing and quality check of _LayerEdge's based on the FACE
337     vector<_Simplex>    _simplices;
338     // data for smoothing of _LayerEdge's based on the EDGE
339     _2NearEdges*        _2neibors;
340
341     _Curvature*         _curvature;
342     // TODO:: detele _Curvature, _plnNorm
343
344     void SetNewLength( double len, SMESH_MesherHelper& helper );
345     bool SetNewLength2d( Handle(Geom_Surface)& surface,
346                          const TopoDS_Face&    F,
347                          SMESH_MesherHelper&   helper );
348     void SetDataByNeighbors( const SMDS_MeshNode* n1,
349                              const SMDS_MeshNode* n2,
350                              SMESH_MesherHelper&  helper);
351     void InvalidateStep( int curStep );
352     bool Smooth(int& badNb);
353     bool SmoothOnEdge(Handle(Geom_Surface)& surface,
354                       const TopoDS_Face&    F,
355                       SMESH_MesherHelper&   helper);
356     bool FindIntersection( SMESH_ElementSearcher&   searcher,
357                            double &                 distance,
358                            const double&            epsilon,
359                            const SMDS_MeshElement** face = 0);
360     bool SegTriaInter( const gp_Ax1&        lastSegment,
361                        const SMDS_MeshNode* n0,
362                        const SMDS_MeshNode* n1,
363                        const SMDS_MeshNode* n2,
364                        double&              dist,
365                        const double&        epsilon) const;
366     gp_Ax1 LastSegment(double& segLen) const;
367     bool IsOnEdge() const { return _2neibors; }
368     gp_XYZ Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
369     void SetCosin( double cosin );
370   };
371   struct _LayerEdgeCmp
372   {
373     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
374     {
375       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
376       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
377     }
378   };
379   //--------------------------------------------------------------------------------
380
381   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
382   
383   //--------------------------------------------------------------------------------
384   /*!
385    * \brief Data of a SOLID
386    */
387   struct _SolidData
388   {
389     TopoDS_Shape                    _solid;
390     const StdMeshers_ViscousLayers* _hyp;
391     TopoDS_Shape                    _hypShape;
392     _MeshOfSolid*                   _proxyMesh;
393     set<TGeomID>                    _reversedFaceIds;
394     set<TGeomID>                    _ignoreFaceIds;
395
396     double                          _stepSize, _stepSizeCoeff;
397     const SMDS_MeshNode*            _stepSizeNodes[2];
398
399     TNode2Edge                      _n2eMap;
400     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
401     map< TGeomID, TNode2Edge* >     _s2neMap;
402     // edges of _n2eMap. We keep same data in two containers because
403     // iteration over the map is 5 time longer than over the vector
404     vector< _LayerEdge* >           _edges;
405     // edges on EDGE's with null _sWOL, whose _simplices are used to stop inflation
406     vector< _LayerEdge* >           _simplexTestEdges;
407
408     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
409     //        layers and a FACE w/o layers
410     // value: the shape (FACE or EDGE) to shrink mesh on.
411     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
412     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
413
414     // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
415     set< TGeomID >                   _noShrinkFaces;
416
417     // <EDGE to smooth on> to <it's curve>
418     map< TGeomID,Handle(Geom_Curve)> _edge2curve;
419
420     // end indices in _edges of _LayerEdge on one shape to smooth
421     vector< int >                    _endEdgeToSmooth;
422
423     double                           _epsilon; // precision for SegTriaInter()
424
425     int                              _index; // for debug
426
427     _SolidData(const TopoDS_Shape&             s=TopoDS_Shape(),
428                const StdMeshers_ViscousLayers* h=0,
429                const TopoDS_Shape&             hs=TopoDS_Shape(),
430                _MeshOfSolid*                   m=0)
431       :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
432     ~_SolidData();
433
434     Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&    E,
435                                        const int             iFrom,
436                                        const int             iTo,
437                                        Handle(Geom_Surface)& surface,
438                                        const TopoDS_Face&    F,
439                                        SMESH_MesherHelper&   helper);
440   };
441   //--------------------------------------------------------------------------------
442   /*!
443    * \brief Data of node on a shrinked FACE
444    */
445   struct _SmoothNode
446   {
447     const SMDS_MeshNode*         _node;
448     //vector<const SMDS_MeshNode*> _nodesAround;
449     vector<_Simplex>             _simplices; // for quality check
450
451     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
452
453     bool Smooth(int&                  badNb,
454                 Handle(Geom_Surface)& surface,
455                 SMESH_MesherHelper&   helper,
456                 const double          refSign,
457                 SmoothType            how,
458                 bool                  set3D);
459
460     gp_XY computeAngularPos(vector<gp_XY>& uv,
461                             const gp_XY&   uvToFix,
462                             const double   refSign );
463   };
464   //--------------------------------------------------------------------------------
465   /*!
466    * \brief Builder of viscous layers
467    */
468   class _ViscousBuilder
469   {
470   public:
471     _ViscousBuilder();
472     // does it's job
473     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
474                                   const TopoDS_Shape& shape);
475
476     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
477     void RestoreListeners();
478
479     // computes SMESH_ProxyMesh::SubMesh::_n2n;
480     bool MakeN2NMap( _MeshOfSolid* pm );
481
482   private:
483
484     bool findSolidsWithLayers();
485     bool findFacesWithLayers();
486     bool makeLayer(_SolidData& data);
487     bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
488                      SMESH_MesherHelper& helper, _SolidData& data);
489     gp_XYZ getWeigthedNormal( const SMDS_MeshNode*         n,
490                               std::pair< TGeomID, gp_XYZ > fId2Normal[],
491                               const int                    nbFaces );
492     bool findNeiborsOnEdge(const _LayerEdge*     edge,
493                            const SMDS_MeshNode*& n1,
494                            const SMDS_MeshNode*& n2,
495                            _SolidData&           data);
496     void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
497                        const set<TGeomID>& ingnoreShapes,
498                        const _SolidData*   dataToCheckOri = 0,
499                        const bool          toSort = false);
500     void findSimplexTestEdges( _SolidData&                    data,
501                                vector< vector<_LayerEdge*> >& edgesByGeom);
502     bool sortEdges( _SolidData&                    data,
503                     vector< vector<_LayerEdge*> >& edgesByGeom);
504     void limitStepSize( _SolidData&             data,
505                         const SMDS_MeshElement* face,
506                         const double            cosin);
507     void limitStepSize( _SolidData& data, const double minSize);
508     bool inflate(_SolidData& data);
509     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
510     bool smoothAnalyticEdge( _SolidData&           data,
511                              const int             iFrom,
512                              const int             iTo,
513                              Handle(Geom_Surface)& surface,
514                              const TopoDS_Face&    F,
515                              SMESH_MesherHelper&   helper);
516     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
517     bool refine(_SolidData& data);
518     bool shrink();
519     bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
520                               SMESH_MesherHelper& helper,
521                               const SMESHDS_SubMesh* faceSubMesh );
522     void fixBadFaces(const TopoDS_Face&          F,
523                      SMESH_MesherHelper&         helper,
524                      const bool                  is2D,
525                      const int                   step,
526                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
527     bool addBoundaryElements();
528
529     bool error( const string& text, int solidID=-1 );
530     SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
531
532     // debug
533     void makeGroupOfLE();
534
535     SMESH_Mesh*           _mesh;
536     SMESH_ComputeErrorPtr _error;
537
538     vector< _SolidData >  _sdVec;
539     int                   _tmpFaceID;
540   };
541   //--------------------------------------------------------------------------------
542   /*!
543    * \brief Shrinker of nodes on the EDGE
544    */
545   class _Shrinker1D
546   {
547     vector<double>                _initU;
548     vector<double>                _normPar;
549     vector<const SMDS_MeshNode*>  _nodes;
550     const _LayerEdge*             _edges[2];
551     bool                          _done;
552   public:
553     void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
554     void Compute(bool set3D, SMESH_MesherHelper& helper);
555     void RestoreParams();
556     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
557   };
558   //--------------------------------------------------------------------------------
559   /*!
560    * \brief Class of temporary mesh face.
561    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
562    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
563    */
564   struct TmpMeshFace : public SMDS_MeshElement
565   {
566     vector<const SMDS_MeshNode* > _nn;
567     TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
568       SMDS_MeshElement(id), _nn(nodes) {}
569     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
570     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
571     virtual vtkIdType GetVtkType() const                      { return -1; }
572     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
573     virtual SMDSAbs_GeometryType GetGeomType() const          { return SMDSGeom_TRIANGLE; }
574     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
575     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
576   };
577   //--------------------------------------------------------------------------------
578   /*!
579    * \brief Class of temporary mesh face storing _LayerEdge it's based on
580    */
581   struct TmpMeshFaceOnEdge : public TmpMeshFace
582   {
583     _LayerEdge *_le1, *_le2;
584     TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
585       TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
586     {
587       _nn[0]=_le1->_nodes[0];
588       _nn[1]=_le1->_nodes.back();
589       _nn[2]=_le2->_nodes.back();
590       _nn[3]=_le2->_nodes[0];
591     }
592   };
593   //--------------------------------------------------------------------------------
594   /*!
595    * \brief Retriever of node coordinates either directly of from a surface by node UV.
596    * \warning Location of a surface is ignored
597    */
598   struct NodeCoordHelper
599   {
600     SMESH_MesherHelper&        _helper;
601     const TopoDS_Face&         _face;
602     Handle(Geom_Surface)       _surface;
603     gp_XYZ (NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
604
605     NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
606       : _helper( helper ), _face( F )
607     {
608       if ( is2D )
609       {
610         TopLoc_Location loc;
611         _surface = BRep_Tool::Surface( _face, loc );
612       }
613       if ( _surface.IsNull() )
614         _fun = & NodeCoordHelper::direct;
615       else
616         _fun = & NodeCoordHelper::byUV;
617     }
618     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
619
620   private:
621     gp_XYZ direct(const SMDS_MeshNode* n) const
622     {
623       return SMESH_TNodeXYZ( n );
624     }
625     gp_XYZ byUV  (const SMDS_MeshNode* n) const
626     {
627       gp_XY uv = _helper.GetNodeUV( _face, n );
628       return _surface->Value( uv.X(), uv.Y() ).XYZ();
629     }
630   };
631 } // namespace VISCOUS_3D
632
633 //================================================================================
634 // StdMeshers_ViscousLayers hypothesis
635 //
636 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
637   :SMESH_Hypothesis(hypId, studyId, gen),
638    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
639 {
640   _name = StdMeshers_ViscousLayers::GetHypType();
641   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
642 } // --------------------------------------------------------------------------------
643 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
644 {
645   if ( faceIds != _shapeIds )
646     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
647   if ( _isToIgnoreShapes != toIgnore )
648     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
649 } // --------------------------------------------------------------------------------
650 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
651 {
652   if ( thickness != _thickness )
653     _thickness = thickness, NotifySubMeshesHypothesisModification();
654 } // --------------------------------------------------------------------------------
655 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
656 {
657   if ( _nbLayers != nb )
658     _nbLayers = nb, NotifySubMeshesHypothesisModification();
659 } // --------------------------------------------------------------------------------
660 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
661 {
662   if ( _stretchFactor != factor )
663     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
664 } // --------------------------------------------------------------------------------
665 SMESH_ProxyMesh::Ptr
666 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
667                                   const TopoDS_Shape& theShape,
668                                   const bool          toMakeN2NMap) const
669 {
670   using namespace VISCOUS_3D;
671   _ViscousBuilder bulder;
672   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
673   if ( err && !err->IsOK() )
674     return SMESH_ProxyMesh::Ptr();
675
676   vector<SMESH_ProxyMesh::Ptr> components;
677   TopExp_Explorer exp( theShape, TopAbs_SOLID );
678   for ( ; exp.More(); exp.Next() )
679   {
680     if ( _MeshOfSolid* pm =
681          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
682     {
683       if ( toMakeN2NMap && !pm->_n2nMapComputed )
684         if ( !bulder.MakeN2NMap( pm ))
685           return SMESH_ProxyMesh::Ptr();
686       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
687       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
688     }
689     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
690   }
691   switch ( components.size() )
692   {
693   case 0: break;
694
695   case 1: return components[0];
696
697   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
698   }
699   return SMESH_ProxyMesh::Ptr();
700 } // --------------------------------------------------------------------------------
701 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
702 {
703   save << " " << _nbLayers
704        << " " << _thickness
705        << " " << _stretchFactor
706        << " " << _shapeIds.size();
707   for ( size_t i = 0; i < _shapeIds.size(); ++i )
708     save << " " << _shapeIds[i];
709   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
710   return save;
711 } // --------------------------------------------------------------------------------
712 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
713 {
714   int nbFaces, faceID, shapeToTreat;
715   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
716   while ( _shapeIds.size() < nbFaces && load >> faceID )
717     _shapeIds.push_back( faceID );
718   if ( load >> shapeToTreat )
719     _isToIgnoreShapes = !shapeToTreat;
720   else
721     _isToIgnoreShapes = true; // old behavior
722   return load;
723 } // --------------------------------------------------------------------------------
724 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
725                                                    const TopoDS_Shape& theShape)
726 {
727   // TODO
728   return false;
729 }
730 // END StdMeshers_ViscousLayers hypothesis
731 //================================================================================
732
733 namespace
734 {
735   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
736   {
737     gp_Vec dir;
738     double f,l;
739     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
740     gp_Pnt p = BRep_Tool::Pnt( fromV );
741     double distF = p.SquareDistance( c->Value( f ));
742     double distL = p.SquareDistance( c->Value( l ));
743     c->D1(( distF < distL ? f : l), p, dir );
744     if ( distL < distF ) dir.Reverse();
745     return dir.XYZ();
746   }
747   //--------------------------------------------------------------------------------
748   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
749                      SMESH_MesherHelper& helper)
750   {
751     gp_Vec dir;
752     double f,l; gp_Pnt p;
753     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
754     double u = helper.GetNodeU( E, atNode );
755     c->D1( u, p, dir );
756     return dir.XYZ();
757   }
758   //--------------------------------------------------------------------------------
759   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
760                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
761   {
762     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
763     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
764     gp_Pnt p; gp_Vec du, dv, norm;
765     surface->D1( uv.X(),uv.Y(), p, du,dv );
766     norm = du ^ dv;
767
768     double f,l;
769     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
770     double u = helper.GetNodeU( fromE, node, 0, &ok );
771     c->D1( u, p, du );
772     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
773     if ( o == TopAbs_REVERSED )
774       du.Reverse();
775
776     gp_Vec dir = norm ^ du;
777
778     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
779          helper.IsClosedEdge( fromE ))
780     {
781       if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
782       else                         c->D1( f, p, dv );
783       if ( o == TopAbs_REVERSED )
784         dv.Reverse();
785       gp_Vec dir2 = norm ^ dv;
786       dir = dir.Normalized() + dir2.Normalized();
787     }
788     return dir.XYZ();
789   }
790   //--------------------------------------------------------------------------------
791   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
792                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
793                      bool& ok, double* cosin=0)
794   {
795     double f,l; TopLoc_Location loc;
796     vector< TopoDS_Edge > edges; // sharing a vertex
797     PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
798     while ( eIt->more())
799     {
800       const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
801       if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
802         edges.push_back( *e );
803     }
804     gp_XYZ dir(0,0,0);
805     if ( !( ok = ( edges.size() > 0 ))) return dir;
806     // get average dir of edges going fromV
807     gp_XYZ edgeDir;
808     //if ( edges.size() > 1 )
809     for ( size_t i = 0; i < edges.size(); ++i )
810     {
811       edgeDir = getEdgeDir( edges[i], fromV );
812       double size2 = edgeDir.SquareModulus();
813       if ( size2 > numeric_limits<double>::min() )
814         edgeDir /= sqrt( size2 );
815       else
816         ok = false;
817       dir += edgeDir;
818     }
819     gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
820     try {
821       if ( edges.size() == 1 )
822         dir = fromEdgeDir;
823       else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
824         dir = fromEdgeDir.Normalized() + getFaceDir( F, edges[1], node, helper, ok ).Normalized();
825       else if ( dir * fromEdgeDir < 0 )
826         dir *= -1;
827     }
828     catch ( Standard_Failure )
829     {
830       ok = false;
831     }
832     if ( ok )
833     {
834       //dir /= edges.size();
835       if ( cosin ) {
836         double angle = gp_Vec( edgeDir ).Angle( dir );
837         *cosin = cos( angle );
838       }
839     }
840     return dir;
841   }
842   //================================================================================
843   /*!
844    * \brief Returns true if a FACE is bound by a concave EDGE
845    */
846   //================================================================================
847
848   bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
849   {
850     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
851     //   return true;
852     gp_Vec2d drv1, drv2;
853     gp_Pnt2d p;
854     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
855     for ( ; eExp.More(); eExp.Next() )
856     {
857       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
858       if ( SMESH_Algo::isDegenerated( E )) continue;
859       // check if 2D curve is concave
860       BRepAdaptor_Curve2d curve( E, F );
861       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
862       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
863       curve.Intervals( intervals, GeomAbs_C2 );
864       bool isConvex = true;
865       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
866       {
867         double u1 = intervals( i );
868         double u2 = intervals( i+1 );
869         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
870         double cross = drv2 ^ drv1;
871         if ( E.Orientation() == TopAbs_REVERSED )
872           cross = -cross;
873         isConvex = ( cross > 0.1 ); //-1e-9 );
874       }
875       // check if concavity is strong enough to care about it
876       //const double maxAngle = 5 * Standard_PI180;
877       if ( !isConvex )
878       {
879         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
880         return true;
881         // map< double, const SMDS_MeshNode* > u2nodes;
882         // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
883         //                                         /*ignoreMedium=*/true, u2nodes))
884         //   continue;
885         // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
886         // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
887         // double    uPrev = u2n->first;
888         // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
889         // {
890         //   gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
891         //   gp_Vec2d segmentDir( uvPrev, uv );
892         //   curve.D1( uPrev, p, drv1 );
893         //   try {
894         //     if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
895         //       return true;
896         //   }
897         //   catch ( ... ) {}
898         //   uvPrev = uv;
899         //   uPrev = u2n->first;
900         // }
901       }
902     }
903     // check angles at VERTEXes
904     TError error;
905     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
906     for ( size_t iW = 0; iW < wires.size(); ++iW )
907     {
908       const int nbEdges = wires[iW]->NbEdges();
909       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
910         continue;
911       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
912       {
913         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
914         int iE2 = ( iE1 + 1 ) % nbEdges;
915         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
916           iE2 = ( iE2 + 1 ) % nbEdges;
917         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
918                                         wires[iW]->Edge( iE2 ), F );
919         if ( angle < -5. * M_PI / 180. )
920           return true;
921       }
922     }
923     return false;
924   }
925   //--------------------------------------------------------------------------------
926   // DEBUG. Dump intermediate node positions into a python script
927 #ifdef __myDEBUG
928   ofstream* py;
929   struct PyDump {
930     PyDump() {
931       const char* fname = "/tmp/viscous.py";
932       cout << "execfile('"<<fname<<"')"<<endl;
933       py = new ofstream(fname);
934       *py << "import SMESH" << endl
935           << "from salome.smesh import smeshBuilder" << endl
936           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
937           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
938           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
939     }
940     void Finish() {
941       if (py)
942         *py << "mesh.MakeGroup('Viscous Prisms',SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA)"<<endl;
943       delete py; py=0;
944     }
945     ~PyDump() { Finish(); }
946   };
947 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
948 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
949 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
950   void _dumpFunction(const string& fun, int ln)
951   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
952   void _dumpMove(const SMDS_MeshNode* n, int ln)
953   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
954                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
955   void _dumpCmd(const string& txt, int ln)
956   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
957   void dumpFunctionEnd()
958   { if (py) *py<< "  return"<< endl; }
959   void dumpChangeNodes( const SMDS_MeshElement* f )
960   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
961       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
962       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
963 #else
964   struct PyDump { void Finish() {} };
965 #define dumpFunction(f) f
966 #define dumpMove(n)
967 #define dumpCmd(txt)
968 #define dumpFunctionEnd()
969 #define dumpChangeNodes(f)
970 #endif
971 }
972
973 using namespace VISCOUS_3D;
974
975 //================================================================================
976 /*!
977  * \brief Constructor of _ViscousBuilder
978  */
979 //================================================================================
980
981 _ViscousBuilder::_ViscousBuilder()
982 {
983   _error = SMESH_ComputeError::New(COMPERR_OK);
984   _tmpFaceID = 0;
985 }
986
987 //================================================================================
988 /*!
989  * \brief Stores error description and returns false
990  */
991 //================================================================================
992
993 bool _ViscousBuilder::error(const string& text, int solidId )
994 {
995   _error->myName    = COMPERR_ALGO_FAILED;
996   _error->myComment = string("Viscous layers builder: ") + text;
997   if ( _mesh )
998   {
999     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1000     if ( !sm && !_sdVec.empty() )
1001       sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
1002     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1003     {
1004       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1005       if ( smError && smError->myAlgo )
1006         _error->myAlgo = smError->myAlgo;
1007       smError = _error;
1008     }
1009   }
1010   makeGroupOfLE(); // debug
1011
1012   return false;
1013 }
1014
1015 //================================================================================
1016 /*!
1017  * \brief At study restoration, restore event listeners used to clear an inferior
1018  *  dim sub-mesh modified by viscous layers
1019  */
1020 //================================================================================
1021
1022 void _ViscousBuilder::RestoreListeners()
1023 {
1024   // TODO
1025 }
1026
1027 //================================================================================
1028 /*!
1029  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1030  */
1031 //================================================================================
1032
1033 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1034 {
1035   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1036   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1037   for ( ; fExp.More(); fExp.Next() )
1038   {
1039     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1040     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1041
1042     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1043       continue;
1044     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1045       continue;
1046
1047     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1048       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1049
1050     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1051     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1052     while( prxIt->more() )
1053     {
1054       const SMDS_MeshElement* fSrc = srcIt->next();
1055       const SMDS_MeshElement* fPrx = prxIt->next();
1056       if ( fSrc->NbNodes() != fPrx->NbNodes())
1057         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1058       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1059         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1060     }
1061   }
1062   pm->_n2nMapComputed = true;
1063   return true;
1064 }
1065
1066 //================================================================================
1067 /*!
1068  * \brief Does its job
1069  */
1070 //================================================================================
1071
1072 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1073                                                const TopoDS_Shape& theShape)
1074 {
1075   // TODO: set priority of solids during Gen::Compute()
1076
1077   _mesh = & theMesh;
1078
1079   // check if proxy mesh already computed
1080   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1081   if ( !exp.More() )
1082     return error("No SOLID's in theShape"), _error;
1083
1084   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1085     return SMESH_ComputeErrorPtr(); // everything already computed
1086
1087   PyDump debugDump;
1088
1089   // TODO: ignore already computed SOLIDs 
1090   if ( !findSolidsWithLayers())
1091     return _error;
1092
1093   if ( !findFacesWithLayers() )
1094     return _error;
1095
1096   for ( size_t i = 0; i < _sdVec.size(); ++i )
1097   {
1098     if ( ! makeLayer(_sdVec[i]) )
1099       return _error;
1100
1101     if ( _sdVec[i]._edges.size() == 0 )
1102       continue;
1103     
1104     if ( ! inflate(_sdVec[i]) )
1105       return _error;
1106
1107     if ( ! refine(_sdVec[i]) )
1108       return _error;
1109   }
1110   if ( !shrink() )
1111     return _error;
1112
1113   addBoundaryElements();
1114
1115   makeGroupOfLE(); // debug
1116   debugDump.Finish();
1117
1118   return _error;
1119 }
1120
1121 //================================================================================
1122 /*!
1123  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1124  */
1125 //================================================================================
1126
1127 bool _ViscousBuilder::findSolidsWithLayers()
1128 {
1129   // get all solids
1130   TopTools_IndexedMapOfShape allSolids;
1131   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1132   _sdVec.reserve( allSolids.Extent());
1133
1134   SMESH_Gen* gen = _mesh->GetGen();
1135   SMESH_HypoFilter filter;
1136   for ( int i = 1; i <= allSolids.Extent(); ++i )
1137   {
1138     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1139     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1140     if ( !algo ) continue;
1141     // TODO: check if algo is hidden
1142     const list <const SMESHDS_Hypothesis *> & allHyps =
1143       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1144     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1145     const StdMeshers_ViscousLayers* viscHyp = 0;
1146     for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1147       viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1148     if ( viscHyp )
1149     {
1150       TopoDS_Shape hypShape;
1151       filter.Init( filter.Is( viscHyp ));
1152       _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1153
1154       _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1155                                                                 allSolids(i),
1156                                                                 /*toCreate=*/true);
1157       _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1158       _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1159     }
1160   }
1161   if ( _sdVec.empty() )
1162     return error
1163       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1164
1165   return true;
1166 }
1167
1168 //================================================================================
1169 /*!
1170  * \brief 
1171  */
1172 //================================================================================
1173
1174 bool _ViscousBuilder::findFacesWithLayers()
1175 {
1176   SMESH_MesherHelper helper( *_mesh );
1177   TopExp_Explorer exp;
1178   TopTools_IndexedMapOfShape solids;
1179
1180   // collect all faces to ignore defined by hyp
1181   for ( size_t i = 0; i < _sdVec.size(); ++i )
1182   {
1183     solids.Add( _sdVec[i]._solid );
1184
1185     vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1186     if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1187     {
1188       for ( size_t ii = 0; ii < ids.size(); ++ii )
1189       {
1190         const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1191         if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1192           _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1193       }
1194     }
1195     else // FACEs with layers are given
1196     {
1197       exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1198       for ( ; exp.More(); exp.Next() )
1199       {
1200         TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1201         if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1202           _sdVec[i]._ignoreFaceIds.insert( faceInd );
1203       }
1204     }
1205
1206     // ignore internal FACEs if inlets and outlets are specified
1207     {
1208       TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1209       if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1210         TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1211                                        TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1212
1213       exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1214       for ( ; exp.More(); exp.Next() )
1215       {
1216         const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1217         if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1218           continue;
1219
1220         const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1221         if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1222         {
1223           int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1224           if ( nbSolids > 1 )
1225             _sdVec[i]._ignoreFaceIds.insert( faceInd );
1226         }
1227
1228         if ( helper.IsReversedSubMesh( face ))
1229         {
1230           _sdVec[i]._reversedFaceIds.insert( faceInd );
1231         }
1232       }
1233     }
1234   }
1235
1236   // Find faces to shrink mesh on (solution 2 in issue 0020832);
1237   TopTools_IndexedMapOfShape shapes;
1238   for ( size_t i = 0; i < _sdVec.size(); ++i )
1239   {
1240     shapes.Clear();
1241     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1242     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1243     {
1244       const TopoDS_Shape& edge = shapes(iE);
1245       // find 2 faces sharing an edge
1246       TopoDS_Shape FF[2];
1247       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1248       while ( fIt->more())
1249       {
1250         const TopoDS_Shape* f = fIt->next();
1251         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1252           FF[ int( !FF[0].IsNull()) ] = *f;
1253       }
1254       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1255       // check presence of layers on them
1256       int ignore[2];
1257       for ( int j = 0; j < 2; ++j )
1258         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1259       if ( ignore[0] == ignore[1] )
1260         continue; // nothing interesting
1261       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1262       // check presence of layers on fWOL within an adjacent SOLID
1263       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1264       while ( const TopoDS_Shape* solid = sIt->next() )
1265         if ( !solid->IsSame( _sdVec[i]._solid ))
1266         {
1267           int iSolid = solids.FindIndex( *solid );
1268           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
1269           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1270           {
1271             _sdVec[i]._noShrinkFaces.insert( iFace );
1272             fWOL.Nullify();
1273           }
1274         }
1275       // add edge to maps
1276       if ( !fWOL.IsNull())
1277       {
1278         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1279         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1280       }
1281     }
1282   }
1283   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1284   // the algo of the SOLID sharing the FACE does not support it
1285   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1286   for ( size_t i = 0; i < _sdVec.size(); ++i )
1287   {
1288     TopTools_MapOfShape noShrinkVertices;
1289     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1290     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1291     {
1292       const TopoDS_Shape& fWOL = e2f->second;
1293       TGeomID           edgeID = e2f->first;
1294       bool notShrinkFace = false;
1295       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1296       while ( soIt->more())
1297       {
1298         const TopoDS_Shape* solid = soIt->next();
1299         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1300         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1301         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1302         notShrinkFace = true;
1303         for ( size_t j = 0; j < _sdVec.size(); ++j )
1304         {
1305           if ( _sdVec[j]._solid.IsSame( *solid ) )
1306             if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1307               notShrinkFace = false;
1308         }
1309       }
1310       if ( notShrinkFace )
1311       {
1312         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1313         for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1314           noShrinkVertices.Add( vExp.Current() );
1315       }
1316     }
1317     // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1318     // to the found not shrinked fWOL's
1319     e2f = _sdVec[i]._shrinkShape2Shape.begin();
1320     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1321     {
1322       TGeomID edgeID = e2f->first;
1323       TopoDS_Vertex VV[2];
1324       TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1325       if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1326       {
1327         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1328         _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1329       }
1330       else
1331       {
1332         e2f++;
1333       }
1334     }
1335   }
1336
1337   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1338
1339   for ( size_t i = 0; i < _sdVec.size(); ++i )
1340   {
1341     shapes.Clear();
1342     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1343     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1344     {
1345       const TopoDS_Shape& vertex = shapes(iV);
1346       // find faces WOL sharing the vertex
1347       vector< TopoDS_Shape > facesWOL;
1348       int totalNbFaces = 0;
1349       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1350       while ( fIt->more())
1351       {
1352         const TopoDS_Shape* f = fIt->next();
1353         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1354         {
1355           totalNbFaces++;
1356           const int fID = getMeshDS()->ShapeToIndex( *f );
1357           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
1358                !_sdVec[i]._noShrinkFaces.count( fID ))
1359             facesWOL.push_back( *f );
1360         }
1361       }
1362       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1363         continue; // no layers at this vertex or no WOL
1364       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1365       switch ( facesWOL.size() )
1366       {
1367       case 1:
1368       {
1369         helper.SetSubShape( facesWOL[0] );
1370         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1371         {
1372           TopoDS_Shape seamEdge;
1373           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1374           while ( eIt->more() && seamEdge.IsNull() )
1375           {
1376             const TopoDS_Shape* e = eIt->next();
1377             if ( helper.IsRealSeam( *e ) )
1378               seamEdge = *e;
1379           }
1380           if ( !seamEdge.IsNull() )
1381           {
1382             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1383             break;
1384           }
1385         }
1386         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1387         break;
1388       }
1389       case 2:
1390       {
1391         // find an edge shared by 2 faces
1392         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1393         while ( eIt->more())
1394         {
1395           const TopoDS_Shape* e = eIt->next();
1396           if ( helper.IsSubShape( *e, facesWOL[0]) &&
1397                helper.IsSubShape( *e, facesWOL[1]))
1398           {
1399             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1400           }
1401         }
1402         break;
1403       }
1404       default:
1405         return error("Not yet supported case", _sdVec[i]._index);
1406       }
1407     }
1408   }
1409
1410   // add FACEs of other SOLIDs to _ignoreFaceIds
1411   for ( size_t i = 0; i < _sdVec.size(); ++i )
1412   {
1413     shapes.Clear();
1414     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1415
1416     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1417     {
1418       if ( !shapes.Contains( exp.Current() ))
1419         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1420     }
1421   }
1422
1423   return true;
1424 }
1425
1426 //================================================================================
1427 /*!
1428  * \brief Create the inner surface of the viscous layer and prepare data for infation
1429  */
1430 //================================================================================
1431
1432 bool _ViscousBuilder::makeLayer(_SolidData& data)
1433 {
1434   // get all sub-shapes to make layers on
1435   set<TGeomID> subIds, faceIds;
1436   subIds = data._noShrinkFaces;
1437   TopExp_Explorer exp( data._solid, TopAbs_FACE );
1438   for ( ; exp.More(); exp.Next() )
1439     {
1440       SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1441       if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1442         faceIds.insert( fSubM->GetId() );
1443       SMESH_subMeshIteratorPtr subIt =
1444         fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1445       while ( subIt->more() )
1446         subIds.insert( subIt->next()->GetId() );
1447     }
1448
1449   // make a map to find new nodes on sub-shapes shared with other SOLID
1450   map< TGeomID, TNode2Edge* >::iterator s2ne;
1451   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1452   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1453   {
1454     TGeomID shapeInd = s2s->first;
1455     for ( size_t i = 0; i < _sdVec.size(); ++i )
1456     {
1457       if ( _sdVec[i]._index == data._index ) continue;
1458       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1459       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1460            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1461       {
1462         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1463         break;
1464       }
1465     }
1466   }
1467
1468   // Create temporary faces and _LayerEdge's
1469
1470   dumpFunction(SMESH_Comment("makeLayers_")<<data._index); 
1471
1472   data._stepSize = Precision::Infinite();
1473   data._stepSizeNodes[0] = 0;
1474
1475   SMESH_MesherHelper helper( *_mesh );
1476   helper.SetSubShape( data._solid );
1477   helper.SetElementsOnShape(true);
1478
1479   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1480   TNode2Edge::iterator n2e2;
1481
1482   // collect _LayerEdge's of shapes they are based on
1483   const int nbShapes = getMeshDS()->MaxShapeIndex();
1484   vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1485
1486   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1487   {
1488     SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1489     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1490
1491     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1492     SMESH_ProxyMesh::SubMesh* proxySub =
1493       data._proxyMesh->getFaceSubM( F, /*create=*/true);
1494
1495     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1496     while ( eIt->more() )
1497     {
1498       const SMDS_MeshElement* face = eIt->next();
1499       newNodes.resize( face->NbCornerNodes() );
1500       double faceMaxCosin = -1;
1501       for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1502       {
1503         const SMDS_MeshNode* n = face->GetNode(i);
1504         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1505         if ( !(*n2e).second )
1506         {
1507           // add a _LayerEdge
1508           _LayerEdge* edge = new _LayerEdge();
1509           n2e->second = edge;
1510           edge->_nodes.push_back( n );
1511           const int shapeID = n->getshapeId();
1512           edgesByGeom[ shapeID ].push_back( edge );
1513
1514           SMESH_TNodeXYZ xyz( n );
1515
1516           // set edge data or find already refined _LayerEdge and get data from it
1517           if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1518                ( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() &&
1519                ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1520           {
1521             _LayerEdge* foundEdge = (*n2e2).second;
1522             gp_XYZ        lastPos = edge->Copy( *foundEdge, helper );
1523             foundEdge->_pos.push_back( lastPos );
1524             // location of the last node is modified and we restore it by foundEdge->_pos.back()
1525             const_cast< SMDS_MeshNode* >
1526               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
1527           }
1528           else
1529           {
1530             edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
1531             if ( !setEdgeData( *edge, subIds, helper, data ))
1532               return false;
1533           }
1534           dumpMove(edge->_nodes.back());
1535           if ( edge->_cosin > 0.01 )
1536           {
1537             if ( edge->_cosin > faceMaxCosin )
1538               faceMaxCosin = edge->_cosin;
1539           }
1540         }
1541         newNodes[ i ] = n2e->second->_nodes.back();
1542       }
1543       // create a temporary face
1544       const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1545       proxySub->AddElement( newFace );
1546
1547       // compute inflation step size by min size of element on a convex surface
1548       if ( faceMaxCosin > 0.1 )
1549         limitStepSize( data, face, faceMaxCosin );
1550     } // loop on 2D elements on a FACE
1551   } // loop on FACEs of a SOLID
1552
1553   data._epsilon = 1e-7;
1554   if ( data._stepSize < 1. )
1555     data._epsilon *= data._stepSize;
1556
1557   // fill data._simplexTestEdges
1558   findSimplexTestEdges( data, edgesByGeom );
1559
1560   // Put _LayerEdge's into the vector data._edges
1561   if ( !sortEdges( data, edgesByGeom ))
1562     return false;
1563
1564   // Set target nodes into _Simplex and _2NearEdges of _LayerEdge's
1565   TNode2Edge::iterator n2e;
1566   for ( size_t i = 0; i < data._edges.size(); ++i )
1567   {
1568     if ( data._edges[i]->IsOnEdge())
1569       for ( int j = 0; j < 2; ++j )
1570       {
1571         if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1572           break; // _LayerEdge is shared by two _SolidData's
1573         const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1574         if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1575           return error("_LayerEdge not found by src node", data._index);
1576         n = (*n2e).second->_nodes.back();
1577         data._edges[i]->_2neibors->_edges[j] = n2e->second;
1578       }
1579     //else
1580     for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
1581     {
1582       _Simplex& s = data._edges[i]->_simplices[j];
1583       s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1584       s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1585     }
1586   }
1587
1588   dumpFunctionEnd();
1589   return true;
1590 }
1591
1592 //================================================================================
1593 /*!
1594  * \brief Compute inflation step size by min size of element on a convex surface
1595  */
1596 //================================================================================
1597
1598 void _ViscousBuilder::limitStepSize( _SolidData&             data,
1599                                      const SMDS_MeshElement* face,
1600                                      const double            cosin)
1601 {
1602   int iN = 0;
1603   double minSize = 10 * data._stepSize;
1604   const int nbNodes = face->NbCornerNodes();
1605   for ( int i = 0; i < nbNodes; ++i )
1606   {
1607     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1608     const SMDS_MeshNode* curN = face->GetNode( i );
1609     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1610          curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1611     {
1612       double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1613       if ( dist < minSize )
1614         minSize = dist, iN = i;
1615     }
1616   }
1617   double newStep = 0.8 * minSize / cosin;
1618   if ( newStep < data._stepSize )
1619   {
1620     data._stepSize = newStep;
1621     data._stepSizeCoeff = 0.8 / cosin;
1622     data._stepSizeNodes[0] = face->GetNode( iN );
1623     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1624   }
1625 }
1626
1627 //================================================================================
1628 /*!
1629  * \brief Compute inflation step size by min size of element on a convex surface
1630  */
1631 //================================================================================
1632
1633 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
1634 {
1635   if ( minSize < data._stepSize )
1636   {
1637     data._stepSize = minSize;
1638     if ( data._stepSizeNodes[0] )
1639     {
1640       double dist =
1641         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1642       data._stepSizeCoeff = data._stepSize / dist;
1643     }
1644   }
1645 }
1646
1647 //================================================================================
1648 /*!
1649  * Fill data._simplexTestEdges. These _LayerEdge's are used to stop inflation
1650  * in the case where there are no _LayerEdge's on a curved convex FACE,
1651  * as e.g. on a fillet surface with no internal nodes - issue 22580,
1652  * so that collision of viscous internal faces is not detected by check of
1653  * intersection of _LayerEdge's with the viscous internal faces.
1654  */
1655 //================================================================================
1656
1657 void _ViscousBuilder::findSimplexTestEdges( _SolidData&                    data,
1658                                             vector< vector<_LayerEdge*> >& edgesByGeom)
1659 {
1660   data._simplexTestEdges.clear();
1661
1662   SMESH_MesherHelper helper( *_mesh );
1663
1664   vector< vector<_LayerEdge*> * > ledgesOnEdges;
1665   set< const SMDS_MeshNode* > usedNodes;
1666
1667   const double minCurvature = 1. / data._hyp->GetTotalThickness();
1668
1669   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1670   {
1671     // look for a FACE with layers and w/o _LayerEdge's
1672     const vector<_LayerEdge*>& eS = edgesByGeom[iS];
1673     if ( !eS.empty() ) continue;
1674     const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1675     if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
1676     if ( data._ignoreFaceIds.count( iS )) continue;
1677
1678     const TopoDS_Face& F = TopoDS::Face( S );
1679
1680     // look for _LayerEdge's on EDGEs with null _sWOL
1681     ledgesOnEdges.clear();
1682     TopExp_Explorer eExp( F, TopAbs_EDGE );
1683     for ( ; eExp.More(); eExp.Next() )
1684     {
1685       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1686       vector<_LayerEdge*>& eE = edgesByGeom[iE];
1687       if ( !eE.empty() && eE[0]->_sWOL.IsNull() )
1688         ledgesOnEdges.push_back( & eE );
1689     }
1690     if ( ledgesOnEdges.empty() ) continue;
1691
1692     // check FACE convexity
1693     const _LayerEdge* le = ledgesOnEdges[0]->back();
1694     gp_XY uv = helper.GetNodeUV( F, le->_nodes[0] );
1695     BRepAdaptor_Surface surf( F );
1696     BRepLProp_SLProps surfProp( surf, uv.X(), uv.Y(), 2, 1e-6 );
1697     if ( !surfProp.IsCurvatureDefined() )
1698       continue;
1699     double surfCurvature = Max( Abs( surfProp.MaxCurvature() ),
1700                                 Abs( surfProp.MinCurvature() ));
1701     if ( surfCurvature < minCurvature )
1702       continue;
1703     gp_Dir minDir, maxDir;
1704     surfProp.CurvatureDirections( maxDir, minDir );
1705     if ( F.Orientation() == TopAbs_REVERSED ) {
1706       maxDir.Reverse(); minDir.Reverse();
1707     }
1708     const gp_XYZ& inDir = le->_normal;
1709     if ( inDir * maxDir.XYZ() < 0 &&
1710          inDir * minDir.XYZ() < 0 )
1711       continue;
1712
1713     limitStepSize( data, 0.9 / surfCurvature );
1714
1715     // add _simplices to the _LayerEdge's
1716     for ( size_t iE = 0; iE < ledgesOnEdges.size(); ++iE )
1717     {
1718       const vector<_LayerEdge*>& ledges = *ledgesOnEdges[iE];
1719       for ( size_t iLE = 0; iLE < ledges.size(); ++iLE )
1720       {
1721         _LayerEdge* ledge = ledges[iLE];
1722         const SMDS_MeshNode* srcNode = ledge->_nodes[0];
1723         if ( !usedNodes.insert( srcNode ).second ) continue;
1724
1725         getSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
1726         for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
1727         {
1728           usedNodes.insert( ledge->_simplices[i]._nPrev );
1729           usedNodes.insert( ledge->_simplices[i]._nNext );
1730         }
1731         data._simplexTestEdges.push_back( ledge );
1732       }
1733     }
1734   }
1735 }
1736
1737 //================================================================================
1738 /*!
1739  * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1740  */
1741 //================================================================================
1742
1743 bool _ViscousBuilder::sortEdges( _SolidData&                    data,
1744                                  vector< vector<_LayerEdge*> >& edgesByGeom)
1745 {
1746   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1747   // boundry inclined at a sharp angle to the shape
1748
1749   list< TGeomID > shapesToSmooth;
1750   
1751   SMESH_MesherHelper helper( *_mesh );
1752   bool ok = true;
1753
1754   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1755   {
1756     vector<_LayerEdge*>& eS = edgesByGeom[iS];
1757     if ( eS.empty() ) continue;
1758     const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1759     bool needSmooth = false;
1760     switch ( S.ShapeType() )
1761     {
1762     case TopAbs_EDGE: {
1763
1764       bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1765       for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1766       {
1767         TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1768         vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1769         if ( eV.empty() ) continue;
1770         double cosin = eV[0]->_cosin;
1771         bool badCosin =
1772           ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1773         if ( badCosin )
1774         {
1775           gp_Vec dir1, dir2;
1776           if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1777             dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1778           else
1779             dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1780                                eV[0]->_nodes[0], helper, ok);
1781           dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1782           double angle = dir1.Angle( dir2 );
1783           cosin = cos( angle );
1784         }
1785         needSmooth = ( cosin > 0.1 );
1786       }
1787       break;
1788     }
1789     case TopAbs_FACE: {
1790
1791       for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1792       {
1793         TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1794         vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1795         if ( eE.empty() ) continue;
1796         if ( eE[0]->_sWOL.IsNull() )
1797         {
1798           for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1799             needSmooth = ( eE[i]->_cosin > 0.1 );
1800         }
1801         else
1802         {
1803           const TopoDS_Face& F1 = TopoDS::Face( S );
1804           const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1805           const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
1806           for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1807           {
1808             gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1809             gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1810             double angle = dir1.Angle( dir2 );
1811             double cosin = cos( angle );
1812             needSmooth = ( cosin > 0.1 );
1813           }
1814         }
1815       }
1816       break;
1817     }
1818     case TopAbs_VERTEX:
1819       continue;
1820     default:;
1821     }
1822     if ( needSmooth )
1823     {
1824       if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1825       else                                shapesToSmooth.push_back ( iS );
1826     }
1827
1828   } // loop on edgesByGeom
1829
1830   data._edges.reserve( data._n2eMap.size() );
1831   data._endEdgeToSmooth.clear();
1832
1833   // first we put _LayerEdge's on shapes to smooth
1834   list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1835   for ( ; gIt != shapesToSmooth.end(); ++gIt )
1836   {
1837     vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1838     if ( eVec.empty() ) continue;
1839     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1840     data._endEdgeToSmooth.push_back( data._edges.size() );
1841     eVec.clear();
1842   }
1843
1844   // then the rest _LayerEdge's
1845   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1846   {
1847     vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1848     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1849     eVec.clear();
1850   }
1851
1852   return ok;
1853 }
1854
1855 //================================================================================
1856 /*!
1857  * \brief Set data of _LayerEdge needed for smoothing
1858  *  \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1859  */
1860 //================================================================================
1861
1862 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
1863                                   const set<TGeomID>& subIds,
1864                                   SMESH_MesherHelper& helper,
1865                                   _SolidData&         data)
1866 {
1867   SMESH_MeshEditor editor(_mesh);
1868
1869   const SMDS_MeshNode* node = edge._nodes[0]; // source node
1870   SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1871
1872   edge._len = 0;
1873   edge._2neibors = 0;
1874   edge._curvature = 0;
1875
1876   // --------------------------
1877   // Compute _normal and _cosin
1878   // --------------------------
1879
1880   edge._cosin = 0;
1881   edge._normal.SetCoord(0,0,0);
1882
1883   int totalNbFaces = 0;
1884   gp_Pnt p;
1885   gp_Vec du, dv, geomNorm;
1886   bool normOK = true;
1887
1888   TGeomID shapeInd = node->getshapeId();
1889   map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1890   bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1891   TopoDS_Shape vertEdge;
1892
1893   if ( onShrinkShape ) // one of faces the node is on has no layers
1894   {
1895     vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1896     if ( s2s->second.ShapeType() == TopAbs_EDGE )
1897     {
1898       // inflate from VERTEX along EDGE
1899       edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1900     }
1901     else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1902     {
1903       // inflate from VERTEX along FACE
1904       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1905                                  node, helper, normOK, &edge._cosin);
1906     }
1907     else
1908     {
1909       // inflate from EDGE along FACE
1910       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1911                                  node, helper, normOK);
1912     }
1913   }
1914   else // layers are on all faces of SOLID the node is on
1915   {
1916     // find indices of geom faces the node lies on
1917     set<TGeomID> faceIds;
1918     if  ( posType == SMDS_TOP_FACE )
1919     {
1920       faceIds.insert( node->getshapeId() );
1921     }
1922     else
1923     {
1924       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1925       while ( fIt->more() )
1926         faceIds.insert( editor.FindShape(fIt->next()));
1927     }
1928
1929     set<TGeomID>::iterator id = faceIds.begin();
1930     TopoDS_Face F;
1931     std::pair< TGeomID, gp_XYZ > id2Norm[20];
1932     for ( ; id != faceIds.end(); ++id )
1933     {
1934       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1935       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1936         continue;
1937       F = TopoDS::Face( s );
1938
1939       gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1940       Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1941       {
1942         gp_Dir normal;
1943         if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
1944         {
1945           geomNorm = normal;
1946           normOK = true;
1947         }
1948         else // hard singularity
1949         {
1950           SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1951           while ( fIt->more() )
1952           {
1953             const SMDS_MeshElement* f = fIt->next();
1954             if ( editor.FindShape( f ) == *id )
1955             {
1956               SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) geomNorm.XYZ(), /*normalized=*/false );
1957               if ( helper.IsReversedSubMesh( F ))
1958                 geomNorm.Reverse();
1959               break;
1960             }
1961           }
1962           double size2 = geomNorm.SquareMagnitude();
1963           if ( size2 > numeric_limits<double>::min() )
1964             geomNorm /= sqrt( size2 );
1965           else
1966             normOK = false;
1967         }
1968       }
1969       if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1970         geomNorm.Reverse();
1971       id2Norm[ totalNbFaces ].first  = *id;
1972       id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
1973       totalNbFaces++;
1974       edge._normal += geomNorm.XYZ();
1975     }
1976     if ( totalNbFaces == 0 )
1977       return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1978
1979     if ( totalNbFaces < 3 )
1980     {
1981       //edge._normal /= totalNbFaces;
1982     }
1983     else
1984     {
1985       edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
1986     }
1987
1988     switch ( posType )
1989     {
1990     case SMDS_TOP_FACE:
1991       edge._cosin = 0; break;
1992
1993     case SMDS_TOP_EDGE: {
1994       TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1995       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1996       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1997       edge._cosin = cos( angle );
1998       //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1999       break;
2000     }
2001     case SMDS_TOP_VERTEX: {
2002       TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2003       gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
2004       double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
2005       edge._cosin = cos( angle );
2006       //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2007       break;
2008     }
2009     default:
2010       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2011     }
2012   }
2013
2014   double normSize = edge._normal.SquareModulus();
2015   if ( normSize < numeric_limits<double>::min() )
2016     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2017
2018   edge._normal /= sqrt( normSize );
2019
2020   // TODO: if ( !normOK ) then get normal by mesh faces
2021
2022   // Set the rest data
2023   // --------------------
2024   if ( onShrinkShape )
2025   {
2026     edge._sWOL = (*s2s).second;
2027
2028     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2029     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2030       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2031
2032     // set initial position which is parameters on _sWOL in this case
2033     if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2034     {
2035       double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2036       edge._pos.push_back( gp_XYZ( u, 0, 0));
2037       getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2038     }
2039     else // TopAbs_FACE
2040     {
2041       gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2042       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2043       getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2044     }
2045   }
2046   else
2047   {
2048     edge._pos.push_back( SMESH_TNodeXYZ( node ));
2049
2050     if ( posType == SMDS_TOP_FACE )
2051     {
2052       getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2053       double avgNormProj = 0, avgLen = 0;
2054       for ( size_t i = 0; i < edge._simplices.size(); ++i )
2055       {
2056         gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
2057         avgNormProj += edge._normal * vec;
2058         avgLen += vec.Modulus();
2059       }
2060       avgNormProj /= edge._simplices.size();
2061       avgLen /= edge._simplices.size();
2062       edge._curvature = _Curvature::New( avgNormProj, avgLen );
2063     }
2064   }
2065
2066   // Set neighbour nodes for a _LayerEdge based on EDGE
2067
2068   if ( posType == SMDS_TOP_EDGE /*||
2069        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2070   {
2071     edge._2neibors = new _2NearEdges;
2072     // target node instead of source ones will be set later
2073     if ( ! findNeiborsOnEdge( &edge,
2074                               edge._2neibors->_nodes[0],
2075                               edge._2neibors->_nodes[1],
2076                               data))
2077       return false;
2078     edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2079                              edge._2neibors->_nodes[1],
2080                              helper);
2081   }
2082
2083   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2084
2085   return true;
2086 }
2087
2088 //================================================================================
2089 /*!
2090  * \brief Return normal at a node weighted with angles taken by FACEs
2091  *  \param [in] n - the node
2092  *  \param [in] fId2Normal - FACE ids and normals
2093  *  \param [in] nbFaces - nb of FACEs meeting at the node
2094  *  \return gp_XYZ - computed normal
2095  */
2096 //================================================================================
2097
2098 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode*         n,
2099                                            std::pair< TGeomID, gp_XYZ > fId2Normal[],
2100                                            const int                    nbFaces )
2101 {
2102   gp_XYZ resNorm(0,0,0);
2103   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2104   if ( V.ShapeType() != TopAbs_VERTEX )
2105   {
2106     for ( int i = 0; i < nbFaces; ++i )
2107       resNorm += fId2Normal[i].second / nbFaces ;
2108     return resNorm;
2109   }
2110
2111   double angles[30];
2112   for ( int i = 0; i < nbFaces; ++i )
2113   {
2114     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2115
2116     // look for two EDGEs shared by F and other FACEs within fId2Normal
2117     TopoDS_Edge ee[2];
2118     int nbE = 0;
2119     PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2120     while ( const TopoDS_Shape* E = eIt->next() )
2121     {
2122       if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2123         continue;
2124       bool isSharedEdge = false;
2125       for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2126       {
2127         if ( i == j ) continue;
2128         const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2129         isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2130       }
2131       if ( !isSharedEdge )
2132         continue;
2133       ee[ nbE ] = TopoDS::Edge( *E );
2134       ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
2135       if ( ++nbE == 2 )
2136         break;
2137     }
2138
2139     // get an angle between the two EDGEs
2140     angles[i] = 0;
2141     if ( nbE < 1 ) continue;
2142     if ( nbE == 1 )
2143     {
2144       ee[ 1 ] == ee[ 0 ];
2145     }
2146     else
2147     {
2148       TopoDS_Vertex v10 = SMESH_MesherHelper::IthVertex( 1, ee[ 0 ]);
2149       TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex( 0, ee[ 1 ]);
2150       if ( !v10.IsSame( v01 ))
2151         std::swap( ee[0], ee[1] );
2152     }
2153     angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F );
2154   }
2155
2156   // compute a weighted normal
2157   double sumAngle = 0;
2158   for ( int i = 0; i < nbFaces; ++i )
2159   {
2160     angles[i] = ( angles[i] > 2*M_PI )  ?  0  :  M_PI - angles[i];
2161     sumAngle += angles[i];
2162   }
2163   for ( int i = 0; i < nbFaces; ++i )
2164     resNorm += angles[i] / sumAngle * fId2Normal[i].second;
2165
2166   return resNorm;
2167 }
2168
2169 //================================================================================
2170 /*!
2171  * \brief Find 2 neigbor nodes of a node on EDGE
2172  */
2173 //================================================================================
2174
2175 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
2176                                         const SMDS_MeshNode*& n1,
2177                                         const SMDS_MeshNode*& n2,
2178                                         _SolidData&           data)
2179 {
2180   const SMDS_MeshNode* node = edge->_nodes[0];
2181   const int shapeInd = node->getshapeId();
2182   SMESHDS_SubMesh* edgeSM = 0;
2183   if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
2184   {
2185     
2186     edgeSM = getMeshDS()->MeshElements( shapeInd );
2187     if ( !edgeSM || edgeSM->NbElements() == 0 )
2188       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
2189   }
2190   int iN = 0;
2191   n2 = 0;
2192   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
2193   while ( eIt->more() && !n2 )
2194   {
2195     const SMDS_MeshElement* e = eIt->next();
2196     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
2197     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
2198     if ( edgeSM )
2199     {
2200       if (!edgeSM->Contains(e)) continue;
2201     }
2202     else
2203     {
2204       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
2205       if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
2206     }
2207     ( iN++ ? n2 : n1 ) = nNeibor;
2208   }
2209   if ( !n2 )
2210     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
2211   return true;
2212 }
2213
2214 //================================================================================
2215 /*!
2216  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2217  */
2218 //================================================================================
2219
2220 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2221                                      const SMDS_MeshNode* n2,
2222                                      SMESH_MesherHelper&  helper)
2223 {
2224   if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2225     return;
2226
2227   gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2228   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2229   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2230
2231   // Set _curvature
2232
2233   double sumLen = vec1.Modulus() + vec2.Modulus();
2234   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2235   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2236   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2237   double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2238   if ( _curvature ) delete _curvature;
2239   _curvature = _Curvature::New( avgNormProj, avgLen );
2240 #ifdef __myDEBUG
2241 //     if ( _curvature )
2242 //       cout << _nodes[0]->GetID()
2243 //            << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2244 //            << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2245 //            << _curvature->lenDelta(0) << endl;
2246 #endif
2247
2248   // Set _plnNorm
2249
2250   if ( _sWOL.IsNull() )
2251   {
2252     TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2253     gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
2254     gp_XYZ plnNorm = dirE ^ _normal;
2255     double proj0 = plnNorm * vec1;
2256     double proj1 = plnNorm * vec2;
2257     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2258     {
2259       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2260       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2261     }
2262   }
2263 }
2264
2265 //================================================================================
2266 /*!
2267  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2268  * this and other _LayerEdge's are inflated along a FACE or an EDGE
2269  */
2270 //================================================================================
2271
2272 gp_XYZ _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2273 {
2274   _nodes     = other._nodes;
2275   _normal    = other._normal;
2276   _len       = 0;
2277   _lenFactor = other._lenFactor;
2278   _cosin     = other._cosin;
2279   _sWOL      = other._sWOL;
2280   _2neibors  = other._2neibors;
2281   _curvature = 0; std::swap( _curvature, other._curvature );
2282   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
2283
2284   gp_XYZ lastPos( 0,0,0 );
2285   if ( _sWOL.ShapeType() == TopAbs_EDGE )
2286   {
2287     double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2288     _pos.push_back( gp_XYZ( u, 0, 0));
2289
2290     u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes.back() );
2291     lastPos.SetX( u );
2292   }
2293   else // TopAbs_FACE
2294   {
2295     gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2296     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2297
2298     uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes.back() );
2299     lastPos.SetX( uv.X() );
2300     lastPos.SetY( uv.Y() );
2301   }
2302   return lastPos;
2303 }
2304
2305 //================================================================================
2306 /*!
2307  * \brief Set _cosin and _lenFactor
2308  */
2309 //================================================================================
2310
2311 void _LayerEdge::SetCosin( double cosin )
2312 {
2313   _cosin = cosin;
2314   _lenFactor = ( Abs( _cosin ) > 0.1 ) ?  1./sqrt(1-_cosin*_cosin) : 1.0;
2315 }
2316
2317 //================================================================================
2318 /*!
2319  * \brief Fills a vector<_Simplex > 
2320  */
2321 //================================================================================
2322
2323 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2324                                     vector<_Simplex>&    simplices,
2325                                     const set<TGeomID>&  ingnoreShapes,
2326                                     const _SolidData*    dataToCheckOri,
2327                                     const bool           toSort)
2328 {
2329   simplices.clear();
2330   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2331   while ( fIt->more() )
2332   {
2333     const SMDS_MeshElement* f = fIt->next();
2334     const TGeomID    shapeInd = f->getshapeId();
2335     if ( ingnoreShapes.count( shapeInd )) continue;
2336     const int nbNodes = f->NbCornerNodes();
2337     const int  srcInd = f->GetNodeIndex( node );
2338     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2339     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2340     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2341     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2342       std::swap( nPrev, nNext );
2343     simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2344   }
2345
2346   if ( toSort )
2347   {
2348     vector<_Simplex> sortedSimplices( simplices.size() );
2349     sortedSimplices[0] = simplices[0];
2350     int nbFound = 0;
2351     for ( size_t i = 1; i < simplices.size(); ++i )
2352     {
2353       for ( size_t j = 1; j < simplices.size(); ++j )
2354         if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2355         {
2356           sortedSimplices[i] = simplices[j];
2357           nbFound++;
2358           break;
2359         }
2360     }
2361     if ( nbFound == simplices.size() - 1 )
2362       simplices.swap( sortedSimplices );
2363   }
2364 }
2365
2366 //================================================================================
2367 /*!
2368  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2369  */
2370 //================================================================================
2371
2372 void _ViscousBuilder::makeGroupOfLE()
2373 {
2374 #ifdef _DEBUG_
2375   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2376   {
2377     if ( _sdVec[i]._edges.empty() ) continue;
2378 //     string name = SMESH_Comment("_LayerEdge's_") << i;
2379 //     int id;
2380 //     SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2381 //     SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2382 //     SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2383
2384     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2385     for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2386     {
2387       _LayerEdge* le = _sdVec[i]._edges[j];
2388       for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2389         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2390                 << ", " << le->_nodes[iN]->GetID() <<"])");
2391       //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2392     }
2393     dumpFunctionEnd();
2394
2395     dumpFunction( SMESH_Comment("makeNormals") << i );
2396     for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2397     {
2398       _LayerEdge& edge = *_sdVec[i]._edges[j];
2399       SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2400       nXYZ += edge._normal * _sdVec[i]._stepSize;
2401       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2402               << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2403     }
2404     dumpFunctionEnd();
2405
2406 //     name = SMESH_Comment("tmp_faces ") << i;
2407 //     g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2408 //     gDS = (SMESHDS_Group*)g->GetGroupDS();
2409 //     SMESH_MeshEditor editor( _mesh );
2410     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2411     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2412     for ( ; fExp.More(); fExp.Next() )
2413     {
2414       if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2415       {
2416         SMDS_ElemIteratorPtr fIt = sm->GetElements();
2417         while ( fIt->more())
2418         {
2419           const SMDS_MeshElement* e = fIt->next();
2420           SMESH_Comment cmd("mesh.AddFace([");
2421           for ( int j=0; j < e->NbCornerNodes(); ++j )
2422             cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2423           dumpCmd( cmd );
2424           //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2425           //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2426         }
2427       }
2428     }
2429     dumpFunctionEnd();
2430   }
2431 #endif
2432 }
2433
2434 //================================================================================
2435 /*!
2436  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2437  */
2438 //================================================================================
2439
2440 bool _ViscousBuilder::inflate(_SolidData& data)
2441 {
2442   SMESH_MesherHelper helper( *_mesh );
2443
2444   // Limit inflation step size by geometry size found by itersecting
2445   // normals of _LayerEdge's with mesh faces
2446   double geomSize = Precision::Infinite(), intersecDist;
2447   auto_ptr<SMESH_ElementSearcher> searcher
2448     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2449                                            data._proxyMesh->GetFaces( data._solid )) );
2450   for ( size_t i = 0; i < data._edges.size(); ++i )
2451   {
2452     if ( data._edges[i]->IsOnEdge() ) continue;
2453     data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2454     if ( geomSize > intersecDist && intersecDist > 0 )
2455       geomSize = intersecDist;
2456   }
2457   if ( data._stepSize > 0.3 * geomSize )
2458     limitStepSize( data, 0.3 * geomSize );
2459
2460   const double tgtThick = data._hyp->GetTotalThickness();
2461   if ( data._stepSize > tgtThick )
2462     limitStepSize( data, tgtThick );
2463
2464   if ( data._stepSize < 1. )
2465     data._epsilon = data._stepSize * 1e-7;
2466
2467 #ifdef __myDEBUG
2468   cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2469 #endif
2470
2471   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2472   int nbSteps = 0, nbRepeats = 0;
2473   while ( 1.01 * avgThick < tgtThick )
2474   {
2475     // new target length
2476     curThick += data._stepSize;
2477     if ( curThick > tgtThick )
2478     {
2479       curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2480       nbRepeats++;
2481     }
2482
2483     // Elongate _LayerEdge's
2484     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2485     for ( size_t i = 0; i < data._edges.size(); ++i )
2486     {
2487       data._edges[i]->SetNewLength( curThick, helper );
2488     }
2489     dumpFunctionEnd();
2490
2491     if ( !nbSteps )
2492       if ( !updateNormals( data, helper ) )
2493         return false;
2494
2495     // Improve and check quality
2496     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2497     {
2498       if ( nbSteps > 0 )
2499       {
2500         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2501         for ( size_t i = 0; i < data._edges.size(); ++i )
2502         {
2503           data._edges[i]->InvalidateStep( nbSteps+1 );
2504         }
2505         dumpFunctionEnd();
2506       }
2507       break; // no more inflating possible
2508     }
2509     nbSteps++;
2510
2511     // Evaluate achieved thickness
2512     avgThick = 0;
2513     for ( size_t i = 0; i < data._edges.size(); ++i )
2514       avgThick += data._edges[i]->_len;
2515     avgThick /= data._edges.size();
2516 #ifdef __myDEBUG
2517     cout << "-- Thickness " << avgThick << " reached" << endl;
2518 #endif
2519
2520     if ( distToIntersection < avgThick*1.5 )
2521     {
2522 #ifdef __myDEBUG
2523       cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2524            << avgThick << " ) * 1.5" << endl;
2525 #endif
2526       break;
2527     }
2528     // new step size
2529     limitStepSize( data, 0.25 * distToIntersection );
2530     if ( data._stepSizeNodes[0] )
2531       data._stepSize = data._stepSizeCoeff *
2532         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2533   }
2534
2535   if (nbSteps == 0 )
2536     return error("failed at the very first inflation step", data._index);
2537
2538   return true;
2539 }
2540
2541 //================================================================================
2542 /*!
2543  * \brief Improve quality of layer inner surface and check intersection
2544  */
2545 //================================================================================
2546
2547 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2548                                      const int   nbSteps,
2549                                      double &    distToIntersection)
2550 {
2551   if ( data._endEdgeToSmooth.empty() )
2552     return true; // no shapes needing smoothing
2553
2554   bool moved, improved;
2555
2556   SMESH_MesherHelper helper(*_mesh);
2557   Handle(Geom_Surface) surface;
2558   TopoDS_Face F;
2559
2560   int iBeg, iEnd = 0;
2561   for ( size_t iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2562   {
2563     iBeg = iEnd;
2564     iEnd = data._endEdgeToSmooth[ iS ];
2565
2566     if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2567          data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2568     {
2569       if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2570         F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2571         helper.SetSubShape( F );
2572         surface = BRep_Tool::Surface( F );
2573       }
2574     }
2575     else
2576     {
2577       F.Nullify(); surface.Nullify();
2578     }
2579     TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2580
2581     if ( data._edges[ iBeg ]->IsOnEdge() )
2582     { 
2583       dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2584
2585       // try a simple solution on an analytic EDGE
2586       if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2587       {
2588         // smooth on EDGE's
2589         int step = 0;
2590         do {
2591           moved = false;
2592           for ( int i = iBeg; i < iEnd; ++i )
2593           {
2594             moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2595           }
2596           dumpCmd( SMESH_Comment("# end step ")<<step);
2597         }
2598         while ( moved && step++ < 5 );
2599         //cout << " NB STEPS: " << step << endl;
2600       }
2601       dumpFunctionEnd();
2602     }
2603     else
2604     {
2605       // smooth on FACE's
2606       int step = 0, stepLimit = 5, badNb = 0; moved = true;
2607       while (( ++step <= stepLimit && moved ) || improved )
2608       {
2609         dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2610                      <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2611         int oldBadNb = badNb;
2612         badNb = 0;
2613         moved = false;
2614         for ( int i = iBeg; i < iEnd; ++i )
2615           moved |= data._edges[i]->Smooth(badNb);
2616         improved = ( badNb < oldBadNb );
2617
2618         // issue 22576. no bad faces but still there are intersections to fix
2619         if ( improved && badNb == 0 )
2620           stepLimit = step + 3;
2621
2622         dumpFunctionEnd();
2623       }
2624       if ( badNb > 0 )
2625       {
2626 #ifdef __myDEBUG
2627         for ( int i = iBeg; i < iEnd; ++i )
2628         {
2629           _LayerEdge* edge = data._edges[i];
2630           SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2631           for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2632             if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2633             {
2634               cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2635                    << " "<< edge->_simplices[j]._nPrev->GetID()
2636                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2637               return false;
2638             }
2639         }
2640 #endif
2641         return false;
2642       }
2643     }
2644   } // loop on shapes to smooth
2645
2646   // Check orientation of simplices of _simplexTestEdges
2647   for ( size_t i = 0; i < data._simplexTestEdges.size(); ++i )
2648   {
2649     const _LayerEdge* edge = data._simplexTestEdges[i];
2650     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2651     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2652       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2653       {
2654 #ifdef __myDEBUG
2655         cout << "Bad simplex of _simplexTestEdges ("
2656              << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2657              << " "<< edge->_simplices[j]._nPrev->GetID()
2658              << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2659 #endif
2660         return false;
2661       }
2662   }
2663
2664   // Check if the last segments of _LayerEdge intersects 2D elements;
2665   // checked elements are either temporary faces or faces on surfaces w/o the layers
2666
2667   auto_ptr<SMESH_ElementSearcher> searcher
2668     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2669                                            data._proxyMesh->GetFaces( data._solid )) );
2670
2671   distToIntersection = Precision::Infinite();
2672   double dist;
2673   const SMDS_MeshElement* intFace = 0;
2674 #ifdef __myDEBUG
2675   const SMDS_MeshElement* closestFace = 0;
2676   int iLE = 0;
2677 #endif
2678   for ( size_t i = 0; i < data._edges.size(); ++i )
2679   {
2680     if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2681       return false;
2682     if ( distToIntersection > dist )
2683     {
2684       distToIntersection = dist;
2685 #ifdef __myDEBUG
2686       iLE = i;
2687       closestFace = intFace;
2688 #endif
2689     }
2690   }
2691 #ifdef __myDEBUG
2692   if ( closestFace )
2693   {
2694     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2695     cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2696          << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2697          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2698          << ") distance = " << distToIntersection<< endl;
2699   }
2700 #endif
2701
2702   return true;
2703 }
2704
2705 //================================================================================
2706 /*!
2707  * \brief Return a curve of the EDGE to be used for smoothing and arrange
2708  *        _LayerEdge's to be in a consequent order
2709  */
2710 //================================================================================
2711
2712 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
2713                                                const int             iFrom,
2714                                                const int             iTo,
2715                                                Handle(Geom_Surface)& surface,
2716                                                const TopoDS_Face&    F,
2717                                                SMESH_MesherHelper&   helper)
2718 {
2719   TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2720
2721   map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2722
2723   if ( i2curve == _edge2curve.end() )
2724   {
2725     // sort _LayerEdge's by position on the EDGE
2726     {
2727       map< double, _LayerEdge* > u2edge;
2728       for ( int i = iFrom; i < iTo; ++i )
2729         u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2730
2731       ASSERT( u2edge.size() == iTo - iFrom );
2732       map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2733       for ( int i = iFrom; i < iTo; ++i, ++u2e )
2734         _edges[i] = u2e->second;
2735
2736       // set _2neibors according to the new order
2737       for ( int i = iFrom; i < iTo-1; ++i )
2738         if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2739           _edges[i]->_2neibors->reverse();
2740       if ( u2edge.size() > 1 &&
2741            _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2742         _edges[iTo-1]->_2neibors->reverse();
2743     }
2744
2745     SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2746
2747     TopLoc_Location loc; double f,l;
2748
2749     Handle(Geom_Line)   line;
2750     Handle(Geom_Circle) circle;
2751     bool isLine, isCirc;
2752     if ( F.IsNull() ) // 3D case
2753     {
2754       // check if the EDGE is a line
2755       Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2756       if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2757         curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2758
2759       line   = Handle(Geom_Line)::DownCast( curve );
2760       circle = Handle(Geom_Circle)::DownCast( curve );
2761       isLine = (!line.IsNull());
2762       isCirc = (!circle.IsNull());
2763
2764       if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2765       {
2766         Bnd_B3d bndBox;
2767         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2768         while ( nIt->more() )
2769           bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2770         gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2771
2772         SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2773         SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2774         const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2775         for ( int i = 0; i < 3 && !isLine; ++i )
2776           isLine = ( size.Coord( i+1 ) <= lineTol );
2777       }
2778       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2779       {
2780         // TODO
2781       }
2782     }
2783     else // 2D case
2784     {
2785       // check if the EDGE is a line
2786       Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2787       if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2788         curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2789
2790       Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
2791       Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2792       isLine = (!line2d.IsNull());
2793       isCirc = (!circle2d.IsNull());
2794
2795       if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2796       {
2797         Bnd_B2d bndBox;
2798         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2799         while ( nIt->more() )
2800           bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2801         gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2802
2803         const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2804         for ( int i = 0; i < 2 && !isLine; ++i )
2805           isLine = ( size.Coord( i+1 ) <= lineTol );
2806       }
2807       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2808       {
2809         // TODO
2810       }
2811       if ( isLine )
2812       {
2813         line = new Geom_Line( gp::OX() ); // only type does matter
2814       }
2815       else if ( isCirc )
2816       {
2817         gp_Pnt2d p = circle2d->Location();
2818         gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2819         circle = new Geom_Circle( ax, 1.); // only center position does matter
2820       }
2821     }
2822
2823     Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2824     if ( isLine )
2825       res = line;
2826     else if ( isCirc )
2827       res = circle;
2828
2829     return res;
2830   }
2831   return i2curve->second;
2832 }
2833
2834 //================================================================================
2835 /*!
2836  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2837  */
2838 //================================================================================
2839
2840 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
2841                                           const int             iFrom,
2842                                           const int             iTo,
2843                                           Handle(Geom_Surface)& surface,
2844                                           const TopoDS_Face&    F,
2845                                           SMESH_MesherHelper&   helper)
2846 {
2847   TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2848                                              helper.GetMeshDS());
2849   TopoDS_Edge E = TopoDS::Edge( S );
2850
2851   Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2852   if ( curve.IsNull() ) return false;
2853
2854   // compute a relative length of segments
2855   vector< double > len( iTo-iFrom+1 );
2856   {
2857     double curLen, prevLen = len[0] = 1.0;
2858     for ( int i = iFrom; i < iTo; ++i )
2859     {
2860       curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2861       len[i-iFrom+1] = len[i-iFrom] + curLen;
2862       prevLen = curLen;
2863     }
2864   }
2865
2866   if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2867   {
2868     if ( F.IsNull() ) // 3D
2869     {
2870       SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2871       SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2872       for ( int i = iFrom; i < iTo; ++i )
2873       {
2874         double r = len[i-iFrom] / len.back();
2875         gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2876         data._edges[i]->_pos.back() = newPos;
2877         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2878         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2879         dumpMove( tgtNode );
2880       }
2881     }
2882     else
2883     {
2884       gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2885       gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2886       if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2887            data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2888       {
2889         int iPeriodic = helper.GetPeriodicIndex();
2890         if ( iPeriodic == 1 || iPeriodic == 2 )
2891         {
2892           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2893           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2894             std::swap( uv0, uv1 );
2895         }
2896       }
2897       const gp_XY rangeUV = uv1 - uv0;
2898       for ( int i = iFrom; i < iTo; ++i )
2899       {
2900         double r = len[i-iFrom] / len.back();
2901         gp_XY newUV = uv0 + r * rangeUV;
2902         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2903
2904         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2905         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2906         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2907         dumpMove( tgtNode );
2908
2909         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2910         pos->SetUParameter( newUV.X() );
2911         pos->SetVParameter( newUV.Y() );
2912       }
2913     }
2914     return true;
2915   }
2916
2917   if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2918   {
2919     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2920     gp_Pnt center3D = circle->Location();
2921
2922     if ( F.IsNull() ) // 3D
2923     {
2924       if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2925            data._edges[iTo-1]->_2neibors->_nodes[1] )
2926         return true; // closed EDGE - nothing to do
2927
2928       return false; // TODO ???
2929     }
2930     else // 2D
2931     {
2932       const gp_XY center( center3D.X(), center3D.Y() );
2933
2934       gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2935       gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2936       gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2937       gp_Vec2d vec0( center, uv0 );
2938       gp_Vec2d vecM( center, uvM );
2939       gp_Vec2d vec1( center, uv1 );
2940       double uLast = vec0.Angle( vec1 ); // -PI - +PI
2941       double uMidl = vec0.Angle( vecM );
2942       if ( uLast * uMidl < 0. )
2943         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2944       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2945
2946       gp_Ax2d   axis( center, vec0 );
2947       gp_Circ2d circ( axis, radius );
2948       for ( int i = iFrom; i < iTo; ++i )
2949       {
2950         double    newU = uLast * len[i-iFrom] / len.back();
2951         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2952         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2953
2954         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2955         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2956         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2957         dumpMove( tgtNode );
2958
2959         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2960         pos->SetUParameter( newUV.X() );
2961         pos->SetVParameter( newUV.Y() );
2962       }
2963     }
2964     return true;
2965   }
2966
2967   return false;
2968 }
2969
2970 //================================================================================
2971 /*!
2972  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2973  * _LayerEdge's on neighbor EDGE's
2974  */
2975 //================================================================================
2976
2977 bool _ViscousBuilder::updateNormals( _SolidData&         data,
2978                                      SMESH_MesherHelper& helper )
2979 {
2980   // make temporary quadrangles got by extrusion of
2981   // mesh edges along _LayerEdge._normal's
2982
2983   vector< const SMDS_MeshElement* > tmpFaces;
2984   {
2985     set< SMESH_TLink > extrudedLinks; // contains target nodes
2986     vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2987
2988     dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2989     for ( size_t i = 0; i < data._edges.size(); ++i )
2990     {
2991       _LayerEdge* edge = data._edges[i];
2992       if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2993       const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2994       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2995       {
2996         const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2997         pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2998           extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2999         if ( !link_isnew.second )
3000         {
3001           extrudedLinks.erase( link_isnew.first );
3002           continue; // already extruded and will no more encounter
3003         }
3004         // look for a _LayerEdge containg tgt2
3005 //         _LayerEdge* neiborEdge = 0;
3006 //         size_t di = 0; // check _edges[i+di] and _edges[i-di]
3007 //         while ( !neiborEdge && ++di <= data._edges.size() )
3008 //         {
3009 //           if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
3010 //             neiborEdge = data._edges[i+di];
3011 //           else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
3012 //             neiborEdge = data._edges[i-di];
3013 //         }
3014 //         if ( !neiborEdge )
3015 //           return error("updateNormals(): neighbor _LayerEdge not found", data._index);
3016         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
3017
3018         TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
3019         tmpFaces.push_back( f );
3020
3021         dumpCmd(SMESH_Comment("mesh.AddFace([ ")
3022                 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
3023                 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
3024       }
3025     }
3026     dumpFunctionEnd();
3027   }
3028   // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
3029   // Perform two loops on _LayerEdge on EDGE's:
3030   // 1) to find and fix intersection
3031   // 2) to check that no new intersection appears as result of 1)
3032
3033   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
3034                                                             tmpFaces.end()));
3035   auto_ptr<SMESH_ElementSearcher> searcher
3036     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
3037
3038   // 1) Find intersections
3039   double dist;
3040   const SMDS_MeshElement* face;
3041   typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
3042   TLEdge2LEdgeSet edge2CloseEdge;
3043
3044   const double eps = data._epsilon * data._epsilon;
3045   for ( size_t i = 0; i < data._edges.size(); ++i )
3046   {
3047     _LayerEdge* edge = data._edges[i];
3048     if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3049     if ( edge->FindIntersection( *searcher, dist, eps, &face ))
3050     {
3051       const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
3052       set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
3053       ee.insert( f->_le1 );
3054       ee.insert( f->_le2 );
3055       if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() ) 
3056         edge2CloseEdge[ f->_le1 ].insert( edge );
3057       if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() ) 
3058         edge2CloseEdge[ f->_le2 ].insert( edge );
3059     }
3060   }
3061
3062   // Set _LayerEdge._normal
3063
3064   if ( !edge2CloseEdge.empty() )
3065   {
3066     dumpFunction(SMESH_Comment("updateNormals")<<data._index);
3067
3068     TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
3069     for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
3070     {
3071       _LayerEdge* edge1       = e2ee->first;
3072       _LayerEdge* edge2       = 0;
3073       set< _LayerEdge*, _LayerEdgeCmp >& ee  = e2ee->second;
3074
3075       // find EDGEs the edges reside
3076       TopoDS_Edge E1, E2;
3077       TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
3078       if ( S.ShapeType() != TopAbs_EDGE )
3079         continue; // TODO: find EDGE by VERTEX
3080       E1 = TopoDS::Edge( S );
3081       set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
3082       while ( E2.IsNull() && eIt != ee.end())
3083       {
3084         _LayerEdge* e2 = *eIt++;
3085         TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
3086         if ( S.ShapeType() == TopAbs_EDGE )
3087           E2 = TopoDS::Edge( S ), edge2 = e2;
3088       }
3089       if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
3090
3091       // find 3 FACEs sharing 2 EDGEs
3092
3093       TopoDS_Face FF1[2], FF2[2];
3094       PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
3095       while ( fIt->more() && FF1[1].IsNull())
3096       {
3097         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3098         if ( helper.IsSubShape( *F, data._solid))
3099           FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
3100       }
3101       fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
3102       while ( fIt->more() && FF2[1].IsNull())
3103       {
3104         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3105         if ( helper.IsSubShape( *F, data._solid))
3106           FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
3107       }
3108       // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
3109       if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
3110         std::swap( FF1[0], FF1[1] );
3111       if ( FF2[0].IsSame( FF1[0]) )
3112         std::swap( FF2[0], FF2[1] );
3113       if ( FF1[0].IsNull() || FF2[0].IsNull() )
3114         continue;
3115
3116       // get a new normal for edge1
3117       bool ok;
3118       gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
3119       if ( edge1->_cosin < 0 )
3120         dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
3121       if ( edge2->_cosin < 0 )
3122         dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
3123       // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3124       // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
3125       // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3126       // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3127       // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3128       // newNorm.Normalize();
3129
3130       double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3131       double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3132       gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3133       newNorm.Normalize();
3134
3135       edge1->_normal = newNorm.XYZ();
3136
3137       // update data of edge1 depending on _normal
3138       const SMDS_MeshNode *n1, *n2;
3139       n1 = edge1->_2neibors->_edges[0]->_nodes[0];
3140       n2 = edge1->_2neibors->_edges[1]->_nodes[0];
3141       //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
3142       //  continue;
3143       edge1->SetDataByNeighbors( n1, n2, helper );
3144       gp_Vec dirInFace;
3145       if ( edge1->_cosin < 0 )
3146         dirInFace = dir1;
3147       else
3148         getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3149       double angle = dir1.Angle( edge1->_normal ); // [0,PI]
3150       edge1->SetCosin( cos( angle ));
3151
3152       // limit data._stepSize
3153       if ( edge1->_cosin > 0.1 )
3154       {
3155         SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3156         while ( fIt->more() )
3157           limitStepSize( data, fIt->next(), edge1->_cosin );
3158       }
3159       // set new XYZ of target node
3160       edge1->InvalidateStep( 1 );
3161       edge1->_len = 0;
3162       edge1->SetNewLength( data._stepSize, helper );
3163     }
3164
3165     // Update normals and other dependent data of not intersecting _LayerEdge's
3166     // neighboring the intersecting ones
3167
3168     for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
3169     {
3170       _LayerEdge* edge1 = e2ee->first;
3171       if ( !edge1->_2neibors )
3172         continue;
3173       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
3174       {
3175         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
3176         if ( edge2CloseEdge.count ( neighbor ))
3177           continue; // j-th neighbor is also intersected
3178         _LayerEdge* prevEdge = edge1;
3179         const int nbSteps = 6;
3180         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
3181         {
3182           if ( !neighbor->_2neibors )
3183             break; // neighbor is on VERTEX
3184           int iNext = 0;
3185           _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
3186           if ( nextEdge == prevEdge )
3187             nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
3188 //           const double&  wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
3189 //           const double&  wgtNext = neighbor->_2neibors->_wgt[iNext];
3190           double r = double(step-1)/nbSteps;
3191           if ( !nextEdge->_2neibors )
3192             r = 0.5;
3193
3194           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
3195           newNorm.Normalize();
3196
3197           neighbor->_normal = newNorm;
3198           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
3199           neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
3200
3201           neighbor->InvalidateStep( 1 );
3202           neighbor->_len = 0;
3203           neighbor->SetNewLength( data._stepSize, helper );
3204
3205           // goto the next neighbor
3206           prevEdge = neighbor;
3207           neighbor = nextEdge;
3208         }
3209       }
3210     }
3211     dumpFunctionEnd();
3212   }
3213   // 2) Check absence of intersections
3214   // TODO?
3215
3216   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
3217     delete tmpFaces[i];
3218
3219   return true;
3220 }
3221
3222 //================================================================================
3223 /*!
3224  * \brief Looks for intersection of it's last segment with faces
3225  *  \param distance - returns shortest distance from the last node to intersection
3226  */
3227 //================================================================================
3228
3229 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
3230                                    double &                 distance,
3231                                    const double&            epsilon,
3232                                    const SMDS_MeshElement** face)
3233 {
3234   vector< const SMDS_MeshElement* > suspectFaces;
3235   double segLen;
3236   gp_Ax1 lastSegment = LastSegment(segLen);
3237   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
3238
3239   bool segmentIntersected = false;
3240   distance = Precision::Infinite();
3241   int iFace = -1; // intersected face
3242   for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
3243   {
3244     const SMDS_MeshElement* face = suspectFaces[j];
3245     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
3246          face->GetNodeIndex( _nodes[0]     ) >= 0 )
3247       continue; // face sharing _LayerEdge node
3248     const int nbNodes = face->NbCornerNodes();
3249     bool intFound = false;
3250     double dist;
3251     SMDS_MeshElement::iterator nIt = face->begin_nodes();
3252     if ( nbNodes == 3 )
3253     {
3254       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
3255     }
3256     else
3257     {
3258       const SMDS_MeshNode* tria[3];
3259       tria[0] = *nIt++;
3260       tria[1] = *nIt++;;
3261       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
3262       {
3263         tria[2] = *nIt++;
3264         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
3265         tria[1] = tria[2];
3266       }
3267     }
3268     if ( intFound )
3269     {
3270       if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
3271         segmentIntersected = true;
3272       if ( distance > dist )
3273         distance = dist, iFace = j;
3274     }
3275   }
3276   if ( iFace != -1 && face ) *face = suspectFaces[iFace];
3277 //   if ( distance && iFace > -1 )
3278 //   {
3279 //     // distance is used to limit size of inflation step which depends on
3280 //     // whether the intersected face bears viscous layers or not
3281 //     bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
3282 //     if ( faceHasVL )
3283 //       *distance /= 2;
3284 //   }
3285   if ( segmentIntersected )
3286   {
3287 #ifdef __myDEBUG
3288     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
3289     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
3290     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
3291          << ", intersection with face ("
3292          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3293          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
3294          << ") distance = " << distance - segLen<< endl;
3295 #endif
3296   }
3297
3298   distance -= segLen;
3299
3300   return segmentIntersected;
3301 }
3302
3303 //================================================================================
3304 /*!
3305  * \brief Returns size and direction of the last segment
3306  */
3307 //================================================================================
3308
3309 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
3310 {
3311   // find two non-coincident positions
3312   gp_XYZ orig = _pos.back();
3313   gp_XYZ dir;
3314   int iPrev = _pos.size() - 2;
3315   while ( iPrev >= 0 )
3316   {
3317     dir = orig - _pos[iPrev];
3318     if ( dir.SquareModulus() > 1e-100 )
3319       break;
3320     else
3321       iPrev--;
3322   }
3323
3324   // make gp_Ax1
3325   gp_Ax1 segDir;
3326   if ( iPrev < 0 )
3327   {
3328     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
3329     segDir.SetDirection( _normal );
3330     segLen = 0;
3331   }
3332   else
3333   {
3334     gp_Pnt pPrev = _pos[ iPrev ];
3335     if ( !_sWOL.IsNull() )
3336     {
3337       TopLoc_Location loc;
3338       if ( _sWOL.ShapeType() == TopAbs_EDGE )
3339       {
3340         double f,l;
3341         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3342         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
3343       }
3344       else
3345       {
3346         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3347         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
3348       }
3349       dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
3350     }
3351     segDir.SetLocation( pPrev );
3352     segDir.SetDirection( dir );
3353     segLen = dir.Modulus();
3354   }
3355
3356   return segDir;
3357 }
3358
3359 //================================================================================
3360 /*!
3361  * \brief Test intersection of the last segment with a given triangle
3362  *   using Moller-Trumbore algorithm
3363  * Intersection is detected if distance to intersection is less than _LayerEdge._len
3364  */
3365 //================================================================================
3366
3367 bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
3368                                const SMDS_MeshNode* n0,
3369                                const SMDS_MeshNode* n1,
3370                                const SMDS_MeshNode* n2,
3371                                double&              t,
3372                                const double&        EPSILON) const
3373 {
3374   //const double EPSILON = 1e-6;
3375
3376   gp_XYZ orig = lastSegment.Location().XYZ();
3377   gp_XYZ dir  = lastSegment.Direction().XYZ();
3378
3379   SMESH_TNodeXYZ vert0( n0 );
3380   SMESH_TNodeXYZ vert1( n1 );
3381   SMESH_TNodeXYZ vert2( n2 );
3382
3383   /* calculate distance from vert0 to ray origin */
3384   gp_XYZ tvec = orig - vert0;
3385
3386   if ( tvec * dir > EPSILON )
3387     // intersected face is at back side of the temporary face this _LayerEdge belongs to
3388     return false;
3389
3390   gp_XYZ edge1 = vert1 - vert0;
3391   gp_XYZ edge2 = vert2 - vert0;
3392
3393   /* begin calculating determinant - also used to calculate U parameter */
3394   gp_XYZ pvec = dir ^ edge2;
3395
3396   /* if determinant is near zero, ray lies in plane of triangle */
3397   double det = edge1 * pvec;
3398
3399   if (det > -EPSILON && det < EPSILON)
3400     return 0;
3401   double inv_det = 1.0 / det;
3402
3403   /* calculate U parameter and test bounds */
3404   double u = ( tvec * pvec ) * inv_det;
3405   if (u < 0.0 || u > 1.0)
3406     return 0;
3407
3408   /* prepare to test V parameter */
3409   gp_XYZ qvec = tvec ^ edge1;
3410
3411   /* calculate V parameter and test bounds */
3412   double v = (dir * qvec) * inv_det;
3413   if ( v < 0.0 || u + v > 1.0 )
3414     return 0;
3415
3416   /* calculate t, ray intersects triangle */
3417   t = (edge2 * qvec) * inv_det;
3418
3419   //   if (det < EPSILON)
3420   //     return false;
3421
3422   //   /* calculate distance from vert0 to ray origin */
3423   //   gp_XYZ tvec = orig - vert0;
3424
3425   //   /* calculate U parameter and test bounds */
3426   //   double u = tvec * pvec;
3427   //   if (u < 0.0 || u > det)
3428 //     return 0;
3429
3430 //   /* prepare to test V parameter */
3431 //   gp_XYZ qvec = tvec ^ edge1;
3432
3433 //   /* calculate V parameter and test bounds */
3434 //   double v = dir * qvec;
3435 //   if (v < 0.0 || u + v > det)
3436 //     return 0;
3437
3438 //   /* calculate t, scale parameters, ray intersects triangle */
3439 //   double t = edge2 * qvec;
3440 //   double inv_det = 1.0 / det;
3441 //   t *= inv_det;
3442 //   //u *= inv_det;
3443 //   //v *= inv_det;
3444
3445   return true;
3446 }
3447
3448 //================================================================================
3449 /*!
3450  * \brief Perform smooth of _LayerEdge's based on EDGE's
3451  *  \retval bool - true if node has been moved
3452  */
3453 //================================================================================
3454
3455 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3456                               const TopoDS_Face&    F,
3457                               SMESH_MesherHelper&   helper)
3458 {
3459   ASSERT( IsOnEdge() );
3460
3461   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3462   SMESH_TNodeXYZ oldPos( tgtNode );
3463   double dist01, distNewOld;
3464   
3465   SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3466   SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3467   dist01 = p0.Distance( _2neibors->_nodes[1] );
3468
3469   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3470   double lenDelta = 0;
3471   if ( _curvature )
3472   {
3473     //lenDelta = _curvature->lenDelta( _len );
3474     lenDelta = _curvature->lenDeltaByDist( dist01 );
3475     newPos.ChangeCoord() += _normal * lenDelta;
3476   }
3477
3478   distNewOld = newPos.Distance( oldPos );
3479
3480   if ( F.IsNull() )
3481   {
3482     if ( _2neibors->_plnNorm )
3483     {
3484       // put newPos on the plane defined by source node and _plnNorm
3485       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3486       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3487       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3488     }
3489     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3490     _pos.back() = newPos.XYZ();
3491   }
3492   else
3493   {
3494     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3495     gp_XY uv( Precision::Infinite(), 0 );
3496     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3497     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3498
3499     newPos = surface->Value( uv.X(), uv.Y() );
3500     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3501   }
3502
3503   if ( _curvature && lenDelta < 0 )
3504   {
3505     gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3506     _len -= prevPos.Distance( oldPos );
3507     _len += prevPos.Distance( newPos );
3508   }
3509   bool moved = distNewOld > dist01/50;
3510   //if ( moved )
3511   dumpMove( tgtNode ); // debug
3512
3513   return moved;
3514 }
3515
3516 //================================================================================
3517 /*!
3518  * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3519  *  \retval bool - true if _tgtNode has been moved
3520  */
3521 //================================================================================
3522
3523 bool _LayerEdge::Smooth(int& badNb)
3524 {
3525   if ( _simplices.size() < 2 )
3526     return false; // _LayerEdge inflated along EDGE or FACE
3527
3528   // compute new position for the last _pos
3529   gp_XYZ newPos (0,0,0);
3530   for ( size_t i = 0; i < _simplices.size(); ++i )
3531     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3532   newPos /= _simplices.size();
3533
3534   if ( _curvature )
3535     newPos += _normal * _curvature->lenDelta( _len );
3536
3537   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3538 //   if ( _cosin < -0.1)
3539 //   {
3540 //     // Avoid decreasing length of edge on concave surface
3541 //     //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3542 //     gp_Vec newMove( prevPos, newPos );
3543 //     newPos = _pos.back() + newMove.XYZ();
3544 //   }
3545 //   else if ( _cosin > 0.3 )
3546 //   {
3547 //     // Avoid increasing length of edge too much
3548
3549 //   }
3550   // count quality metrics (orientation) of tetras around _tgtNode
3551   int nbOkBefore = 0;
3552   SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3553   for ( size_t i = 0; i < _simplices.size(); ++i )
3554     nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3555
3556   int nbOkAfter = 0;
3557   for ( size_t i = 0; i < _simplices.size(); ++i )
3558     nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3559
3560   if ( nbOkAfter < nbOkBefore )
3561     return false;
3562
3563   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3564
3565   _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3566   _len += prevPos.Distance(newPos);
3567
3568   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3569   _pos.back() = newPos;
3570
3571   badNb += _simplices.size() - nbOkAfter;
3572
3573   dumpMove( n );
3574
3575   return true;
3576 }
3577
3578 //================================================================================
3579 /*!
3580  * \brief Add a new segment to _LayerEdge during inflation
3581  */
3582 //================================================================================
3583
3584 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3585 {
3586   if ( _len - len > -1e-6 )
3587   {
3588     _pos.push_back( _pos.back() );
3589     return;
3590   }
3591
3592   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3593   SMESH_TNodeXYZ oldXYZ( n );
3594   gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3595   n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3596
3597   _pos.push_back( nXYZ );
3598   _len = len;
3599   if ( !_sWOL.IsNull() )
3600   {
3601     double distXYZ[4];
3602     if ( _sWOL.ShapeType() == TopAbs_EDGE )
3603     {
3604       double u = Precision::Infinite(); // to force projection w/o distance check
3605       helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3606       _pos.back().SetCoord( u, 0, 0 );
3607       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3608       pos->SetUParameter( u );
3609     }
3610     else //  TopAbs_FACE
3611     {
3612       gp_XY uv( Precision::Infinite(), 0 );
3613       helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3614       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3615       SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3616       pos->SetUParameter( uv.X() );
3617       pos->SetVParameter( uv.Y() );
3618     }
3619     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3620   }
3621   dumpMove( n ); //debug
3622 }
3623
3624 //================================================================================
3625 /*!
3626  * \brief Remove last inflation step
3627  */
3628 //================================================================================
3629
3630 void _LayerEdge::InvalidateStep( int curStep )
3631 {
3632   if ( _pos.size() > curStep )
3633   {
3634     _pos.resize( curStep );
3635     gp_Pnt nXYZ = _pos.back();
3636     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3637     if ( !_sWOL.IsNull() )
3638     {
3639       TopLoc_Location loc;
3640       if ( _sWOL.ShapeType() == TopAbs_EDGE )
3641       {
3642         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3643         pos->SetUParameter( nXYZ.X() );
3644         double f,l;
3645         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3646         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3647       }
3648       else
3649       {
3650         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3651         pos->SetUParameter( nXYZ.X() );
3652         pos->SetVParameter( nXYZ.Y() );
3653         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3654         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3655       }
3656     }
3657     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3658     dumpMove( n );
3659   }
3660 }
3661
3662 //================================================================================
3663 /*!
3664  * \brief Create layers of prisms
3665  */
3666 //================================================================================
3667
3668 bool _ViscousBuilder::refine(_SolidData& data)
3669 {
3670   SMESH_MesherHelper helper( *_mesh );
3671   helper.SetSubShape( data._solid );
3672   helper.SetElementsOnShape(false);
3673
3674   Handle(Geom_Curve) curve;
3675   Handle(Geom_Surface) surface;
3676   TopoDS_Edge geomEdge;
3677   TopoDS_Face geomFace;
3678   TopoDS_Shape prevSWOL;
3679   TopLoc_Location loc;
3680   double f,l, u;
3681   gp_XY uv;
3682   bool isOnEdge;
3683   TGeomID prevBaseId = -1;
3684   TNode2Edge* n2eMap = 0;
3685   TNode2Edge::iterator n2e;
3686
3687   for ( size_t i = 0; i < data._edges.size(); ++i )
3688   {
3689     _LayerEdge& edge = *data._edges[i];
3690
3691     // get accumulated length of segments
3692     vector< double > segLen( edge._pos.size() );
3693     segLen[0] = 0.0;
3694     for ( size_t j = 1; j < edge._pos.size(); ++j )
3695       segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3696
3697     // allocate memory for new nodes if it is not yet refined
3698     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3699     if ( edge._nodes.size() == 2 )
3700     {
3701       edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3702       edge._nodes[1] = 0;
3703       edge._nodes.back() = tgtNode;
3704     }
3705     // get data of a shrink shape
3706     if ( !edge._sWOL.IsNull() && edge._sWOL != prevSWOL )
3707     {
3708       isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3709       if ( isOnEdge )
3710       {
3711         geomEdge = TopoDS::Edge( edge._sWOL );
3712         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
3713       }
3714       else
3715       {
3716         geomFace = TopoDS::Face( edge._sWOL );
3717         surface  = BRep_Tool::Surface( geomFace, loc );
3718       }
3719       prevSWOL = edge._sWOL;
3720     }
3721     // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
3722     const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
3723     if ( baseShapeId != prevBaseId )
3724     {
3725       map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
3726       n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
3727       prevBaseId = baseShapeId;
3728     }
3729     if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
3730     {
3731       _LayerEdge*  foundEdge = n2e->second;
3732       const gp_XYZ& foundPos = foundEdge->_pos.back();
3733       SMDS_PositionPtr lastPos = tgtNode->GetPosition();
3734       if ( isOnEdge )
3735       {
3736         SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
3737         epos->SetUParameter( foundPos.X() );
3738       }
3739       else
3740       {
3741         SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
3742         fpos->SetUParameter( foundPos.X() );
3743         fpos->SetVParameter( foundPos.Y() );
3744       }
3745     }
3746     // calculate height of the first layer
3747     double h0;
3748     const double T = segLen.back(); //data._hyp.GetTotalThickness();
3749     const double f = data._hyp->GetStretchFactor();
3750     const int    N = data._hyp->GetNumberLayers();
3751     const double fPowN = pow( f, N );
3752     if ( fPowN - 1 <= numeric_limits<double>::min() )
3753       h0 = T / N;
3754     else
3755       h0 = T * ( f - 1 )/( fPowN - 1 );
3756
3757     const double zeroLen = std::numeric_limits<double>::min();
3758
3759     // create intermediate nodes
3760     double hSum = 0, hi = h0/f;
3761     size_t iSeg = 1;
3762     for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
3763     {
3764       // compute an intermediate position
3765       hi *= f;
3766       hSum += hi;
3767       while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3768         ++iSeg;
3769       int iPrevSeg = iSeg-1;
3770       while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3771         --iPrevSeg;
3772       double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3773       gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3774
3775       SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3776       if ( !edge._sWOL.IsNull() )
3777       {
3778         // compute XYZ by parameters <pos>
3779         if ( isOnEdge )
3780         {
3781           u = pos.X();
3782           if ( !node )
3783             pos = curve->Value( u ).Transformed(loc);
3784         }
3785         else
3786         {
3787           uv.SetCoord( pos.X(), pos.Y() );
3788           if ( !node )
3789             pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3790         }
3791       }
3792       // create or update the node
3793       if ( !node )
3794       {
3795         node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3796         if ( !edge._sWOL.IsNull() )
3797         {
3798           if ( isOnEdge )
3799             getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3800           else
3801             getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3802         }
3803         else
3804         {
3805           getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3806         }
3807       }
3808       else
3809       {
3810         if ( !edge._sWOL.IsNull() )
3811         {
3812           // make average pos from new and current parameters
3813           if ( isOnEdge )
3814           {
3815             u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3816             pos = curve->Value( u ).Transformed(loc);
3817
3818             SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
3819             epos->SetUParameter( u );
3820           }
3821           else
3822           {
3823             uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3824             pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3825
3826             SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
3827             fpos->SetUParameter( uv.X() );
3828             fpos->SetVParameter( uv.Y() );
3829           }
3830         }
3831         node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3832       }
3833     }
3834   }
3835
3836   if ( !getMeshDS()->IsEmbeddedMode() )
3837     // Log node movement
3838     for ( size_t i = 0; i < data._edges.size(); ++i )
3839     {
3840       _LayerEdge& edge = *data._edges[i];
3841       SMESH_TNodeXYZ p ( edge._nodes.back() );
3842       getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3843     }
3844
3845   // TODO: make quadratic prisms and polyhedrons(?)
3846
3847   helper.SetElementsOnShape(true);
3848
3849   TopExp_Explorer exp( data._solid, TopAbs_FACE );
3850   for ( ; exp.More(); exp.Next() )
3851   {
3852     if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3853       continue;
3854     SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3855     SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3856     vector< vector<const SMDS_MeshNode*>* > nnVec;
3857     while ( fIt->more() )
3858     {
3859       const SMDS_MeshElement* face = fIt->next();
3860       int nbNodes = face->NbCornerNodes();
3861       nnVec.resize( nbNodes );
3862       SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3863       for ( int iN = 0; iN < nbNodes; ++iN )
3864       {
3865         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3866         nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3867       }
3868
3869       int nbZ = nnVec[0]->size();
3870       switch ( nbNodes )
3871       {
3872       case 3:
3873         for ( int iZ = 1; iZ < nbZ; ++iZ )
3874           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3875                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
3876         break;
3877       case 4:
3878         for ( int iZ = 1; iZ < nbZ; ++iZ )
3879           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3880                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3881                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
3882                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
3883         break;
3884       default:
3885         return error("Not supported type of element", data._index);
3886       }
3887     }
3888   }
3889   return true;
3890 }
3891
3892 //================================================================================
3893 /*!
3894  * \brief Shrink 2D mesh on faces to let space for inflated layers
3895  */
3896 //================================================================================
3897
3898 bool _ViscousBuilder::shrink()
3899 {
3900   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3901   // inflated along FACE or EDGE)
3902   map< TGeomID, _SolidData* > f2sdMap;
3903   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3904   {
3905     _SolidData& data = _sdVec[i];
3906     TopTools_MapOfShape FFMap;
3907     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3908     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3909       if ( s2s->second.ShapeType() == TopAbs_FACE )
3910       {
3911         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3912
3913         if ( FFMap.Add( (*s2s).second ))
3914           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3915           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3916           // by StdMeshers_QuadToTriaAdaptor
3917           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3918           {
3919             SMESH_ProxyMesh::SubMesh* proxySub =
3920               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3921             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3922             while ( fIt->more() )
3923               proxySub->AddElement( fIt->next() );
3924             // as a result 3D algo will use elements from proxySub and not from smDS
3925           }
3926       }
3927   }
3928
3929   SMESH_MesherHelper helper( *_mesh );
3930   helper.ToFixNodeParameters( true );
3931
3932   // EDGE's to shrink
3933   map< TGeomID, _Shrinker1D > e2shrMap;
3934
3935   // loop on FACES to srink mesh on
3936   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3937   for ( ; f2sd != f2sdMap.end(); ++f2sd )
3938   {
3939     _SolidData&     data = *f2sd->second;
3940     TNode2Edge&   n2eMap = data._n2eMap;
3941     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3942
3943     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3944
3945     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
3946     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3947
3948     helper.SetSubShape(F);
3949
3950     // ===========================
3951     // Prepare data for shrinking
3952     // ===========================
3953
3954     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3955     // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3956     vector < const SMDS_MeshNode* > smoothNodes;
3957     {
3958       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3959       while ( nIt->more() )
3960       {
3961         const SMDS_MeshNode* n = nIt->next();
3962         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3963           smoothNodes.push_back( n );
3964       }
3965     }
3966     // Find out face orientation
3967     double refSign = 1;
3968     const set<TGeomID> ignoreShapes;
3969     bool isOkUV;
3970     if ( !smoothNodes.empty() )
3971     {
3972       vector<_Simplex> simplices;
3973       getSimplices( smoothNodes[0], simplices, ignoreShapes );
3974       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3975       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3976       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3977       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3978         refSign = -1;
3979     }
3980
3981     // Find _LayerEdge's inflated along F
3982     vector< _LayerEdge* > lEdges;
3983     {
3984       SMESH_subMeshIteratorPtr subIt =
3985         sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3986       while ( subIt->more() )
3987       {
3988         SMESH_subMesh*     sub = subIt->next();
3989         SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3990         if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3991           continue;
3992         SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3993         while ( nIt->more() )
3994         {
3995           _LayerEdge* edge = n2eMap[ nIt->next() ];
3996           lEdges.push_back( edge );
3997           prepareEdgeToShrink( *edge, F, helper, smDS );
3998         }
3999       }
4000     }
4001
4002     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
4003     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4004     while ( fIt->more() )
4005       if ( const SMDS_MeshElement* f = fIt->next() )
4006         dumpChangeNodes( f );
4007
4008     // Replace source nodes by target nodes in mesh faces to shrink
4009     const SMDS_MeshNode* nodes[20];
4010     for ( size_t i = 0; i < lEdges.size(); ++i )
4011     {
4012       _LayerEdge& edge = *lEdges[i];
4013       const SMDS_MeshNode* srcNode = edge._nodes[0];
4014       const SMDS_MeshNode* tgtNode = edge._nodes.back();
4015       SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4016       while ( fIt->more() )
4017       {
4018         const SMDS_MeshElement* f = fIt->next();
4019         if ( !smDS->Contains( f ))
4020           continue;
4021         SMDS_NodeIteratorPtr nIt = f->nodeIterator();
4022         for ( int iN = 0; nIt->more(); ++iN )
4023         {
4024           const SMDS_MeshNode* n = nIt->next();
4025           nodes[iN] = ( n == srcNode ? tgtNode : n );
4026         }
4027         helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
4028       }
4029     }
4030
4031     // find out if a FACE is concave
4032     const bool isConcaveFace = isConcave( F, helper );
4033
4034     // Create _SmoothNode's on face F
4035     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
4036     {
4037       const bool sortSimplices = isConcaveFace;
4038       for ( size_t i = 0; i < smoothNodes.size(); ++i )
4039       {
4040         const SMDS_MeshNode* n = smoothNodes[i];
4041         nodesToSmooth[ i ]._node = n;
4042         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
4043         getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
4044         // fix up incorrect uv of nodes on the FACE
4045         helper.GetNodeUV( F, n, 0, &isOkUV);
4046         dumpMove( n );
4047       }
4048     }
4049     //if ( nodesToSmooth.empty() ) continue;
4050
4051     // Find EDGE's to shrink and set simpices to LayerEdge's
4052     set< _Shrinker1D* > eShri1D;
4053     {
4054       for ( size_t i = 0; i < lEdges.size(); ++i )
4055       {
4056         _LayerEdge* edge = lEdges[i];
4057         if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
4058         {
4059           TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
4060           _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
4061           eShri1D.insert( & srinker );
4062           srinker.AddEdge( edge, helper );
4063           VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
4064           // restore params of nodes on EGDE if the EDGE has been already
4065           // srinked while srinking another FACE
4066           srinker.RestoreParams();
4067         }
4068         getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
4069       }
4070     }
4071
4072     bool toFixTria = false; // to improve quality of trias by diagonal swap
4073     if ( isConcaveFace )
4074     {
4075       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
4076       if ( hasTria != hasQuad ) {
4077         toFixTria = hasTria;
4078       }
4079       else {
4080         set<int> nbNodesSet;
4081         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4082         while ( fIt->more() && nbNodesSet.size() < 2 )
4083           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
4084         toFixTria = ( *nbNodesSet.begin() == 3 );
4085       }
4086     }
4087
4088     // ==================
4089     // Perform shrinking
4090     // ==================
4091
4092     bool shrinked = true;
4093     int badNb, shriStep=0, smooStep=0;
4094     _SmoothNode::SmoothType smoothType
4095       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
4096     while ( shrinked )
4097     {
4098       shriStep++;
4099       // Move boundary nodes (actually just set new UV)
4100       // -----------------------------------------------
4101       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
4102       shrinked = false;
4103       for ( size_t i = 0; i < lEdges.size(); ++i )
4104       {
4105         shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
4106       }
4107       dumpFunctionEnd();
4108
4109       // Move nodes on EDGE's
4110       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
4111       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
4112       for ( ; shr != eShri1D.end(); ++shr )
4113         (*shr)->Compute( /*set3D=*/false, helper );
4114
4115       // Smoothing in 2D
4116       // -----------------
4117       int nbNoImpSteps = 0;
4118       bool       moved = true;
4119       badNb = 1;
4120       while (( nbNoImpSteps < 5 && badNb > 0) && moved)
4121       {
4122         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4123
4124         int oldBadNb = badNb;
4125         badNb = 0;
4126         moved = false;
4127         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4128         {
4129           moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4130                                             smoothType, /*set3D=*/isConcaveFace);
4131         }
4132         if ( badNb < oldBadNb )
4133           nbNoImpSteps = 0;
4134         else
4135           nbNoImpSteps++;
4136
4137         dumpFunctionEnd();
4138       }
4139       if ( badNb > 0 )
4140         return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
4141       if ( shriStep > 200 )
4142         return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
4143
4144       // Fix narrow triangles by swapping diagonals
4145       // ---------------------------------------
4146       if ( toFixTria )
4147       {
4148         set<const SMDS_MeshNode*> usedNodes;
4149         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
4150
4151         // update working data
4152         set<const SMDS_MeshNode*>::iterator n;
4153         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
4154         {
4155           n = usedNodes.find( nodesToSmooth[ i ]._node );
4156           if ( n != usedNodes.end())
4157           {
4158             getSimplices( nodesToSmooth[ i ]._node,
4159                           nodesToSmooth[ i ]._simplices,
4160                           ignoreShapes, NULL,
4161                           /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
4162             usedNodes.erase( n );
4163           }
4164         }
4165         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
4166         {
4167           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
4168           if ( n != usedNodes.end())
4169           {
4170             getSimplices( lEdges[i]->_nodes.back(),
4171                           lEdges[i]->_simplices,
4172                           ignoreShapes );
4173             usedNodes.erase( n );
4174           }
4175         }
4176       }
4177     } // while ( shrinked )
4178
4179     // No wrongly shaped faces remain; final smooth. Set node XYZ.
4180     bool isStructuredFixed = false;
4181     if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
4182       isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
4183     if ( !isStructuredFixed )
4184     {
4185       if ( isConcaveFace ) // fix narrow faces by swapping diagonals
4186         fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
4187
4188       for ( int st = 3; st; --st )
4189       {
4190         switch( st ) {
4191         case 1: smoothType = _SmoothNode::LAPLACIAN; break;
4192         case 2: smoothType = _SmoothNode::LAPLACIAN; break;
4193         case 3: smoothType = _SmoothNode::ANGULAR; break;
4194         }
4195         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4196         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4197         {
4198           nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4199                                    smoothType,/*set3D=*/st==1 );
4200         }
4201         dumpFunctionEnd();
4202       }
4203     }
4204     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
4205     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
4206
4207     if ( !getMeshDS()->IsEmbeddedMode() )
4208       // Log node movement
4209       for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4210       {
4211         SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
4212         getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
4213       }
4214
4215   } // loop on FACES to srink mesh on
4216
4217
4218   // Replace source nodes by target nodes in shrinked mesh edges
4219
4220   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
4221   for ( ; e2shr != e2shrMap.end(); ++e2shr )
4222     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
4223
4224   return true;
4225 }
4226
4227 //================================================================================
4228 /*!
4229  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
4230  */
4231 //================================================================================
4232
4233 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
4234                                            const TopoDS_Face&     F,
4235                                            SMESH_MesherHelper&    helper,
4236                                            const SMESHDS_SubMesh* faceSubMesh)
4237 {
4238   const SMDS_MeshNode* srcNode = edge._nodes[0];
4239   const SMDS_MeshNode* tgtNode = edge._nodes.back();
4240
4241   edge._pos.clear();
4242
4243   if ( edge._sWOL.ShapeType() == TopAbs_FACE )
4244   {
4245     gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4246     gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4247     gp_Vec2d uvDir( srcUV, tgtUV );
4248     double uvLen = uvDir.Magnitude();
4249     uvDir /= uvLen;
4250     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
4251     edge._len = uvLen;
4252
4253     // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4254     // vector<const SMDS_MeshElement*> faces;
4255     // multimap< double, const SMDS_MeshNode* > proj2node;
4256     // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4257     // while ( fIt->more() )
4258     // {
4259     //   const SMDS_MeshElement* f = fIt->next();
4260     //   if ( faceSubMesh->Contains( f ))
4261     //     faces.push_back( f );
4262     // }
4263     // for ( size_t i = 0; i < faces.size(); ++i )
4264     // {
4265     //   const int nbNodes = faces[i]->NbCornerNodes();
4266     //   for ( int j = 0; j < nbNodes; ++j )
4267     //   {
4268     //     const SMDS_MeshNode* n = faces[i]->GetNode(j);
4269     //     if ( n == srcNode ) continue;
4270     //     if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
4271     //          ( faces.size() > 1 || nbNodes > 3 ))
4272     //       continue;
4273     //     gp_Pnt2d uv = helper.GetNodeUV( F, n );
4274     //     gp_Vec2d uvDirN( srcUV, uv );
4275     //     double proj = uvDirN * uvDir;
4276     //     proj2node.insert( make_pair( proj, n ));
4277     //   }
4278     // }
4279
4280     // multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
4281     // const double       minProj = p2n->first;
4282     // const double projThreshold = 1.1 * uvLen;
4283     // if ( minProj > projThreshold )
4284     // {
4285     //   // tgtNode is located so that it does not make faces with wrong orientation
4286     //   return true;
4287     // }
4288     edge._pos.resize(1);
4289     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4290
4291     // store most risky nodes in _simplices
4292     // p2nEnd = proj2node.lower_bound( projThreshold );
4293     // int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
4294     // edge._simplices.resize( nbSimpl );
4295     // for ( int i = 0; i < nbSimpl; ++i )
4296     // {
4297     //   edge._simplices[i]._nPrev = p2n->second;
4298     //   if ( ++p2n != p2nEnd )
4299     //     edge._simplices[i]._nNext = p2n->second;
4300     // }
4301     // set UV of source node to target node
4302     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4303     pos->SetUParameter( srcUV.X() );
4304     pos->SetVParameter( srcUV.Y() );
4305   }
4306   else // _sWOL is TopAbs_EDGE
4307   {
4308     TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4309     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4310     if ( !edgeSM || edgeSM->NbElements() == 0 )
4311       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4312
4313     const SMDS_MeshNode* n2 = 0;
4314     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4315     while ( eIt->more() && !n2 )
4316     {
4317       const SMDS_MeshElement* e = eIt->next();
4318       if ( !edgeSM->Contains(e)) continue;
4319       n2 = e->GetNode( 0 );
4320       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
4321     }
4322     if ( !n2 )
4323       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4324
4325     double uSrc = helper.GetNodeU( E, srcNode, n2 );
4326     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
4327     double u2   = helper.GetNodeU( E, n2,      srcNode );
4328
4329     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
4330     {
4331       // tgtNode is located so that it does not make faces with wrong orientation
4332       return true;
4333     }
4334     edge._pos.resize(1);
4335     edge._pos[0].SetCoord( U_TGT, uTgt );
4336     edge._pos[0].SetCoord( U_SRC, uSrc );
4337     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
4338
4339     edge._simplices.resize( 1 );
4340     edge._simplices[0]._nPrev = n2;
4341
4342     // set UV of source node to target node
4343     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4344     pos->SetUParameter( uSrc );
4345   }
4346   return true;
4347
4348   //================================================================================
4349   /*!
4350    * \brief Compute positions (UV) to set to a node on edge moved during shrinking
4351    */
4352   //================================================================================
4353   
4354   // Compute UV to follow during shrinking
4355
4356 //   const SMDS_MeshNode* srcNode = edge._nodes[0];
4357 //   const SMDS_MeshNode* tgtNode = edge._nodes.back();
4358
4359 //   gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4360 //   gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4361 //   gp_Vec2d uvDir( srcUV, tgtUV );
4362 //   double uvLen = uvDir.Magnitude();
4363 //   uvDir /= uvLen;
4364
4365 //   // Select shrinking step such that not to make faces with wrong orientation.
4366 //   // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4367 //   const double minStepSize = uvLen / 20;
4368 //   double stepSize = uvLen;
4369 //   SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4370 //   while ( fIt->more() )
4371 //   {
4372 //     const SMDS_MeshElement* f = fIt->next();
4373 //     if ( !faceSubMesh->Contains( f )) continue;
4374 //     const int nbNodes = f->NbCornerNodes();
4375 //     for ( int i = 0; i < nbNodes; ++i )
4376 //     {
4377 //       const SMDS_MeshNode* n = f->GetNode(i);
4378 //       if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
4379 //         continue;
4380 //       gp_XY uv = helper.GetNodeUV( F, n );
4381 //       gp_Vec2d uvDirN( srcUV, uv );
4382 //       double proj = uvDirN * uvDir;
4383 //       if ( proj < stepSize && proj > minStepSize )
4384 //         stepSize = proj;
4385 //     }
4386 //   }
4387 //   stepSize *= 0.8;
4388
4389 //   const int nbSteps = ceil( uvLen / stepSize );
4390 //   gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
4391 //   gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
4392 //   edge._pos.resize( nbSteps );
4393 //   edge._pos[0] = tgtUV0;
4394 //   for ( int i = 1; i < nbSteps; ++i )
4395 //   {
4396 //     double r = i / double( nbSteps );
4397 //     edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
4398 //   }
4399 //   return true;
4400 }
4401
4402 //================================================================================
4403 /*!
4404  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
4405  */
4406 //================================================================================
4407
4408 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
4409                                   SMESH_MesherHelper&         helper,
4410                                   const bool                  is2D,
4411                                   const int                   step,
4412                                   set<const SMDS_MeshNode*> * involvedNodes)
4413 {
4414   SMESH::Controls::AspectRatio qualifier;
4415   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
4416   const double maxAspectRatio = is2D ? 4. : 2;
4417   NodeCoordHelper xyz( F, helper, is2D );
4418
4419   // find bad triangles
4420
4421   vector< const SMDS_MeshElement* > badTrias;
4422   vector< double >                  badAspects;
4423   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
4424   SMDS_ElemIteratorPtr fIt = sm->GetElements();
4425   while ( fIt->more() )
4426   {
4427     const SMDS_MeshElement * f = fIt->next();
4428     if ( f->NbCornerNodes() != 3 ) continue;
4429     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
4430     double aspect = qualifier.GetValue( points );
4431     if ( aspect > maxAspectRatio )
4432     {
4433       badTrias.push_back( f );
4434       badAspects.push_back( aspect );
4435     }
4436   }
4437   if ( step == 1 )
4438   {
4439     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4440     SMDS_ElemIteratorPtr fIt = sm->GetElements();
4441     while ( fIt->more() )
4442     {
4443       const SMDS_MeshElement * f = fIt->next();
4444       if ( f->NbCornerNodes() == 3 )
4445         dumpChangeNodes( f );
4446     }
4447     dumpFunctionEnd();
4448   }
4449   if ( badTrias.empty() )
4450     return;
4451
4452   // find couples of faces to swap diagonal
4453
4454   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
4455   vector< T2Trias > triaCouples; 
4456
4457   TIDSortedElemSet involvedFaces, emptySet;
4458   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
4459   {
4460     T2Trias trias    [3];
4461     double  aspRatio [3];
4462     int i1, i2, i3;
4463
4464     if ( !involvedFaces.insert( badTrias[iTia] ).second )
4465       continue;
4466     for ( int iP = 0; iP < 3; ++iP )
4467       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
4468
4469     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
4470     int bestCouple = -1;
4471     for ( int iSide = 0; iSide < 3; ++iSide )
4472     {
4473       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
4474       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
4475       trias [iSide].first  = badTrias[iTia];
4476       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
4477                                                              & i1, & i2 );
4478       if (( ! trias[iSide].second ) ||
4479           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
4480           ( ! sm->Contains( trias[iSide].second )))
4481         continue;
4482
4483       // aspect ratio of an adjacent tria
4484       for ( int iP = 0; iP < 3; ++iP )
4485         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
4486       double aspectInit = qualifier.GetValue( points2 );
4487
4488       // arrange nodes as after diag-swaping
4489       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
4490         i3 = helper.WrapIndex( i1-1, 3 );
4491       else
4492         i3 = helper.WrapIndex( i1+1, 3 );
4493       points1 = points;
4494       points1( 1+ iSide ) = points2( 1+ i3 );
4495       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
4496
4497       // aspect ratio after diag-swaping
4498       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
4499       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
4500         continue;
4501
4502       // prevent inversion of a triangle
4503       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
4504       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
4505       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
4506         continue;
4507
4508       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
4509         bestCouple = iSide;
4510     }
4511
4512     if ( bestCouple >= 0 )
4513     {
4514       triaCouples.push_back( trias[bestCouple] );
4515       involvedFaces.insert ( trias[bestCouple].second );
4516     }
4517     else
4518     {
4519       involvedFaces.erase( badTrias[iTia] );
4520     }
4521   }
4522   if ( triaCouples.empty() )
4523     return;
4524
4525   // swap diagonals
4526
4527   SMESH_MeshEditor editor( helper.GetMesh() );
4528   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4529   for ( size_t i = 0; i < triaCouples.size(); ++i )
4530   {
4531     dumpChangeNodes( triaCouples[i].first );
4532     dumpChangeNodes( triaCouples[i].second );
4533     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4534   }
4535
4536   if ( involvedNodes )
4537     for ( size_t i = 0; i < triaCouples.size(); ++i )
4538     {
4539       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
4540                              triaCouples[i].first->end_nodes() );
4541       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
4542                              triaCouples[i].second->end_nodes() );
4543     }
4544
4545   // just for debug dump resulting triangles
4546   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4547   for ( size_t i = 0; i < triaCouples.size(); ++i )
4548   {
4549     dumpChangeNodes( triaCouples[i].first );
4550     dumpChangeNodes( triaCouples[i].second );
4551   }
4552 }
4553
4554 //================================================================================
4555 /*!
4556  * \brief Move target node to it's final position on the FACE during shrinking
4557  */
4558 //================================================================================
4559
4560 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4561                                  const TopoDS_Face&    F,
4562                                  SMESH_MesherHelper&   helper )
4563 {
4564   if ( _pos.empty() )
4565     return false; // already at the target position
4566
4567   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4568
4569   if ( _sWOL.ShapeType() == TopAbs_FACE )
4570   {
4571     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
4572     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
4573     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4574     const double uvLen = tgtUV.Distance( curUV );
4575     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
4576
4577     // Select shrinking step such that not to make faces with wrong orientation.
4578     double stepSize = uvLen;
4579     for ( size_t i = 0; i < _simplices.size(); ++i )
4580     {
4581       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
4582       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
4583       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
4584       gp_XY dirN = uvN2 - uvN1;
4585       double det = uvDir.Crossed( dirN );
4586       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
4587       gp_XY dirN2Cur = curUV - uvN1;
4588       double step = dirN.Crossed( dirN2Cur ) / det;
4589       if ( step > 0 )
4590         stepSize = Min( step, stepSize );
4591     }
4592     gp_Pnt2d newUV;
4593     if ( uvLen - stepSize < _len / 200. )
4594     {
4595       newUV = tgtUV;
4596       _pos.clear();
4597     }
4598     else if ( stepSize > 0 )
4599     {
4600       newUV = curUV + uvDir.XY() * stepSize * kSafe;
4601     }
4602     else
4603     {
4604       return true;
4605     }
4606     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4607     pos->SetUParameter( newUV.X() );
4608     pos->SetVParameter( newUV.Y() );
4609
4610 #ifdef __myDEBUG
4611     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4612     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4613     dumpMove( tgtNode );
4614 #endif
4615   }
4616   else // _sWOL is TopAbs_EDGE
4617   {
4618     TopoDS_Edge E = TopoDS::Edge( _sWOL );
4619     const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4620     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4621
4622     const double u2 = helper.GetNodeU( E, n2, tgtNode );
4623     const double uSrc   = _pos[0].Coord( U_SRC );
4624     const double lenTgt = _pos[0].Coord( LEN_TGT );
4625
4626     double newU = _pos[0].Coord( U_TGT );
4627     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
4628     {
4629       _pos.clear();
4630     }
4631     else
4632     {
4633       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
4634     }
4635     tgtPos->SetUParameter( newU );
4636 #ifdef __myDEBUG
4637     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4638     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4639     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4640     dumpMove( tgtNode );
4641 #endif
4642   }
4643   return true;
4644 }
4645
4646 //================================================================================
4647 /*!
4648  * \brief Perform smooth on the FACE
4649  *  \retval bool - true if the node has been moved
4650  */
4651 //================================================================================
4652
4653 bool _SmoothNode::Smooth(int&                  badNb,
4654                          Handle(Geom_Surface)& surface,
4655                          SMESH_MesherHelper&   helper,
4656                          const double          refSign,
4657                          SmoothType            how,
4658                          bool                  set3D)
4659 {
4660   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4661
4662   // get uv of surrounding nodes
4663   vector<gp_XY> uv( _simplices.size() );
4664   for ( size_t i = 0; i < _simplices.size(); ++i )
4665     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4666
4667   // compute new UV for the node
4668   gp_XY newPos (0,0);
4669   if ( how == TFI && _simplices.size() == 4 )
4670   {
4671     gp_XY corners[4];
4672     for ( size_t i = 0; i < _simplices.size(); ++i )
4673       if ( _simplices[i]._nOpp )
4674         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
4675       else
4676         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
4677
4678     newPos = helper.calcTFI ( 0.5, 0.5,
4679                               corners[0], corners[1], corners[2], corners[3],
4680                               uv[1], uv[2], uv[3], uv[0] );
4681   }
4682   else if ( how == ANGULAR )
4683   {
4684     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
4685   }
4686   else if ( how == CENTROIDAL && _simplices.size() > 3 )
4687   {
4688     // average centers of diagonals wieghted with their reciprocal lengths
4689     if ( _simplices.size() == 4 )
4690     {
4691       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4692       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4693       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4694     }
4695     else
4696     {
4697       double sumWeight = 0;
4698       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4699       for ( int i = 0; i < nb; ++i )
4700       {
4701         int iFrom = i + 2;
4702         int iTo   = i + _simplices.size() - 1;
4703         for ( int j = iFrom; j < iTo; ++j )
4704         {
4705           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4706           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4707           sumWeight += w;
4708           newPos += w * ( uv[i]+uv[i2] );
4709         }
4710       }
4711       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
4712     }
4713   }
4714   else
4715   {
4716     // Laplacian smooth
4717     for ( size_t i = 0; i < _simplices.size(); ++i )
4718       newPos += uv[i];
4719     newPos /= _simplices.size();
4720   }
4721
4722   // count quality metrics (orientation) of triangles around the node
4723   int nbOkBefore = 0;
4724   gp_XY tgtUV = helper.GetNodeUV( face, _node );
4725   for ( size_t i = 0; i < _simplices.size(); ++i )
4726     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4727
4728   int nbOkAfter = 0;
4729   for ( size_t i = 0; i < _simplices.size(); ++i )
4730     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4731
4732   if ( nbOkAfter < nbOkBefore )
4733   {
4734     badNb += _simplices.size() - nbOkBefore;
4735     return false;
4736   }
4737
4738   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4739   pos->SetUParameter( newPos.X() );
4740   pos->SetVParameter( newPos.Y() );
4741
4742 #ifdef __myDEBUG
4743   set3D = true;
4744 #endif
4745   if ( set3D )
4746   {
4747     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4748     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4749     dumpMove( _node );
4750   }
4751
4752   badNb += _simplices.size() - nbOkAfter;
4753   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4754 }
4755
4756 //================================================================================
4757 /*!
4758  * \brief Computes new UV using angle based smoothing technic
4759  */
4760 //================================================================================
4761
4762 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
4763                                      const gp_XY&   uvToFix,
4764                                      const double   refSign)
4765 {
4766   uv.push_back( uv.front() );
4767
4768   vector< gp_XY >  edgeDir ( uv.size() );
4769   vector< double > edgeSize( uv.size() );
4770   for ( size_t i = 1; i < edgeDir.size(); ++i )
4771   {
4772     edgeDir [i-1] = uv[i] - uv[i-1];
4773     edgeSize[i-1] = edgeDir[i-1].Modulus();
4774     if ( edgeSize[i-1] < numeric_limits<double>::min() )
4775       edgeDir[i-1].SetX( 100 );
4776     else
4777       edgeDir[i-1] /= edgeSize[i-1] * refSign;
4778   }
4779   edgeDir.back()  = edgeDir.front();
4780   edgeSize.back() = edgeSize.front();
4781
4782   gp_XY  newPos(0,0);
4783   int    nbEdges = 0;
4784   double sumSize = 0;
4785   for ( size_t i = 1; i < edgeDir.size(); ++i )
4786   {
4787     if ( edgeDir[i-1].X() > 1. ) continue;
4788     int i1 = i-1;
4789     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
4790     if ( i == edgeDir.size() ) break;
4791     gp_XY p = uv[i];
4792     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
4793     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
4794     gp_XY bisec = norm1 + norm2;
4795     double bisecSize = bisec.Modulus();
4796     if ( bisecSize < numeric_limits<double>::min() )
4797     {
4798       bisec = -edgeDir[i1] + edgeDir[i];
4799       bisecSize = bisec.Modulus();
4800     }
4801     bisec /= bisecSize;
4802
4803     gp_XY  dirToN  = uvToFix - p;
4804     double distToN = dirToN.Modulus();
4805     if ( bisec * dirToN < 0 )
4806       distToN = -distToN;
4807
4808     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
4809     ++nbEdges;
4810     sumSize += edgeSize[i1] + edgeSize[i];
4811   }
4812   newPos /= /*nbEdges * */sumSize;
4813   return newPos;
4814 }
4815
4816 //================================================================================
4817 /*!
4818  * \brief Delete _SolidData
4819  */
4820 //================================================================================
4821
4822 _SolidData::~_SolidData()
4823 {
4824   for ( size_t i = 0; i < _edges.size(); ++i )
4825   {
4826     if ( _edges[i] && _edges[i]->_2neibors )
4827       delete _edges[i]->_2neibors;
4828     delete _edges[i];
4829   }
4830   _edges.clear();
4831 }
4832 //================================================================================
4833 /*!
4834  * \brief Add a _LayerEdge inflated along the EDGE
4835  */
4836 //================================================================================
4837
4838 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4839 {
4840   // init
4841   if ( _nodes.empty() )
4842   {
4843     _edges[0] = _edges[1] = 0;
4844     _done = false;
4845   }
4846   // check _LayerEdge
4847   if ( e == _edges[0] || e == _edges[1] )
4848     return;
4849   if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4850     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4851   if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4852     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4853
4854   // store _LayerEdge
4855   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4856   double f,l;
4857   BRep_Tool::Range( E, f,l );
4858   double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4859   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4860
4861   // Update _nodes
4862
4863   const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4864   const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4865
4866   if ( _nodes.empty() )
4867   {
4868     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4869     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4870       return;
4871     TopLoc_Location loc;
4872     Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4873     GeomAdaptor_Curve aCurve(C, f,l);
4874     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4875
4876     int nbExpectNodes = eSubMesh->NbNodes();
4877     _initU  .reserve( nbExpectNodes );
4878     _normPar.reserve( nbExpectNodes );
4879     _nodes  .reserve( nbExpectNodes );
4880     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4881     while ( nIt->more() )
4882     {
4883       const SMDS_MeshNode* node = nIt->next();
4884       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4885            node == tgtNode0 || node == tgtNode1 )
4886         continue; // refinement nodes
4887       _nodes.push_back( node );
4888       _initU.push_back( helper.GetNodeU( E, node ));
4889       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4890       _normPar.push_back(  len / totLen );
4891     }
4892   }
4893   else
4894   {
4895     // remove target node of the _LayerEdge from _nodes
4896     int nbFound = 0;
4897     for ( size_t i = 0; i < _nodes.size(); ++i )
4898       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4899         _nodes[i] = 0, nbFound++;
4900     if ( nbFound == _nodes.size() )
4901       _nodes.clear();
4902   }
4903 }
4904
4905 //================================================================================
4906 /*!
4907  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4908  */
4909 //================================================================================
4910
4911 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4912 {
4913   if ( _done || _nodes.empty())
4914     return;
4915   const _LayerEdge* e = _edges[0];
4916   if ( !e ) e = _edges[1];
4917   if ( !e ) return;
4918
4919   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4920             ( !_edges[1] || _edges[1]->_pos.empty() ));
4921
4922   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4923   double f,l;
4924   if ( set3D || _done )
4925   {
4926     Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4927     GeomAdaptor_Curve aCurve(C, f,l);
4928
4929     if ( _edges[0] )
4930       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4931     if ( _edges[1] )
4932       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4933     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4934
4935     for ( size_t i = 0; i < _nodes.size(); ++i )
4936     {
4937       if ( !_nodes[i] ) continue;
4938       double len = totLen * _normPar[i];
4939       GCPnts_AbscissaPoint discret( aCurve, len, f );
4940       if ( !discret.IsDone() )
4941         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4942       double u = discret.Parameter();
4943       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4944       pos->SetUParameter( u );
4945       gp_Pnt p = C->Value( u );
4946       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4947     }
4948   }
4949   else
4950   {
4951     BRep_Tool::Range( E, f,l );
4952     if ( _edges[0] )
4953       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4954     if ( _edges[1] )
4955       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4956     
4957     for ( size_t i = 0; i < _nodes.size(); ++i )
4958     {
4959       if ( !_nodes[i] ) continue;
4960       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4961       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4962       pos->SetUParameter( u );
4963     }
4964   }
4965 }
4966
4967 //================================================================================
4968 /*!
4969  * \brief Restore initial parameters of nodes on EDGE
4970  */
4971 //================================================================================
4972
4973 void _Shrinker1D::RestoreParams()
4974 {
4975   if ( _done )
4976     for ( size_t i = 0; i < _nodes.size(); ++i )
4977     {
4978       if ( !_nodes[i] ) continue;
4979       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4980       pos->SetUParameter( _initU[i] );
4981     }
4982   _done = false;
4983 }
4984
4985 //================================================================================
4986 /*!
4987  * \brief Replace source nodes by target nodes in shrinked mesh edges
4988  */
4989 //================================================================================
4990
4991 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4992 {
4993   const SMDS_MeshNode* nodes[3];
4994   for ( int i = 0; i < 2; ++i )
4995   {
4996     if ( !_edges[i] ) continue;
4997
4998     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4999     if ( !eSubMesh ) return;
5000     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
5001     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
5002     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
5003     while ( eIt->more() )
5004     {
5005       const SMDS_MeshElement* e = eIt->next();
5006       if ( !eSubMesh->Contains( e ))
5007           continue;
5008       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5009       for ( int iN = 0; iN < e->NbNodes(); ++iN )
5010       {
5011         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
5012         nodes[iN] = ( n == srcNode ? tgtNode : n );
5013       }
5014       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
5015     }
5016   }
5017 }
5018
5019 //================================================================================
5020 /*!
5021  * \brief Creates 2D and 1D elements on boundaries of new prisms
5022  */
5023 //================================================================================
5024
5025 bool _ViscousBuilder::addBoundaryElements()
5026 {
5027   SMESH_MesherHelper helper( *_mesh );
5028
5029   for ( size_t i = 0; i < _sdVec.size(); ++i )
5030   {
5031     _SolidData& data = _sdVec[i];
5032     TopTools_IndexedMapOfShape geomEdges;
5033     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
5034     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
5035     {
5036       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
5037
5038       // Get _LayerEdge's based on E
5039
5040       map< double, const SMDS_MeshNode* > u2nodes;
5041       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
5042         continue;
5043
5044       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
5045       TNode2Edge & n2eMap = data._n2eMap;
5046       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
5047       {
5048         //check if 2D elements are needed on E
5049         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
5050         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
5051         ledges.push_back( n2e->second );
5052         u2n++;
5053         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
5054           continue; // no layers on E
5055         ledges.push_back( n2eMap[ u2n->second ]);
5056
5057         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
5058         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
5059         int nbSharedPyram = 0;
5060         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
5061         while ( vIt->more() )
5062         {
5063           const SMDS_MeshElement* v = vIt->next();
5064           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
5065         }
5066         if ( nbSharedPyram > 1 )
5067           continue; // not free border of the pyramid
5068
5069         if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
5070                                     ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
5071           continue; // faces already created
5072       }
5073       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
5074         ledges.push_back( n2eMap[ u2n->second ]);
5075
5076       // Find out orientation and type of face to create
5077
5078       bool reverse = false, isOnFace;
5079       
5080       map< TGeomID, TopoDS_Shape >::iterator e2f =
5081         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
5082       TopoDS_Shape F;
5083       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
5084       {
5085         F = e2f->second.Oriented( TopAbs_FORWARD );
5086         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
5087         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
5088           reverse = !reverse, F.Reverse();
5089         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
5090           reverse = !reverse;
5091       }
5092       else
5093       {
5094         // find FACE with layers sharing E
5095         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
5096         while ( fIt->more() && F.IsNull() )
5097         {
5098           const TopoDS_Shape* pF = fIt->next();
5099           if ( helper.IsSubShape( *pF, data._solid) &&
5100                !data._ignoreFaceIds.count( e2f->first ))
5101             F = *pF;
5102         }
5103       }
5104       // Find the sub-mesh to add new faces
5105       SMESHDS_SubMesh* sm = 0;
5106       if ( isOnFace )
5107         sm = getMeshDS()->MeshElements( F );
5108       else
5109         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
5110       if ( !sm )
5111         return error("error in addBoundaryElements()", data._index);
5112
5113       // Make faces
5114       const int dj1 = reverse ? 0 : 1;
5115       const int dj2 = reverse ? 1 : 0;
5116       for ( size_t j = 1; j < ledges.size(); ++j )
5117       {
5118         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
5119         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
5120         if ( isOnFace )
5121           for ( size_t z = 1; z < nn1.size(); ++z )
5122             sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
5123         else
5124           for ( size_t z = 1; z < nn1.size(); ++z )
5125             sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
5126       }
5127
5128       // Make edges
5129       for ( int isFirst = 0; isFirst < 2; ++isFirst )
5130       {
5131         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
5132         if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
5133         {
5134           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
5135           if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
5136             continue;
5137           helper.SetSubShape( edge->_sWOL );
5138           helper.SetElementsOnShape( true );
5139           for ( size_t z = 1; z < nn.size(); ++z )
5140             helper.AddEdge( nn[z-1], nn[z] );
5141         }
5142       }
5143     }
5144   }
5145
5146   return true;
5147 }