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