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