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