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