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