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