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