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