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