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