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