Salome HOME
bos #20256: [CEA 18523] Porting SMESH to int 64 bits
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers2D.cxx
1 // Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers2D.cxx
21 // Created   : 23 Jul 2012
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers2D.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 "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshEditor.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_Quadtree.hxx"
45 #include "SMESH_subMesh.hxx"
46 #include "SMESH_subMeshEventListener.hxx"
47 #include "StdMeshers_FaceSide.hxx"
48
49 #include "utilities.h"
50
51 #include <BRepAdaptor_Curve.hxx>
52 #include <BRepAdaptor_Curve2d.hxx>
53 #include <BRep_Tool.hxx>
54 #include <Bnd_B2d.hxx>
55 #include <Bnd_B3d.hxx>
56 #include <ElCLib.hxx>
57 #include <GCPnts_AbscissaPoint.hxx>
58 #include <Geom2dAdaptor_Curve.hxx>
59 #include <Geom2dInt_GInter.hxx>
60 #include <Geom2d_Circle.hxx>
61 #include <Geom2d_Line.hxx>
62 #include <Geom2d_TrimmedCurve.hxx>
63 #include <GeomAdaptor_Curve.hxx>
64 #include <Geom_Circle.hxx>
65 #include <Geom_Curve.hxx>
66 #include <Geom_Line.hxx>
67 #include <Geom_TrimmedCurve.hxx>
68 #include <IntRes2d_IntersectionPoint.hxx>
69 #include <Precision.hxx>
70 #include <Standard_ErrorHandler.hxx>
71 #include <TColStd_Array1OfReal.hxx>
72 #include <TopExp.hxx>
73 #include <TopExp_Explorer.hxx>
74 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
75 #include <TopTools_IndexedMapOfShape.hxx>
76 #include <TopTools_ListIteratorOfListOfShape.hxx>
77 #include <TopTools_ListOfShape.hxx>
78 #include <TopTools_MapOfShape.hxx>
79 #include <TopoDS.hxx>
80 #include <TopoDS_Edge.hxx>
81 #include <TopoDS_Face.hxx>
82 #include <TopoDS_Vertex.hxx>
83 #include <gp_Ax1.hxx>
84 #include <gp_Vec.hxx>
85 #include <gp_XY.hxx>
86 #include <smIdType.hxx>
87
88 #include <list>
89 #include <string>
90 #include <cmath>
91 #include <limits>
92
93 #ifdef _DEBUG_
94 //#define __myDEBUG
95 #endif
96
97 using namespace std;
98
99 //================================================================================
100 namespace VISCOUS_2D
101 {
102   typedef int TGeomID;
103
104   //--------------------------------------------------------------------------------
105   /*!
106    * \brief Proxy Mesh of FACE with viscous layers. It's needed only to 
107    *        redefine newSubmesh().
108    */
109   struct _ProxyMeshOfFace : public SMESH_ProxyMesh
110   {
111     //---------------------------------------------------
112     // Proxy sub-mesh of an EDGE. It contains nodes in _uvPtStructVec.
113     struct _EdgeSubMesh : public SMESH_ProxyMesh::SubMesh
114     {
115       _EdgeSubMesh(const SMDS_Mesh* mesh, int index=0): SubMesh(mesh,index) {}
116       //virtual int NbElements() const { return _elements.size()+1; }
117       virtual smIdType NbNodes() const { return Max( 0, _uvPtStructVec.size()-2 ); }
118       void SetUVPtStructVec(UVPtStructVec& vec) { _uvPtStructVec.swap( vec ); }
119       UVPtStructVec& GetUVPtStructVec() { return _uvPtStructVec; }
120     };
121     _ProxyMeshOfFace(const SMESH_Mesh& mesh): SMESH_ProxyMesh(mesh) {}
122     _EdgeSubMesh* GetEdgeSubMesh(int ID) { return (_EdgeSubMesh*) getProxySubMesh(ID); }
123     virtual SubMesh* newSubmesh(int index=0) const { return new _EdgeSubMesh( GetMeshDS(), index); }
124   };
125   //--------------------------------------------------------------------------------
126   /*!
127    * \brief SMESH_subMeshEventListener used to store _ProxyMeshOfFace, computed
128    *        by _ViscousBuilder2D, in a SMESH_subMesh of the FACE.
129    *        This is to delete _ProxyMeshOfFace when StdMeshers_ViscousLayers2D
130    *        hypothesis is modified
131    */
132   struct _ProxyMeshHolder : public SMESH_subMeshEventListener
133   {
134     _ProxyMeshHolder( const TopoDS_Face&    face,
135                       SMESH_ProxyMesh::Ptr& mesh)
136       : SMESH_subMeshEventListener( /*deletable=*/true, Name() )
137     {
138       SMESH_subMesh* faceSM = mesh->GetMesh()->GetSubMesh( face );
139       faceSM->SetEventListener( this, new _Data( mesh ), faceSM );
140     }
141     // Finds a proxy mesh of face
142     static SMESH_ProxyMesh::Ptr FindProxyMeshOfFace( const TopoDS_Shape& face,
143                                                      SMESH_Mesh&         mesh )
144     {
145       SMESH_ProxyMesh::Ptr proxy;
146       SMESH_subMesh* faceSM = mesh.GetSubMesh( face );
147       if ( EventListenerData* ld = faceSM->GetEventListenerData( Name() ))
148         proxy = static_cast< _Data* >( ld )->_mesh;
149       return proxy;
150     }
151     // Treat events
152     void ProcessEvent(const int          event,
153                       const int          eventType,
154                       SMESH_subMesh*     /*subMesh*/,
155                       EventListenerData* data,
156                       const SMESH_Hypothesis*  /*hyp*/)
157     {
158       if ( event == SMESH_subMesh::CLEAN && eventType == SMESH_subMesh::COMPUTE_EVENT)
159         ((_Data*) data)->_mesh.reset();
160     }
161   private:
162     // holder of a proxy mesh
163     struct _Data : public SMESH_subMeshEventListenerData
164     {
165       SMESH_ProxyMesh::Ptr _mesh;
166       _Data( SMESH_ProxyMesh::Ptr& mesh )
167         :SMESH_subMeshEventListenerData( /*isDeletable=*/true), _mesh( mesh )
168       {}
169     };
170     // Returns identifier string
171     static const char* Name() { return "VISCOUS_2D::_ProxyMeshHolder"; }
172   };
173   
174   struct _PolyLine;
175   //--------------------------------------------------------------------------------
176   /*!
177    * \brief Segment connecting inner ends of two _LayerEdge's.
178    */
179   struct _Segment
180   {
181     const gp_XY* _uv[2];       // pointer to _LayerEdge::_uvIn
182     int          _indexInLine; // position in _PolyLine
183
184     _Segment() {}
185     _Segment(const gp_XY& p1, const gp_XY& p2):_indexInLine(-1) { _uv[0] = &p1; _uv[1] = &p2; }
186     const gp_XY& p1() const { return *_uv[0]; }
187     const gp_XY& p2() const { return *_uv[1]; }
188   };
189   //--------------------------------------------------------------------------------
190   /*!
191    * \brief Tree of _Segment's used for a faster search of _Segment's.
192    */
193   struct _SegmentTree : public SMESH_Quadtree
194   {
195     typedef boost::shared_ptr< _SegmentTree > Ptr;
196
197     _SegmentTree( const vector< _Segment >& segments );
198     void GetSegmentsNear( const _Segment& seg, vector< const _Segment* >& found );
199     void GetSegmentsNear( const gp_Ax2d& ray, vector< const _Segment* >& found );
200   protected:
201     _SegmentTree() {}
202     _SegmentTree* newChild() const { return new _SegmentTree; }
203     void          buildChildrenData();
204     Bnd_B2d*      buildRootBox();
205   private:
206     static int    maxNbSegInLeaf() { return 5; }
207     struct _SegBox
208     {
209       const _Segment* _seg;
210       bool            _iMin[2];
211       void Set( const _Segment& seg )
212       {
213         _seg = &seg;
214         _iMin[0] = ( seg._uv[1]->X() < seg._uv[0]->X() );
215         _iMin[1] = ( seg._uv[1]->Y() < seg._uv[0]->Y() );
216       }
217       bool IsOut( const _Segment& seg ) const;
218       bool IsOut( const gp_Ax2d& ray ) const;
219     };
220     vector< _SegBox > _segments;
221   };
222   //--------------------------------------------------------------------------------
223   /*!
224    * \brief Edge normal to FACE boundary, connecting a point on EDGE (_uvOut)
225    * and a point of a layer internal boundary (_uvIn)
226    */
227   struct _LayerEdge
228   {
229     gp_XY         _uvOut;    // UV on the FACE boundary
230     gp_XY         _uvIn;     // UV inside the FACE
231     double        _length2D; // distance between _uvOut and _uvIn
232
233     bool          _isBlocked;// is more inflation possible or not
234
235     gp_XY         _normal2D; // to curve
236     double        _len2dTo3dRatio; // to pass 2D <--> 3D
237     gp_Ax2d       _ray;      // a ray starting at _uvOut
238
239     vector<gp_XY> _uvRefined; // divisions by layers
240
241     bool SetNewLength( const double length );
242
243 #ifdef _DEBUG_
244     int           _ID;
245 #endif
246   };
247   //--------------------------------------------------------------------------------
248   /*!
249    * \brief Poly line composed of _Segment's of one EDGE.
250    *        It's used to detect intersection of inflated layers by intersecting
251    *        _Segment's in 2D.
252    */
253   struct _PolyLine
254   {
255     StdMeshers_FaceSide* _wire;
256     int                  _edgeInd;     // index of my EDGE in _wire
257     bool                 _advancable;  // true if there is a viscous layer on my EDGE
258     bool                 _isStraight2D;// pcurve type
259     _PolyLine*           _leftLine;    // lines of neighbour EDGE's
260     _PolyLine*           _rightLine;
261     int                  _firstPntInd; // index in vector<UVPtStruct> of _wire
262     int                  _lastPntInd;
263     int                  _index;       // index in _ViscousBuilder2D::_polyLineVec
264
265     vector< _LayerEdge > _lEdges;      /* _lEdges[0] is usually is not treated
266                                           as it is equal to the last one of the _leftLine */
267     vector< _Segment >   _segments;    // segments connecting _uvIn's of _lEdges
268     _SegmentTree::Ptr    _segTree;
269
270     vector< _PolyLine* > _reachableLines;       // lines able to interfere with my layer
271
272     vector< const SMDS_MeshNode* > _leftNodes;  // nodes built from a left VERTEX
273     vector< const SMDS_MeshNode* > _rightNodes; // nodes built from a right VERTEX
274
275     typedef vector< _Segment >::iterator   TSegIterator;
276     typedef vector< _LayerEdge >::iterator TEdgeIterator;
277
278     TIDSortedElemSet     _newFaces; // faces generated from this line
279
280     bool IsCommonEdgeShared( const _PolyLine& other );
281     size_t FirstLEdge() const
282     {
283       return ( _leftLine->_advancable && _lEdges.size() > 2 ) ? 1 : 0;
284     }
285     bool IsAdjacent( const _Segment& seg, const _LayerEdge* LE=0 ) const
286     {
287       if ( LE /*&& seg._indexInLine < _lEdges.size()*/ )
288         return ( seg._uv[0] == & LE->_uvIn ||
289                  seg._uv[1] == & LE->_uvIn );
290       return ( & seg == &_leftLine->_segments.back() ||
291                & seg == &_rightLine->_segments[0] );
292     }
293     bool IsConcave() const;
294   };
295   //--------------------------------------------------------------------------------
296   /*!
297    * \brief Intersector of _Segment's
298    */
299   struct _SegmentIntersection
300   {
301     gp_XY    _vec1, _vec2;     // Vec( _seg.p1(), _seg.p2() )
302     gp_XY    _vec21;           // Vec( _seg2.p1(), _seg1.p1() )
303     double   _D;               // _vec1.Crossed( _vec2 )
304     double   _param1, _param2; // intersection param on _seg1 and _seg2
305
306     _SegmentIntersection(): _D(0), _param1(0), _param2(0) {}
307
308     bool Compute(const _Segment& seg1, const _Segment& seg2, bool seg2IsRay = false )
309     {
310       // !!! If seg2IsRay, returns true at any _param2 !!!
311       const double eps = 1e-10;
312       _vec1  = seg1.p2() - seg1.p1(); 
313       _vec2  = seg2.p2() - seg2.p1(); 
314       _vec21 = seg1.p1() - seg2.p1(); 
315       _D = _vec1.Crossed(_vec2);
316       if ( fabs(_D) < std::numeric_limits<double>::min())
317         return false;
318       _param1 = _vec2.Crossed(_vec21) / _D; 
319       if (_param1 < -eps || _param1 > 1 + eps )
320         return false;
321       _param2 = _vec1.Crossed(_vec21) / _D;
322       return seg2IsRay || ( _param2 > -eps && _param2 < 1 + eps );
323     }
324     bool Compute( const _Segment& seg1, const gp_Ax2d& ray )
325     {
326       gp_XY segEnd = ray.Location().XY() + ray.Direction().XY();
327       _Segment seg2( ray.Location().XY(), segEnd );
328       return Compute( seg1, seg2, true );
329     }
330     //gp_XY GetPoint() { return _seg1.p1() + _param1 * _vec1; }
331   };
332   //--------------------------------------------------------------------------------
333
334   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
335   typedef StdMeshers_ViscousLayers2D                           THypVL;
336   
337   //--------------------------------------------------------------------------------
338   /*!
339    * \brief Builder of viscous layers
340    */
341   class _ViscousBuilder2D
342   {
343   public:
344     _ViscousBuilder2D(SMESH_Mesh&                       theMesh,
345                       const TopoDS_Face&                theFace,
346                       vector< const THypVL* > &         theHyp,
347                       vector< TopoDS_Shape > &          theHypShapes);
348     SMESH_ComputeErrorPtr GetError() const { return _error; }
349     // does it's job
350     SMESH_ProxyMesh::Ptr  Compute();
351
352   private:
353
354     friend class ::StdMeshers_ViscousLayers2D;
355
356     bool findEdgesWithLayers();
357     bool makePolyLines();
358     bool inflate();
359     bool fixCollisions();
360     bool refine();
361     bool shrink();
362     bool improve();
363     bool toShrinkForAdjacent( const TopoDS_Face& adjFace,
364                               const TopoDS_Edge& E,
365                               const TopoDS_Vertex& V);
366     void setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut );
367     void setLayerEdgeData( _LayerEdge&                 lEdge,
368                            const double                u,
369                            Handle(Geom2d_Curve)&       pcurve,
370                            Handle(Geom_Curve)&         curve,
371                            const gp_Pnt                pOut,
372                            const bool                  reverse,
373                            GeomAPI_ProjectPointOnSurf* faceProj);
374     void adjustCommonEdge( _PolyLine& LL, _PolyLine& LR );
375     void calcLayersHeight(const double    totalThick,
376                           vector<double>& heights,
377                           const THypVL*   hyp);
378     bool removeMeshFaces(const TopoDS_Shape& face);
379
380     const THypVL*     getLineHypothesis(int iPL);
381     double            getLineThickness (int iPL);
382
383     bool              error( const string& text );
384     SMESHDS_Mesh*     getMeshDS() { return _mesh->GetMeshDS(); }
385     _ProxyMeshOfFace* getProxyMesh();
386
387     // debug
388     //void makeGroupOfLE();
389
390   private:
391
392     // input data
393     SMESH_Mesh*                 _mesh;
394     TopoDS_Face                 _face;
395     vector< const THypVL* >     _hyps;
396     vector< TopoDS_Shape >      _hypShapes;
397
398     // result data
399     SMESH_ProxyMesh::Ptr        _proxyMesh;
400     SMESH_ComputeErrorPtr       _error;
401
402     // working data
403     Handle(Geom_Surface)        _surface;
404     SMESH_MesherHelper          _helper;
405     TSideVector                 _faceSideVec; // wires (StdMeshers_FaceSide) of _face
406     vector<_PolyLine>           _polyLineVec; // fronts to advance
407     vector< const THypVL* >     _hypOfEdge; // a hyp per an EDGE of _faceSideVec
408     bool                        _is2DIsotropic; // is same U and V resoulution of _face
409     vector<TopoDS_Face>         _clearedFaces; // FACEs whose mesh was removed by shrink()
410
411     //double                      _fPowN; // to compute thickness of layers
412     double                      _maxThickness; // max possible layers thickness
413
414     // sub-shapes of _face 
415     set<TGeomID>                _ignoreShapeIds; // ids of EDGEs w/o layers
416     set<TGeomID>                _noShrinkVert;   // ids of VERTEXes that are extremities
417     // of EDGEs along which _LayerEdge can't be inflated because no viscous layers
418     // defined on neighbour FACEs sharing an EDGE. Nonetheless _LayerEdge's
419     // are inflated along such EDGEs but then such _LayerEdge's are turned into
420     // a node on VERTEX, i.e. all nodes on a _LayerEdge are melded into one node.
421     
422     int                         _nbLE; // for DEBUG
423   };
424
425   //================================================================================
426   /*!
427    * \brief Returns StdMeshers_ViscousLayers2D for the FACE
428    */
429   bool findHyps(SMESH_Mesh&                                   theMesh,
430                 const TopoDS_Face&                            theFace,
431                 vector< const StdMeshers_ViscousLayers2D* > & theHyps,
432                 vector< TopoDS_Shape > &                      theAssignedTo)
433   {
434     theHyps.clear();
435     theAssignedTo.clear();
436     SMESH_HypoFilter hypFilter
437       ( SMESH_HypoFilter::HasName( StdMeshers_ViscousLayers2D::GetHypType() ));
438     list< const SMESHDS_Hypothesis * > hypList;
439     list< TopoDS_Shape >               hypShapes;
440     int nbHyps = theMesh.GetHypotheses
441       ( theFace, hypFilter, hypList, /*ancestors=*/true, &hypShapes );
442     if ( nbHyps )
443     {
444       theHyps.reserve( nbHyps );
445       theAssignedTo.reserve( nbHyps );
446       list< const SMESHDS_Hypothesis * >::iterator hyp = hypList.begin();
447       list< TopoDS_Shape >::iterator               shape = hypShapes.begin();
448       for ( ; hyp != hypList.end(); ++hyp, ++shape )
449       {
450         theHyps.push_back( static_cast< const StdMeshers_ViscousLayers2D* > ( *hyp ));
451         theAssignedTo.push_back( *shape );
452       }
453     }
454     return nbHyps;
455   }
456
457   //================================================================================
458   /*!
459    * \brief Returns ids of EDGEs not to create Viscous Layers on
460    *  \param [in] theHyp - the hypothesis, holding edges either to ignore or not to.
461    *  \param [in] theFace - the FACE whose EDGEs are checked.
462    *  \param [in] theMesh - the mesh.
463    *  \param [in,out] theEdgeIds - container returning EDGEs to ignore.
464    *  \return int - number of found EDGEs of the FACE.
465    */
466   //================================================================================
467
468   int getEdgesToIgnore( const StdMeshers_ViscousLayers2D* theHyp,
469                         const TopoDS_Shape&               theFace,
470                         const SMESHDS_Mesh*               theMesh,
471                         set< int > &                      theEdgeIds)
472   {
473     int nbEdgesToIgnore = 0;
474     vector<TGeomID> ids = theHyp->GetBndShapes();
475     if ( theHyp->IsToIgnoreShapes() ) // EDGEs to ignore are given
476     {
477       for ( size_t i = 0; i < ids.size(); ++i )
478       {
479         const TopoDS_Shape& E = theMesh->IndexToShape( ids[i] );
480         if ( !E.IsNull() &&
481              E.ShapeType() == TopAbs_EDGE &&
482              SMESH_MesherHelper::IsSubShape( E, theFace ))
483         {
484           theEdgeIds.insert( ids[i] );
485           ++nbEdgesToIgnore;
486         }
487       }
488     }
489     else // EDGEs to make the Viscous Layers on are given
490     {
491       TopExp_Explorer E( theFace, TopAbs_EDGE );
492       for ( ; E.More(); E.Next(), ++nbEdgesToIgnore )
493         theEdgeIds.insert( theMesh->ShapeToIndex( E.Current() ));
494
495       for ( size_t i = 0; i < ids.size(); ++i )
496         nbEdgesToIgnore -= theEdgeIds.erase( ids[i] );
497     }
498     return nbEdgesToIgnore;
499   }
500
501 } // namespace VISCOUS_2D
502
503 //================================================================================
504 // StdMeshers_ViscousLayers hypothesis
505 //
506 StdMeshers_ViscousLayers2D::StdMeshers_ViscousLayers2D(int hypId, SMESH_Gen* gen)
507   :StdMeshers_ViscousLayers(hypId, gen)
508 {
509   _name = StdMeshers_ViscousLayers2D::GetHypType();
510   _param_algo_dim = -2; // auxiliary hyp used by 2D algos
511 }
512 // --------------------------------------------------------------------------------
513 bool StdMeshers_ViscousLayers2D::SetParametersByMesh(const SMESH_Mesh*   /*theMesh*/,
514                                                      const TopoDS_Shape& /*theShape*/)
515 {
516   // TODO ???
517   return false;
518 }
519 // --------------------------------------------------------------------------------
520 SMESH_ProxyMesh::Ptr
521 StdMeshers_ViscousLayers2D::Compute(SMESH_Mesh&        theMesh,
522                                     const TopoDS_Face& theFace)
523 {
524   using namespace VISCOUS_2D;
525   vector< const StdMeshers_ViscousLayers2D* > hyps;
526   vector< TopoDS_Shape >                      hypShapes;
527
528   SMESH_ProxyMesh::Ptr pm = _ProxyMeshHolder::FindProxyMeshOfFace( theFace, theMesh );
529   if ( !pm )
530   {
531     if ( findHyps( theMesh, theFace, hyps, hypShapes ))
532     {
533       VISCOUS_2D::_ViscousBuilder2D builder( theMesh, theFace, hyps, hypShapes );
534       pm = builder.Compute();
535       SMESH_ComputeErrorPtr error = builder.GetError();
536       if ( error && !error->IsOK() )
537         theMesh.GetSubMesh( theFace )->GetComputeError() = error;
538       else if ( !pm )
539         pm.reset( new SMESH_ProxyMesh( theMesh ));
540       if ( getenv("__ONLY__VL2D__"))
541         pm.reset();
542     }
543     else
544     {
545       pm.reset( new SMESH_ProxyMesh( theMesh ));
546     }
547   }
548   return pm;
549 }
550 // --------------------------------------------------------------------------------
551 void StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( const StdMeshers_FaceSide& edgeNodes )
552 {
553   using namespace VISCOUS_2D;
554   SMESH_ProxyMesh::Ptr pm =
555     _ProxyMeshHolder::FindProxyMeshOfFace( edgeNodes.Face(), *edgeNodes.GetMesh() );
556   if ( !pm ) {
557     _ProxyMeshOfFace* proxyMeshOfFace = new _ProxyMeshOfFace( *edgeNodes.GetMesh() );
558     pm.reset( proxyMeshOfFace );
559     new _ProxyMeshHolder( edgeNodes.Face(), pm );
560   }
561   _ProxyMeshOfFace*  proxyMeshOfFace = static_cast<_ProxyMeshOfFace*>( pm.get() );
562   _ProxyMeshOfFace::_EdgeSubMesh* sm = proxyMeshOfFace->GetEdgeSubMesh( edgeNodes.EdgeID(0) );
563   sm->GetUVPtStructVec() = edgeNodes.GetUVPtStruct();
564 }
565 // --------------------------------------------------------------------------------
566 bool StdMeshers_ViscousLayers2D::HasProxyMesh( const TopoDS_Face& face, SMESH_Mesh& mesh )
567 {
568   return VISCOUS_2D::_ProxyMeshHolder::FindProxyMeshOfFace( face, mesh ).get();
569 }
570 // --------------------------------------------------------------------------------
571 SMESH_ComputeErrorPtr
572 StdMeshers_ViscousLayers2D::CheckHypothesis(SMESH_Mesh&                          theMesh,
573                                             const TopoDS_Shape&                  theShape,
574                                             SMESH_Hypothesis::Hypothesis_Status& theStatus)
575 {
576   SMESH_ComputeErrorPtr error = SMESH_ComputeError::New(COMPERR_OK);
577   theStatus = SMESH_Hypothesis::HYP_OK;
578
579   TopExp_Explorer exp( theShape, TopAbs_FACE );
580   for ( ; exp.More() && theStatus == SMESH_Hypothesis::HYP_OK; exp.Next() )
581   {
582     const TopoDS_Face& face = TopoDS::Face( exp.Current() );
583     vector< const StdMeshers_ViscousLayers2D* > hyps;
584     vector< TopoDS_Shape >                      hypShapes;
585     if ( VISCOUS_2D::findHyps( theMesh, face, hyps, hypShapes ))
586     {
587       VISCOUS_2D::_ViscousBuilder2D builder( theMesh, face, hyps, hypShapes );
588       builder._faceSideVec =
589         StdMeshers_FaceSide::GetFaceWires( face, theMesh, true, error,
590                                            NULL, SMESH_ProxyMesh::Ptr(),
591                                            /*theCheckVertexNodes=*/false);
592       if ( error->IsOK() && !builder.findEdgesWithLayers())
593       {
594         error = builder.GetError();
595         if ( error && !error->IsOK() )
596           theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
597       }
598     }
599   }
600   return error;
601 }
602 // --------------------------------------------------------------------------------
603 void StdMeshers_ViscousLayers2D::RestoreListeners() const
604 {
605   StudyContextStruct* sc = _gen->GetStudyContext();
606   std::map < int, SMESH_Mesh * >::iterator i_smesh = sc->mapMesh.begin();
607   for ( ; i_smesh != sc->mapMesh.end(); ++i_smesh )
608   {
609     SMESH_Mesh* smesh = i_smesh->second;
610     if ( !smesh ||
611          !smesh->HasShapeToMesh() ||
612          !smesh->GetMeshDS() ||
613          !smesh->GetMeshDS()->IsUsedHypothesis( this ))
614       continue;
615
616     // set event listeners to EDGE's of FACE where this hyp is used
617     TopoDS_Shape shape = i_smesh->second->GetShapeToMesh();
618     for ( TopExp_Explorer face( shape, TopAbs_FACE); face.More(); face.Next() )
619       if ( SMESH_Algo* algo = _gen->GetAlgo( *smesh, face.Current() ))
620       {
621         const std::list <const SMESHDS_Hypothesis *> & usedHyps =
622           algo->GetUsedHypothesis( *smesh, face.Current(), /*ignoreAuxiliary=*/false );
623         if ( std::find( usedHyps.begin(), usedHyps.end(), this ) != usedHyps.end() )
624           for ( TopExp_Explorer edge( face.Current(), TopAbs_EDGE); edge.More(); edge.Next() )
625             VISCOUS_3D::ToClearSubWithMain( smesh->GetSubMesh( edge.Current() ), face.Current() );
626       }
627   }
628 }
629 // END StdMeshers_ViscousLayers2D hypothesis
630 //================================================================================
631
632 using namespace VISCOUS_2D;
633
634 //================================================================================
635 /*!
636  * \brief Constructor of _ViscousBuilder2D
637  */
638 //================================================================================
639
640 _ViscousBuilder2D::_ViscousBuilder2D(SMESH_Mesh&               theMesh,
641                                      const TopoDS_Face&        theFace,
642                                      vector< const THypVL* > & theHyps,
643                                      vector< TopoDS_Shape > &  theAssignedTo):
644   _mesh( &theMesh ), _face( theFace ), _helper( theMesh )
645 {
646   _hyps.swap( theHyps );
647   _hypShapes.swap( theAssignedTo );
648
649   _helper.SetSubShape( _face );
650   _helper.SetElementsOnShape( true );
651
652   _face.Orientation( TopAbs_FORWARD ); // 2D logic works only in this case
653   _surface = BRep_Tool::Surface( _face );
654
655   _error = SMESH_ComputeError::New(COMPERR_OK);
656
657   _nbLE = 0;
658 }
659
660 //================================================================================
661 /*!
662  * \brief Stores error description and returns false
663  */
664 //================================================================================
665
666 bool _ViscousBuilder2D::error(const string& text )
667 {
668   _error->myName    = COMPERR_ALGO_FAILED;
669   _error->myComment = string("Viscous layers builder 2D: ") + text;
670   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( _face ) )
671   {
672     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
673     if ( smError && smError->myAlgo )
674       _error->myAlgo = smError->myAlgo;
675     smError = _error;
676   }
677 #ifdef _DEBUG_
678   cout << "_ViscousBuilder2D::error " << text << endl;
679 #endif
680   return false;
681 }
682
683 //================================================================================
684 /*!
685  * \brief Does its job
686  */
687 //================================================================================
688
689 SMESH_ProxyMesh::Ptr _ViscousBuilder2D::Compute()
690 {
691   _faceSideVec = StdMeshers_FaceSide::GetFaceWires( _face, *_mesh, true, _error, &_helper );
692
693   if ( !_error->IsOK() )
694     return _proxyMesh;
695
696   if ( !findEdgesWithLayers() ) // analysis of a shape
697     return _proxyMesh;
698
699   if ( ! makePolyLines() ) // creation of fronts
700     return _proxyMesh;
701     
702   if ( ! inflate() ) // advance fronts
703     return _proxyMesh;
704
705   // remove elements and nodes from _face
706   removeMeshFaces( _face );
707
708   if ( !shrink() ) // shrink segments on edges w/o layers
709     return _proxyMesh;
710
711   if ( ! refine() ) // make faces
712     return _proxyMesh;
713
714   //improve();
715
716   return _proxyMesh;
717 }
718
719 //================================================================================
720 /*!
721  * \brief Finds EDGE's to make viscous layers on.
722  */
723 //================================================================================
724
725 bool _ViscousBuilder2D::findEdgesWithLayers()
726 {
727   // collect all EDGEs to ignore defined by _hyps
728   typedef std::pair< set<TGeomID>, const THypVL* > TEdgesOfHyp;
729   vector< TEdgesOfHyp > ignoreEdgesOfHyp( _hyps.size() );
730   for ( size_t i = 0; i < _hyps.size(); ++i )
731   {
732     ignoreEdgesOfHyp[i].second = _hyps[i];
733     getEdgesToIgnore( _hyps[i], _face, getMeshDS(), ignoreEdgesOfHyp[i].first );
734   }
735
736   // get all shared EDGEs
737   TopTools_MapOfShape sharedEdges;
738   TopTools_IndexedMapOfShape hypFaces; // faces with VL hyps
739   for ( size_t i = 0; i < _hypShapes.size(); ++i )
740     TopExp::MapShapes( _hypShapes[i], TopAbs_FACE, hypFaces );
741   TopTools_IndexedDataMapOfShapeListOfShape facesOfEdgeMap;
742   for ( int iF = 1; iF <= hypFaces.Extent(); ++iF )
743     TopExp::MapShapesAndAncestors( hypFaces(iF), TopAbs_EDGE, TopAbs_FACE, facesOfEdgeMap);
744   for ( int iE = 1; iE <= facesOfEdgeMap.Extent(); ++iE )
745     if ( facesOfEdgeMap( iE ).Extent() > 1 )
746       sharedEdges.Add( facesOfEdgeMap.FindKey( iE ));
747
748   // fill _hypOfEdge
749   if ( _hyps.size() > 1 )
750   {
751     // check if two hypotheses define different parameters for the same EDGE
752     for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
753     {
754       StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
755       for ( int iE = 0; iE < wire->NbEdges(); ++iE )
756       {
757         const THypVL* hyp = 0;
758         const TGeomID edgeID = wire->EdgeID( iE );
759         if ( !sharedEdges.Contains( wire->Edge( iE )))
760         {
761           for ( size_t i = 0; i < ignoreEdgesOfHyp.size(); ++i )
762             if ( ! ignoreEdgesOfHyp[i].first.count( edgeID ))
763             {
764               if ( hyp )
765                 return error(SMESH_Comment("Several hypotheses define "
766                                            "Viscous Layers on the edge #") << edgeID );
767               hyp = ignoreEdgesOfHyp[i].second;
768             }
769         }
770         _hypOfEdge.push_back( hyp );
771         if ( !hyp )
772           _ignoreShapeIds.insert( edgeID );
773       }
774       // check if two hypotheses define different number of viscous layers for
775       // adjacent EDGEs
776       const THypVL *hyp, *prevHyp = _hypOfEdge.back();
777       size_t iH = _hypOfEdge.size() - wire->NbEdges();
778       for ( ; iH < _hypOfEdge.size(); ++iH )
779       {
780         hyp = _hypOfEdge[ iH ];
781         if ( hyp && prevHyp &&
782              hyp->GetNumberLayers() != prevHyp->GetNumberLayers() )
783         {
784           return error("Two hypotheses define different number of "
785                        "viscous layers on adjacent edges");
786         }
787         prevHyp = hyp;
788       }
789     }
790   }
791   else if ( _hyps.size() == 1 )
792   {
793     _ignoreShapeIds.swap( ignoreEdgesOfHyp[0].first );
794   }
795
796   // check all EDGEs of the _face to fill _ignoreShapeIds and _noShrinkVert
797
798   int totalNbEdges = 0;
799   for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
800   {
801     StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
802     totalNbEdges += wire->NbEdges();
803     for ( int iE = 0; iE < wire->NbEdges(); ++iE )
804     {
805       if ( sharedEdges.Contains( wire->Edge( iE )))
806       {
807         // ignore internal EDGEs (shared by several FACEs)
808         const TGeomID edgeID = wire->EdgeID( iE );
809         _ignoreShapeIds.insert( edgeID );
810
811         // check if ends of an EDGE are to be added to _noShrinkVert
812         const TopTools_ListOfShape& faceList = facesOfEdgeMap.FindFromKey( wire->Edge( iE ));
813         TopTools_ListIteratorOfListOfShape faceIt( faceList );
814         for ( ; faceIt.More(); faceIt.Next() )
815         {
816           const TopoDS_Shape& neighbourFace = faceIt.Value();
817           if ( neighbourFace.IsSame( _face )) continue;
818           SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, neighbourFace );
819           if ( !algo ) continue;
820
821           const StdMeshers_ViscousLayers2D* viscHyp = 0;
822           const list <const SMESHDS_Hypothesis *> & allHyps =
823             algo->GetUsedHypothesis(*_mesh, neighbourFace, /*noAuxiliary=*/false);
824           list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
825           for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
826             viscHyp = dynamic_cast<const StdMeshers_ViscousLayers2D*>( *hyp );
827
828           // set<TGeomID> neighbourIgnoreEdges;
829           // if (viscHyp)
830           //   getEdgesToIgnore( viscHyp, neighbourFace, getMeshDS(), neighbourIgnoreEdges );
831
832           for ( int iV = 0; iV < 2; ++iV )
833           {
834             TopoDS_Vertex vertex = iV ? wire->LastVertex(iE) : wire->FirstVertex(iE);
835             if ( !viscHyp )
836               _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
837             else
838             {
839               PShapeIteratorPtr edgeIt = _helper.GetAncestors( vertex, *_mesh, TopAbs_EDGE );
840               while ( const TopoDS_Shape* edge = edgeIt->next() )
841                 if ( !edge->IsSame( wire->Edge( iE )) &&
842                      _helper.IsSubShape( *edge, neighbourFace ))
843                 {
844                   const TGeomID neighbourID = getMeshDS()->ShapeToIndex( *edge );
845                   bool hasVL = !sharedEdges.Contains( *edge );
846                   if ( hasVL )
847                   {
848                     hasVL = false;
849                     for ( hyp = allHyps.begin(); hyp != allHyps.end() && !hasVL; ++hyp )
850                       if (( viscHyp = dynamic_cast<const THypVL*>( *hyp )))
851                         hasVL = viscHyp->IsShapeWithLayers( neighbourID );
852                   }
853                   if ( !hasVL )
854                   {
855                     _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
856                     break;
857                   }
858                 }
859             }
860           }
861         }
862       }
863     }
864   }
865
866   int nbMyEdgesIgnored = _ignoreShapeIds.size();
867
868   // add VERTEXes w/o layers to _ignoreShapeIds (this is used by toShrinkForAdjacent())
869   // for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
870   // {
871   //   StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
872   //   for ( int iE = 0; iE < wire->NbEdges(); ++iE )
873   //   {
874   //     TGeomID edge1 = wire->EdgeID( iE );
875   //     TGeomID edge2 = wire->EdgeID( iE+1 );
876   //     if ( _ignoreShapeIds.count( edge1 ) && _ignoreShapeIds.count( edge2 ))
877   //       _ignoreShapeIds.insert( getMeshDS()->ShapeToIndex( wire->LastVertex( iE )));
878   //   }
879   // }
880
881   return ( nbMyEdgesIgnored < totalNbEdges );
882 }
883
884 //================================================================================
885 /*!
886  * \brief Create the inner front of the viscous layers and prepare data for inflation
887  */
888 //================================================================================
889
890 bool _ViscousBuilder2D::makePolyLines()
891 {
892   // Create _PolyLines and _LayerEdge's
893
894   // count total nb of EDGEs to allocate _polyLineVec
895   int nbEdges = 0;
896   for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
897   {
898     StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
899     nbEdges += wire->NbEdges();
900     if ( wire->GetUVPtStruct().empty() && wire->NbPoints() > 0 )
901       return error("Invalid node parameters on some EDGE");
902   }
903   _polyLineVec.resize( nbEdges );
904
905   // check if 2D normal should be computed by 3D one by means of projection
906   GeomAPI_ProjectPointOnSurf* faceProj = 0;
907   TopLoc_Location loc;
908   {
909     _LayerEdge tmpLE;
910     const UVPtStruct& uv = _faceSideVec[0]->GetUVPtStruct()[0];
911     gp_Pnt p = SMESH_TNodeXYZ( uv.node );
912     tmpLE._uvOut.SetCoord( uv.u, uv.v );
913     tmpLE._normal2D.SetCoord( 1., 0. );
914     setLenRatio( tmpLE, p );
915     const double r1 = tmpLE._len2dTo3dRatio;
916     tmpLE._normal2D.SetCoord( 0., 1. );
917     setLenRatio( tmpLE, p );
918     const double r2 = tmpLE._len2dTo3dRatio;
919     // projection is needed if two _len2dTo3dRatio's differ too much
920     const double maxR = Max( r2, r1 );
921     if ( Abs( r2-r1 )/maxR > 0.2*maxR )
922       faceProj = & _helper.GetProjector( _face, loc );
923   }
924   _is2DIsotropic = !faceProj;
925
926   // Assign data to _PolyLine's
927   // ---------------------------
928
929   size_t iPoLine = 0;
930   for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
931   {
932     StdMeshers_FaceSidePtr      wire = _faceSideVec[ iWire ];
933     const vector<UVPtStruct>& points = wire->GetUVPtStruct();
934     int iPnt = 0;
935     for ( int iE = 0; iE < wire->NbEdges(); ++iE )
936     {
937       _PolyLine& L  = _polyLineVec[ iPoLine++ ];
938       L._index      = iPoLine-1;
939       L._wire       = wire.get();
940       L._edgeInd    = iE;
941       L._advancable = !_ignoreShapeIds.count( wire->EdgeID( iE ));
942
943       int iRight    = iPoLine - (( iE+1 < wire->NbEdges() ) ? 0 : wire->NbEdges() );
944       L._rightLine  = &_polyLineVec[ iRight ];
945       _polyLineVec[ iRight ]._leftLine = &L;
946
947       L._firstPntInd = iPnt;
948       double lastNormPar = wire->LastParameter( iE ) - 1e-10;
949       while ( points[ iPnt ].normParam < lastNormPar )
950         ++iPnt;
951       L._lastPntInd = iPnt;
952       L._lEdges.resize( Max( 3, L._lastPntInd - L._firstPntInd + 1 )); // 3 edges minimum
953
954       // TODO: add more _LayerEdge's to strongly curved EDGEs
955       // in order not to miss collisions
956
957       double u; gp_Pnt p;
958       Handle(Geom_Curve)   curve  = BRep_Tool::Curve( L._wire->Edge( iE ), loc, u, u );
959       Handle(Geom2d_Curve) pcurve = L._wire->Curve2d( L._edgeInd );
960       const bool reverse = (( L._wire->Edge( iE ).Orientation() == TopAbs_REVERSED ) ^
961                             (_face.Orientation()                == TopAbs_REVERSED ));
962       for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
963       {
964         _LayerEdge& lEdge = L._lEdges[ i - L._firstPntInd ];
965         u = ( i == L._firstPntInd ? wire->FirstU(iE) : points[ i ].param );
966         p = SMESH_TNodeXYZ( points[ i ].node );
967         setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, faceProj );
968         setLenRatio( lEdge, p );
969       }
970       if ( L._lastPntInd - L._firstPntInd + 1 < 3 ) // add 3-d _LayerEdge in the middle
971       {
972         L._lEdges[2] = L._lEdges[1];
973         u = 0.5 * ( wire->FirstU(iE) + wire->LastU(iE) );
974         if ( !curve.IsNull() )
975           p = curve->Value( u );
976         else
977           p = 0.5 * ( SMESH_TNodeXYZ( points[ L._firstPntInd ].node ) +
978                       SMESH_TNodeXYZ( points[ L._lastPntInd ].node ));
979         setLayerEdgeData( L._lEdges[1], u, pcurve, curve, p, reverse, faceProj );
980         setLenRatio( L._lEdges[1], p );
981       }
982     }
983   }
984
985   // Fill _PolyLine's with _segments
986   // --------------------------------
987
988   double maxLen2dTo3dRatio = 0;
989   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
990   {
991     _PolyLine& L = _polyLineVec[ iPoLine ];
992     L._segments.resize( L._lEdges.size() - 1 );
993     for ( size_t i = 1; i < L._lEdges.size(); ++i )
994     {
995       _Segment & S   = L._segments[i-1];
996       S._uv[0]       = & L._lEdges[i-1]._uvIn;
997       S._uv[1]       = & L._lEdges[i  ]._uvIn;
998       S._indexInLine = i-1;
999       if ( maxLen2dTo3dRatio < L._lEdges[i]._len2dTo3dRatio )
1000         maxLen2dTo3dRatio = L._lEdges[i]._len2dTo3dRatio;
1001     }
1002     // // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
1003     // // becomes not connected to any segment
1004     // if ( L._leftLine->_advancable )
1005     //   L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
1006
1007     L._segTree.reset( new _SegmentTree( L._segments ));
1008   }
1009
1010   // Evaluate max possible _thickness if required layers thickness seems too high
1011   // ----------------------------------------------------------------------------
1012
1013   _maxThickness = _hyps[0]->GetTotalThickness();
1014   for ( size_t iH = 1; iH < _hyps.size(); ++iH )
1015     _maxThickness = Max( _maxThickness, _hyps[iH]->GetTotalThickness() );
1016
1017   _SegmentTree::box_type faceBndBox2D;
1018   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1019     faceBndBox2D.Add( *_polyLineVec[ iPoLine]._segTree->getBox() );
1020   const double boxTol = 1e-3 * sqrt( faceBndBox2D.SquareExtent() );
1021
1022   if ( _maxThickness * maxLen2dTo3dRatio > sqrt( faceBndBox2D.SquareExtent() ) / 10 )
1023   {
1024     vector< const _Segment* > foundSegs;
1025     double maxPossibleThick = 0;
1026     _SegmentIntersection intersection;
1027     for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1028     {
1029       _PolyLine& L1 = _polyLineVec[ iL1 ];
1030       _SegmentTree::box_type boxL1 = * L1._segTree->getBox();
1031       boxL1.Enlarge( boxTol );
1032       // consider case of a circle as well!
1033       for ( size_t iL2 = iL1; iL2 < _polyLineVec.size(); ++iL2 )
1034       {
1035         _PolyLine& L2 = _polyLineVec[ iL2 ];
1036         _SegmentTree::box_type boxL2 = * L2._segTree->getBox();
1037         boxL2.Enlarge( boxTol );
1038         if ( boxL1.IsOut( boxL2 ))
1039           continue;
1040         for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1041         {
1042           foundSegs.clear();
1043           L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
1044           for ( size_t i = 0; i < foundSegs.size(); ++i )
1045             if ( intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
1046             {
1047               double  distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
1048               double psblThick = distToL2 / ( 1 + L1._advancable + L2._advancable );
1049               maxPossibleThick = Max( psblThick, maxPossibleThick );
1050             }
1051         }
1052       }
1053     }
1054     if ( maxPossibleThick > 0. )
1055       _maxThickness = Min( _maxThickness, maxPossibleThick );
1056   }
1057
1058   // Adjust _LayerEdge's at _PolyLine's extremities
1059   // -----------------------------------------------
1060
1061   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1062   {
1063     _PolyLine& LL = _polyLineVec[ iPoLine ];
1064     _PolyLine& LR = *LL._rightLine;
1065     adjustCommonEdge( LL, LR );
1066   }
1067   // recreate _segments if some _LayerEdge's have been removed by adjustCommonEdge()
1068   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1069   {
1070     _PolyLine& L = _polyLineVec[ iPoLine ];
1071     // if ( L._segments.size() ==  L._lEdges.size() - 1 )
1072     //   continue;
1073     L._segments.resize( L._lEdges.size() - 1 );
1074     for ( size_t i = 1; i < L._lEdges.size(); ++i )
1075     {
1076       _Segment & S   = L._segments[i-1];
1077       S._uv[0]       = & L._lEdges[i-1]._uvIn;
1078       S._uv[1]       = & L._lEdges[i  ]._uvIn;
1079       S._indexInLine = i-1;
1080     }
1081     L._segTree.reset( new _SegmentTree( L._segments ));
1082   }
1083   // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
1084   // becomes not connected to any segment
1085   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1086   {
1087     _PolyLine& L = _polyLineVec[ iPoLine ];
1088     if ( L._leftLine->_advancable )
1089       L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
1090   }
1091
1092   // Fill _reachableLines.
1093   // ----------------------
1094
1095   // compute bnd boxes taking into account the layers total thickness
1096   vector< _SegmentTree::box_type > lineBoxes( _polyLineVec.size() );
1097   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1098   {
1099     lineBoxes[ iPoLine ] = *_polyLineVec[ iPoLine ]._segTree->getBox();
1100     lineBoxes[ iPoLine ].Enlarge( maxLen2dTo3dRatio * getLineThickness( iPoLine ) * 
1101                                   ( _polyLineVec[ iPoLine ]._advancable ? 2. : 1.2 ));
1102   }
1103   // _reachableLines
1104   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1105   {
1106     _PolyLine& L1 = _polyLineVec[ iPoLine ];
1107     const double thick1 = getLineThickness( iPoLine );
1108     for ( size_t iL2 = 0; iL2 < _polyLineVec.size(); ++iL2 )
1109     {
1110       _PolyLine& L2 = _polyLineVec[ iL2 ];
1111       if ( iPoLine == iL2 || lineBoxes[ iPoLine ].IsOut( lineBoxes[ iL2 ]))
1112         continue;
1113       if ( !L1._advancable && ( L1._leftLine == &L2 || L1._rightLine == &L2 ))
1114         continue;
1115       // check reachability by _LayerEdge's
1116       int iDelta = 1; //Max( 1, L1._lEdges.size() / 100 );
1117       for ( size_t iLE = 1; iLE < L1._lEdges.size(); iLE += iDelta )
1118       {
1119         _LayerEdge& LE = L1._lEdges[iLE];
1120         if ( !lineBoxes[ iL2 ].IsOut ( LE._uvOut,
1121                                        LE._uvOut + LE._normal2D * thick1 * LE._len2dTo3dRatio ))
1122         {
1123           L1._reachableLines.push_back( & L2 );
1124           break;
1125         }
1126       }
1127     }
1128     // add self to _reachableLines
1129     Geom2dAdaptor_Curve pcurve( L1._wire->Curve2d( L1._edgeInd ));
1130     L1._isStraight2D = ( pcurve.GetType() == GeomAbs_Line );
1131     if ( !L1._isStraight2D )
1132     {
1133       // TODO: check carefully
1134       L1._reachableLines.push_back( & L1 );
1135     }
1136   }
1137
1138   return true;
1139 }
1140
1141 //================================================================================
1142 /*!
1143  * \brief adjust common _LayerEdge of two adjacent _PolyLine's
1144  *  \param LL - left _PolyLine
1145  *  \param LR - right _PolyLine
1146  */
1147 //================================================================================
1148
1149 void _ViscousBuilder2D::adjustCommonEdge( _PolyLine& LL, _PolyLine& LR )
1150 {
1151   int nbAdvancableL = LL._advancable + LR._advancable;
1152   if ( nbAdvancableL == 0 )
1153     return;
1154
1155   _LayerEdge& EL = LL._lEdges.back();
1156   _LayerEdge& ER = LR._lEdges.front();
1157   gp_XY normL    = EL._normal2D;
1158   gp_XY normR    = ER._normal2D;
1159   gp_XY tangL ( normL.Y(), -normL.X() );
1160
1161   // set common direction to a VERTEX _LayerEdge shared by two _PolyLine's
1162   gp_XY normCommon = ( normL * int( LL._advancable ) +
1163                        normR * int( LR._advancable )).Normalized();
1164   EL._normal2D = normCommon;
1165   EL._ray.SetLocation ( EL._uvOut );
1166   EL._ray.SetDirection( EL._normal2D );
1167   if ( nbAdvancableL == 1 ) { // _normal2D is true normal (not average)
1168     EL._isBlocked = true; // prevent intersecting with _Segments of _advancable line
1169     EL._length2D  = 0;
1170   }
1171   // update _LayerEdge::_len2dTo3dRatio according to a new direction
1172   const vector<UVPtStruct>& points = LL._wire->GetUVPtStruct();
1173   setLenRatio( EL, SMESH_TNodeXYZ( points[ LL._lastPntInd ].node ));
1174
1175   ER = EL;
1176
1177   const double dotNormTang = normR * tangL;
1178   const bool    largeAngle = Abs( dotNormTang ) > 0.2;
1179   if ( largeAngle ) // not 180 degrees
1180   {
1181     // recompute _len2dTo3dRatio to take into account angle between EDGEs
1182     gp_Vec2d oldNorm( LL._advancable ? normL : normR );
1183     double angleFactor  = 1. / Max( 0.3, Cos( oldNorm.Angle( normCommon )));
1184     EL._len2dTo3dRatio *= angleFactor;
1185     ER._len2dTo3dRatio  = EL._len2dTo3dRatio;
1186
1187     gp_XY normAvg = ( normL + normR ).Normalized(); // average normal at VERTEX
1188
1189     if ( dotNormTang < 0. ) // ---------------------------- CONVEX ANGLE
1190     {
1191       // Remove _LayerEdge's intersecting the normAvg to avoid collisions
1192       // during inflate().
1193       //
1194       // find max length of the VERTEX-based _LayerEdge whose direction is normAvg
1195       double       maxLen2D  = _maxThickness * EL._len2dTo3dRatio;
1196       const gp_XY& pCommOut  = ER._uvOut;
1197       gp_XY        pCommIn   = pCommOut + normAvg * maxLen2D;
1198       _Segment segCommon( pCommOut, pCommIn );
1199       _SegmentIntersection intersection;
1200       vector< const _Segment* > foundSegs;
1201       for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1202       {
1203         _PolyLine& L1 = _polyLineVec[ iL1 ];
1204         const _SegmentTree::box_type* boxL1 = L1._segTree->getBox();
1205         if ( boxL1->IsOut ( pCommOut, pCommIn ))
1206           continue;
1207         for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1208         {
1209           foundSegs.clear();
1210           L1._segTree->GetSegmentsNear( segCommon, foundSegs );
1211           for ( size_t i = 0; i < foundSegs.size(); ++i )
1212             if ( intersection.Compute( *foundSegs[i], segCommon ) &&
1213                  intersection._param2 > 1e-10 )
1214             {
1215               double len2D = intersection._param2 * maxLen2D / ( 2 + L1._advancable );
1216               if ( len2D < maxLen2D ) {
1217                 maxLen2D = len2D;
1218                 pCommIn  = pCommOut + normAvg * maxLen2D; // here length of segCommon changes
1219               }
1220             }
1221         }
1222       }
1223
1224       // remove _LayerEdge's intersecting segCommon
1225       for ( int isR = 0; isR < 2; ++isR ) // loop on [ LL, LR ]
1226       {
1227         _PolyLine&                 L = isR ? LR : LL;
1228         _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1229         int                      dIt = isR ? +1 : -1;
1230         if ( nbAdvancableL == 1 && L._advancable && normL * normR > -0.01 )
1231           continue;  // obtuse internal angle
1232         // at least 3 _LayerEdge's should remain in a _PolyLine
1233         if ( L._lEdges.size() < 4 ) continue;
1234         size_t iLE = 1;
1235         _SegmentIntersection lastIntersection;
1236         for ( ; iLE < L._lEdges.size(); ++iLE, eIt += dIt )
1237         {
1238           gp_XY uvIn = eIt->_uvOut + eIt->_normal2D * _maxThickness * eIt->_len2dTo3dRatio;
1239           _Segment segOfEdge( eIt->_uvOut, uvIn );
1240           if ( !intersection.Compute( segCommon, segOfEdge ))
1241             break;
1242           lastIntersection._param1 = intersection._param1;
1243           lastIntersection._param2 = intersection._param2;
1244         }
1245         if ( iLE >= L._lEdges.size() - 1 )
1246         {
1247           // all _LayerEdge's intersect the segCommon, limit inflation
1248           // of remaining 3 _LayerEdge's
1249           vector< _LayerEdge > newEdgeVec( Min( 3, L._lEdges.size() ));
1250           newEdgeVec.front() = L._lEdges.front();
1251           newEdgeVec.back()  = L._lEdges.back();
1252           if ( newEdgeVec.size() == 3 )
1253           {
1254             newEdgeVec[1] = L._lEdges[ isR ? (L._lEdges.size() - 2) : 1 ];
1255             newEdgeVec[1]._len2dTo3dRatio *= lastIntersection._param2;
1256           }
1257           L._lEdges.swap( newEdgeVec );
1258           if ( !isR ) std::swap( lastIntersection._param1 , lastIntersection._param2 );
1259           L._lEdges.front()._len2dTo3dRatio *= lastIntersection._param1; // ??
1260           L._lEdges.back ()._len2dTo3dRatio *= lastIntersection._param2;
1261         }
1262         else if ( iLE != 1 )
1263         {
1264           // eIt points to the _LayerEdge not intersecting with segCommon
1265           if ( isR )
1266             LR._lEdges.erase( LR._lEdges.begin()+1, eIt );
1267           else
1268             LL._lEdges.erase( eIt+1, --LL._lEdges.end() );
1269           // eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1270           // for ( size_t i = 1; i < iLE; ++i, eIt += dIt )
1271           //   eIt->_isBlocked = true;
1272         }
1273       }
1274     }
1275     else // ------------------------------------------ CONCAVE ANGLE
1276     {
1277       if ( nbAdvancableL == 1 )
1278       {
1279         // make that the _LayerEdge at VERTEX is not shared by LL and LR:
1280         // different normals is a sign that they are not shared
1281         _LayerEdge& notSharedEdge = LL._advancable ? LR._lEdges[0] : LL._lEdges.back();
1282         _LayerEdge&    sharedEdge = LR._advancable ? LR._lEdges[0] : LL._lEdges.back();
1283
1284         notSharedEdge._normal2D.SetCoord( 0.,0. );
1285         sharedEdge._normal2D     = normAvg;
1286         sharedEdge._isBlocked    = false;
1287         notSharedEdge._isBlocked = true;
1288       }
1289     }
1290   }
1291 }
1292
1293 //================================================================================
1294 /*!
1295  * \brief initialize data of a _LayerEdge
1296  */
1297 //================================================================================
1298
1299 void _ViscousBuilder2D::setLayerEdgeData( _LayerEdge&                 lEdge,
1300                                           const double                u,
1301                                           Handle(Geom2d_Curve)&       pcurve,
1302                                           Handle(Geom_Curve)&         curve,
1303                                           const gp_Pnt                pOut,
1304                                           const bool                  reverse,
1305                                           GeomAPI_ProjectPointOnSurf* faceProj)
1306 {
1307   gp_Pnt2d uv;
1308   if ( faceProj && !curve.IsNull() )
1309   {
1310     uv = pcurve->Value( u );
1311     gp_Vec tangent; gp_Pnt p; gp_Vec du, dv;
1312     curve->D1( u, p, tangent );
1313     if ( reverse )
1314       tangent.Reverse();
1315     _surface->D1( uv.X(), uv.Y(), p, du, dv );
1316     gp_Vec faceNorm = du ^ dv;
1317     gp_Vec normal   = faceNorm ^ tangent;
1318     normal.Normalize();
1319     p = pOut.XYZ() + normal.XYZ() * /*1e-2 * */_hyps[0]->GetTotalThickness() / _hyps[0]->GetNumberLayers();
1320     faceProj->Perform( p );
1321     if ( !faceProj->IsDone() || faceProj->NbPoints() < 1 )
1322       return setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, NULL );
1323     Standard_Real U,V;
1324     faceProj->LowerDistanceParameters(U,V);
1325     lEdge._normal2D.SetCoord( U - uv.X(), V - uv.Y() );
1326     lEdge._normal2D.Normalize();
1327   }
1328   else
1329   {
1330     gp_Vec2d tangent;
1331     pcurve->D1( u, uv, tangent );
1332     tangent.Normalize();
1333     if ( reverse )
1334       tangent.Reverse();
1335     lEdge._normal2D.SetCoord( -tangent.Y(), tangent.X() );
1336   }
1337   lEdge._uvOut = lEdge._uvIn = uv.XY();
1338   lEdge._ray.SetLocation ( lEdge._uvOut );
1339   lEdge._ray.SetDirection( lEdge._normal2D );
1340   lEdge._isBlocked = false;
1341   lEdge._length2D  = 0;
1342 #ifdef _DEBUG_
1343   lEdge._ID        = _nbLE++;
1344 #endif
1345 }
1346
1347 //================================================================================
1348 /*!
1349  * \brief Compute and set _LayerEdge::_len2dTo3dRatio
1350  */
1351 //================================================================================
1352
1353 void _ViscousBuilder2D::setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut )
1354 {
1355   const double probeLen2d = 1e-3;
1356
1357   gp_Pnt2d p2d = LE._uvOut + LE._normal2D * probeLen2d;
1358   gp_Pnt   p3d = _surface->Value( p2d.X(), p2d.Y() );
1359   double len3d = p3d.Distance( pOut );
1360   if ( len3d < std::numeric_limits<double>::min() )
1361     LE._len2dTo3dRatio = std::numeric_limits<double>::min();
1362   else
1363     LE._len2dTo3dRatio = probeLen2d / len3d;
1364 }
1365
1366 //================================================================================
1367 /*!
1368  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
1369  */
1370 //================================================================================
1371
1372 bool _ViscousBuilder2D::inflate()
1373 {
1374   // Limit size of inflation step by geometry size found by
1375   // itersecting _LayerEdge's with _Segment's
1376   double minSize = _maxThickness, maxSize = 0;
1377   vector< const _Segment* > foundSegs;
1378   _SegmentIntersection intersection;
1379   for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1380   {
1381     _PolyLine& L1 = _polyLineVec[ iL1 ];
1382     for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1383     {
1384       _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1385       for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1386       {
1387         foundSegs.clear();
1388         L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
1389         for ( size_t i = 0; i < foundSegs.size(); ++i )
1390           if ( ! L1.IsAdjacent( *foundSegs[i], & L1._lEdges[iLE] ) &&
1391                intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
1392           {
1393             double distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
1394             double     size = distToL2 / ( 1 + L1._advancable + L2._advancable );
1395             if ( 1e-10 < size && size < minSize )
1396               minSize = size;
1397             if ( size > maxSize )
1398               maxSize = size;
1399           }
1400       }
1401     }
1402   }
1403   if ( minSize > maxSize ) // no collisions possible
1404     maxSize = _maxThickness;
1405 #ifdef __myDEBUG
1406   cout << "-- minSize = " << minSize << ", maxSize = " << maxSize << endl;
1407 #endif
1408
1409   double curThick = 0, stepSize = minSize;
1410   int nbSteps = 0;
1411   if ( maxSize > _maxThickness )
1412     maxSize = _maxThickness;
1413   while ( curThick < maxSize )
1414   {
1415     curThick += stepSize * 1.25;
1416     if ( curThick > _maxThickness )
1417       curThick = _maxThickness;
1418
1419     // Elongate _LayerEdge's
1420     for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1421     {
1422       _PolyLine& L = _polyLineVec[ iL ];
1423       if ( !L._advancable ) continue;
1424       const double lineThick = Min( curThick, getLineThickness( iL ));
1425       bool lenChange = false;
1426       for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1427         lenChange |= L._lEdges[iLE].SetNewLength( lineThick );
1428       // for ( int k=0; k<L._segments.size(); ++k)
1429       //   cout << "( " << L._segments[k].p1().X() << ", " <<L._segments[k].p1().Y() << " ) "
1430       //        << "( " << L._segments[k].p2().X() << ", " <<L._segments[k].p2().Y() << " ) "
1431       //        << endl;
1432       if ( lenChange )
1433         L._segTree.reset( new _SegmentTree( L._segments ));
1434     }
1435
1436     // Avoid intersection of _Segment's
1437     bool allBlocked = fixCollisions();
1438     if ( allBlocked )
1439     {
1440       break; // no more inflating possible
1441     }
1442     stepSize = Max( stepSize , _maxThickness / 10. );
1443     nbSteps++;
1444   }
1445
1446   // if (nbSteps == 0 )
1447   //   return error("failed at the very first inflation step");
1448
1449
1450   // remove _LayerEdge's of one line intersecting with each other
1451   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1452   {
1453     _PolyLine& L = _polyLineVec[ iL ];
1454     if ( !L._advancable ) continue;
1455
1456     // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
1457     if ( /*!L._leftLine->_advancable &&*/ L.IsCommonEdgeShared( *L._leftLine ) ) {
1458       L._lEdges[0] = L._leftLine->_lEdges.back();
1459     }
1460     if ( !L._rightLine->_advancable && L.IsCommonEdgeShared( *L._rightLine ) ) {
1461       L._lEdges.back() = L._rightLine->_lEdges[0];
1462     }
1463
1464     _SegmentIntersection intersection;
1465     for ( int isR = 0; ( isR < 2 && L._lEdges.size() > 2 ); ++isR )
1466     {
1467       int nbRemove = 0, deltaIt = isR ? -1 : +1;
1468       _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.end()-1 : L._lEdges.begin();
1469       if ( eIt->_length2D == 0 ) continue;
1470       _Segment seg1( eIt->_uvOut, eIt->_uvIn );
1471       for ( eIt += deltaIt; nbRemove < (int)L._lEdges.size()-1; eIt += deltaIt )
1472       {
1473         _Segment seg2( eIt->_uvOut, eIt->_uvIn );
1474         if ( !intersection.Compute( seg1, seg2 ))
1475           break;
1476         ++nbRemove;
1477       }
1478       if ( nbRemove > 0 ) {
1479         if ( nbRemove == (int)L._lEdges.size()-1 ) // 1st and last _LayerEdge's intersect
1480         {
1481           --nbRemove;
1482           _LayerEdge& L0 = L._lEdges.front();
1483           _LayerEdge& L1 = L._lEdges.back();
1484           L0._length2D *= intersection._param1 * 0.5;
1485           L1._length2D *= intersection._param2 * 0.5;
1486           L0._uvIn = L0._uvOut + L0._normal2D * L0._length2D;
1487           L1._uvIn = L1._uvOut + L1._normal2D * L1._length2D;
1488           if ( L.IsCommonEdgeShared( *L._leftLine ))
1489             L._leftLine->_lEdges.back() = L0;
1490         }
1491         if ( isR )
1492           L._lEdges.erase( L._lEdges.end()-nbRemove-1,
1493                            L._lEdges.end()-nbRemove );
1494         else
1495           L._lEdges.erase( L._lEdges.begin()+1,
1496                            L._lEdges.begin()+1+nbRemove );
1497       }
1498     }
1499   }
1500   return true;
1501 }
1502
1503 //================================================================================
1504 /*!
1505  * \brief Remove intersection of _PolyLine's
1506  */
1507 //================================================================================
1508
1509 bool _ViscousBuilder2D::fixCollisions()
1510 {
1511   // look for intersections of _Segment's by intersecting _LayerEdge's with
1512   // _Segment's
1513   vector< const _Segment* > foundSegs;
1514   _SegmentIntersection intersection;
1515
1516   list< pair< _LayerEdge*, double > > edgeLenLimitList;
1517   list< _LayerEdge* >                 blockedEdgesList;
1518
1519   for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1520   {
1521     _PolyLine& L1 = _polyLineVec[ iL1 ];
1522     //if ( !L1._advancable ) continue;
1523     for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1524     {
1525       _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1526       for ( size_t iLE = L1.FirstLEdge(); iLE < L1._lEdges.size(); ++iLE )
1527       {
1528         _LayerEdge& LE1 = L1._lEdges[iLE];
1529         if ( LE1._isBlocked ) continue;
1530         foundSegs.clear();
1531         L2._segTree->GetSegmentsNear( LE1._ray, foundSegs );
1532         for ( size_t i = 0; i < foundSegs.size(); ++i )
1533         {
1534           if ( ! L1.IsAdjacent( *foundSegs[i], &LE1 ) &&
1535                intersection.Compute( *foundSegs[i], LE1._ray ))
1536           {
1537             const double dist2DToL2 = intersection._param2;
1538             double         newLen2D = dist2DToL2 / 2;
1539             if ( newLen2D < 1.1 * LE1._length2D ) // collision!
1540             {
1541               if ( newLen2D > 0 || !L1._advancable )
1542               {
1543                 blockedEdgesList.push_back( &LE1 );
1544                 if ( L1._advancable && newLen2D > 0 )
1545                 {
1546                   edgeLenLimitList.push_back( make_pair( &LE1, newLen2D ));
1547                   blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine     ]);
1548                   blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine + 1 ]);
1549                 }
1550                 else // here dist2DToL2 < 0 and LE1._length2D == 0
1551                 {
1552                   _LayerEdge* LE2[2] = { & L2._lEdges[ foundSegs[i]->_indexInLine     ],
1553                                          & L2._lEdges[ foundSegs[i]->_indexInLine + 1 ] };
1554                   _Segment outSeg2( LE2[0]->_uvOut, LE2[1]->_uvOut );
1555                   intersection.Compute( outSeg2, LE1._ray );
1556                   newLen2D = intersection._param2 / 2;
1557                   if ( newLen2D > 0 )
1558                   {
1559                     edgeLenLimitList.push_back( make_pair( LE2[0], newLen2D ));
1560                     edgeLenLimitList.push_back( make_pair( LE2[1], newLen2D ));
1561                   }
1562                 }
1563               }
1564             }
1565           }
1566         }
1567       }
1568     }
1569   }
1570
1571   // limit length of _LayerEdge's that are extrema of _PolyLine's
1572   // to avoid intersection of these _LayerEdge's
1573   for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1574   {
1575     _PolyLine& L = _polyLineVec[ iL1 ];
1576     if ( L._lEdges.size() < 4 ) // all intermediate _LayerEdge's intersect with extremum ones
1577     {
1578       _LayerEdge& LEL = L._leftLine->_lEdges.back();
1579       _LayerEdge& LER = L._lEdges.back();
1580       _Segment segL( LEL._uvOut, LEL._uvIn );
1581       _Segment segR( LER._uvOut, LER._uvIn );
1582       double newLen2DL, newLen2DR;
1583       if ( intersection.Compute( segL, LER._ray ))
1584       {
1585         newLen2DR = intersection._param2 / 2;
1586         newLen2DL = LEL._length2D * intersection._param1 / 2;
1587       }
1588       else if ( intersection.Compute( segR, LEL._ray ))
1589       {
1590         newLen2DL = intersection._param2 / 2;
1591         newLen2DR = LER._length2D * intersection._param1 / 2;
1592       }
1593       else
1594       {
1595         continue;
1596       }
1597       if ( newLen2DL > 0 && newLen2DR > 0 )
1598       {
1599         if ( newLen2DL < 1.1 * LEL._length2D )
1600           edgeLenLimitList.push_back( make_pair( &LEL, newLen2DL ));
1601         if ( newLen2DR < 1.1 * LER._length2D )
1602           edgeLenLimitList.push_back( make_pair( &LER, newLen2DR ));
1603       }
1604     }
1605   }
1606
1607   // set limited length to _LayerEdge's
1608   list< pair< _LayerEdge*, double > >::iterator edge2Len = edgeLenLimitList.begin();
1609   for ( ; edge2Len != edgeLenLimitList.end(); ++edge2Len )
1610   {
1611     _LayerEdge* LE = edge2Len->first;
1612     if ( LE->_length2D > edge2Len->second )
1613     {
1614       LE->_isBlocked = false;
1615       LE->SetNewLength( edge2Len->second / LE->_len2dTo3dRatio );
1616     }
1617     LE->_isBlocked = true;
1618   }
1619
1620   // block inflation of _LayerEdge's
1621   list< _LayerEdge* >::iterator edge = blockedEdgesList.begin();
1622   for ( ; edge != blockedEdgesList.end(); ++edge )
1623     (*edge)->_isBlocked = true;
1624
1625   // find a not blocked _LayerEdge
1626   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1627   {
1628     _PolyLine& L = _polyLineVec[ iL ];
1629     if ( !L._advancable ) continue;
1630     for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1631       if ( !L._lEdges[ iLE ]._isBlocked )
1632         return false;
1633   }
1634
1635   return true;
1636 }
1637
1638 //================================================================================
1639 /*!
1640  * \brief Create new edges and shrink edges existing on a non-advancable _PolyLine
1641  *        adjacent to an advancable one.
1642  */
1643 //================================================================================
1644
1645 bool _ViscousBuilder2D::shrink()
1646 {
1647   gp_Pnt2d uv; //gp_Vec2d tangent;
1648   _SegmentIntersection intersection;
1649   double sign;
1650
1651   for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1652   {
1653     _PolyLine& L = _polyLineVec[ iL1 ]; // line with no layers
1654     if ( L._advancable )
1655       continue;
1656     const int nbAdvancable = ( L._rightLine->_advancable + L._leftLine->_advancable );
1657     if ( nbAdvancable == 0 )
1658       continue;
1659
1660     const TopoDS_Vertex&  V1 = L._wire->FirstVertex( L._edgeInd );
1661     const TopoDS_Vertex&  V2 = L._wire->LastVertex ( L._edgeInd );
1662     const int           v1ID = getMeshDS()->ShapeToIndex( V1 );
1663     const int           v2ID = getMeshDS()->ShapeToIndex( V2 );
1664     const bool isShrinkableL = ! _noShrinkVert.count( v1ID ) && L._leftLine->_advancable;
1665     const bool isShrinkableR = ! _noShrinkVert.count( v2ID ) && L._rightLine->_advancable;
1666     if ( !isShrinkableL && !isShrinkableR )
1667       continue;
1668
1669     const TopoDS_Edge&        E = L._wire->Edge       ( L._edgeInd );
1670     const int            edgeID = L._wire->EdgeID     ( L._edgeInd );
1671     const double        edgeLen = L._wire->EdgeLength ( L._edgeInd );
1672     Handle(Geom2d_Curve) pcurve = L._wire->Curve2d    ( L._edgeInd );
1673     const bool     edgeReversed = ( E.Orientation() == TopAbs_REVERSED );
1674
1675     SMESH_MesherHelper helper( *_mesh ); // to create nodes and edges on E
1676     helper.SetSubShape( E );
1677     helper.SetElementsOnShape( true );
1678
1679     // Check a FACE adjacent to _face by E
1680     bool existingNodesFound = false;
1681     TopoDS_Face adjFace;
1682     PShapeIteratorPtr faceIt = _helper.GetAncestors( E, *_mesh, TopAbs_FACE );
1683     while ( const TopoDS_Shape* f = faceIt->next() )
1684       if ( !_face.IsSame( *f ))
1685       {
1686         adjFace = TopoDS::Face( *f );
1687         SMESH_ProxyMesh::Ptr pm = _ProxyMeshHolder::FindProxyMeshOfFace( adjFace, *_mesh );
1688         if ( !pm || pm->NbProxySubMeshes() == 0 /*|| !pm->GetProxySubMesh( E )*/)
1689         {
1690           // There are no viscous layers on an adjacent FACE, clear it's 2D mesh
1691           removeMeshFaces( adjFace );
1692           // if ( removeMeshFaces( adjFace ))
1693           //   _clearedFaces.push_back( adjFace ); // to re-compute after all
1694         }
1695         else
1696         {
1697           // There are viscous layers on the adjacent FACE; shrink must be already done;
1698           //
1699           // copy layer nodes
1700           //
1701           const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1702           int iPFrom = L._firstPntInd, iPTo = L._lastPntInd;
1703           if ( isShrinkableL )
1704           {
1705             const THypVL* hyp = getLineHypothesis( L._leftLine->_index );
1706             vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
1707             for ( int i = 0; i < hyp->GetNumberLayers(); ++i ) {
1708               const UVPtStruct& uvPt = points[ iPFrom + i + 1 ];
1709               L._leftNodes.push_back( uvPt.node );
1710               uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1711             }
1712             iPFrom += hyp->GetNumberLayers();
1713           }
1714           if ( isShrinkableR )
1715           {
1716             const THypVL* hyp = getLineHypothesis( L._rightLine->_index );
1717             vector<gp_XY>& uvVec = L._lEdges.back()._uvRefined;
1718             for ( int i = 0; i < hyp->GetNumberLayers(); ++i ) {
1719               const UVPtStruct& uvPt = points[ iPTo - i - 1 ];
1720               L._rightNodes.push_back( uvPt.node );
1721               uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1722             }
1723             iPTo -= hyp->GetNumberLayers();
1724           }
1725           // make proxy sub-mesh data of present nodes
1726           //
1727           UVPtStructVec nodeDataVec( & points[ iPFrom ], & points[ iPTo + 1 ]);
1728
1729           double normSize = nodeDataVec.back().normParam - nodeDataVec.front().normParam;
1730           for ( int iP = nodeDataVec.size()-1; iP >= 0 ; --iP )
1731             nodeDataVec[iP].normParam =
1732               ( nodeDataVec[iP].normParam - nodeDataVec[0].normParam ) / normSize;
1733
1734           const SMDS_MeshNode* n = nodeDataVec.front().node;
1735           if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1736             nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
1737           n = nodeDataVec.back().node;
1738           if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1739             nodeDataVec.back().param = L._wire->LastU( L._edgeInd );
1740
1741           _ProxyMeshOfFace::_EdgeSubMesh* myEdgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
1742           myEdgeSM->SetUVPtStructVec( nodeDataVec );
1743
1744           existingNodesFound = true;
1745           break;
1746         }
1747       } // loop on FACEs sharing E
1748
1749     // Check if L is an already shrinked seam
1750     if ( adjFace.IsNull() && _helper.IsRealSeam( edgeID ))
1751       if ( L._wire->Edge( L._edgeInd ).Orientation() == TopAbs_FORWARD )
1752         continue;
1753     // Commented as a case with a seam EDGE (issue 0052461) is hard to support
1754     // because SMESH_ProxyMesh can't hold different sub-meshes for two
1755     // 2D representations of the seam. But such a case is not a real practice one.
1756     // {
1757     //   for ( int iL2 = iL1-1; iL2 > -1; --iL2 )
1758     //   {
1759     //     _PolyLine& L2 = _polyLineVec[ iL2 ];
1760     //     if ( edgeID == L2._wire->EdgeID( L2._edgeInd ))
1761     //     {
1762     //       // copy layer nodes
1763     //       const int seamPar = _helper.GetPeriodicIndex();
1764     //       vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
1765     //       if ( isShrinkableL )
1766     //       {
1767     //         L._leftNodes = L2._rightNodes;
1768     //         uvVec = L2._lEdges.back()._uvRefined;
1769     //       }
1770     //       if ( isShrinkableR )
1771     //       {
1772     //         L._rightNodes = L2._leftNodes;
1773     //         uvVec = L2._lEdges.front()._uvRefined;
1774     //       }
1775     //       for ( size_t i = 0; i < uvVec.size(); ++i )
1776     //       {
1777     //         gp_XY & uv = uvVec[i];
1778     //         uv.SetCoord( seamPar, _helper.GetOtherParam( uv.Coord( seamPar )));
1779     //       }
1780
1781     //       existingNodesFound = true;
1782     //       break;
1783     //     }
1784     //   }
1785     // }
1786
1787     if ( existingNodesFound )
1788       continue; // nothing more to do in this case
1789
1790     double u1 = L._wire->FirstU( L._edgeInd ), uf = u1;
1791     double u2 = L._wire->LastU ( L._edgeInd ), ul = u2;
1792
1793     // a ratio to pass 2D <--> 1D
1794     const double len1D = 1e-3;
1795     const double len2D = pcurve->Value(uf).Distance( pcurve->Value(uf+len1D));
1796     double len1dTo2dRatio = len1D / len2D;
1797
1798     // create a vector of proxy nodes
1799     const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1800     UVPtStructVec nodeDataVec( & points[ L._firstPntInd ],
1801                                & points[ L._lastPntInd + 1 ]);
1802     nodeDataVec.front().param = u1; // U on vertex is correct on only one of shared edges
1803     nodeDataVec.back ().param = u2;
1804     nodeDataVec.front().normParam = 0;
1805     nodeDataVec.back ().normParam = 1;
1806
1807     // Get length of existing segments (from an edge start to a node) and their nodes
1808     vector< double > segLengths( nodeDataVec.size() - 1 );
1809     BRepAdaptor_Curve curve( E );
1810     for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
1811     {
1812       const double len = GCPnts_AbscissaPoint::Length( curve, uf, nodeDataVec[iP].param );
1813       segLengths[ iP-1 ] = len;
1814     }
1815
1816     // Move first and last parameters on EDGE (U of n1) according to layers' thickness
1817     // and create nodes of layers on EDGE ( -x-x-x )
1818
1819     // Before
1820     //  n1    n2    n3    n4
1821     //  x-----x-----x-----x-----
1822     //  |  e1    e2    e3    e4
1823
1824     // After
1825     //  n1          n2    n3
1826     //  x-x-x-x-----x-----x----
1827     //  | | | |  e1    e2    e3
1828
1829     int isRShrinkedForAdjacent = 0;
1830     UVPtStructVec nodeDataForAdjacent;
1831     for ( int isR = 0; isR < 2; ++isR )
1832     {
1833       _PolyLine* L2 = isR ? L._rightLine : L._leftLine; // line with layers
1834       if ( !L2->_advancable &&
1835            !toShrinkForAdjacent( adjFace, E, L._wire->FirstVertex( L._edgeInd + isR )))
1836         continue;
1837       if ( isR ? !isShrinkableR : !isShrinkableL )
1838         continue;
1839
1840       double & u = isR ? u2 : u1; // param to move
1841       double  u0 = isR ? ul : uf; // init value of the param to move
1842       int  iPEnd = isR ? nodeDataVec.size() - 1 : 0;
1843
1844       _LayerEdge& nearLE = isR ? L._lEdges.back() : L._lEdges.front();
1845       _LayerEdge&  farLE = isR ? L._lEdges.front() : L._lEdges.back();
1846
1847       // try to find length of advancement along L by intersecting L with
1848       // an adjacent _Segment of L2
1849
1850       double& length2D = nearLE._length2D;
1851       double  length1D = 0;
1852       sign = ( isR ^ edgeReversed ) ? -1. : 1.;
1853
1854       bool isConvex = false;
1855       if ( L2->_advancable )
1856       {
1857         const uvPtStruct& tang2P1 = points[ isR ? L2->_firstPntInd   : L2->_lastPntInd ];
1858         const uvPtStruct& tang2P2 = points[ isR ? L2->_firstPntInd+1 : L2->_lastPntInd-1 ];
1859         gp_XY seg2Dir( tang2P2.u - tang2P1.u,
1860                        tang2P2.v - tang2P1.v );
1861         int iFSeg2 = isR ? 0 : L2->_segments.size() - 1;
1862         int iLSeg2 = isR ? 1 : L2->_segments.size() - 2;
1863         gp_XY uvLSeg2In  = L2->_lEdges[ iLSeg2 ]._uvIn;
1864         Handle(Geom2d_Line) seg2Line = new Geom2d_Line( uvLSeg2In, seg2Dir );
1865
1866         Geom2dAdaptor_Curve edgeCurve( pcurve, Min( uf, ul ), Max( uf, ul ));
1867         Geom2dAdaptor_Curve seg2Curve( seg2Line );
1868         Geom2dInt_GInter     curveInt( edgeCurve, seg2Curve, 1e-7, 1e-7 );
1869         isConvex = ( curveInt.IsDone() && !curveInt.IsEmpty() );
1870         if ( isConvex ) {
1871           /*                   convex VERTEX */
1872           length1D = Abs( u - curveInt.Point( 1 ).ParamOnFirst() );
1873           double maxDist2d = 2 * L2->_lEdges[ iLSeg2 ]._length2D;
1874           isConvex = ( length1D < maxDist2d * len1dTo2dRatio );
1875           /*                                          |L  seg2
1876            *                                          |  o---o---
1877            *                                          | /    |
1878            *                                          |/     |  L2
1879            *                                          x------x---      */
1880         }
1881         if ( !isConvex ) { /* concave VERTEX */   /*  o-----o---
1882                                                    *   \    |
1883                                                    *    \   |  L2
1884                                                    *     x--x---
1885                                                    *    /
1886                                                    * L /               */
1887           length2D = L2->_lEdges[ iFSeg2 ]._length2D;
1888           //if ( L2->_advancable ) continue;
1889         }
1890       }
1891       else // L2 is advancable but in the face adjacent by L
1892       {
1893         length2D = farLE._length2D;
1894         if ( length2D == 0 ) {
1895           _LayerEdge& neighborLE =
1896             ( isR ? L._leftLine->_lEdges.back() : L._rightLine->_lEdges.front() );
1897           length2D = neighborLE._length2D;
1898           if ( length2D == 0 )
1899             length2D = _maxThickness * nearLE._len2dTo3dRatio;
1900         }
1901       }
1902
1903       // move u to the internal boundary of layers
1904       //  u --> u
1905       //  x-x-x-x-----x-----x----
1906       double maxLen3D = Min( _maxThickness, edgeLen / ( 1 + nbAdvancable ));
1907       double maxLen2D = maxLen3D * nearLE._len2dTo3dRatio;
1908       if ( !length2D ) length2D = length1D / len1dTo2dRatio;
1909       if ( Abs( length2D ) > maxLen2D )
1910         length2D = maxLen2D;
1911       nearLE._uvIn = nearLE._uvOut + nearLE._normal2D * length2D;
1912
1913       u += length2D * len1dTo2dRatio * sign;
1914       nodeDataVec[ iPEnd ].param = u;
1915
1916       gp_Pnt2d newUV = pcurve->Value( u );
1917       nodeDataVec[ iPEnd ].u = newUV.X();
1918       nodeDataVec[ iPEnd ].v = newUV.Y();
1919
1920       // compute params of layers on L
1921       vector<double> heights;
1922       const THypVL* hyp = getLineHypothesis( L2->_index );
1923       calcLayersHeight( u - u0, heights, hyp );
1924       //
1925       vector< double > params( heights.size() );
1926       for ( size_t i = 0; i < params.size(); ++i )
1927         params[ i ] = u0 + heights[ i ];
1928
1929       // create nodes of layers and edges between them
1930       //  x-x-x-x---
1931       vector< const SMDS_MeshNode* >& layersNode = isR ? L._rightNodes : L._leftNodes;
1932       vector<gp_XY>& nodeUV = ( isR ? L._lEdges.back() : L._lEdges[0] )._uvRefined;
1933       nodeUV.resize    ( hyp->GetNumberLayers() );
1934       layersNode.resize( hyp->GetNumberLayers() );
1935       const SMDS_MeshNode* vertexNode = nodeDataVec[ iPEnd ].node;
1936       const SMDS_MeshNode *  prevNode = vertexNode;
1937       for ( size_t i = 0; i < params.size(); ++i )
1938       {
1939         const gp_Pnt p  = curve.Value( params[i] );
1940         layersNode[ i ] = helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, params[i] );
1941         nodeUV    [ i ] = pcurve->Value( params[i] ).XY();
1942         helper.AddEdge( prevNode, layersNode[ i ] );
1943         prevNode = layersNode[ i ];
1944       }
1945
1946       // store data of layer nodes made for adjacent FACE
1947       if ( !L2->_advancable )
1948       {
1949         isRShrinkedForAdjacent = isR;
1950         nodeDataForAdjacent.resize( hyp->GetNumberLayers() );
1951
1952         size_t iFrw = 0, iRev = nodeDataForAdjacent.size()-1, *i = isR ? &iRev : &iFrw;
1953         nodeDataForAdjacent[ *i ] = points[ isR ? L._lastPntInd : L._firstPntInd ];
1954         nodeDataForAdjacent[ *i ].param     = u0;
1955         nodeDataForAdjacent[ *i ].normParam = isR;
1956         for ( ++iFrw, --iRev; iFrw < layersNode.size(); ++iFrw, --iRev )
1957         {
1958           nodeDataForAdjacent[ *i ].node  = layersNode[ iFrw - 1 ];
1959           nodeDataForAdjacent[ *i ].u     = nodeUV    [ iFrw - 1 ].X();
1960           nodeDataForAdjacent[ *i ].v     = nodeUV    [ iFrw - 1 ].Y();
1961           nodeDataForAdjacent[ *i ].param = params    [ iFrw - 1 ];
1962         }
1963       }
1964       // replace a node on vertex by a node of last (most internal) layer
1965       // in a segment on E
1966       SMDS_ElemIteratorPtr segIt = vertexNode->GetInverseElementIterator( SMDSAbs_Edge );
1967       const SMDS_MeshNode* segNodes[3];
1968       while ( segIt->more() )
1969       {
1970         const SMDS_MeshElement* segment = segIt->next();
1971         if ( segment->getshapeId() != edgeID ) continue;
1972
1973         const int nbNodes = segment->NbNodes();
1974         for ( int i = 0; i < nbNodes; ++i )
1975         {
1976           const SMDS_MeshNode* n = segment->GetNode( i );
1977           segNodes[ i ] = ( n == vertexNode ? layersNode.back() : n );
1978         }
1979         getMeshDS()->ChangeElementNodes( segment, segNodes, nbNodes );
1980         break;
1981       }
1982       nodeDataVec[ iPEnd ].node = layersNode.back();
1983
1984     } // loop on the extremities of L
1985
1986     // Shrink edges to fit in between the layers at EDGE ends
1987
1988     double newLength = GCPnts_AbscissaPoint::Length( curve, u1, u2 );
1989     double lenRatio  = newLength / edgeLen * ( edgeReversed ? -1. : 1. );
1990     for ( size_t iP = 1; iP < nodeDataVec.size()-1; ++iP )
1991     {
1992       const SMDS_MeshNode* oldNode = nodeDataVec[iP].node;
1993
1994       GCPnts_AbscissaPoint discret( curve, segLengths[iP-1] * lenRatio, u1 );
1995       if ( !discret.IsDone() )
1996         throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
1997
1998       nodeDataVec[iP].param = discret.Parameter();
1999       if ( oldNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2000         throw SALOME_Exception(SMESH_Comment("ViscousBuilder2D: not SMDS_TOP_EDGE node position: ")
2001                                << oldNode->GetPosition()->GetTypeOfPosition()
2002                                << " of node " << oldNode->GetID());
2003       SMDS_EdgePositionPtr pos = oldNode->GetPosition();
2004       pos->SetUParameter( nodeDataVec[iP].param );
2005
2006       gp_Pnt newP = curve.Value( nodeDataVec[iP].param );
2007       getMeshDS()->MoveNode( oldNode, newP.X(), newP.Y(), newP.Z() );
2008
2009       gp_Pnt2d newUV = pcurve->Value( nodeDataVec[iP].param ).XY();
2010       nodeDataVec[iP].u         = newUV.X();
2011       nodeDataVec[iP].v         = newUV.Y();
2012       nodeDataVec[iP].normParam = segLengths[iP-1] / edgeLen;
2013       // nodeDataVec[iP].x         = segLengths[iP-1] / edgeLen;
2014       // nodeDataVec[iP].y         = segLengths[iP-1] / edgeLen;
2015     }
2016
2017     // Add nodeDataForAdjacent to nodeDataVec
2018
2019     if ( !nodeDataForAdjacent.empty() )
2020     {
2021       const double par1      = isRShrinkedForAdjacent ? u2 : uf;
2022       const double par2      = isRShrinkedForAdjacent ? ul : u1;
2023       const double shrinkLen = GCPnts_AbscissaPoint::Length( curve, par1, par2 );
2024
2025       // compute new normParam for nodeDataVec
2026       for ( size_t iP = 0; iP < nodeDataVec.size()-1; ++iP )
2027         nodeDataVec[iP+1].normParam = segLengths[iP] / ( edgeLen + shrinkLen );
2028       double normDelta = 1 - nodeDataVec.back().normParam;
2029       if ( !isRShrinkedForAdjacent )
2030         for ( size_t iP = 0; iP < nodeDataVec.size(); ++iP )
2031           nodeDataVec[iP].normParam += normDelta;
2032
2033       // compute new normParam for nodeDataForAdjacent
2034       const double deltaR = isRShrinkedForAdjacent ? nodeDataVec.back().normParam : 0;
2035       for ( size_t iP = !isRShrinkedForAdjacent; iP < nodeDataForAdjacent.size(); ++iP )
2036       {
2037         double lenFromPar1 =
2038           GCPnts_AbscissaPoint::Length( curve, par1, nodeDataForAdjacent[iP].param );
2039         nodeDataForAdjacent[iP].normParam = deltaR + normDelta * lenFromPar1 / shrinkLen;
2040       }
2041       // concatenate nodeDataVec and nodeDataForAdjacent
2042       nodeDataVec.insert(( isRShrinkedForAdjacent ? nodeDataVec.end() : nodeDataVec.begin() ),
2043                          nodeDataForAdjacent.begin(), nodeDataForAdjacent.end() );
2044     }
2045
2046     // Extend nodeDataVec by a node located at the end of not shared _LayerEdge
2047     /*      n - to add to nodeDataVec
2048      *      o-----o---
2049      *      |\    |
2050      *      | o---o---
2051      *      | |x--x--- L2
2052      *      | /
2053      *      |/ L
2054      *      x
2055      *     /    */
2056     for ( int isR = 0; isR < 2; ++isR )
2057     {
2058       _PolyLine& L2 = *( isR ? L._rightLine : L._leftLine ); // line with layers
2059       if ( ! L2._advancable || L.IsCommonEdgeShared( L2 ) )
2060         continue;
2061       vector< const SMDS_MeshNode* >& layerNodes2 = isR ? L2._leftNodes : L2._rightNodes;
2062       _LayerEdge& LE2 = isR ? L2._lEdges.front() : L2._lEdges.back();
2063       if ( layerNodes2.empty() )
2064       {
2065         // refine the not shared _LayerEdge
2066         vector<double> layersHeight;
2067         calcLayersHeight( LE2._length2D, layersHeight, getLineHypothesis( L2._index ));
2068
2069         vector<gp_XY>& nodeUV2 = LE2._uvRefined;
2070         nodeUV2.resize    ( layersHeight.size() );
2071         layerNodes2.resize( layersHeight.size() );
2072         for ( size_t i = 0; i < layersHeight.size(); ++i )
2073         {
2074           gp_XY uv = LE2._uvOut + LE2._normal2D * layersHeight[i];
2075           gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
2076           nodeUV2    [ i ] = uv;
2077           layerNodes2[ i ] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
2078         }
2079       }
2080       UVPtStruct ptOfNode;
2081       ptOfNode.u         = LE2._uvRefined.back().X();
2082       ptOfNode.v         = LE2._uvRefined.back().Y();
2083       ptOfNode.node      = layerNodes2.back();
2084       ptOfNode.param     = isR ? ul : uf;
2085       ptOfNode.normParam = isR ? 1 : 0;
2086
2087       nodeDataVec.insert(( isR ? nodeDataVec.end() : nodeDataVec.begin() ), ptOfNode );
2088
2089       // recompute normParam of nodes in nodeDataVec
2090       newLength = GCPnts_AbscissaPoint::Length( curve,
2091                                                 nodeDataVec.front().param,
2092                                                 nodeDataVec.back().param);
2093       for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
2094       {
2095         const double len = GCPnts_AbscissaPoint::Length( curve,
2096                                                          nodeDataVec.front().param,
2097                                                          nodeDataVec[iP].param );
2098         nodeDataVec[iP].normParam = len / newLength;
2099       }
2100     }
2101
2102     // create a proxy sub-mesh containing the moved nodes
2103     _ProxyMeshOfFace::_EdgeSubMesh* edgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
2104     edgeSM->SetUVPtStructVec( nodeDataVec );
2105
2106     // set a sub-mesh event listener to remove just created edges when
2107     // "ViscousLayers2D" hypothesis is modified
2108     VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( E ), _face );
2109
2110   } // loop on _polyLineVec
2111
2112   return true;
2113 }
2114
2115 //================================================================================
2116 /*!
2117  * \brief Returns true if there will be a shrinked mesh on EDGE E of FACE adjFace
2118  *        near VERTEX V
2119  */
2120 //================================================================================
2121
2122 bool _ViscousBuilder2D::toShrinkForAdjacent( const TopoDS_Face&   adjFace,
2123                                              const TopoDS_Edge&   E,
2124                                              const TopoDS_Vertex& V)
2125 {
2126   if ( _noShrinkVert.count( getMeshDS()->ShapeToIndex( V )) || adjFace.IsNull() )
2127     return false;
2128
2129   vector< const StdMeshers_ViscousLayers2D* > hyps;
2130   vector< TopoDS_Shape >                      hypShapes;
2131   if ( VISCOUS_2D::findHyps( *_mesh, adjFace, hyps, hypShapes ))
2132   {
2133     VISCOUS_2D::_ViscousBuilder2D builder( *_mesh, adjFace, hyps, hypShapes );
2134     builder._faceSideVec = StdMeshers_FaceSide::GetFaceWires( adjFace, *_mesh, true, _error );
2135     builder.findEdgesWithLayers();
2136
2137     PShapeIteratorPtr edgeIt = _helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
2138     while ( const TopoDS_Shape* edgeAtV = edgeIt->next() )
2139     {
2140       if ( !edgeAtV->IsSame( E ) &&
2141            _helper.IsSubShape( *edgeAtV, adjFace ) &&
2142            !builder._ignoreShapeIds.count( getMeshDS()->ShapeToIndex( *edgeAtV )))
2143       {
2144         return true;
2145       }
2146     }
2147   }
2148   return false;
2149 }
2150
2151 //================================================================================
2152 /*!
2153  * \brief Make faces
2154  */
2155 //================================================================================
2156
2157 bool _ViscousBuilder2D::refine()
2158 {
2159   // find out orientation of faces to create
2160   bool isReverse = 
2161     ( _helper.GetSubShapeOri( _mesh->GetShapeToMesh(), _face ) == TopAbs_REVERSED );
2162
2163   // store a proxyMesh in a sub-mesh
2164   // make faces on each _PolyLine
2165   vector< double > layersHeight;
2166   //double prevLen2D = -1;
2167   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2168   {
2169     _PolyLine& L = _polyLineVec[ iL ];
2170     if ( !L._advancable ) continue;
2171
2172     // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
2173     //size_t iLE = 0, nbLE = L._lEdges.size();
2174     const bool leftEdgeShared  = L.IsCommonEdgeShared( *L._leftLine );
2175     const bool rightEdgeShared = L.IsCommonEdgeShared( *L._rightLine );
2176     if ( /*!L._leftLine->_advancable &&*/ leftEdgeShared )
2177     {
2178       L._lEdges[0] = L._leftLine->_lEdges.back();
2179       //iLE += int( !L._leftLine->_advancable );
2180     }
2181     if ( !L._rightLine->_advancable && rightEdgeShared )
2182     {
2183       L._lEdges.back() = L._rightLine->_lEdges[0];
2184       //--nbLE;
2185     }
2186
2187     // limit length of neighbour _LayerEdge's to avoid sharp change of layers thickness
2188
2189     vector< double > segLen( L._lEdges.size() );
2190     segLen[0] = 0.0;
2191
2192     // check if length modification is useful: look for _LayerEdge's
2193     // with length limited due to collisions
2194     bool lenLimited = false;
2195     for ( size_t iLE = 1; ( iLE < L._lEdges.size()-1 && !lenLimited ); ++iLE )
2196       lenLimited = L._lEdges[ iLE ]._isBlocked;
2197
2198     if ( lenLimited )
2199     {
2200       for ( size_t i = 1; i < segLen.size(); ++i )
2201       {
2202         // accumulate length of segments
2203         double sLen = (L._lEdges[i-1]._uvOut - L._lEdges[i]._uvOut ).Modulus();
2204         segLen[i] = segLen[i-1] + sLen;
2205       }
2206       const double totSegLen = segLen.back();
2207       // normalize the accumulated length
2208       for ( size_t iS = 1; iS < segLen.size(); ++iS )
2209         segLen[iS] /= totSegLen;
2210
2211       for ( int isR = 0; isR < 2; ++isR )
2212       {
2213         size_t iF = 0, iL = L._lEdges.size()-1;
2214         size_t *i = isR ? &iL : &iF;
2215         _LayerEdge* prevLE = & L._lEdges[ *i ];
2216         double weight = 0;
2217         for ( ++iF, --iL; iF < L._lEdges.size()-1; ++iF, --iL )
2218         {
2219           _LayerEdge& LE = L._lEdges[*i];
2220           if ( prevLE->_length2D > 0 )
2221           {
2222             gp_XY tangent ( LE._normal2D.Y(), -LE._normal2D.X() );
2223             weight += Abs( tangent * ( prevLE->_uvIn - LE._uvIn )) / totSegLen;
2224             // gp_XY prevTang( LE._uvOut - prevLE->_uvOut );
2225             // gp_XY prevNorm( -prevTang.Y(), prevTang.X() );
2226             gp_XY prevNorm = LE._normal2D;
2227             double prevProj = prevNorm * ( prevLE->_uvIn - prevLE->_uvOut );
2228             if ( prevProj > 0 ) {
2229               prevProj /= prevNorm.Modulus();
2230               if ( LE._length2D < prevProj )
2231                 weight += 0.75 * ( 1 - weight ); // length decrease is more preferable
2232               LE._length2D  = weight * LE._length2D + ( 1 - weight ) * prevProj;
2233               LE._uvIn = LE._uvOut + LE._normal2D * LE._length2D;
2234             }
2235           }
2236           prevLE = & LE;
2237         }
2238       }
2239     }
2240     // DEBUG:  to see _uvRefined. cout can be redirected to hide NETGEN output
2241     // cerr << "import smesh" << endl << "mesh = smesh.Mesh()"<< endl;
2242
2243     const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
2244
2245     // analyse extremities of the _PolyLine to find existing nodes
2246     const TopoDS_Vertex&  V1 = L._wire->FirstVertex( L._edgeInd );
2247     const TopoDS_Vertex&  V2 = L._wire->LastVertex ( L._edgeInd );
2248     const int           v1ID = getMeshDS()->ShapeToIndex( V1 );
2249     const int           v2ID = getMeshDS()->ShapeToIndex( V2 );
2250     const bool isShrinkableL = ! _noShrinkVert.count( v1ID );
2251     const bool isShrinkableR = ! _noShrinkVert.count( v2ID );
2252
2253     bool hasLeftNode     = ( !L._leftLine->_rightNodes.empty() && leftEdgeShared  );
2254     bool hasRightNode    = ( !L._rightLine->_leftNodes.empty() && rightEdgeShared );
2255     bool hasOwnLeftNode  = ( !L._leftNodes.empty() );
2256     bool hasOwnRightNode = ( !L._rightNodes.empty() );
2257     bool isClosedEdge    = ( points[ L._firstPntInd ].node == points[ L._lastPntInd ].node );
2258     const size_t
2259       nbN = L._lastPntInd - L._firstPntInd + 1,
2260       iN0 = ( hasLeftNode || hasOwnLeftNode || isClosedEdge || !isShrinkableL ),
2261       iNE = nbN - ( hasRightNode || hasOwnRightNode || !isShrinkableR );
2262
2263     // update _uvIn of end _LayerEdge's by existing nodes
2264     const SMDS_MeshNode *nL = 0, *nR = 0;
2265     if ( hasOwnLeftNode )    nL = L._leftNodes.back();
2266     else if ( hasLeftNode )  nL = L._leftLine->_rightNodes.back();
2267     if ( hasOwnRightNode )   nR = L._rightNodes.back();
2268     else if ( hasRightNode ) nR = L._rightLine->_leftNodes.back();
2269     if ( nL )
2270       L._lEdges[0]._uvIn = _helper.GetNodeUV( _face, nL, points[ L._firstPntInd + 1 ].node );
2271     if ( nR )
2272       L._lEdges.back()._uvIn = _helper.GetNodeUV( _face, nR, points[ L._lastPntInd - 1 ].node );
2273
2274     // compute normalized [0;1] node parameters of nodes on a _PolyLine
2275     vector< double > normPar( nbN );
2276     const double
2277       normF    = L._wire->FirstParameter( L._edgeInd ),
2278       normL    = L._wire->LastParameter ( L._edgeInd ),
2279       normDist = normL - normF;
2280     for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2281       normPar[ i - L._firstPntInd ] = ( points[i].normParam - normF ) / normDist;
2282
2283     // Calculate UV of most inner nodes
2284
2285     vector< gp_XY > innerUV( nbN );
2286
2287     // check if innerUV should be interpolated between _LayerEdge::_uvIn's
2288     const size_t nbLE = L._lEdges.size();
2289     bool needInterpol = ( nbN != nbLE );
2290     if ( !needInterpol )
2291     {
2292       // more check: compare length of inner and outer end segments
2293       double lenIn, lenOut;
2294       for ( int isR = 0; isR < 2 && !needInterpol; ++isR )
2295       {
2296         const _Segment& segIn = isR ? L._segments.back() : L._segments[0];
2297         const gp_XY&   uvIn1  = segIn.p1();
2298         const gp_XY&   uvIn2  = segIn.p2();
2299         const gp_XY&   uvOut1 = L._lEdges[ isR ? nbLE-1 : 0 ]._uvOut;
2300         const gp_XY&   uvOut2 = L._lEdges[ isR ? nbLE-2 : 1 ]._uvOut;
2301         if ( _is2DIsotropic )
2302         {
2303           lenIn  = ( uvIn1  - uvIn2  ).Modulus();
2304           lenOut = ( uvOut1 - uvOut2 ).Modulus();
2305         }
2306         else
2307         {
2308           lenIn  = _surface->Value( uvIn1.X(), uvIn1.Y() )
2309             .Distance( _surface->Value( uvIn2.X(), uvIn2.Y() ));
2310           lenOut  = _surface->Value( uvOut1.X(), uvOut1.Y() )
2311             .Distance( _surface->Value( uvOut2.X(), uvOut2.Y() ));
2312         }
2313         needInterpol = ( lenIn < 0.66 * lenOut );
2314       }
2315     }
2316
2317     if ( needInterpol )
2318     {
2319       // compute normalized accumulated length of inner segments
2320       size_t iS;
2321       if ( _is2DIsotropic )
2322         for ( iS = 1; iS < segLen.size(); ++iS )
2323         {
2324           double sLen = ( L._lEdges[iS-1]._uvIn - L._lEdges[iS]._uvIn ).Modulus();
2325           segLen[iS] = segLen[iS-1] + sLen;
2326         }
2327       else
2328         for ( iS = 1; iS < segLen.size(); ++iS )
2329         {
2330           const gp_XY& uv1 = L._lEdges[iS-1]._uvIn;
2331           const gp_XY& uv2 = L._lEdges[iS  ]._uvIn;
2332           gp_Pnt p1 = _surface->Value( uv1.X(), uv1.Y() );
2333           gp_Pnt p2 = _surface->Value( uv2.X(), uv2.Y() );
2334           double sLen = p1.Distance( p2 );
2335           segLen[iS] = segLen[iS-1] + sLen;
2336         }
2337       // normalize the accumulated length
2338       for ( iS = 1; iS < segLen.size(); ++iS )
2339         segLen[iS] /= segLen.back();
2340
2341       // calculate UV of most inner nodes according to the normalized node parameters
2342       iS = 0;
2343       for ( size_t i = 0; i < innerUV.size(); ++i )
2344       {
2345         while ( normPar[i] > segLen[iS+1] )
2346           ++iS;
2347         double r = ( normPar[i] - segLen[iS] ) / ( segLen[iS+1] - segLen[iS] );
2348         innerUV[ i ] = r * L._lEdges[iS+1]._uvIn + (1-r) * L._lEdges[iS]._uvIn;
2349       }
2350     }
2351     else // ! needInterpol
2352     {
2353       for ( size_t i = 0; i < nbLE; ++i )
2354         innerUV[ i ] = L._lEdges[i]._uvIn;
2355     }
2356
2357     // normalized height of layers
2358     const THypVL* hyp = getLineHypothesis( iL );
2359     calcLayersHeight( 1., layersHeight, hyp);
2360
2361     // Create layers of faces
2362
2363     // nodes to create 1 layer of faces
2364     vector< const SMDS_MeshNode* > outerNodes( nbN );
2365     vector< const SMDS_MeshNode* > innerNodes( nbN );
2366
2367     // initialize outerNodes by nodes of the L._wire
2368     for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2369       outerNodes[ i-L._firstPntInd ] = points[i].node;
2370
2371     L._leftNodes .reserve( hyp->GetNumberLayers() );
2372     L._rightNodes.reserve( hyp->GetNumberLayers() );
2373     int cur = 0, prev = -1; // to take into account orientation of _face
2374     if ( isReverse ) std::swap( cur, prev );
2375     for ( int iF = 0; iF < hyp->GetNumberLayers(); ++iF ) // loop on layers of faces
2376     {
2377       // create innerNodes of a current layer
2378       for ( size_t i = iN0; i < iNE; ++i )
2379       {
2380         gp_XY uvOut = points[ L._firstPntInd + i ].UV();
2381         gp_XY& uvIn = innerUV[ i ];
2382         gp_XY    uv = layersHeight[ iF ] * uvIn + ( 1.-layersHeight[ iF ]) * uvOut;
2383         gp_Pnt    p = _surface->Value( uv.X(), uv.Y() );
2384         innerNodes[i] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
2385       }
2386       // use nodes created for adjacent _PolyLine's
2387       if ( hasOwnLeftNode )    innerNodes.front() = L._leftNodes [ iF ];
2388       else if ( hasLeftNode )  innerNodes.front() = L._leftLine->_rightNodes[ iF ];
2389       if ( hasOwnRightNode )   innerNodes.back()  = L._rightNodes[ iF ];
2390       else if ( hasRightNode ) innerNodes.back()  = L._rightLine->_leftNodes[ iF ];
2391       if ( isClosedEdge )      innerNodes.front() = innerNodes.back(); // circle
2392       if ( !isShrinkableL )    innerNodes.front() = outerNodes.front();
2393       if ( !isShrinkableR )    innerNodes.back()  = outerNodes.back();
2394       if ( !hasOwnLeftNode )   L._leftNodes.push_back( innerNodes.front() );
2395       if ( !hasOwnRightNode )  L._rightNodes.push_back( innerNodes.back() );
2396
2397       // create faces
2398       for ( size_t i = 1; i < innerNodes.size(); ++i )
2399         if ( SMDS_MeshElement* f = _helper.AddFace( outerNodes[ i+prev ], outerNodes[ i+cur ],
2400                                                     innerNodes[ i+cur  ], innerNodes[ i+prev ]))
2401           L._newFaces.insert( L._newFaces.end(), f );
2402
2403       outerNodes.swap( innerNodes );
2404     }
2405
2406     // Add faces to a group
2407     SMDS_MeshGroup* group = StdMeshers_ViscousLayers::CreateGroup( hyp->GetGroupName(),
2408                                                                    *_helper.GetMesh(),
2409                                                                    SMDSAbs_Face );
2410     if ( group )
2411     {
2412       TIDSortedElemSet::iterator fIt = L._newFaces.begin();
2413       for ( ; fIt != L._newFaces.end(); ++fIt )
2414         group->Add( *fIt );
2415     }
2416
2417     // faces between not shared _LayerEdge's (at concave VERTEX)
2418     for ( int isR = 0; isR < 2; ++isR )
2419     {
2420       if ( isR ? rightEdgeShared : leftEdgeShared )
2421         continue;
2422       vector< const SMDS_MeshNode* > &
2423         lNodes = (isR ? L._rightNodes : L._leftLine->_rightNodes ),
2424         rNodes = (isR ? L._rightLine->_leftNodes : L._leftNodes );
2425       if ( lNodes.empty() || rNodes.empty() || lNodes.size() != rNodes.size() )
2426         continue;
2427
2428       const SMDS_MeshElement* face = 0;
2429       for ( size_t i = 1; i < lNodes.size(); ++i )
2430       {
2431         face = _helper.AddFace( lNodes[ i+prev ], rNodes[ i+prev ],
2432                                 rNodes[ i+cur ],  lNodes[ i+cur ]);
2433         if ( group )
2434           group->Add( face );
2435       }
2436
2437       const UVPtStruct& ptOnVertex = points[ isR ? L._lastPntInd : L._firstPntInd ];
2438       if ( isReverse )
2439         face = _helper.AddFace( ptOnVertex.node, lNodes[ 0 ], rNodes[ 0 ]);
2440       else
2441         face = _helper.AddFace( ptOnVertex.node, rNodes[ 0 ], lNodes[ 0 ]);
2442       if ( group )
2443         group->Add( face );
2444     }
2445
2446     // Fill the _ProxyMeshOfFace
2447
2448     UVPtStructVec nodeDataVec( outerNodes.size() ); // outerNodes swapped with innerNodes
2449     for ( size_t i = 0; i < outerNodes.size(); ++i )
2450     {
2451       gp_XY uv = _helper.GetNodeUV( _face, outerNodes[i] );
2452       nodeDataVec[i].u         = uv.X();
2453       nodeDataVec[i].v         = uv.Y();
2454       nodeDataVec[i].node      = outerNodes[i];
2455       nodeDataVec[i].param     = points [i + L._firstPntInd].param;
2456       nodeDataVec[i].normParam = normPar[i];
2457       nodeDataVec[i].x         = normPar[i];
2458       nodeDataVec[i].y         = normPar[i];
2459     }
2460     nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
2461     nodeDataVec.back() .param = L._wire->LastU ( L._edgeInd );
2462
2463     if (( nodeDataVec[0].node == nodeDataVec.back().node ) &&
2464         ( _helper.GetPeriodicIndex() == 1 || _helper.GetPeriodicIndex() == 2 )) // closed EDGE
2465     {
2466       const int iCoord = _helper.GetPeriodicIndex();
2467       gp_XY uv = nodeDataVec[0].UV();
2468       uv.SetCoord( iCoord, L._lEdges[0]._uvOut.Coord( iCoord ));
2469       nodeDataVec[0].SetUV( uv );
2470
2471       uv = nodeDataVec.back().UV();
2472       uv.SetCoord( iCoord, L._lEdges.back()._uvOut.Coord( iCoord ));
2473       nodeDataVec.back().SetUV( uv );
2474     }
2475
2476     _ProxyMeshOfFace::_EdgeSubMesh* edgeSM
2477       = getProxyMesh()->GetEdgeSubMesh( L._wire->EdgeID( L._edgeInd ));
2478     edgeSM->SetUVPtStructVec( nodeDataVec );
2479
2480   } // loop on _PolyLine's
2481
2482   // re-compute FACEs whose mesh was removed by shrink()
2483   for ( size_t i = 0; i < _clearedFaces.size(); ++i )
2484   {
2485     SMESH_subMesh* sm = _mesh->GetSubMesh( _clearedFaces[i] );
2486     if ( sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE )
2487       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2488   }
2489
2490   return true;
2491 }
2492
2493 //================================================================================
2494 /*!
2495  * \brief Improve quality of the created mesh elements
2496  */
2497 //================================================================================
2498
2499 bool _ViscousBuilder2D::improve()
2500 {
2501   if ( !_proxyMesh )
2502     return false;
2503
2504   // fixed nodes on EDGE's
2505   std::set<const SMDS_MeshNode*> fixedNodes;
2506   for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
2507   {
2508     StdMeshers_FaceSidePtr      wire = _faceSideVec[ iWire ];
2509     const vector<UVPtStruct>& points = wire->GetUVPtStruct();
2510     for ( size_t i = 0; i < points.size(); ++i )
2511       fixedNodes.insert( fixedNodes.end(), points[i].node );
2512   }
2513   // fixed proxy nodes
2514   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2515   {
2516     _PolyLine&         L = _polyLineVec[ iL ];
2517     const TopoDS_Edge& E = L._wire->Edge( L._edgeInd );
2518     if ( const SMESH_ProxyMesh::SubMesh* sm = _proxyMesh->GetProxySubMesh( E ))
2519     {
2520       const UVPtStructVec& points = sm->GetUVPtStructVec();
2521       for ( size_t i = 0; i < points.size(); ++i )
2522         fixedNodes.insert( fixedNodes.end(), points[i].node );
2523     }
2524     for ( size_t i = 0; i < L._rightNodes.size(); ++i )
2525       fixedNodes.insert( fixedNodes.end(), L._rightNodes[i] );
2526   }
2527
2528   // smoothing
2529   SMESH_MeshEditor editor( _mesh );
2530   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2531   {
2532     _PolyLine& L = _polyLineVec[ iL ];
2533     if ( L._isStraight2D ) continue;
2534     // SMESH_MeshEditor::SmoothMethod how =
2535     //   L._isStraight2D ? SMESH_MeshEditor::LAPLACIAN : SMESH_MeshEditor::CENTROIDAL;
2536     //editor.Smooth( L._newFaces, fixedNodes, how, /*nbIt = */3 );
2537     //editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::LAPLACIAN, /*nbIt = */1 );
2538     editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::CENTROIDAL, /*nbIt = */3 );
2539   }
2540   return true;
2541 }
2542
2543 //================================================================================
2544 /*!
2545  * \brief Remove elements and nodes from a face
2546  */
2547 //================================================================================
2548
2549 bool _ViscousBuilder2D::removeMeshFaces(const TopoDS_Shape& face)
2550 {
2551   // we don't use SMESH_subMesh::ComputeStateEngine() because of a listener
2552   // which clears EDGEs together with _face.
2553   bool thereWereElems = false;
2554   SMESH_subMesh* sm = _mesh->GetSubMesh( face );
2555   if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2556   {
2557     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2558     thereWereElems = eIt->more();
2559     while ( eIt->more() ) getMeshDS()->RemoveFreeElement( eIt->next(), smDS );
2560     SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2561     while ( nIt->more() ) getMeshDS()->RemoveFreeNode( nIt->next(), smDS );
2562   }
2563   sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2564
2565   return thereWereElems;
2566 }
2567
2568 //================================================================================
2569 /*!
2570  * \brief Returns a hypothesis for a _PolyLine
2571  */
2572 //================================================================================
2573
2574 const StdMeshers_ViscousLayers2D* _ViscousBuilder2D::getLineHypothesis(int iPL)
2575 {
2576   return iPL < (int)_hypOfEdge.size() ? _hypOfEdge[ iPL ] : _hyps[0];
2577 }
2578
2579 //================================================================================
2580 /*!
2581  * \brief Returns a layers thickness for a _PolyLine
2582  */
2583 //================================================================================
2584
2585 double _ViscousBuilder2D::getLineThickness(int iPL)
2586 {
2587   if ( const StdMeshers_ViscousLayers2D* h = getLineHypothesis( iPL ))
2588     return Min( _maxThickness, h->GetTotalThickness() );
2589   return _maxThickness;
2590 }
2591
2592 //================================================================================
2593 /*!
2594  * \brief Creates a _ProxyMeshOfFace and store it in a sub-mesh of FACE
2595  */
2596 //================================================================================
2597
2598 _ProxyMeshOfFace* _ViscousBuilder2D::getProxyMesh()
2599 {
2600   if ( _proxyMesh.get() )
2601     return (_ProxyMeshOfFace*) _proxyMesh.get();
2602
2603   _ProxyMeshOfFace* proxyMeshOfFace = new _ProxyMeshOfFace( *_mesh );
2604   _proxyMesh.reset( proxyMeshOfFace );
2605   new _ProxyMeshHolder( _face, _proxyMesh );
2606
2607   return proxyMeshOfFace;
2608 }
2609
2610 //================================================================================
2611 /*!
2612  * \brief Calculate height of layers for the given thickness. Height is measured
2613  *        from the outer boundary
2614  */
2615 //================================================================================
2616
2617 void _ViscousBuilder2D::calcLayersHeight(const double    totalThick,
2618                                          vector<double>& heights,
2619                                          const THypVL*   hyp)
2620 {
2621   const double fPowN = pow( hyp->GetStretchFactor(), hyp->GetNumberLayers() );
2622   heights.resize( hyp->GetNumberLayers() );
2623   double h0;
2624   if ( fPowN - 1 <= numeric_limits<double>::min() )
2625     h0 = totalThick / hyp->GetNumberLayers();
2626   else
2627     h0 = totalThick * ( hyp->GetStretchFactor() - 1 )/( fPowN - 1 );
2628
2629   double hSum = 0, hi = h0;
2630   for ( int i = 0; i < hyp->GetNumberLayers(); ++i )
2631   {
2632     hSum += hi;
2633     heights[ i ] = hSum;
2634     hi *= hyp->GetStretchFactor();
2635   }
2636 }
2637
2638 //================================================================================
2639 /*!
2640  * \brief Elongate this _LayerEdge
2641  */
2642 //================================================================================
2643
2644 bool _LayerEdge::SetNewLength( const double length3D )
2645 {
2646   if ( _isBlocked ) return false;
2647
2648   //_uvInPrev = _uvIn;
2649   _length2D = length3D * _len2dTo3dRatio;
2650   _uvIn     = _uvOut + _normal2D * _length2D;
2651   return true;
2652 }
2653
2654 //================================================================================
2655 /*!
2656  * \brief Return true if _LayerEdge at a common VERTEX between EDGEs with
2657  *  and w/o layer is common to the both _PolyLine's. If this is true, nodes
2658  *  of this _LayerEdge are inflated along a _PolyLine w/o layer, else the nodes
2659  *  are inflated along _normal2D of _LayerEdge of EDGE with layer
2660  */
2661 //================================================================================
2662
2663 bool _PolyLine::IsCommonEdgeShared( const _PolyLine& other )
2664 {
2665   const double tol = 1e-30;
2666
2667   if ( & other == _leftLine )
2668     return _lEdges[0]._normal2D.IsEqual( _leftLine->_lEdges.back()._normal2D, tol );
2669
2670   if ( & other == _rightLine )
2671     return _lEdges.back()._normal2D.IsEqual( _rightLine->_lEdges[0]._normal2D, tol );
2672
2673   return false;
2674 }
2675
2676 //================================================================================
2677 /*!
2678  * \brief Return \c true if the EDGE of this _PolyLine is concave
2679  */
2680 //================================================================================
2681
2682 bool _PolyLine::IsConcave() const
2683 {
2684   if ( _lEdges.size() < 2 )
2685     return false;
2686
2687   gp_Vec2d v1( _lEdges[0]._uvOut, _lEdges[1]._uvOut );
2688   gp_Vec2d v2( _lEdges[0]._uvOut, _lEdges[2]._uvOut );
2689   const double size2 = v2.Magnitude();
2690
2691   return ( v1 ^ v2 ) / size2 < -1e-3 * size2;
2692 }
2693
2694 //================================================================================
2695 /*!
2696  * \brief Constructor of SegmentTree
2697  */
2698 //================================================================================
2699
2700 _SegmentTree::_SegmentTree( const vector< _Segment >& segments ):
2701   SMESH_Quadtree()
2702 {
2703   _segments.resize( segments.size() );
2704   for ( size_t i = 0; i < segments.size(); ++i )
2705     _segments[i].Set( segments[i] );
2706
2707   compute();
2708 }
2709
2710 //================================================================================
2711 /*!
2712  * \brief Return the maximal bnd box
2713  */
2714 //================================================================================
2715
2716 _SegmentTree::box_type* _SegmentTree::buildRootBox()
2717 {
2718   _SegmentTree::box_type* box = new _SegmentTree::box_type;
2719   for ( size_t i = 0; i < _segments.size(); ++i )
2720   {
2721     box->Add( *_segments[i]._seg->_uv[0] );
2722     box->Add( *_segments[i]._seg->_uv[1] );
2723   }
2724   return box;
2725 }
2726
2727 //================================================================================
2728 /*!
2729  * \brief Redistrubute _segments among children
2730  */
2731 //================================================================================
2732
2733 void _SegmentTree::buildChildrenData()
2734 {
2735   for ( size_t i = 0; i < _segments.size(); ++i )
2736     for (int j = 0; j < nbChildren(); j++)
2737       if ( !myChildren[j]->getBox()->IsOut( *_segments[i]._seg->_uv[0],
2738                                             *_segments[i]._seg->_uv[1] ))
2739         ((_SegmentTree*)myChildren[j])->_segments.push_back( _segments[i]);
2740
2741   SMESHUtils::FreeVector( _segments ); // = _elements.clear() + free memory
2742
2743   for (int j = 0; j < nbChildren(); j++)
2744   {
2745     _SegmentTree* child = static_cast<_SegmentTree*>( myChildren[j]);
2746     child->myIsLeaf = ((int) child->_segments.size() <= maxNbSegInLeaf() );
2747   }
2748 }
2749
2750 //================================================================================
2751 /*!
2752  * \brief Return elements which can include the point
2753  */
2754 //================================================================================
2755
2756 void _SegmentTree::GetSegmentsNear( const _Segment&            seg,
2757                                     vector< const _Segment* >& found )
2758 {
2759   if ( getBox()->IsOut( *seg._uv[0], *seg._uv[1] ))
2760     return;
2761
2762   if ( isLeaf() )
2763   {
2764     for ( size_t i = 0; i < _segments.size(); ++i )
2765       if ( !_segments[i].IsOut( seg ))
2766         found.push_back( _segments[i]._seg );
2767   }
2768   else
2769   {
2770     for (int i = 0; i < nbChildren(); i++)
2771       ((_SegmentTree*) myChildren[i])->GetSegmentsNear( seg, found );
2772   }
2773 }
2774
2775
2776 //================================================================================
2777 /*!
2778  * \brief Return segments intersecting a ray
2779  */
2780 //================================================================================
2781
2782 void _SegmentTree::GetSegmentsNear( const gp_Ax2d&             ray,
2783                                     vector< const _Segment* >& found )
2784 {
2785   if ( getBox()->IsOut( ray ))
2786     return;
2787
2788   if ( isLeaf() )
2789   {
2790     for ( size_t i = 0; i < _segments.size(); ++i )
2791       if ( !_segments[i].IsOut( ray ))
2792         found.push_back( _segments[i]._seg );
2793   }
2794   else
2795   {
2796     for (int i = 0; i < nbChildren(); i++)
2797       ((_SegmentTree*) myChildren[i])->GetSegmentsNear( ray, found );
2798   }
2799 }
2800
2801 //================================================================================
2802 /*!
2803  * \brief Classify a _Segment
2804  */
2805 //================================================================================
2806
2807 bool _SegmentTree::_SegBox::IsOut( const _Segment& seg ) const
2808 {
2809   const double eps = std::numeric_limits<double>::min();
2810   for ( int iC = 0; iC < 2; ++iC )
2811   {
2812     if ( seg._uv[0]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps &&
2813          seg._uv[1]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps )
2814       return true;
2815     if ( seg._uv[0]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps &&
2816          seg._uv[1]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps )
2817       return true;
2818   }
2819   return false;
2820 }
2821
2822 //================================================================================
2823 /*!
2824  * \brief Classify a ray
2825  */
2826 //================================================================================
2827
2828 bool _SegmentTree::_SegBox::IsOut( const gp_Ax2d& ray ) const
2829 {
2830   double distBoxCenter2Ray =
2831     ray.Direction().XY() ^ ( ray.Location().XY() - 0.5 * (*_seg->_uv[0] + *_seg->_uv[1]));
2832
2833   double boxSectionDiam =
2834     Abs( ray.Direction().X() ) * ( _seg->_uv[1-_iMin[1]]->Y() - _seg->_uv[_iMin[1]]->Y() ) +
2835     Abs( ray.Direction().Y() ) * ( _seg->_uv[1-_iMin[0]]->X() - _seg->_uv[_iMin[0]]->X() );
2836
2837   return Abs( distBoxCenter2Ray ) > 0.5 * boxSectionDiam;
2838 }