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