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