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