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