Salome HOME
4872d5c9b46f9d747194ab00b3ed61f857377974
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 //  Copyright (C) 2007-2011  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.
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_Gen.hxx"
36 #include "SMESH_Group.hxx"
37 #include "SMESH_Mesh.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_subMesh.hxx"
40 #include "SMESH_subMeshEventListener.hxx"
41 #include "SMESH_ProxyMesh.hxx"
42
43 #include "utilities.h"
44
45 #include <BRep_Tool.hxx>
46 #include <GCPnts_AbscissaPoint.hxx>
47 #include <GeomAdaptor_Curve.hxx>
48 #include <Geom_Curve.hxx>
49 #include <Precision.hxx>
50 #include <TopExp.hxx>
51 #include <TopExp_Explorer.hxx>
52 #include <TopTools_IndexedMapOfShape.hxx>
53 #include <TopTools_MapOfShape.hxx>
54 #include <TopoDS.hxx>
55 #include <TopoDS_Edge.hxx>
56 #include <TopoDS_Face.hxx>
57 #include <TopoDS_Vertex.hxx>
58 #include <gp_Ax1.hxx>
59 #include <gp_Vec.hxx>
60 #include <gp_XY.hxx>
61 #include <gp_XYZ.hxx>
62
63 #include <list>
64 #include <string>
65 #include <math.h>
66 #include <limits>
67
68 //#define __myDEBUG
69
70 using namespace std;
71
72 //================================================================================
73 namespace VISCOUS
74 {
75   typedef int TGeomID;
76
77   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
78
79   /*!
80    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
81    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
82    */
83   struct _MeshOfSolid : public SMESH_ProxyMesh,
84                         public SMESH_subMeshEventListenerData
85   {
86     bool _n2nMapComputed;
87
88     _MeshOfSolid( SMESH_Mesh* mesh)
89       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
90     {
91       SMESH_ProxyMesh::setMesh( *mesh );
92     }
93
94     // returns submesh for a geom face
95     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
96     {
97       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
98       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
99     }
100     void setNode2Node(const SMDS_MeshNode*                 srcNode,
101                       const SMDS_MeshNode*                 proxyNode,
102                       const SMESH_ProxyMesh::SubMesh* subMesh)
103     {
104       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
105     }
106   };
107   //--------------------------------------------------------------------------------
108   /*!
109    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
110    * It is used to clear an inferior dim sub-mesh modified by viscous layers
111    */
112   class _SrinkShapeListener : SMESH_subMeshEventListener
113   {
114     _SrinkShapeListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
115     static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
116   public:
117     virtual void ProcessEvent(const int                       event,
118                               const int                       eventType,
119                               SMESH_subMesh*                  solidSM,
120                               SMESH_subMeshEventListenerData* data,
121                               const SMESH_Hypothesis*         hyp)
122     {
123       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
124       {
125         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
126       }
127     }
128     static void ToClearSubMeshWithSolid( SMESH_subMesh*      sm,
129                                          const TopoDS_Shape& solid)
130     {
131       SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
132       SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
133       if ( data )
134       {
135         if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
136              data->mySubMeshes.end())
137           data->mySubMeshes.push_back( sm );
138       }
139       else
140       {
141         data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
142         sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
143       }
144     }
145   };
146   //--------------------------------------------------------------------------------
147   /*!
148    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
149    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
150    * delete the data as soon as it has been used
151    */
152   class _ViscousListener : SMESH_subMeshEventListener
153   {
154     _ViscousListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
155     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
156   public:
157     virtual void ProcessEvent(const int                       event,
158                               const int                       eventType,
159                               SMESH_subMesh*                  subMesh,
160                               SMESH_subMeshEventListenerData* data,
161                               const SMESH_Hypothesis*         hyp)
162     {
163       if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
164       {
165         // delete SMESH_ProxyMesh containing temporary faces
166         subMesh->DeleteEventListener( this );
167       }
168     }
169     // Finds or creates proxy mesh of the solid
170     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
171                                       const TopoDS_Shape& solid,
172                                       bool                toCreate=false)
173     {
174       if ( !mesh ) return 0;
175       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
176       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
177       if ( !data && toCreate )
178       {
179         data = new _MeshOfSolid(mesh);
180         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
181         sm->SetEventListener( Get(), data, sm );
182       }
183       return data;
184     }
185     // Removes proxy mesh of the solid
186     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
187     {
188       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
189     }
190   };
191   
192   //--------------------------------------------------------------------------------
193   /*!
194    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
195    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
196    * The class is used to check validity of face or volumes around a smoothed node;
197    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
198    */
199   struct _Simplex
200   {
201     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
202     _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
203       : _nPrev(nPrev), _nNext(nNext) {}
204     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
205     {
206       const double M[3][3] =
207         {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
208          { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
209          { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
210       double determinant = ( + M[0][0]*M[1][1]*M[2][2]
211                              + M[0][1]*M[1][2]*M[2][0]
212                              + M[0][2]*M[1][0]*M[2][1]
213                              - M[0][0]*M[1][2]*M[2][1]
214                              - M[0][1]*M[1][0]*M[2][2]
215                              - M[0][2]*M[1][1]*M[2][0]);
216       return determinant > 1e-100;
217     }
218     bool IsForward(const gp_XY&        tgtUV,
219                    const TopoDS_Face&  face,
220                    SMESH_MesherHelper& helper,
221                    const double        refSign) const
222     {
223       gp_XY prevUV = helper.GetNodeUV( face, _nPrev );
224       gp_XY nextUV = helper.GetNodeUV( face, _nNext );
225       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
226       double d = v1 ^ v2;
227       return d*refSign > 1e-100;
228     }
229   };
230   //--------------------------------------------------------------------------------
231   /*!
232    * Structure used to take into account surface curvature while smoothing
233    */
234   struct _Curvature
235   {
236     double _r; // radius
237     double _k; // factor to correct node smoothed position
238   public:
239     static _Curvature* New( double avgNormProj, double avgDist )
240     {
241       _Curvature* c = 0;
242       if ( fabs( avgNormProj / avgDist ) > 1./200 )
243       {
244         c = new _Curvature;
245         c->_r = avgDist * avgDist / avgNormProj;
246         c->_k = avgDist * avgDist / c->_r / c->_r;
247         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
248       }
249       return c;
250     }
251     double lenDelta(double len) const { return _k * ( _r + len ); }
252   };
253   struct _LayerEdge;
254   //--------------------------------------------------------------------------------
255   /*!
256    * Structure used to smooth a _LayerEdge (master) based on an EDGE.
257    */
258   struct _2NearEdges
259   {
260     // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
261     const SMDS_MeshNode* _nodes[2];
262     // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
263     //gp_XYZ               _vec[2];
264     double               _wgt[2]; // weights of _nodes
265     _LayerEdge*          _edges[2];
266
267      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
268     gp_XYZ*              _plnNorm;
269
270     _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
271   };
272   //--------------------------------------------------------------------------------
273   /*!
274    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
275    * and a node of the most internal layer (_nodes.back())
276    */
277   struct _LayerEdge
278   {
279     vector< const SMDS_MeshNode*> _nodes;
280
281     gp_XYZ              _normal; // to solid surface
282     vector<gp_XYZ>      _pos; // points computed during inflation
283     double              _len; // length achived with the last step
284     double              _cosin; // of angle (_normal ^ surface)
285     double              _lenFactor; // to compute _len taking _cosin into account
286
287     // face or edge w/o layer along or near which _LayerEdge is inflated
288     TopoDS_Shape        _sWOL;
289     // simplices connected to the source node (_nodes[0]);
290     // used for smoothing and quality check of _LayerEdge's based on the FACE
291     vector<_Simplex>    _simplices;
292     // data for smoothing of _LayerEdge's based on the EDGE
293     _2NearEdges*        _2neibors;
294
295     _Curvature*         _curvature;
296     // TODO:: detele _Curvature, _plnNorm
297
298     void SetNewLength( double len, SMESH_MesherHelper& helper );
299     bool SetNewLength2d( Handle(Geom_Surface)& surface,
300                          const TopoDS_Face&    F,
301                          SMESH_MesherHelper&   helper );
302     void SetDataByNeighbors( const SMDS_MeshNode* n1,
303                              const SMDS_MeshNode* n2,
304                              SMESH_MesherHelper&  helper);
305     void InvalidateStep( int curStep );
306     bool Smooth(int& badNb);
307     bool SmoothOnEdge(Handle(Geom_Surface)& surface,
308                       const TopoDS_Face&    F,
309                       SMESH_MesherHelper&   helper);
310     bool FindIntersection( SMESH_ElementSearcher&   searcher,
311                            double &                 distance,
312                            const double&            epsilon,
313                            const SMDS_MeshElement** face = 0);
314     bool SegTriaInter( const gp_Ax1&        lastSegment,
315                        const SMDS_MeshNode* n0,
316                        const SMDS_MeshNode* n1,
317                        const SMDS_MeshNode* n2,
318                        double&              dist,
319                        const double&        epsilon) const;
320     gp_Ax1 LastSegment(double& segLen) const;
321     bool IsOnEdge() const { return _2neibors; }
322     void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
323     void SetCosin( double cosin );
324   };
325   struct _LayerEdgeCmp
326   {
327     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
328     {
329       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
330       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
331     }
332   };
333   //--------------------------------------------------------------------------------
334
335   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
336   
337   //--------------------------------------------------------------------------------
338   /*!
339    * \brief Data of a SOLID
340    */
341   struct _SolidData
342   {
343     TopoDS_Shape                    _solid;
344     const StdMeshers_ViscousLayers* _hyp;
345     _MeshOfSolid*                   _proxyMesh;
346     set<TGeomID>                    _reversedFaceIds;
347
348     double                          _stepSize, _stepSizeCoeff;
349     const SMDS_MeshNode*            _stepSizeNodes[2];
350
351     TNode2Edge                      _n2eMap;
352     // edges of _n2eMap. We keep same data in two containers because
353     // iteration over the map is 5 time longer than over the vector
354     vector< _LayerEdge* >           _edges;
355
356     // key: an id of shape (EDGE or VERTEX) shared by a FACE with
357     // layers and a FACE w/o layers
358     // value: the shape (FACE or EDGE) to shrink mesh on.
359     // _LayerEdge's basing on nodes on key shape are inflated along the value shape
360     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
361
362     // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
363     set< TGeomID >                   _noShrinkFaces;
364
365     // end index in _edges of _LayerEdge's based on EDGE (map key) to
366     // FACE (maybe NULL) they are inflated along
367     //map< int, TopoDS_Face >          _endEdge2Face;
368
369     // end indices in _edges of _LayerEdge on one shape to smooth
370     vector< int >                    _endEdgeToSmooth;
371
372     double                           _epsilon; // precision for SegTriaInter()
373
374     int                              _index; // for debug
375
376     _SolidData(const TopoDS_Shape&             s=TopoDS_Shape(),
377                const StdMeshers_ViscousLayers* h=0,
378                _MeshOfSolid*                   m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
379     ~_SolidData();
380   };
381   //--------------------------------------------------------------------------------
382   /*!
383    * \brief Data of node on a shrinked FACE
384    */
385   struct _SmoothNode
386   {
387     const SMDS_MeshNode*         _node;
388     //vector<const SMDS_MeshNode*> _nodesAround;
389     vector<_Simplex>             _simplices; // for quality check
390
391     bool Smooth(int&                  badNb,
392                 Handle(Geom_Surface)& surface,
393                 SMESH_MesherHelper&   helper,
394                 const double          refSign,
395                 bool                  set3D);
396   };
397   //--------------------------------------------------------------------------------
398   /*!
399    * \brief Builder of viscous layers
400    */
401   class _ViscousBuilder
402   {
403   public:
404     _ViscousBuilder();
405     // does it's job
406     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
407                                   const TopoDS_Shape& shape);
408
409     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
410     void RestoreListeners();
411
412     // computes SMESH_ProxyMesh::SubMesh::_n2n;
413     bool MakeN2NMap( _MeshOfSolid* pm );
414
415   private:
416
417     bool findSolidsWithLayers();
418     bool findFacesWithLayers();
419     bool makeLayer(_SolidData& data);
420     bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
421                      SMESH_MesherHelper& helper, _SolidData& data);
422     bool findNeiborsOnEdge(const _LayerEdge*     edge,
423                            const SMDS_MeshNode*& n1,
424                            const SMDS_MeshNode*& n2,
425                            _SolidData&           data);
426     void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
427                        const set<TGeomID>& ingnoreShapes,
428                        const _SolidData* dataToCheckOri = 0);
429     bool sortEdges( _SolidData&                    data,
430                     vector< vector<_LayerEdge*> >& edgesByGeom);
431     void limitStepSize( _SolidData&             data,
432                         const SMDS_MeshElement* face,
433                         const double            cosin);
434     void limitStepSize( _SolidData& data, const double minSize);
435     bool inflate(_SolidData& data);
436     bool smoothAndCheck(_SolidData& data, int nbSteps, double & distToIntersection);
437     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
438     bool refine(_SolidData& data);
439     bool shrink();
440     bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
441                               SMESH_MesherHelper& helper,
442                               const SMESHDS_SubMesh* faceSubMesh );
443     bool addBoundaryElements();
444
445     bool error( const string& text, int solidID=-1 );
446     SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
447
448     // debug
449     void makeGroupOfLE();
450
451     SMESH_Mesh*           _mesh;
452     SMESH_ComputeErrorPtr _error;
453
454     vector< _SolidData >  _sdVec;
455     set<TGeomID>          _ignoreShapeIds;
456     int                   _tmpFaceID;
457   };
458   //--------------------------------------------------------------------------------
459   /*!
460    * \brief Shrinker of nodes on the EDGE
461    */
462   class _Shrinker1D
463   {
464     vector<double>                _initU;
465     vector<double>                _normPar;
466     vector<const SMDS_MeshNode*>  _nodes;
467     const _LayerEdge*             _edges[2];
468     bool                          _done;
469   public:
470     void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
471     void Compute(bool set3D, SMESH_MesherHelper& helper);
472     void RestoreParams();
473     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
474   };
475   //--------------------------------------------------------------------------------
476   /*!
477    * \brief Class of temporary mesh face.
478    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
479    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
480    */
481   struct TmpMeshFace : public SMDS_MeshElement
482   {
483     vector<const SMDS_MeshNode* > _nn;
484     TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
485       SMDS_MeshElement(id), _nn(nodes) {}
486     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
487     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
488     virtual vtkIdType GetVtkType() const                      { return -1; }
489     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
490     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
491     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
492   };
493   //--------------------------------------------------------------------------------
494   /*!
495    * \brief Class of temporary mesh face storing _LayerEdge it's based on
496    */
497   struct TmpMeshFaceOnEdge : public TmpMeshFace
498   {
499     _LayerEdge *_le1, *_le2;
500     TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
501       TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
502     {
503       _nn[0]=_le1->_nodes[0];
504       _nn[1]=_le1->_nodes.back();
505       _nn[2]=_le2->_nodes.back();
506       _nn[3]=_le2->_nodes[0];
507     }
508   };
509 } // namespace VISCOUS
510
511 //================================================================================
512 // StdMeshers_ViscousLayers hypothesis
513 //
514 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
515   :SMESH_Hypothesis(hypId, studyId, gen),
516    _nbLayers(1), _thickness(1), _stretchFactor(1)
517 {
518   _name = StdMeshers_ViscousLayers::GetHypType();
519   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
520 } // --------------------------------------------------------------------------------
521 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
522 {
523   if ( faceIds != _ignoreFaceIds )
524     _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
525 } // --------------------------------------------------------------------------------
526 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
527 {
528   if ( thickness != _thickness )
529     _thickness = thickness, NotifySubMeshesHypothesisModification();
530 } // --------------------------------------------------------------------------------
531 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
532 {
533   if ( _nbLayers != nb )
534     _nbLayers = nb, NotifySubMeshesHypothesisModification();
535 } // --------------------------------------------------------------------------------
536 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
537 {
538   if ( _stretchFactor != factor )
539     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
540 } // --------------------------------------------------------------------------------
541 SMESH_ProxyMesh::Ptr
542 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
543                                   const TopoDS_Shape& theShape,
544                                   const bool          toMakeN2NMap) const
545 {
546   using namespace VISCOUS;
547   _ViscousBuilder bulder;
548   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
549   if ( err && !err->IsOK() )
550     return SMESH_ProxyMesh::Ptr();
551
552   vector<SMESH_ProxyMesh::Ptr> components;
553   TopExp_Explorer exp( theShape, TopAbs_SOLID );
554   for ( ; exp.More(); exp.Next() )
555   {
556     if ( _MeshOfSolid* pm =
557          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
558     {
559       if ( toMakeN2NMap && !pm->_n2nMapComputed )
560         if ( !bulder.MakeN2NMap( pm ))
561           return SMESH_ProxyMesh::Ptr();
562       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
563       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
564     }
565     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
566   }
567   switch ( components.size() )
568   {
569   case 0: break;
570
571   case 1: return components[0];
572
573   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
574   }
575   return SMESH_ProxyMesh::Ptr();
576 } // --------------------------------------------------------------------------------
577 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
578 {
579   save << " " << _nbLayers
580        << " " << _thickness
581        << " " << _stretchFactor
582        << " " << _ignoreFaceIds.size();
583   for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
584     save << " " << _ignoreFaceIds[i];
585   return save;
586 } // --------------------------------------------------------------------------------
587 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
588 {
589   int nbFaces, faceID;
590   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
591   while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
592     _ignoreFaceIds.push_back( faceID );
593   return load;
594 } // --------------------------------------------------------------------------------
595 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
596                                                    const TopoDS_Shape& theShape)
597 {
598   // TODO
599   return false;
600 }
601 // END StdMeshers_ViscousLayers hypothesis
602 //================================================================================
603
604 namespace
605 {
606   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
607   {
608     gp_Vec dir;
609     double f,l;
610     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
611     gp_Pnt p = BRep_Tool::Pnt( fromV );
612     double distF = p.SquareDistance( c->Value( f ));
613     double distL = p.SquareDistance( c->Value( l ));
614     c->D1(( distF < distL ? f : l), p, dir );
615     if ( distL < distF ) dir.Reverse();
616     return dir.XYZ();
617   }
618   //--------------------------------------------------------------------------------
619   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
620                      SMESH_MesherHelper& helper)
621   {
622     gp_Vec dir;
623     double f,l; gp_Pnt p;
624     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
625     double u = helper.GetNodeU( E, atNode );
626     c->D1( u, p, dir );
627     return dir.XYZ();
628   }
629   //--------------------------------------------------------------------------------
630   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
631                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
632   {
633     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
634     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
635     gp_Pnt p; gp_Vec du, dv, norm;
636     surface->D1( uv.X(),uv.Y(), p, du,dv );
637     norm = du ^ dv;
638
639     double f,l;
640     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
641     double u = helper.GetNodeU( fromE, node, 0, &ok );
642     c->D1( u, p, du );
643     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
644     if ( o == TopAbs_REVERSED )
645       du.Reverse();
646
647     gp_Vec dir = norm ^ du;
648
649     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
650          helper.IsClosedEdge( fromE ))
651     {
652       if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
653       else                         c->D1( f, p, dv );
654       if ( o == TopAbs_REVERSED )
655         dv.Reverse();
656       gp_Vec dir2 = norm ^ dv;
657       dir = dir.Normalized() + dir2.Normalized();
658     }
659     return dir.XYZ();
660   }
661   //--------------------------------------------------------------------------------
662   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
663                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
664                      bool& ok, double* cosin=0)
665   {
666     double f,l; TopLoc_Location loc;
667     vector< TopoDS_Edge > edges; // sharing a vertex
668     PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
669     while ( eIt->more())
670     {
671       const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
672       if ( helper.IsSubShape( *e, F ) && BRep_Tool::Curve( *e, loc,f,l))
673         edges.push_back( *e );
674     }
675     gp_XYZ dir(0,0,0);
676     if ( !( ok = ( edges.size() > 0 ))) return dir;
677     // get average dir of edges going fromV
678     gp_Vec edgeDir;
679     for ( unsigned i = 0; i < edges.size(); ++i )
680     {
681       edgeDir = getEdgeDir( edges[i], fromV );
682       double size2 = edgeDir.SquareMagnitude();
683       if ( size2 > numeric_limits<double>::min() )
684         edgeDir /= sqrt( size2 );
685       else
686         ok = false;
687       dir += edgeDir.XYZ();
688     }
689     gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
690     if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
691       dir = fromEdgeDir;
692     else if ( dir * fromEdgeDir < 0 )
693       dir *= -1;
694     if ( ok )
695     {
696       //dir /= edges.size();
697       if ( cosin ) {
698         double angle = edgeDir.Angle( dir );
699         *cosin = cos( angle );
700       }
701     }
702     return dir;
703   }
704   //--------------------------------------------------------------------------------
705   // DEBUG. Dump intermediate node positions into a python script
706 #ifdef __myDEBUG
707   ofstream* py;
708   struct PyDump {
709     PyDump() {
710       const char* fname = "/tmp/viscous.py";
711       cout << "execfile('"<<fname<<"')"<<endl;
712       py = new ofstream(fname);
713       *py << "from smesh import *" << endl
714           << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
715           << "mesh = Mesh( meshSO.GetObject()._narrow( SMESH.SMESH_Mesh ))"<<endl;
716     }
717     ~PyDump() {
718       *py << "mesh.MakeGroup('Prisms of viscous layers',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"
719           <<endl; delete py; py=0;
720     }
721   };
722 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
723 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
724 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
725   void _dumpFunction(const string& fun, int ln)
726   { *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
727   void _dumpMove(const SMDS_MeshNode* n, int ln)
728   { *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
729        << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
730   void _dumpCmd(const string& txt, int ln)
731   { *py<< "  "<<txt<<" # "<< ln <<endl; }
732   void dumpFunctionEnd()
733   { *py<< "  return"<< endl; }
734 #else
735   struct PyDump { PyDump() {} };
736   void dumpFunction(const string& fun ){}
737   void dumpFunctionEnd() {}
738   void dumpMove(const SMDS_MeshNode* n ){}
739   void dumpCmd(const string& txt){}
740 #endif
741 }
742
743 using namespace VISCOUS;
744
745 //================================================================================
746 /*!
747  * \brief Constructor of _ViscousBuilder
748  */
749 //================================================================================
750
751 _ViscousBuilder::_ViscousBuilder()
752 {
753   _error = SMESH_ComputeError::New(COMPERR_OK);
754   _tmpFaceID = 0;
755 }
756
757 //================================================================================
758 /*!
759  * \brief Stores error description and returns false
760  */
761 //================================================================================
762
763 bool _ViscousBuilder::error(const string& text, int solidId )
764 {
765   _error->myName    = COMPERR_ALGO_FAILED;
766   _error->myComment = string("Viscous layers builder: ") + text;
767   if ( _mesh )
768   {
769     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
770     if ( !sm && !_sdVec.empty() )
771       sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
772     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
773     {
774       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
775       if ( smError && smError->myAlgo )
776         _error->myAlgo = smError->myAlgo;
777       smError = _error;
778     }
779   }
780   makeGroupOfLE(); // debug
781
782   return false;
783 }
784
785 //================================================================================
786 /*!
787  * \brief At study restoration, restore event listeners used to clear an inferior
788  *  dim sub-mesh modified by viscous layers
789  */
790 //================================================================================
791
792 void _ViscousBuilder::RestoreListeners()
793 {
794   // TODO
795 }
796
797 //================================================================================
798 /*!
799  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
800  */
801 //================================================================================
802
803 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
804 {
805   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
806   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
807   for ( ; fExp.More(); fExp.Next() )
808   {
809     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
810     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
811
812     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
813       continue;
814     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
815       continue;
816
817     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
818       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
819
820     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
821     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
822     while( prxIt->more() )
823     {
824       const SMDS_MeshElement* fSrc = srcIt->next();
825       const SMDS_MeshElement* fPrx = prxIt->next();
826       if ( fSrc->NbNodes() != fPrx->NbNodes())
827         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
828       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
829         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
830     }
831   }
832   pm->_n2nMapComputed = true;
833   return true;
834 }
835
836 //================================================================================
837 /*!
838  * \brief Does its job
839  */
840 //================================================================================
841
842 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
843                                                const TopoDS_Shape& theShape)
844 {
845   // TODO: set priority of solids during Gen::Compute()
846
847   _mesh = & theMesh;
848
849   // check if proxy mesh already computed
850   TopExp_Explorer exp( theShape, TopAbs_SOLID );
851   if ( !exp.More() )
852     return error("No SOLID's in theShape"), _error;
853
854   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
855     return SMESH_ComputeErrorPtr(); // everything already computed
856
857   PyDump debugDump;
858
859   // TODO: ignore already computed SOLIDs 
860   if ( !findSolidsWithLayers())
861     return _error;
862
863   if ( !findFacesWithLayers() )
864     return _error;
865
866   for ( unsigned i = 0; i < _sdVec.size(); ++i )
867   {
868     if ( ! makeLayer(_sdVec[i]) )
869       return _error;
870     
871     if ( ! inflate(_sdVec[i]) )
872       return _error;
873
874     if ( ! refine(_sdVec[i]) )
875       return _error;
876   }
877   if ( !shrink() )
878     return _error;
879
880   addBoundaryElements();
881   
882   makeGroupOfLE(); // debug
883
884   return _error;
885 }
886
887 //================================================================================
888 /*!
889  * \brief Finds SOLIDs to compute using viscous layers. Fill _sdVec
890  */
891 //================================================================================
892
893 bool _ViscousBuilder::findSolidsWithLayers()
894 {
895   // get all solids
896   TopTools_IndexedMapOfShape allSolids;
897   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
898   _sdVec.reserve( allSolids.Extent());
899
900   SMESH_Gen* gen = _mesh->GetGen();
901   for ( int i = 1; i <= allSolids.Extent(); ++i )
902   {
903     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
904     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
905     if ( !algo ) continue;
906     // TODO: check if algo is hidden
907     const list <const SMESHDS_Hypothesis *> & allHyps =
908       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
909     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
910     const StdMeshers_ViscousLayers* viscHyp = 0;
911     for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
912       viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
913     if ( viscHyp )
914     {
915       _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
916                                                                 allSolids(i),
917                                                                 /*toCreate=*/true);
918       _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
919       _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
920     }
921   }
922   if ( _sdVec.empty() )
923     return error
924       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
925
926   return true;
927 }
928
929 //================================================================================
930 /*!
931  * \brief 
932  */
933 //================================================================================
934
935 bool _ViscousBuilder::findFacesWithLayers()
936 {
937   // collect all faces to ignore defined by hyp
938   vector<TopoDS_Shape> ignoreFaces;
939   for ( unsigned i = 0; i < _sdVec.size(); ++i )
940   {
941     vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
942     for ( unsigned i = 0; i < ids.size(); ++i )
943     {
944       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
945       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
946       {
947         _ignoreShapeIds.insert( ids[i] );
948         ignoreFaces.push_back( s );
949       }
950     }
951   }
952
953   // ignore internal faces
954   SMESH_MesherHelper helper( *_mesh );
955   TopExp_Explorer exp;
956   for ( unsigned i = 0; i < _sdVec.size(); ++i )
957   {
958     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
959     for ( ; exp.More(); exp.Next() )
960     {
961       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
962       if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
963       {     
964         _ignoreShapeIds.insert( faceInd );
965         ignoreFaces.push_back( exp.Current() );
966         if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
967           _sdVec[i]._reversedFaceIds.insert( faceInd );
968       }
969     }
970   }
971
972   // Find faces to shrink mesh on (solution 2 in issue 0020832);
973   TopTools_IndexedMapOfShape shapes;
974   for ( unsigned i = 0; i < _sdVec.size(); ++i )
975   {
976     shapes.Clear();
977     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
978     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
979     {
980       const TopoDS_Shape& edge = shapes(iE);
981       // find 2 faces sharing an edge
982       TopoDS_Shape FF[2];
983       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
984       while ( fIt->more())
985       {
986         const TopoDS_Shape* f = fIt->next();
987         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
988           FF[ int( !FF[0].IsNull()) ] = *f;
989       }
990       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
991       // check presence of layers on them
992       int ignore[2];
993       for ( int j = 0; j < 2; ++j )
994         ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
995       if ( ignore[0] == ignore[1] ) continue; // nothing interesting
996       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
997       // add edge to maps
998       TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
999       _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1000     }
1001   }
1002   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1003   // the algo of the SOLID sharing the FACE does not support it
1004   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1005   for ( unsigned i = 0; i < _sdVec.size(); ++i )
1006   {
1007     TopTools_MapOfShape noShrinkVertices;
1008     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1009     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1010     {
1011       const TopoDS_Shape& fWOL = e2f->second;
1012       TGeomID           edgeID = e2f->first;
1013       bool notShrinkFace = false;
1014       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1015       while ( soIt->more())
1016       {
1017         const TopoDS_Shape* solid = soIt->next();
1018         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1019         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1020         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1021         notShrinkFace = true;
1022         for ( unsigned j = 0; j < _sdVec.size(); ++j )
1023         {
1024           if ( _sdVec[j]._solid.IsSame( *solid ) )
1025             if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1026               notShrinkFace = false;
1027         }
1028       }
1029       if ( notShrinkFace )
1030       {
1031         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1032         for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1033           noShrinkVertices.Add( vExp.Current() );
1034       }
1035     }
1036     // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1037     // to the found not shrinked fWOL's
1038     e2f = _sdVec[i]._shrinkShape2Shape.begin();
1039     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1040     {
1041       TGeomID edgeID = e2f->first;
1042       TopoDS_Vertex VV[2];
1043       TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1044       if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1045         _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1046       else
1047         e2f++;
1048     }
1049   }
1050       
1051   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1052
1053   for ( unsigned i = 0; i < _sdVec.size(); ++i )
1054   {
1055     shapes.Clear();
1056     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1057     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1058     {
1059       const TopoDS_Shape& vertex = shapes(iV);
1060       // find faces WOL sharing the vertex
1061       vector< TopoDS_Shape > facesWOL;
1062       int totalNbFaces = 0;
1063       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1064       while ( fIt->more())
1065       {
1066         const TopoDS_Shape* f = fIt->next();
1067         const int         fID = getMeshDS()->ShapeToIndex( *f );
1068         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1069         {
1070           totalNbFaces++;
1071           if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1072             facesWOL.push_back( *f );
1073         }
1074       }
1075       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1076         continue; // no layers at this vertex or no WOL
1077       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1078       switch ( facesWOL.size() )
1079       {
1080       case 1:
1081         {
1082           _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] )); break;
1083         }
1084       case 2:
1085         {
1086           // find an edge shared by 2 faces
1087           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1088           while ( eIt->more())
1089           {
1090             const TopoDS_Shape* e = eIt->next();
1091             if ( helper.IsSubShape( *e, facesWOL[0]) &&
1092                  helper.IsSubShape( *e, facesWOL[1]))
1093             {
1094               _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1095             }
1096           }
1097           break;
1098         }
1099       default:
1100         return error("Not yet supported case", _sdVec[i]._index);
1101       }
1102     }
1103   }
1104
1105   return true;
1106 }
1107
1108 //================================================================================
1109 /*!
1110  * \brief Create the inner surface of the viscous layer and prepare data for infation
1111  */
1112 //================================================================================
1113
1114 bool _ViscousBuilder::makeLayer(_SolidData& data)
1115 {
1116   // get all sub-shapes to make layers on
1117   set<TGeomID> subIds, faceIds;
1118   subIds = data._noShrinkFaces;
1119   TopExp_Explorer exp( data._solid, TopAbs_FACE );
1120   for ( ; exp.More(); exp.Next() )
1121     if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1122     {
1123       SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1124       faceIds.insert( fSubM->GetId() );
1125       SMESH_subMeshIteratorPtr subIt =
1126         fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1127       while ( subIt->more() )
1128         subIds.insert( subIt->next()->GetId() );
1129     }
1130
1131   // make a map to find new nodes on sub-shapes shared with other SOLID
1132   map< TGeomID, TNode2Edge* > s2neMap;
1133   map< TGeomID, TNode2Edge* >::iterator s2ne;
1134   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1135   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1136   {
1137     TGeomID shapeInd = s2s->first;
1138     for ( unsigned i = 0; i < _sdVec.size(); ++i )
1139     {
1140       if ( _sdVec[i]._index == data._index ) continue;
1141       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1142       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1143            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1144       {
1145         s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1146         break;
1147       }
1148     }
1149   }
1150
1151   // Create temporary faces and _LayerEdge's
1152
1153   dumpFunction(SMESH_Comment("makeLayers_")<<data._index); 
1154
1155   data._stepSize = Precision::Infinite();
1156   data._stepSizeNodes[0] = 0;
1157
1158   SMESH_MesherHelper helper( *_mesh );
1159   helper.SetSubShape( data._solid );
1160   helper.SetElementsOnShape(true);
1161
1162   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1163   TNode2Edge::iterator n2e2;
1164
1165   // collect _LayerEdge's of shapes they are based on
1166   const int nbShapes = getMeshDS()->MaxShapeIndex();
1167   vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1168
1169   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1170   {
1171     SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1172     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1173
1174     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1175     SMESH_ProxyMesh::SubMesh* proxySub =
1176       data._proxyMesh->getFaceSubM( F, /*create=*/true);
1177
1178     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1179     while ( eIt->more() )
1180     {
1181       const SMDS_MeshElement* face = eIt->next();
1182       newNodes.resize( face->NbCornerNodes() );
1183       double faceMaxCosin = -1;
1184       for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1185       {
1186         const SMDS_MeshNode* n = face->GetNode(i);
1187         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1188         if ( !(*n2e).second )
1189         {
1190           // add a _LayerEdge
1191           _LayerEdge* edge = new _LayerEdge();
1192           n2e->second = edge;
1193           edge->_nodes.push_back( n );
1194           const int shapeID = n->getshapeId();
1195           edgesByGeom[ shapeID ].push_back( edge );
1196
1197           // set edge data or find already refined _LayerEdge and get data from it
1198           if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1199                ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1200                ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1201           {
1202             _LayerEdge* foundEdge = (*n2e2).second;
1203             edge->Copy( *foundEdge, helper );
1204             // location of the last node is modified but we can restore
1205             // it by node position on _sWOL stored by the node
1206             const_cast< SMDS_MeshNode* >
1207               ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1208           }
1209           else
1210           {
1211             edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1212             if ( !setEdgeData( *edge, subIds, helper, data ))
1213               return false;
1214           }
1215           dumpMove(edge->_nodes.back());
1216           if ( edge->_cosin > 0.01 )
1217           {
1218             if ( edge->_cosin > faceMaxCosin )
1219               faceMaxCosin = edge->_cosin;
1220           }
1221         }
1222         newNodes[ i ] = n2e->second->_nodes.back();
1223       }
1224       // create a temporary face
1225       const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1226       proxySub->AddElement( newFace );
1227
1228       // compute inflation step size by min size of element on a convex surface
1229       if ( faceMaxCosin > 0.1 )
1230         limitStepSize( data, face, faceMaxCosin );
1231     } // loop on 2D elements on a FACE
1232   } // loop on FACEs of a SOLID
1233
1234   data._epsilon = 1e-7;
1235   if ( data._stepSize < 1. )
1236     data._epsilon *= data._stepSize;
1237
1238   // Put _LayerEdge's into a vector
1239
1240   if ( !sortEdges( data, edgesByGeom ))
1241     return false;
1242
1243   // Set target nodes into _Simplex and _2NearEdges
1244   TNode2Edge::iterator n2e;
1245   for ( unsigned i = 0; i < data._edges.size(); ++i )
1246   {
1247     if ( data._edges[i]->IsOnEdge())
1248       for ( int j = 0; j < 2; ++j )
1249       {
1250         if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1251           break; // _LayerEdge is shared by two _SolidData's
1252         const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1253         if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1254           return error("_LayerEdge not found by src node", data._index);
1255         n = (*n2e).second->_nodes.back();
1256         data._edges[i]->_2neibors->_edges[j] = n2e->second;
1257       }
1258     else
1259       for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1260       {
1261         _Simplex& s = data._edges[i]->_simplices[j];
1262         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1263         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1264       }
1265   }
1266
1267   dumpFunctionEnd();
1268   return true;
1269 }
1270
1271 //================================================================================
1272 /*!
1273  * \brief Compute inflation step size by min size of element on a convex surface
1274  */
1275 //================================================================================
1276
1277 void _ViscousBuilder::limitStepSize( _SolidData&             data,
1278                                      const SMDS_MeshElement* face,
1279                                      const double            cosin)
1280 {
1281   int iN = 0;
1282   double minSize = 10 * data._stepSize;
1283   const int nbNodes = face->NbCornerNodes();
1284   for ( int i = 0; i < nbNodes; ++i )
1285   {
1286     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1287     const SMDS_MeshNode* curN = face->GetNode( i );
1288     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1289          curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1290     {
1291       double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1292       if ( dist < minSize )
1293         minSize = dist, iN = i;
1294     }
1295   }
1296   double newStep = 0.8 * minSize / cosin;
1297   if ( newStep < data._stepSize )
1298   {
1299     data._stepSize = newStep;
1300     data._stepSizeCoeff = 0.8 / cosin;
1301     data._stepSizeNodes[0] = face->GetNode( iN );
1302     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1303   }
1304 }
1305
1306 //================================================================================
1307 /*!
1308  * \brief Compute inflation step size by min size of element on a convex surface
1309  */
1310 //================================================================================
1311
1312 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1313 {
1314   if ( minSize < data._stepSize )
1315   {
1316     data._stepSize = minSize;
1317     if ( data._stepSizeNodes[0] )
1318     {
1319       double dist =
1320         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1321       data._stepSizeCoeff = data._stepSize / dist;
1322     }
1323   }
1324 }
1325
1326 //================================================================================
1327 /*!
1328  * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1329  */
1330 //================================================================================
1331
1332 bool _ViscousBuilder::sortEdges( _SolidData&                    data,
1333                                  vector< vector<_LayerEdge*> >& edgesByGeom)
1334 {
1335   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1336   // boundry inclined at a sharp angle to the shape
1337
1338   list< TGeomID > shapesToSmooth;
1339   
1340   SMESH_MesherHelper helper( *_mesh );
1341   bool ok;
1342
1343   for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1344   {
1345     vector<_LayerEdge*>& eS = edgesByGeom[iS];
1346     if ( eS.empty() ) continue;
1347     TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1348     bool needSmooth = false;
1349     switch ( S.ShapeType() )
1350     {
1351     case TopAbs_EDGE: {
1352
1353       bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1354       for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1355       {
1356         TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1357         vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1358         if ( eV.empty() ) continue;
1359         double cosin = eV[0]->_cosin;
1360         bool badCosin =
1361           ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1362         if ( badCosin )
1363         {
1364           gp_Vec dir1, dir2;
1365           if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1366             dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1367           else
1368             dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1369                                eV[0]->_nodes[0], helper, ok);
1370           dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1371           double angle = dir1.Angle( dir2 );
1372           cosin = cos( angle );
1373         }
1374         needSmooth = ( cosin > 0.1 );
1375       }
1376       break;
1377     }
1378     case TopAbs_FACE: {
1379
1380       for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1381       {
1382         TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1383         vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1384         if ( eE.empty() ) continue;
1385         if ( eE[0]->_sWOL.IsNull() )
1386         {
1387           for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1388             needSmooth = ( eE[i]->_cosin > 0.1 );
1389         }
1390         else
1391         {
1392           const TopoDS_Face& F1 = TopoDS::Face( S );
1393           const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1394           const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
1395           for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1396           {
1397             gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1398             gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1399             double angle = dir1.Angle( dir2 );
1400             double cosin = cos( angle );
1401             needSmooth = ( cosin > 0.1 );
1402           }
1403         }
1404       }
1405       break;
1406     }
1407     case TopAbs_VERTEX:
1408       continue;
1409     default:;
1410     }
1411     if ( needSmooth )
1412     {
1413       if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1414       else                                shapesToSmooth.push_back ( iS );
1415     }
1416
1417   } // loop on edgesByGeom
1418
1419   data._edges.reserve( data._n2eMap.size() );
1420   data._endEdgeToSmooth.clear();
1421
1422   // first we put _LayerEdge's on shapes to smooth
1423   list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1424   for ( ; gIt != shapesToSmooth.end(); ++gIt )
1425   {
1426     vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1427     if ( eVec.empty() ) continue;
1428     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1429     data._endEdgeToSmooth.push_back( data._edges.size() );
1430     eVec.clear();
1431   }
1432
1433   // then the rest _LayerEdge's
1434   for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1435   {
1436     vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1437     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1438     eVec.clear();
1439   }
1440
1441   return ok;
1442 }
1443
1444 //================================================================================
1445 /*!
1446  * \brief Set data of _LayerEdge needed for smoothing
1447  *  \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1448  */
1449 //================================================================================
1450
1451 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
1452                                   const set<TGeomID>& subIds,
1453                                   SMESH_MesherHelper& helper,
1454                                   _SolidData&         data)
1455 {
1456   SMESH_MeshEditor editor(_mesh);
1457
1458   const SMDS_MeshNode* node = edge._nodes[0]; // source node
1459   SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1460
1461   edge._len = 0;
1462   edge._2neibors = 0;
1463   edge._curvature = 0;
1464
1465   // --------------------------
1466   // Compute _normal and _cosin
1467   // --------------------------
1468
1469   edge._cosin = 0;
1470   edge._normal.SetCoord(0,0,0);
1471
1472   int totalNbFaces = 0;
1473   gp_Pnt p;
1474   gp_Vec du, dv, geomNorm;
1475   bool normOK = true;
1476
1477   TGeomID shapeInd = node->getshapeId();
1478   map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1479   bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1480   TopoDS_Shape vertEdge;
1481
1482   if ( onShrinkShape ) // one of faces the node is on has no layers
1483   {
1484     vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1485     if ( s2s->second.ShapeType() == TopAbs_EDGE )
1486     {
1487       // inflate from VERTEX along EDGE
1488       edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1489     }
1490     else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1491     {
1492       // inflate from VERTEX along FACE
1493       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1494                                  node, helper, normOK, &edge._cosin);
1495     }
1496     else
1497     {
1498       // inflate from EDGE along FACE
1499       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1500                                  node, helper, normOK);
1501     }
1502   }
1503   else // layers are on all faces of SOLID the node is on
1504   {
1505     // find indices of geom faces the node lies on
1506     set<TGeomID> faceIds;
1507     if  ( posType == SMDS_TOP_FACE )
1508     {
1509       faceIds.insert( node->getshapeId() );
1510     }
1511     else
1512     {
1513       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1514       while ( fIt->more() )
1515         faceIds.insert( editor.FindShape(fIt->next()));
1516     }
1517
1518     set<TGeomID>::iterator id = faceIds.begin();
1519     TopoDS_Face F;
1520     for ( ; id != faceIds.end(); ++id )
1521     {
1522       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1523       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1524         continue;
1525       totalNbFaces++;
1526       //nbLayerFaces += subIds.count( *id );
1527       F = TopoDS::Face( s );
1528
1529       gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1530       Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1531       surface->D1( uv.X(),uv.Y(), p, du,dv );
1532       geomNorm = du ^ dv;
1533       double size2 = geomNorm.SquareMagnitude();
1534       if ( size2 > numeric_limits<double>::min() )
1535         geomNorm /= sqrt( size2 );
1536       else
1537         normOK = false;
1538       if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1539         geomNorm.Reverse();
1540       edge._normal += geomNorm.XYZ();
1541     }
1542     if ( totalNbFaces == 0 )
1543       return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1544
1545     edge._normal /= totalNbFaces;
1546
1547     switch ( posType )
1548     {
1549     case SMDS_TOP_FACE:
1550       edge._cosin = 0; break;
1551
1552     case SMDS_TOP_EDGE: {
1553       TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1554       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1555       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1556       edge._cosin = cos( angle );
1557       //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1558       break;
1559     }
1560     case SMDS_TOP_VERTEX: {
1561       TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1562       gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1563       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1564       edge._cosin = cos( angle );
1565       //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1566       break;
1567     }
1568     default:
1569       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1570     }
1571   }
1572
1573   double normSize = edge._normal.SquareModulus();
1574   if ( normSize < numeric_limits<double>::min() )
1575     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1576
1577   edge._normal /= sqrt( normSize );
1578
1579   // TODO: if ( !normOK ) then get normal by mesh faces
1580
1581   // Set the rest data
1582   // --------------------
1583   if ( onShrinkShape )
1584   {
1585     edge._sWOL = (*s2s).second;
1586
1587     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1588     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1589       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1590
1591     // set initial position which is parameters on _sWOL in this case
1592     if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1593     {
1594       double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1595       edge._pos.push_back( gp_XYZ( u, 0, 0));
1596       getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1597     }
1598     else // TopAbs_FACE
1599     {
1600       gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1601       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1602       getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1603     }
1604   }
1605   else
1606   {
1607     edge._pos.push_back( SMESH_TNodeXYZ( node ));
1608
1609     if ( posType == SMDS_TOP_FACE )
1610     {
1611       getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1612       double avgNormProj = 0, avgLen = 0;
1613       for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1614       {
1615         gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1616         avgNormProj += edge._normal * vec;
1617         avgLen += vec.Modulus();
1618       }
1619       avgNormProj /= edge._simplices.size();
1620       avgLen /= edge._simplices.size();
1621       edge._curvature = _Curvature::New( avgNormProj, avgLen );
1622     }
1623   }
1624
1625   // Set neighbour nodes for a _LayerEdge based on EDGE
1626
1627   if ( posType == SMDS_TOP_EDGE /*||
1628        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1629   {
1630     edge._2neibors = new _2NearEdges;
1631     // target node instead of source ones will be set later
1632     if ( ! findNeiborsOnEdge( &edge,
1633                               edge._2neibors->_nodes[0],
1634                               edge._2neibors->_nodes[1],
1635                               data))
1636       return false;
1637     edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1638                              edge._2neibors->_nodes[1],
1639                              helper);
1640   }
1641
1642   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1643
1644   return true;
1645 }
1646
1647 //================================================================================
1648 /*!
1649  * \brief Find 2 neigbor nodes of a node on EDGE
1650  */
1651 //================================================================================
1652
1653 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
1654                                         const SMDS_MeshNode*& n1,
1655                                         const SMDS_MeshNode*& n2,
1656                                         _SolidData&           data)
1657 {
1658   const SMDS_MeshNode* node = edge->_nodes[0];
1659   const int shapeInd = node->getshapeId();
1660   SMESHDS_SubMesh* edgeSM = 0;
1661   if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1662   {
1663     
1664     edgeSM = getMeshDS()->MeshElements( shapeInd );
1665     if ( !edgeSM || edgeSM->NbElements() == 0 )
1666       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1667   }
1668   int iN = 0;
1669   n2 = 0;
1670   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1671   while ( eIt->more() && !n2 )
1672   {
1673     const SMDS_MeshElement* e = eIt->next();
1674     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
1675     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1676     if ( edgeSM )
1677     {
1678       if (!edgeSM->Contains(e)) continue;
1679     }
1680     else
1681     {
1682       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1683       if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1684     }
1685     ( iN++ ? n2 : n1 ) = nNeibor;
1686   }
1687   if ( !n2 )
1688     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1689   return true;
1690 }
1691
1692 //================================================================================
1693 /*!
1694  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1695  */
1696 //================================================================================
1697
1698 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1699                                      const SMDS_MeshNode* n2,
1700                                      SMESH_MesherHelper&  helper)
1701 {
1702   if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1703     return;
1704
1705   gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1706   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1707   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1708
1709   // Set _curvature
1710
1711   double sumLen = vec1.Modulus() + vec2.Modulus();
1712   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1713   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1714   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1715   double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1716   if ( _curvature ) delete _curvature;
1717   _curvature = _Curvature::New( avgNormProj, avgLen );
1718 #ifdef __myDEBUG
1719 //     if ( _curvature )
1720 //       cout << _nodes[0]->GetID()
1721 //            << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1722 //            << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1723 //            << _curvature->lenDelta(0) << endl;
1724 #endif
1725
1726   // Set _plnNorm
1727
1728   if ( _sWOL.IsNull() )
1729   {
1730     TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1731     gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1732     gp_XYZ plnNorm = dirE ^ _normal;
1733     double proj0 = plnNorm * vec1;
1734     double proj1 = plnNorm * vec2;
1735     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1736     {
1737       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1738       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1739     }
1740   }
1741 }
1742
1743 //================================================================================
1744 /*!
1745  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1746  * this and other _LayerEdge's are inflated along a FACE or an EDGE
1747  */
1748 //================================================================================
1749
1750 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1751 {
1752   _nodes     = other._nodes;
1753   _normal    = other._normal;
1754   _len       = 0;
1755   _lenFactor = other._lenFactor;
1756   _cosin     = other._cosin;
1757   _sWOL      = other._sWOL;
1758   _2neibors  = other._2neibors;
1759   _curvature = 0; std::swap( _curvature, other._curvature );
1760   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
1761
1762   if ( _sWOL.ShapeType() == TopAbs_EDGE )
1763   {
1764     double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1765     _pos.push_back( gp_XYZ( u, 0, 0));
1766   }
1767   else // TopAbs_FACE
1768   {
1769     gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1770     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1771   }
1772 }
1773
1774 //================================================================================
1775 /*!
1776  * \brief Set _cosin and _lenFactor
1777  */
1778 //================================================================================
1779
1780 void _LayerEdge::SetCosin( double cosin )
1781 {
1782   _cosin = cosin;
1783   _lenFactor = ( _cosin > 0.1 ) ?  1./sqrt(1-_cosin*_cosin) : 1.0;
1784 }
1785
1786 //================================================================================
1787 /*!
1788  * \brief Fills a vector<_Simplex > 
1789  */
1790 //================================================================================
1791
1792 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1793                                     vector<_Simplex>&    simplices,
1794                                     const set<TGeomID>&  ingnoreShapes,
1795                                     const _SolidData*    dataToCheckOri)
1796 {
1797   SMESH_MeshEditor editor( _mesh );
1798   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1799   while ( fIt->more() )
1800   {
1801     const SMDS_MeshElement* f = fIt->next();
1802     const TGeomID shapeInd = editor.FindShape( f );
1803     if ( ingnoreShapes.count( shapeInd )) continue;
1804     const int nbNodes = f->NbCornerNodes();
1805     int srcInd = f->GetNodeIndex( node );
1806     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1807     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1808     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1809       std::swap( nPrev, nNext );
1810     simplices.push_back( _Simplex( nPrev, nNext ));
1811   }
1812   simplices.resize( simplices.size() );
1813 }
1814
1815 //================================================================================
1816 /*!
1817  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1818  */
1819 //================================================================================
1820
1821 void _ViscousBuilder::makeGroupOfLE()
1822 {
1823 #ifdef _DEBUG_
1824   for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1825   {
1826     if ( _sdVec[i]._edges.empty() ) continue;
1827 //     string name = SMESH_Comment("_LayerEdge's_") << i;
1828 //     int id;
1829 //     SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1830 //     SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1831 //     SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1832
1833     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1834     for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1835     {
1836       _LayerEdge* le = _sdVec[i]._edges[j];
1837       for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1838         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1839                 << ", " << le->_nodes[iN]->GetID() <<"])");
1840       //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1841     }
1842     dumpFunctionEnd();
1843
1844     dumpFunction( SMESH_Comment("makeNormals") << i );
1845     for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1846     {
1847       _LayerEdge& edge = *_sdVec[i]._edges[j];
1848       SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
1849       nXYZ += edge._normal * _sdVec[i]._stepSize;
1850       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
1851               << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
1852     }
1853     dumpFunctionEnd();
1854
1855 //     name = SMESH_Comment("tmp_faces ") << i;
1856 //     g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
1857 //     gDS = (SMESHDS_Group*)g->GetGroupDS();
1858 //     SMESH_MeshEditor editor( _mesh );
1859     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
1860     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
1861     for ( ; fExp.More(); fExp.Next() )
1862     {
1863       if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
1864       {
1865         SMDS_ElemIteratorPtr fIt = sm->GetElements();
1866         while ( fIt->more())
1867         {
1868           const SMDS_MeshElement* e = fIt->next();
1869           SMESH_Comment cmd("mesh.AddFace([");
1870           for ( int j=0; j < e->NbCornerNodes(); ++j )
1871             cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
1872           dumpCmd( cmd );
1873           //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
1874           //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
1875         }
1876       }
1877     }
1878     dumpFunctionEnd();
1879   }
1880 #endif
1881 }
1882
1883 //================================================================================
1884 /*!
1885  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
1886  */
1887 //================================================================================
1888
1889 bool _ViscousBuilder::inflate(_SolidData& data)
1890 {
1891   SMESH_MesherHelper helper( *_mesh );
1892
1893   // Limit inflation step size by geometry size found by itersecting
1894   // normals of _LayerEdge's with mesh faces
1895   double geomSize = Precision::Infinite(), intersecDist;
1896   SMESH_MeshEditor editor( _mesh );
1897   auto_ptr<SMESH_ElementSearcher> searcher
1898     ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
1899   for ( unsigned i = 0; i < data._edges.size(); ++i )
1900   {
1901     if ( data._edges[i]->IsOnEdge() ) continue;
1902     data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
1903     if ( geomSize > intersecDist )
1904       geomSize = intersecDist;
1905   }
1906   if ( data._stepSize > 0.3 * geomSize )
1907     limitStepSize( data, 0.3 * geomSize );
1908
1909   const double tgtThick = data._hyp->GetTotalThickness();
1910   if ( data._stepSize > tgtThick )
1911     limitStepSize( data, tgtThick );
1912
1913   if ( data._stepSize < 1. )
1914     data._epsilon = data._stepSize * 1e-7;
1915
1916 #ifdef __myDEBUG
1917   cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
1918 #endif
1919
1920   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
1921   int nbSteps = 0, nbRepeats = 0;
1922   while ( 1.01 * avgThick < tgtThick )
1923   {
1924     // new target length
1925     curThick += data._stepSize;
1926     if ( curThick > tgtThick )
1927     {
1928       curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
1929       nbRepeats++;
1930     }
1931
1932     // Elongate _LayerEdge's
1933     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
1934     for ( unsigned i = 0; i < data._edges.size(); ++i )
1935     {
1936       data._edges[i]->SetNewLength( curThick, helper );
1937     }
1938     dumpFunctionEnd();
1939
1940     if ( !nbSteps )
1941       if ( !updateNormals( data, helper ) )
1942         return false;
1943
1944     // Improve and check quality
1945     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
1946     {
1947       if ( nbSteps > 0 )
1948       {
1949         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
1950         for ( unsigned i = 0; i < data._edges.size(); ++i )
1951         {
1952           data._edges[i]->InvalidateStep( nbSteps+1 );
1953         }
1954         dumpFunctionEnd();
1955       }
1956       break; // no more inflating possible
1957     }
1958     nbSteps++;
1959
1960     // Evaluate achieved thickness
1961     avgThick = 0;
1962     for ( unsigned i = 0; i < data._edges.size(); ++i )
1963       avgThick += data._edges[i]->_len;
1964     avgThick /= data._edges.size();
1965 #ifdef __myDEBUG
1966     cout << "-- Thickness " << avgThick << " reached" << endl;
1967 #endif
1968
1969     if ( distToIntersection < avgThick*1.5 )
1970     {
1971 #ifdef __myDEBUG
1972       cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
1973            << avgThick << " ) * 1.5" << endl;
1974 #endif
1975       break;
1976     }
1977     // new step size
1978     limitStepSize( data, 0.25 * distToIntersection );
1979     if ( data._stepSizeNodes[0] )
1980       data._stepSize = data._stepSizeCoeff *
1981         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1982   }
1983
1984   if (nbSteps == 0 )
1985     return error("failed at the very first inflation step", data._index);
1986
1987   return true;
1988 }
1989
1990 //================================================================================
1991 /*!
1992  * \brief Improve quality of layer inner surface and check intersection
1993  */
1994 //================================================================================
1995
1996 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
1997                                      int         nbSteps,
1998                                      double &    distToIntersection)
1999 {
2000   if ( data._endEdgeToSmooth.empty() )
2001     return true; // no shapes needing smoothing
2002
2003   bool moved, improved;
2004
2005   SMESH_MesherHelper helper(*_mesh);
2006   Handle(Geom_Surface) surface;
2007   TopoDS_Face F;
2008
2009   int iBeg, iEnd = 0;
2010   for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2011   {
2012     iBeg = iEnd;
2013     iEnd = data._endEdgeToSmooth[ iS ];
2014
2015     if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2016          data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2017     {
2018       if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2019         F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2020         helper.SetSubShape( F );
2021         surface = BRep_Tool::Surface( F );
2022       }
2023     }
2024     else
2025     {
2026       F.Nullify(); surface.Nullify();
2027     }
2028     TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2029
2030     if ( data._edges[ iBeg ]->IsOnEdge() )
2031     {
2032       dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2033       // smooth on EDGE's
2034       int step = 0;
2035       do {
2036         moved = false;
2037         for ( int i = iBeg; i < iEnd; ++i )
2038         {
2039           moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2040         }
2041         dumpCmd( SMESH_Comment("# end step ")<<step);
2042       }
2043       while ( moved && step++ < 5 );
2044
2045       dumpFunctionEnd();
2046     }
2047     else
2048     {
2049       // smooth on FACE's
2050       int step = 0, badNb = 0; moved = true;
2051       while (( ++step <= 5 && moved ) || improved )
2052       {
2053         dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2054                      <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2055         int oldBadNb = badNb;
2056         badNb = 0;
2057         moved = false;
2058         for ( int i = iBeg; i < iEnd; ++i )
2059           moved |= data._edges[i]->Smooth(badNb);
2060         improved = ( badNb < oldBadNb );
2061
2062         dumpFunctionEnd();
2063       }
2064       if ( badNb > 0 )
2065       {
2066 #ifdef __myDEBUG
2067         for ( int i = iBeg; i < iEnd; ++i )
2068         {
2069           _LayerEdge* edge = data._edges[i];
2070           SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2071           for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2072             if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2073             {
2074               cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2075                    << " "<< edge->_simplices[j]._nPrev->GetID()
2076                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2077               return false;
2078             }
2079         }
2080 #endif
2081         return false;
2082       }
2083     }
2084   } // loop on shapes to smooth
2085
2086   // Check if the last segments of _LayerEdge intersects 2D elements;
2087   // checked elements are either temporary faces or faces on surfaces w/o the layers
2088
2089   SMESH_MeshEditor editor( _mesh );
2090   auto_ptr<SMESH_ElementSearcher> searcher
2091     ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2092
2093   distToIntersection = Precision::Infinite();
2094   double dist;
2095   const SMDS_MeshElement* intFace = 0, *closestFace = 0;
2096   int iLE = 0;
2097   for ( unsigned i = 0; i < data._edges.size(); ++i )
2098   {
2099     if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2100       return false;
2101     if ( distToIntersection > dist )
2102       distToIntersection = dist, closestFace = intFace, iLE = i;
2103   }
2104 #ifdef __myDEBUG
2105   if ( closestFace )
2106   {
2107     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2108     cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2109          << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2110          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2111          << ") distance = " << distToIntersection<< endl;
2112   }
2113 #endif
2114
2115   return true;
2116 }
2117
2118 //================================================================================
2119 /*!
2120  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2121  * _LayerEdge's on neighbor EDGE's
2122  */
2123 //================================================================================
2124
2125 bool _ViscousBuilder::updateNormals( _SolidData&         data,
2126                                      SMESH_MesherHelper& helper )
2127 {
2128   // make temporary quadrangles got by extrusion of
2129   // mesh edges along _LayerEdge._normal's
2130
2131   vector< const SMDS_MeshElement* > tmpFaces;
2132   {
2133     set< SMESH_TLink > extrudedLinks; // contains target nodes
2134     vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2135
2136     dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2137     for ( unsigned i = 0; i < data._edges.size(); ++i )
2138     {
2139       _LayerEdge* edge = data._edges[i];
2140       if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2141       const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2142       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2143       {
2144         const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2145         pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2146           extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2147         if ( !link_isnew.second )
2148         {
2149           extrudedLinks.erase( link_isnew.first );
2150           continue; // already extruded and will no more encounter
2151         }
2152         // look for a _LayerEdge containg tgt2
2153 //         _LayerEdge* neiborEdge = 0;
2154 //         unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2155 //         while ( !neiborEdge && ++di <= data._edges.size() )
2156 //         {
2157 //           if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2158 //             neiborEdge = data._edges[i+di];
2159 //           else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2160 //             neiborEdge = data._edges[i-di];
2161 //         }
2162 //         if ( !neiborEdge )
2163 //           return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2164         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2165
2166         TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2167         tmpFaces.push_back( f );
2168
2169         dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2170                 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2171                 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2172       }
2173     }
2174     dumpFunctionEnd();
2175   }
2176   // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2177   // Perform two loops on _LayerEdge on EDGE's:
2178   // 1) to find and fix intersection
2179   // 2) to check that no new intersection appears as result of 1)
2180
2181   SMESH_MeshEditor editor( _mesh );
2182   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2183                                                             tmpFaces.end()));
2184   auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2185
2186   // 1) Find intersections
2187   double dist;
2188   const SMDS_MeshElement* face;
2189   typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2190   TLEdge2LEdgeSet edge2CloseEdge;
2191
2192   const double eps = data._epsilon * data._epsilon;
2193   for ( unsigned i = 0; i < data._edges.size(); ++i )
2194   {
2195     _LayerEdge* edge = data._edges[i];
2196     if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2197     if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2198     {
2199       const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2200       set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2201       ee.insert( f->_le1 );
2202       ee.insert( f->_le2 );
2203       if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() ) 
2204         edge2CloseEdge[ f->_le1 ].insert( edge );
2205       if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() ) 
2206         edge2CloseEdge[ f->_le2 ].insert( edge );
2207     }
2208   }
2209
2210   // Set _LayerEdge._normal
2211
2212   if ( !edge2CloseEdge.empty() )
2213   {
2214     dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2215
2216     TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2217     for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2218     {
2219       _LayerEdge* edge1       = e2ee->first;
2220       _LayerEdge* edge2       = 0;
2221       set< _LayerEdge*, _LayerEdgeCmp >& ee  = e2ee->second;
2222
2223       // find EDGEs the edges reside
2224       TopoDS_Edge E1, E2;
2225       TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2226       if ( S.ShapeType() != TopAbs_EDGE )
2227         continue; // TODO: find EDGE by VERTEX
2228       E1 = TopoDS::Edge( S );
2229       set< _LayerEdge* >::iterator eIt = ee.begin();
2230       while ( E2.IsNull() && eIt != ee.end())
2231       {
2232         _LayerEdge* e2 = *eIt++;
2233         TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2234         if ( S.ShapeType() == TopAbs_EDGE )
2235           E2 = TopoDS::Edge( S ), edge2 = e2;
2236       }
2237       if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2238
2239       // find 3 FACEs sharing 2 EDGEs
2240
2241       TopoDS_Face FF1[2], FF2[2];
2242       PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2243       while ( fIt->more() && FF1[1].IsNull())
2244       {
2245         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2246         if ( helper.IsSubShape( *F, data._solid))
2247           FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2248       }
2249       fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2250       while ( fIt->more() && FF2[1].IsNull())
2251       {
2252         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2253         if ( helper.IsSubShape( *F, data._solid))
2254           FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2255       }
2256       // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2257       if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2258         std::swap( FF1[0], FF1[1] );
2259       if ( FF2[0].IsSame( FF1[0]) )
2260         std::swap( FF2[0], FF2[1] );
2261       if ( FF1[0].IsNull() || FF2[0].IsNull() )
2262         continue;
2263
2264 //       // get a new normal for edge1
2265       bool ok;
2266       gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2267       if ( edge1->_cosin < 0 )
2268         dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2269       if ( edge2->_cosin < 0 )
2270         dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2271       //      gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2272 //       gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2273 //       double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2274 //       double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2275 //       gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2276 //       newNorm.Normalize();
2277
2278       double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2279       double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2280       gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2281       newNorm.Normalize();
2282
2283       edge1->_normal = newNorm.XYZ();
2284
2285       // update data of edge1 depending on _normal
2286       const SMDS_MeshNode *n1, *n2;
2287       n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2288       n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2289       //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2290       //continue;
2291       edge1->SetDataByNeighbors( n1, n2, helper );
2292       gp_Vec dirInFace;
2293       if ( edge1->_cosin < 0 )
2294         dirInFace = dir1;
2295       else
2296         getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2297       double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2298       edge1->SetCosin( cos( angle ));
2299
2300       // limit data._stepSize
2301       if ( edge1->_cosin > 0.1 )
2302       {
2303         SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2304         while ( fIt->more() )
2305           limitStepSize( data, fIt->next(), edge1->_cosin );
2306       }
2307       // set new XYZ of target node
2308       edge1->InvalidateStep( 1 );
2309       edge1->_len = 0;
2310       edge1->SetNewLength( data._stepSize, helper );
2311     }
2312
2313     // Update normals and other dependent data of not intersecting _LayerEdge's
2314     // neighboring the intersecting ones
2315
2316     for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2317     {
2318       _LayerEdge* edge1 = e2ee->first;
2319       if ( !edge1->_2neibors )
2320         continue;
2321       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2322       {
2323         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2324         if ( edge2CloseEdge.count ( neighbor ))
2325           continue; // j-th neighbor is also intersected
2326         _LayerEdge* prevEdge = edge1;
2327         const int nbSteps = 6;
2328         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2329         {
2330           if ( !neighbor->_2neibors )
2331             break; // neighbor is on VERTEX
2332           int iNext = 0;
2333           _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2334           if ( nextEdge == prevEdge )
2335             nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2336 //           const double&  wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2337 //           const double&  wgtNext = neighbor->_2neibors->_wgt[iNext];
2338           double r = double(step-1)/nbSteps;
2339           if ( !nextEdge->_2neibors )
2340             r = 0.5;
2341
2342           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2343           newNorm.Normalize();
2344
2345           neighbor->_normal = newNorm;
2346           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2347           neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2348
2349           neighbor->InvalidateStep( 1 );
2350           neighbor->_len = 0;
2351           neighbor->SetNewLength( data._stepSize, helper );
2352
2353           // goto the next neighbor
2354           prevEdge = neighbor;
2355           neighbor = nextEdge;
2356         }
2357       }
2358     }
2359     dumpFunctionEnd();
2360   }
2361   // 2) Check absence of intersections
2362   // TODO?
2363
2364   for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2365     delete tmpFaces[i];
2366
2367   return true;
2368 }
2369
2370 //================================================================================
2371 /*!
2372  * \brief Looks for intersection of it's last segment with faces
2373  *  \param distance - returns shortest distance from the last node to intersection
2374  */
2375 //================================================================================
2376
2377 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
2378                                    double &                 distance,
2379                                    const double&            epsilon,
2380                                    const SMDS_MeshElement** face)
2381 {
2382   vector< const SMDS_MeshElement* > suspectFaces;
2383   double segLen;
2384   gp_Ax1 lastSegment = LastSegment(segLen);
2385   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2386
2387   bool segmentIntersected = false;
2388   distance = Precision::Infinite();
2389   int iFace = -1; // intersected face
2390   for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2391   {
2392     const SMDS_MeshElement* face = suspectFaces[j];
2393     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2394          face->GetNodeIndex( _nodes[0]     ) >= 0 )
2395       continue; // face sharing _LayerEdge node
2396     const int nbNodes = face->NbCornerNodes();
2397     bool intFound = false;
2398     double dist;
2399     SMDS_MeshElement::iterator nIt = face->begin_nodes();
2400     if ( nbNodes == 3 )
2401     {
2402       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2403     }
2404     else
2405     {
2406       const SMDS_MeshNode* tria[3];
2407       tria[0] = *nIt++;
2408       tria[1] = *nIt++;;
2409       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2410       {
2411         tria[2] = *nIt++;
2412         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2413         tria[1] = tria[2];
2414       }
2415     }
2416     if ( intFound )
2417     {
2418       if ( dist < segLen*(1.01))
2419         segmentIntersected = true;
2420       if ( distance > dist )
2421         distance = dist, iFace = j;
2422     }
2423   }
2424   if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2425 //   if ( distance && iFace > -1 )
2426 //   {
2427 //     // distance is used to limit size of inflation step which depends on
2428 //     // whether the intersected face bears viscous layers or not
2429 //     bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2430 //     if ( faceHasVL )
2431 //       *distance /= 2;
2432 //   }
2433   if ( segmentIntersected )
2434   {
2435 #ifdef __myDEBUG
2436     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2437     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2438     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2439          << ", intersection with face ("
2440          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2441          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2442          << ") distance = " << distance - segLen<< endl;
2443 #endif
2444   }
2445
2446   distance -= segLen;
2447
2448   return segmentIntersected;
2449 }
2450
2451 //================================================================================
2452 /*!
2453  * \brief Returns size and direction of the last segment
2454  */
2455 //================================================================================
2456
2457 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2458 {
2459   // find two non-coincident positions
2460   gp_XYZ orig = _pos.back();
2461   gp_XYZ dir;
2462   int iPrev = _pos.size() - 2;
2463   while ( iPrev >= 0 )
2464   {
2465     dir = orig - _pos[iPrev];
2466     if ( dir.SquareModulus() > 1e-100 )
2467       break;
2468     else
2469       iPrev--;
2470   }
2471
2472   // make gp_Ax1
2473   gp_Ax1 segDir;
2474   if ( iPrev < 0 )
2475   {
2476     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2477     segDir.SetDirection( _normal );
2478     segLen = 0;
2479   }
2480   else
2481   {
2482     gp_Pnt pPrev = _pos[ iPrev ];
2483     if ( !_sWOL.IsNull() )
2484     {
2485       TopLoc_Location loc;
2486       if ( _sWOL.ShapeType() == TopAbs_EDGE )
2487       {
2488         double f,l;
2489         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2490         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2491       }
2492       else
2493       {
2494         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2495         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2496       }
2497       dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2498     }
2499     segDir.SetLocation( pPrev );
2500     segDir.SetDirection( dir );
2501     segLen = dir.Modulus();
2502   }
2503
2504   return segDir;
2505 }
2506
2507 //================================================================================
2508 /*!
2509  * \brief Test intersection of the last segment with a given triangle
2510  *   using Moller-Trumbore algorithm
2511  * Intersection is detected if distance to intersection is less than _LayerEdge._len
2512  */
2513 //================================================================================
2514
2515 bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
2516                                const SMDS_MeshNode* n0,
2517                                const SMDS_MeshNode* n1,
2518                                const SMDS_MeshNode* n2,
2519                                double&              t,
2520                                const double&        EPSILON) const
2521 {
2522   //const double EPSILON = 1e-6;
2523
2524   gp_XYZ orig = lastSegment.Location().XYZ();
2525   gp_XYZ dir  = lastSegment.Direction().XYZ();
2526
2527   SMESH_TNodeXYZ vert0( n0 );
2528   SMESH_TNodeXYZ vert1( n1 );
2529   SMESH_TNodeXYZ vert2( n2 );
2530
2531   /* calculate distance from vert0 to ray origin */
2532   gp_XYZ tvec = orig - vert0;
2533
2534   if ( tvec * dir > EPSILON )
2535     // intersected face is at back side of the temporary face this _LayerEdge belongs to
2536     return false;
2537
2538   gp_XYZ edge1 = vert1 - vert0;
2539   gp_XYZ edge2 = vert2 - vert0;
2540
2541   /* begin calculating determinant - also used to calculate U parameter */
2542   gp_XYZ pvec = dir ^ edge2;
2543
2544   /* if determinant is near zero, ray lies in plane of triangle */
2545   double det = edge1 * pvec;
2546
2547   if (det > -EPSILON && det < EPSILON)
2548     return 0;
2549   double inv_det = 1.0 / det;
2550
2551   /* calculate U parameter and test bounds */
2552   double u = ( tvec * pvec ) * inv_det;
2553   if (u < 0.0 || u > 1.0)
2554     return 0;
2555
2556   /* prepare to test V parameter */
2557   gp_XYZ qvec = tvec ^ edge1;
2558
2559   /* calculate V parameter and test bounds */
2560   double v = (dir * qvec) * inv_det;
2561   if ( v < 0.0 || u + v > 1.0 )
2562     return 0;
2563
2564   /* calculate t, ray intersects triangle */
2565   t = (edge2 * qvec) * inv_det;
2566
2567   //   if (det < EPSILON)
2568   //     return false;
2569
2570   //   /* calculate distance from vert0 to ray origin */
2571   //   gp_XYZ tvec = orig - vert0;
2572
2573   //   /* calculate U parameter and test bounds */
2574   //   double u = tvec * pvec;
2575   //   if (u < 0.0 || u > det)
2576 //     return 0;
2577
2578 //   /* prepare to test V parameter */
2579 //   gp_XYZ qvec = tvec ^ edge1;
2580
2581 //   /* calculate V parameter and test bounds */
2582 //   double v = dir * qvec;
2583 //   if (v < 0.0 || u + v > det)
2584 //     return 0;
2585
2586 //   /* calculate t, scale parameters, ray intersects triangle */
2587 //   double t = edge2 * qvec;
2588 //   double inv_det = 1.0 / det;
2589 //   t *= inv_det;
2590 //   //u *= inv_det;
2591 //   //v *= inv_det;
2592
2593   return true;
2594 }
2595
2596 //================================================================================
2597 /*!
2598  * \brief Perform smooth of _LayerEdge's based on EDGE's
2599  *  \retval bool - true if node has been moved
2600  */
2601 //================================================================================
2602
2603 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
2604                               const TopoDS_Face&    F,
2605                               SMESH_MesherHelper&   helper)
2606 {
2607   ASSERT( IsOnEdge() );
2608
2609   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
2610   SMESH_TNodeXYZ oldPos( tgtNode );
2611   double dist01, distNewOld;
2612   
2613   SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
2614   SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
2615   dist01 = p0.Distance( _2neibors->_nodes[1] );
2616
2617   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
2618   double lenDelta = 0;
2619   if ( _curvature )
2620   {
2621     lenDelta = _curvature->lenDelta( _len );
2622     newPos.ChangeCoord() += _normal * lenDelta;
2623   }
2624
2625   distNewOld = newPos.Distance( oldPos );
2626
2627   if ( F.IsNull() )
2628   {
2629     if ( _2neibors->_plnNorm )
2630     {
2631       // put newPos on the plane defined by source node and _plnNorm
2632       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
2633       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
2634       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
2635     }
2636     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2637     _pos.back() = newPos.XYZ();
2638   }
2639   else
2640   {
2641     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2642     gp_XY uv( Precision::Infinite(), 0 );
2643     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
2644     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
2645
2646     newPos = surface->Value( uv.X(), uv.Y() );
2647     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2648   }
2649
2650   if ( _curvature && lenDelta < 0 )
2651   {
2652     gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
2653     _len -= prevPos.Distance( oldPos );
2654     _len += prevPos.Distance( newPos );
2655   }
2656   bool moved = distNewOld > dist01/50;
2657   //if ( moved )
2658   dumpMove( tgtNode ); // debug
2659
2660   return moved;
2661 }
2662
2663 //================================================================================
2664 /*!
2665  * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
2666  *  \retval bool - true if _tgtNode has been moved
2667  */
2668 //================================================================================
2669
2670 bool _LayerEdge::Smooth(int& badNb)
2671 {
2672   if ( _simplices.size() < 2 )
2673     return false; // _LayerEdge inflated along EDGE or FACE
2674
2675   // compute new position for the last _pos
2676   gp_XYZ newPos (0,0,0);
2677   for ( unsigned i = 0; i < _simplices.size(); ++i )
2678     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
2679   newPos /= _simplices.size();
2680
2681   if ( _curvature )
2682     newPos += _normal * _curvature->lenDelta( _len );
2683
2684   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
2685 //   if ( _cosin < -0.1)
2686 //   {
2687 //     // Avoid decreasing length of edge on concave surface
2688 //     //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
2689 //     gp_Vec newMove( prevPos, newPos );
2690 //     newPos = _pos.back() + newMove.XYZ();
2691 //   }
2692 //   else if ( _cosin > 0.3 )
2693 //   {
2694 //     // Avoid increasing length of edge too much
2695
2696 //   }
2697   // count quality metrics (orientation) of tetras around _tgtNode
2698   int nbOkBefore = 0;
2699   SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
2700   for ( unsigned i = 0; i < _simplices.size(); ++i )
2701     nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
2702
2703   int nbOkAfter = 0;
2704   for ( unsigned i = 0; i < _simplices.size(); ++i )
2705     nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
2706
2707   if ( nbOkAfter < nbOkBefore )
2708     return false;
2709
2710   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
2711
2712   _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
2713   _len += prevPos.Distance(newPos);
2714
2715   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
2716   _pos.back() = newPos;
2717
2718   badNb += _simplices.size() - nbOkAfter;
2719
2720   dumpMove( n );
2721
2722   return true;
2723 }
2724
2725 //================================================================================
2726 /*!
2727  * \brief Add a new segment to _LayerEdge during inflation
2728  */
2729 //================================================================================
2730
2731 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
2732 {
2733   if ( _len - len > -1e-6 )
2734   {
2735     _pos.push_back( _pos.back() );
2736     return;
2737   }
2738
2739   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
2740   SMESH_TNodeXYZ oldXYZ( n );
2741   gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
2742   n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
2743
2744   _pos.push_back( nXYZ );
2745   _len = len;
2746   if ( !_sWOL.IsNull() )
2747   {
2748     double distXYZ[4];
2749     if ( _sWOL.ShapeType() == TopAbs_EDGE )
2750     {
2751       double u = Precision::Infinite(); // to force projection w/o distance check
2752       helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
2753       _pos.back().SetCoord( u, 0, 0 );
2754       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
2755       pos->SetUParameter( u );
2756     }
2757     else //  TopAbs_FACE
2758     {
2759       gp_XY uv( Precision::Infinite(), 0 );
2760       helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
2761       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
2762       SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
2763       pos->SetUParameter( uv.X() );
2764       pos->SetVParameter( uv.Y() );
2765     }
2766     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
2767   }
2768   dumpMove( n ); //debug
2769 }
2770
2771 //================================================================================
2772 /*!
2773  * \brief Remove last inflation step
2774  */
2775 //================================================================================
2776
2777 void _LayerEdge::InvalidateStep( int curStep )
2778 {
2779   if ( _pos.size() > curStep )
2780   {
2781     _pos.resize( curStep );
2782     gp_Pnt nXYZ = _pos.back();
2783     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
2784     if ( !_sWOL.IsNull() )
2785     {
2786       TopLoc_Location loc;
2787       if ( _sWOL.ShapeType() == TopAbs_EDGE )
2788       {
2789         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
2790         pos->SetUParameter( nXYZ.X() );
2791         double f,l;
2792         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2793         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
2794       }
2795       else
2796       {
2797         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
2798         pos->SetUParameter( nXYZ.X() );
2799         pos->SetVParameter( nXYZ.Y() );
2800         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2801         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
2802       }
2803     }
2804     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
2805     dumpMove( n );
2806   }
2807 }
2808
2809 //================================================================================
2810 /*!
2811  * \brief Create layers of prisms
2812  */
2813 //================================================================================
2814
2815 bool _ViscousBuilder::refine(_SolidData& data)
2816 {
2817   SMESH_MesherHelper helper( *_mesh );
2818   helper.SetSubShape( data._solid );
2819   helper.SetElementsOnShape(false);
2820
2821   Handle(Geom_Curve) curve;
2822   Handle(Geom_Surface) surface;
2823   TopoDS_Edge geomEdge;
2824   TopoDS_Face geomFace;
2825   TopLoc_Location loc;
2826   double f,l, u/*, distXYZ[4]*/;
2827   gp_XY uv;
2828   bool isOnEdge;
2829
2830   for ( unsigned i = 0; i < data._edges.size(); ++i )
2831   {
2832     _LayerEdge& edge = *data._edges[i];
2833
2834     // get accumulated length of segments
2835     vector< double > segLen( edge._pos.size() );
2836     segLen[0] = 0.0;
2837     for ( unsigned j = 1; j < edge._pos.size(); ++j )
2838       segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
2839
2840     // allocate memory for new nodes if it is not yet refined
2841     const SMDS_MeshNode* tgtNode = edge._nodes.back();
2842     if ( edge._nodes.size() == 2 )
2843     {
2844       edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
2845       edge._nodes[1] = 0;
2846       edge._nodes.back() = tgtNode;
2847     }
2848     if ( !edge._sWOL.IsNull() )
2849     {
2850       isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
2851       // restore position of the last node
2852 //       gp_Pnt p;
2853       if ( isOnEdge )
2854       {
2855         geomEdge = TopoDS::Edge( edge._sWOL );
2856         curve = BRep_Tool::Curve( geomEdge, loc, f,l);
2857 //         double u = helper.GetNodeU( tgtNode );
2858 //         p = curve->Value( u );
2859       }
2860       else
2861       {
2862         geomFace = TopoDS::Face( edge._sWOL );
2863         surface = BRep_Tool::Surface( geomFace, loc );
2864 //         gp_XY uv = helper.GetNodeUV( tgtNode );
2865 //         p = surface->Value( uv.X(), uv.Y() );
2866       }
2867 //       p.Transform( loc );
2868 //       const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
2869     }
2870     // calculate height of the first layer
2871     double h0;
2872     const double T = segLen.back(); //data._hyp.GetTotalThickness();
2873     const double f = data._hyp->GetStretchFactor();
2874     const int    N = data._hyp->GetNumberLayers();
2875     const double fPowN = pow( f, N );
2876     if ( fPowN - 1 <= numeric_limits<double>::min() )
2877       h0 = T / N;
2878     else
2879       h0 = T * ( f - 1 )/( fPowN - 1 );
2880
2881     const double zeroLen = std::numeric_limits<double>::min();
2882
2883     // create intermediate nodes
2884     double hSum = 0, hi = h0/f;
2885     unsigned iSeg = 1;
2886     for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
2887     {
2888       // compute an intermediate position
2889       hi *= f;
2890       hSum += hi;
2891       while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
2892         ++iSeg;
2893       int iPrevSeg = iSeg-1;
2894       while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
2895         --iPrevSeg;
2896       double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
2897       gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
2898
2899       SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
2900       if ( !edge._sWOL.IsNull() )
2901       {
2902         // compute XYZ by parameters <pos>
2903         if ( isOnEdge )
2904         {
2905           u = pos.X();
2906           pos = curve->Value( u ).Transformed(loc);
2907         }
2908         else
2909         {
2910           uv.SetCoord( pos.X(), pos.Y() );
2911           pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
2912         }
2913       }
2914       // create or update the node
2915       if ( !node )
2916       {
2917         node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
2918         if ( !edge._sWOL.IsNull() )
2919         {
2920           if ( isOnEdge )
2921             getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
2922           else
2923             getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
2924         }
2925         else
2926         {
2927           getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
2928         }
2929       }
2930       else
2931       {
2932         if ( !edge._sWOL.IsNull() )
2933         {
2934           // make average pos from new and current parameters
2935           if ( isOnEdge )
2936           {
2937             u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
2938             pos = curve->Value( u ).Transformed(loc);
2939           }
2940           else
2941           {
2942             uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
2943             pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
2944           }
2945         }
2946         node->setXYZ( pos.X(), pos.Y(), pos.Z() );
2947       }
2948     }
2949   }
2950
2951   // TODO: make quadratic prisms and polyhedrons(?)
2952
2953   helper.SetElementsOnShape(true);
2954
2955   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2956   for ( ; exp.More(); exp.Next() )
2957   {
2958     if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
2959       continue;
2960     SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
2961     SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
2962     vector< vector<const SMDS_MeshNode*>* > nnVec;
2963     while ( fIt->more() )
2964     {
2965       const SMDS_MeshElement* face = fIt->next();
2966       int nbNodes = face->NbCornerNodes();
2967       nnVec.resize( nbNodes );
2968       SMDS_ElemIteratorPtr nIt = face->nodesIterator();
2969       for ( int iN = 0; iN < nbNodes; ++iN )
2970       {
2971         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
2972         nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
2973       }
2974
2975       int nbZ = nnVec[0]->size();
2976       switch ( nbNodes )
2977       {
2978       case 3:
2979         for ( int iZ = 1; iZ < nbZ; ++iZ )
2980           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
2981                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
2982         break;
2983       case 4:
2984         for ( int iZ = 1; iZ < nbZ; ++iZ )
2985           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
2986                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
2987                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
2988                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
2989         break;
2990       default:
2991         return error("Not supported type of element", data._index);
2992       }
2993     }
2994   }
2995   return true;
2996 }
2997
2998 //================================================================================
2999 /*!
3000  * \brief Shrink 2D mesh on faces to let space for inflated layers
3001  */
3002 //================================================================================
3003
3004 bool _ViscousBuilder::shrink()
3005 {
3006   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3007   // inflated along FACE or EDGE)
3008   map< TGeomID, _SolidData* > f2sdMap;
3009   for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3010   {
3011     _SolidData& data = _sdVec[i];
3012     TopTools_MapOfShape FFMap;
3013     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3014     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3015       if ( s2s->second.ShapeType() == TopAbs_FACE )
3016       {
3017         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3018
3019         if ( FFMap.Add( (*s2s).second ))
3020           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3021           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3022           // by StdMeshers_QuadToTriaAdaptor
3023           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3024           {
3025             SMESH_ProxyMesh::SubMesh* proxySub =
3026               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3027             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3028             while ( fIt->more() )
3029               proxySub->AddElement( fIt->next() );
3030           }
3031       }
3032   }
3033
3034   SMESH_MesherHelper helper( *_mesh );
3035
3036   // EDGE's to shrink
3037   map< int, _Shrinker1D > e2shrMap;
3038
3039   // loop on FACES to srink mesh on
3040   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3041   for ( ; f2sd != f2sdMap.end(); ++f2sd )
3042   {
3043     _SolidData&     data = *f2sd->second;
3044     TNode2Edge&   n2eMap = data._n2eMap;
3045     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3046     const bool   reverse = ( data._reversedFaceIds.count( f2sd->first ));
3047
3048     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3049
3050     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
3051     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3052
3053     helper.SetSubShape(F);
3054
3055     // ===========================
3056     // Prepare data for shrinking
3057     // ===========================
3058
3059     // Collect nodes to smooth as src nodes are not yet replaced by tgt ones
3060     // and thus all nodes on FACE connected to 2d elements are to be smoothed
3061     vector < const SMDS_MeshNode* > smoothNodes;
3062     {
3063       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3064       while ( nIt->more() )
3065       {
3066         const SMDS_MeshNode* n = nIt->next();
3067         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3068           smoothNodes.push_back( n );
3069       }
3070     }
3071     // Find out face orientation
3072     double refSign = 1;
3073     const set<TGeomID> ignoreShapes;
3074     if ( !smoothNodes.empty() )
3075     {
3076       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0] );
3077       vector<_Simplex> simplices;
3078       getSimplices( smoothNodes[0], simplices, ignoreShapes );
3079       if ( simplices[0].IsForward(uv, F, helper,refSign) != (!reverse))
3080         refSign = -1;
3081     }
3082
3083     // Find _LayerEdge's inflated along F
3084     vector< _LayerEdge* > lEdges;
3085     {
3086       SMESH_subMeshIteratorPtr subIt =
3087         sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3088       while ( subIt->more() )
3089       {
3090         SMESH_subMesh* sub = subIt->next();
3091         SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3092         if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3093           continue;
3094         SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3095         while ( nIt->more() )
3096         {
3097           _LayerEdge* edge = n2eMap[ nIt->next() ];
3098           lEdges.push_back( edge );
3099           prepareEdgeToShrink( *edge, F, helper, smDS );
3100         }
3101       }
3102     }
3103
3104     // Replace source nodes by target nodes in mesh faces to shrink
3105     const SMDS_MeshNode* nodes[20];
3106     for ( unsigned i = 0; i < lEdges.size(); ++i )
3107     {
3108       _LayerEdge& edge = *lEdges[i];
3109       const SMDS_MeshNode* srcNode = edge._nodes[0];
3110       const SMDS_MeshNode* tgtNode = edge._nodes.back();
3111       SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3112       while ( fIt->more() )
3113       {
3114         const SMDS_MeshElement* f = fIt->next();
3115         if ( !smDS->Contains( f ))
3116           continue;
3117         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3118         for ( int iN = 0; iN < f->NbNodes(); ++iN )
3119         {
3120           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3121           nodes[iN] = ( n == srcNode ? tgtNode : n );
3122         }
3123         helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3124       }
3125     }
3126
3127     // Create _SmoothNode's on face F
3128     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3129     {
3130       dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3131       for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3132       {
3133         const SMDS_MeshNode* n = smoothNodes[i];
3134         nodesToSmooth[ i ]._node = n;
3135         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3136         getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes );
3137         dumpMove( n );
3138       }
3139       dumpFunctionEnd();
3140     }
3141     //if ( nodesToSmooth.empty() ) continue;
3142
3143     // Find EDGE's to shrink
3144     set< _Shrinker1D* > eShri1D;
3145     {
3146       for ( unsigned i = 0; i < lEdges.size(); ++i )
3147       {
3148         _LayerEdge* edge = lEdges[i];
3149         if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3150         {
3151           TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3152           _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3153           eShri1D.insert( & srinker );
3154           srinker.AddEdge( edge, helper );
3155           // restore params of nodes on EGDE if the EDGE has been already
3156           // srinked while srinking another FACE
3157           srinker.RestoreParams();
3158         }
3159       }
3160     }
3161
3162     // ==================
3163     // Perform shrinking
3164     // ==================
3165
3166     bool shrinked = true;
3167     int badNb, shriStep=0, smooStep=0;
3168     while ( shrinked )
3169     {
3170       // Move boundary nodes (actually just set new UV)
3171       // -----------------------------------------------
3172       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3173       shrinked = false;
3174       for ( unsigned i = 0; i < lEdges.size(); ++i )
3175       {
3176         shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3177       }
3178       dumpFunctionEnd();
3179       if ( !shrinked )
3180         break;
3181
3182       // Move nodes on EDGE's
3183       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3184       for ( ; shr != eShri1D.end(); ++shr )
3185         (*shr)->Compute( /*set3D=*/false, helper );
3186
3187       // Smoothing in 2D
3188       // -----------------
3189       int nbNoImpSteps = 0;
3190       bool moved = true;
3191       badNb = 1;
3192       while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3193       {
3194         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3195
3196         int oldBadNb = badNb;
3197         badNb = 0;
3198         moved = false;
3199         for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3200         {
3201           moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,/*set3D=*/false );
3202         }
3203         if ( badNb < oldBadNb )
3204           nbNoImpSteps = 0;
3205         else
3206           nbNoImpSteps++;
3207
3208         dumpFunctionEnd();
3209       }
3210       if ( badNb > 0 )
3211         return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3212     }
3213     // No wrongly shaped faces remain; final smooth. Set node XYZ
3214     for ( int st = 3; st; --st )
3215     {
3216       dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3217       for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3218         nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,/*set3D=*/st==1 );
3219       dumpFunctionEnd();
3220     }
3221     // Set event listener to clear FACE sub-mesh together with SOLID sub-mesh
3222     _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3223
3224   }// loop on FACES to srink mesh on
3225
3226
3227   // Replace source nodes by target nodes in shrinked mesh edges
3228
3229   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3230   for ( ; e2shr != e2shrMap.end(); ++e2shr )
3231     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3232
3233   return true;
3234 }
3235
3236 //================================================================================
3237 /*!
3238  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3239  */
3240 //================================================================================
3241
3242 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
3243                                            const TopoDS_Face&     F,
3244                                            SMESH_MesherHelper&    helper,
3245                                            const SMESHDS_SubMesh* faceSubMesh)
3246 {
3247   const SMDS_MeshNode* srcNode = edge._nodes[0];
3248   const SMDS_MeshNode* tgtNode = edge._nodes.back();
3249
3250   edge._pos.clear();
3251
3252   if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3253   {
3254     gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3255     gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3256     gp_Vec2d uvDir( srcUV, tgtUV );
3257     double uvLen = uvDir.Magnitude();
3258     uvDir /= uvLen;
3259     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3260
3261     // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3262     vector<const SMDS_MeshElement*> faces;
3263     multimap< double, const SMDS_MeshNode* > proj2node;
3264     SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3265     while ( fIt->more() )
3266     {
3267       const SMDS_MeshElement* f = fIt->next();
3268       if ( faceSubMesh->Contains( f ))
3269         faces.push_back( f );
3270     }
3271     for ( unsigned i = 0; i < faces.size(); ++i )
3272     {
3273       const int nbNodes = faces[i]->NbCornerNodes();
3274       for ( int j = 0; j < nbNodes; ++j )
3275       {
3276         const SMDS_MeshNode* n = faces[i]->GetNode(j);
3277         if ( n == srcNode ) continue;
3278         if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3279              ( faces.size() > 1 || nbNodes > 3 ))
3280           continue;
3281         gp_Pnt2d uv = helper.GetNodeUV( F, n );
3282         gp_Vec2d uvDirN( srcUV, uv );
3283         double proj = uvDirN * uvDir;
3284         proj2node.insert( make_pair( proj, n ));
3285       }
3286     }
3287
3288     multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3289     const double minProj = p2n->first;
3290     const double projThreshold = 1.1 * uvLen;
3291     if ( minProj > projThreshold )
3292     {
3293       // tgtNode is located so that it does not make faces with wrong orientation
3294       return true;
3295     }
3296     edge._pos.resize(1);
3297     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3298
3299     // store most risky nodes in _simplices
3300     p2nEnd = proj2node.lower_bound( projThreshold );
3301     int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3302     edge._simplices.resize( nbSimpl );
3303     for ( int i = 0; i < nbSimpl; ++i )
3304     {
3305       edge._simplices[i]._nPrev = p2n->second;
3306       if ( ++p2n != p2nEnd )
3307         edge._simplices[i]._nNext = p2n->second;
3308     }
3309     // set UV of source node to target node
3310     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3311     pos->SetUParameter( srcUV.X() );
3312     pos->SetVParameter( srcUV.Y() );
3313   }
3314   else // _sWOL is TopAbs_EDGE
3315   {
3316     TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3317     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3318     if ( !edgeSM || edgeSM->NbElements() == 0 )
3319       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3320
3321     const SMDS_MeshNode* n2 = 0;
3322     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3323     while ( eIt->more() && !n2 )
3324     {
3325       const SMDS_MeshElement* e = eIt->next();
3326       if ( !edgeSM->Contains(e)) continue;
3327       n2 = e->GetNode( 0 );
3328       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3329     }
3330     if ( !n2 )
3331       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3332
3333     double uSrc = helper.GetNodeU( E, srcNode, n2 );
3334     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3335     double u2   = helper.GetNodeU( E, n2,      srcNode );
3336
3337     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3338     {
3339       // tgtNode is located so that it does not make faces with wrong orientation
3340       return true;
3341     }
3342     edge._pos.resize(1);
3343     edge._pos[0].SetCoord( U_TGT, uTgt );
3344     edge._pos[0].SetCoord( U_SRC, uSrc );
3345     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3346
3347     edge._simplices.resize( 1 );
3348     edge._simplices[0]._nPrev = n2;
3349
3350     // set UV of source node to target node
3351     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3352     pos->SetUParameter( uSrc );
3353   }
3354   return true;
3355
3356   //================================================================================
3357   /*!
3358    * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3359    */
3360   //================================================================================
3361   
3362   // Compute UV to follow during shrinking
3363
3364 //   const SMDS_MeshNode* srcNode = edge._nodes[0];
3365 //   const SMDS_MeshNode* tgtNode = edge._nodes.back();
3366
3367 //   gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3368 //   gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3369 //   gp_Vec2d uvDir( srcUV, tgtUV );
3370 //   double uvLen = uvDir.Magnitude();
3371 //   uvDir /= uvLen;
3372
3373 //   // Select shrinking step such that not to make faces with wrong orientation.
3374 //   // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3375 //   const double minStepSize = uvLen / 20;
3376 //   double stepSize = uvLen;
3377 //   SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3378 //   while ( fIt->more() )
3379 //   {
3380 //     const SMDS_MeshElement* f = fIt->next();
3381 //     if ( !faceSubMesh->Contains( f )) continue;
3382 //     const int nbNodes = f->NbCornerNodes();
3383 //     for ( int i = 0; i < nbNodes; ++i )
3384 //     {
3385 //       const SMDS_MeshNode* n = f->GetNode(i);
3386 //       if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3387 //         continue;
3388 //       gp_XY uv = helper.GetNodeUV( F, n );
3389 //       gp_Vec2d uvDirN( srcUV, uv );
3390 //       double proj = uvDirN * uvDir;
3391 //       if ( proj < stepSize && proj > minStepSize )
3392 //         stepSize = proj;
3393 //     }
3394 //   }
3395 //   stepSize *= 0.8;
3396
3397 //   const int nbSteps = ceil( uvLen / stepSize );
3398 //   gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3399 //   gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3400 //   edge._pos.resize( nbSteps );
3401 //   edge._pos[0] = tgtUV0;
3402 //   for ( int i = 1; i < nbSteps; ++i )
3403 //   {
3404 //     double r = i / double( nbSteps );
3405 //     edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3406 //   }
3407 //   return true;
3408 }
3409
3410 //================================================================================
3411 /*!
3412  * \brief Move target node to it's final position on the FACE during shrinking
3413  */
3414 //================================================================================
3415
3416 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3417                                  const TopoDS_Face&    F,
3418                                  SMESH_MesherHelper&   helper )
3419 {
3420   if ( _pos.empty() )
3421     return false; // already at the target position
3422
3423   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
3424
3425   if ( _sWOL.ShapeType() == TopAbs_FACE )
3426   {
3427     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
3428     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
3429     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
3430     const double uvLen = tgtUV.Distance( curUV );
3431
3432     // Select shrinking step such that not to make faces with wrong orientation.
3433     const double kSafe = 0.8;
3434     const double minStepSize = uvLen / 10;
3435     double stepSize = uvLen;
3436     for ( unsigned i = 0; i < _simplices.size(); ++i )
3437     {
3438       const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
3439       for ( int j = 0; j < 2; ++j )
3440         if ( const SMDS_MeshNode* n = nn[j] )
3441         {
3442           gp_XY uv = helper.GetNodeUV( F, n );
3443           gp_Vec2d uvDirN( curUV, uv );
3444           double proj = uvDirN * uvDir * kSafe;
3445           if ( proj < stepSize && proj > minStepSize )
3446             stepSize = proj;
3447         }
3448     }
3449
3450     gp_Pnt2d newUV;
3451     if ( stepSize == uvLen )
3452     {
3453       newUV = tgtUV;
3454       _pos.clear();
3455     }
3456     else
3457     {
3458       newUV = curUV + uvDir.XY() * stepSize;
3459     }
3460
3461     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3462     pos->SetUParameter( newUV.X() );
3463     pos->SetVParameter( newUV.Y() );
3464
3465 #ifdef __myDEBUG
3466     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
3467     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
3468     dumpMove( tgtNode );
3469 #endif
3470   }
3471   else // _sWOL is TopAbs_EDGE
3472   {
3473     TopoDS_Edge E = TopoDS::Edge( _sWOL );
3474     const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
3475
3476     const double u2 = helper.GetNodeU( E, n2, tgtNode );
3477     const double uSrc   = _pos[0].Coord( U_SRC );
3478     const double lenTgt = _pos[0].Coord( LEN_TGT );
3479
3480     double newU = _pos[0].Coord( U_TGT );
3481     if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
3482     {
3483       _pos.clear();
3484     }
3485     else
3486     {
3487       newU = 0.1 * uSrc + 0.9 * u2;
3488     }
3489     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3490     pos->SetUParameter( newU );
3491 #ifdef __myDEBUG
3492     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
3493     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
3494     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
3495     dumpMove( tgtNode );
3496 #endif
3497   }
3498   return true;
3499 }
3500
3501 //================================================================================
3502 /*!
3503  * \brief Perform laplacian smooth on the FACE
3504  *  \retval bool - true if the node has been moved
3505  */
3506 //================================================================================
3507
3508 bool _SmoothNode::Smooth(int&                  badNb,
3509                          Handle(Geom_Surface)& surface,
3510                          SMESH_MesherHelper&   helper,
3511                          const double          refSign,
3512                          bool                  set3D)
3513 {
3514   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
3515
3516   // compute new UV for the node
3517   gp_XY newPos (0,0);
3518   for ( unsigned i = 0; i < _simplices.size(); ++i )
3519     newPos += helper.GetNodeUV( face, _simplices[i]._nPrev );
3520   newPos /= _simplices.size();
3521
3522   // count quality metrics (orientation) of triangles around the node
3523   int nbOkBefore = 0;
3524   gp_XY tgtUV = helper.GetNodeUV( face, _node );
3525   for ( unsigned i = 0; i < _simplices.size(); ++i )
3526     nbOkBefore += _simplices[i].IsForward( tgtUV, face, helper, refSign );
3527
3528   int nbOkAfter = 0;
3529   for ( unsigned i = 0; i < _simplices.size(); ++i )
3530     nbOkAfter += _simplices[i].IsForward( newPos, face, helper, refSign );
3531
3532   if ( nbOkAfter < nbOkBefore )
3533     return false;
3534
3535   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
3536   pos->SetUParameter( newPos.X() );
3537   pos->SetVParameter( newPos.Y() );
3538
3539 #ifdef __myDEBUG
3540   set3D = true;
3541 #endif
3542   if ( set3D )
3543   {
3544     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
3545     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
3546     dumpMove( _node );
3547   }
3548
3549   badNb += _simplices.size() - nbOkAfter;
3550   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
3551 }
3552
3553 //================================================================================
3554 /*!
3555  * \brief Delete _SolidData
3556  */
3557 //================================================================================
3558
3559 _SolidData::~_SolidData()
3560 {
3561   for ( unsigned i = 0; i < _edges.size(); ++i )
3562   {
3563     if ( _edges[i] && _edges[i]->_2neibors )
3564       delete _edges[i]->_2neibors;
3565     delete _edges[i];
3566   }
3567   _edges.clear();
3568 }
3569 //================================================================================
3570 /*!
3571  * \brief Add a _LayerEdge inflated along the EDGE
3572  */
3573 //================================================================================
3574
3575 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
3576 {
3577   // init
3578   if ( _nodes.empty() )
3579   {
3580     _edges[0] = _edges[1] = 0;
3581     _done = false;
3582   }
3583   // check _LayerEdge
3584   if ( e == _edges[0] || e == _edges[1] )
3585     return;
3586   if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
3587     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
3588   if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
3589     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
3590
3591   // store _LayerEdge
3592   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
3593   double f,l;
3594   BRep_Tool::Range( E, f,l );
3595   double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
3596   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
3597
3598   // Update _nodes
3599
3600   const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
3601   const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
3602
3603   if ( _nodes.empty() )
3604   {
3605     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
3606     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
3607       return;
3608     TopLoc_Location loc;
3609     Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
3610     GeomAdaptor_Curve aCurve(C);
3611     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
3612
3613     int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
3614     _initU  .reserve( nbExpectNodes );
3615     _normPar.reserve( nbExpectNodes );
3616     _nodes  .reserve( nbExpectNodes );
3617     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
3618     while ( nIt->more() )
3619     {
3620       const SMDS_MeshNode* node = nIt->next();
3621       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
3622            node == tgtNode0 || node == tgtNode1 )
3623         continue; // refinement nodes
3624       _nodes.push_back( node );
3625       _initU.push_back( helper.GetNodeU( E, node ));
3626       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
3627       _normPar.push_back(  len / totLen );
3628     }
3629   }
3630   else
3631   {
3632     // remove target node of the _LayerEdge from _nodes
3633     int nbFound = 0;
3634     for ( unsigned i = 0; i < _nodes.size(); ++i )
3635       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
3636         _nodes[i] = 0, nbFound++;
3637     if ( nbFound == _nodes.size() )
3638       _nodes.clear();
3639   }
3640 }
3641
3642 //================================================================================
3643 /*!
3644  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
3645  */
3646 //================================================================================
3647
3648 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
3649 {
3650   if ( _done || _nodes.empty())
3651     return;
3652   const _LayerEdge* e = _edges[0];
3653   if ( !e ) e = _edges[1];
3654   if ( !e ) return;
3655
3656   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
3657             ( !_edges[1] || _edges[1]->_pos.empty() ));
3658
3659   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
3660   double f,l;
3661   if ( set3D || _done )
3662   {
3663     Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
3664     GeomAdaptor_Curve aCurve(C);
3665
3666     if ( _edges[0] )
3667       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
3668     if ( _edges[1] )
3669       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
3670     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
3671
3672     for ( unsigned i = 0; i < _nodes.size(); ++i )
3673     {
3674       if ( !_nodes[i] ) continue;
3675       double len = totLen * _normPar[i];
3676       GCPnts_AbscissaPoint discret( aCurve, len, f );
3677       if ( !discret.IsDone() )
3678         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
3679       double u = discret.Parameter();
3680       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3681       pos->SetUParameter( u );
3682       gp_Pnt p = C->Value( u );
3683       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
3684     }
3685   }
3686   else
3687   {
3688     BRep_Tool::Range( E, f,l );
3689     if ( _edges[0] )
3690       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
3691     if ( _edges[1] )
3692       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
3693     
3694     for ( unsigned i = 0; i < _nodes.size(); ++i )
3695     {
3696       if ( !_nodes[i] ) continue;
3697       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
3698       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3699       pos->SetUParameter( u );
3700     }
3701   }
3702 }
3703
3704 //================================================================================
3705 /*!
3706  * \brief Restore initial parameters of nodes on EDGE
3707  */
3708 //================================================================================
3709
3710 void _Shrinker1D::RestoreParams()
3711 {
3712   if ( _done )
3713     for ( unsigned i = 0; i < _nodes.size(); ++i )
3714     {
3715       if ( !_nodes[i] ) continue;
3716       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3717       pos->SetUParameter( _initU[i] );
3718     }
3719   _done = false;
3720 }
3721 //================================================================================
3722 /*!
3723  * \brief Replace source nodes by target nodes in shrinked mesh edges
3724  */
3725 //================================================================================
3726
3727 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
3728 {
3729   const SMDS_MeshNode* nodes[3];
3730   for ( int i = 0; i < 2; ++i )
3731   {
3732     if ( !_edges[i] ) continue;
3733
3734     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
3735     if ( !eSubMesh ) return;
3736     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
3737     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
3738     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3739     while ( eIt->more() )
3740     {
3741       const SMDS_MeshElement* e = eIt->next();
3742       if ( !eSubMesh->Contains( e ))
3743           continue;
3744       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3745       for ( int iN = 0; iN < e->NbNodes(); ++iN )
3746       {
3747         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3748         nodes[iN] = ( n == srcNode ? tgtNode : n );
3749       }
3750       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
3751     }
3752   }
3753 }
3754
3755 //================================================================================
3756 /*!
3757  * \brief Creates 2D and 1D elements on boundaries of new prisms
3758  */
3759 //================================================================================
3760
3761 bool _ViscousBuilder::addBoundaryElements()
3762 {
3763   SMESH_MesherHelper helper( *_mesh );
3764
3765   for ( unsigned i = 0; i < _sdVec.size(); ++i )
3766   {
3767     _SolidData& data = _sdVec[i];
3768     TopTools_IndexedMapOfShape geomEdges;
3769     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
3770     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
3771     {
3772       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
3773
3774       // Get _LayerEdge's based on E
3775
3776       map< double, const SMDS_MeshNode* > u2nodes;
3777       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
3778         continue;
3779
3780       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
3781       TNode2Edge & n2eMap = data._n2eMap;
3782       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
3783       {
3784         //check if 2D elements are needed on E
3785         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
3786         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
3787         ledges.push_back( n2e->second );
3788         u2n++;
3789         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
3790           continue; // no layers on E
3791         ledges.push_back( n2eMap[ u2n->second ]);
3792
3793         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
3794         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
3795         int nbSharedPyram = 0;
3796         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
3797         while ( vIt->more() )
3798         {
3799           const SMDS_MeshElement* v = vIt->next();
3800           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
3801         }
3802         if ( nbSharedPyram > 1 )
3803           continue; // not free border of the pyramid
3804
3805         if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
3806                                     ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
3807           continue; // faces already created
3808       }
3809       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
3810         ledges.push_back( n2eMap[ u2n->second ]);
3811
3812       // Find out orientation and type of face to create
3813
3814       bool reverse = false, tria = false, isOnFace;
3815       
3816       map< TGeomID, TopoDS_Shape >::iterator e2f =
3817         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
3818       TopoDS_Shape F;
3819       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
3820       {
3821         F = e2f->second.Oriented( TopAbs_FORWARD );
3822         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
3823         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
3824           reverse = !reverse;
3825       }
3826       else
3827       {
3828         // find FACE with layers sharing E
3829         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
3830         while ( fIt->more() && F.IsNull() )
3831         {
3832           const TopoDS_Shape* pF = fIt->next();
3833           if ( helper.IsSubShape( *pF, data._solid) &&
3834                !_ignoreShapeIds.count( e2f->first ))
3835             F = *pF;
3836         }
3837         
3838         tria = true;
3839       }
3840       // Find the sub-mesh to add new faces
3841       SMESHDS_SubMesh* sm = 0;
3842       if ( isOnFace )
3843         sm = getMeshDS()->MeshElements( F );
3844       else
3845         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
3846       if ( !sm )
3847         return error("error in addBoundaryElements()", data._index);
3848
3849       // Make faces
3850       const int dj1 = reverse ? 0 : 1;
3851       const int dj2 = reverse ? 1 : 0;
3852       for ( unsigned j = 1; j < ledges.size(); ++j )
3853       {
3854         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
3855         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
3856         if ( isOnFace )
3857           for ( unsigned z = 1; z < nn1.size(); ++z )
3858             sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
3859         else
3860           for ( unsigned z = 1; z < nn1.size(); ++z )
3861             sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
3862       }
3863     }
3864   }
3865
3866   return true;
3867 }