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