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