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