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