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