Salome HOME
bos #20144 [CEA 20142] Import1D - Error: Algorithm failed
[modules/smesh.git] / src / SMESHUtils / SMESH_MAT2d.cxx
1 // Copyright (C) 2007-2020  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // File      : SMESH_MAT2d.cxx
23 // Created   : Thu May 28 17:49:53 2015
24 // Author    : Edward AGAPOV (eap)
25
26 #include "SMESH_MAT2d.hxx"
27
28 #include <list>
29
30 #include <BRepAdaptor_CompCurve.hxx>
31 #include <BRepBuilderAPI_MakeEdge.hxx>
32 #include <BRepBuilderAPI_MakeVertex.hxx>
33 #include <BRep_Builder.hxx>
34 #include <BRep_Tool.hxx>
35 #include <Bnd_B2d.hxx>
36 //#include <GCPnts_AbscissaPoint.hxx>
37 #include <GCPnts_TangentialDeflection.hxx>
38 // #include <GCPnts_UniformAbscissa.hxx>
39 // #include <GCPnts_UniformDeflection.hxx>
40 #include <Geom2d_Curve.hxx>
41 //#include <GeomAdaptor_Curve.hxx>
42 #include <Geom2dAdaptor_Curve.hxx>
43 #include <Geom_Curve.hxx>
44 #include <Geom_Surface.hxx>
45 #include <TopExp.hxx>
46 #include <TopoDS_Vertex.hxx>
47 #include <TopoDS_Wire.hxx>
48
49 #ifdef _DEBUG_
50 //#define _MYDEBUG_
51 #include "SMESH_File.hxx"
52 #include "SMESH_Comment.hxx"
53 #endif
54
55 using namespace std;
56 using boost::polygon::x;
57 using boost::polygon::y;
58 using SMESH_MAT2d::TVD;
59 using SMESH_MAT2d::TVDEdge;
60 using SMESH_MAT2d::TVDCell;
61 using SMESH_MAT2d::TVDVertex;
62
63 namespace
64 {
65   // Input data for construct_voronoi()
66   // -------------------------------------------------------------------------------------
67
68   struct InPoint
69   {
70     int _a, _b;    // coordinates
71     double _param; // param on EDGE
72     InPoint(int x, int y, double param) : _a(x), _b(y), _param(param) {}
73     InPoint() : _a(0), _b(0), _param(0) {}
74
75     // working data
76     list< const TVDEdge* > _edges; // MA edges of a concave InPoint in CCW order
77
78     size_t index( const vector< InPoint >& inPoints ) const { return this - &inPoints[0]; }
79     bool operator==( const InPoint& other ) const { return _a == other._a && _b == other._b; }
80     bool operator==( const TVDVertex* v ) const { return ( Abs( _a - v->x() ) < 1. &&
81                                                            Abs( _b - v->y() ) < 1. ); }
82   };
83   // -------------------------------------------------------------------------------------
84
85   struct InSegment
86   {
87     InPoint * _p0;
88     InPoint * _p1;
89
90     // working data
91     size_t                 _geomEdgeInd; // EDGE index within the FACE
92     const TVDCell*         _cell;
93     list< const TVDEdge* > _edges; // MA edges in CCW order within _cell
94
95     InSegment( InPoint * p0, InPoint * p1, size_t iE)
96       : _p0(p0), _p1(p1), _geomEdgeInd(iE), _cell(0) {}
97     InSegment() : _p0(0), _p1(0), _geomEdgeInd(0), _cell(0) {}
98
99     const InPoint& point0() const { return *_p0; }
100     const InPoint& point1() const { return *_p1; }
101
102     inline bool isConnected( const TVDEdge* edge );
103
104     inline bool isExternal( const TVDEdge* edge );
105
106     static void setGeomEdgeToCell( const TVDCell* cell, size_t eID ) { cell->color( eID ); }
107
108     static size_t getGeomEdge( const TVDCell* cell ) { return cell->color(); }
109   };
110
111   // check  if a TVDEdge begins at my end or ends at my start
112   inline bool InSegment::isConnected( const TVDEdge* edge )
113   {
114     return (( edge->vertex0() && edge->vertex1() )
115             &&
116             ((Abs( edge->vertex0()->x() - _p1->_a ) < 1.&&
117               Abs( edge->vertex0()->y() - _p1->_b ) < 1.  ) ||
118              (Abs( edge->vertex1()->x() - _p0->_a ) < 1.&&
119               Abs( edge->vertex1()->y() - _p0->_b ) < 1.  )));
120   }
121
122   // check if a MA TVDEdge is outside of a domain
123   inline bool InSegment::isExternal( const TVDEdge* edge )
124   {
125     double dot = // x1*x2 + y1*y2;   (x1,y1) - internal normal of InSegment
126       ( _p0->_b - _p1->_b ) * ( 0.5 * ( edge->vertex0()->x() + edge->vertex1()->x() ) - _p0->_a ) +
127       ( _p1->_a - _p0->_a ) * ( 0.5 * ( edge->vertex0()->y() + edge->vertex1()->y() ) - _p0->_b );
128     return dot < 0.;
129   }
130
131   // // -------------------------------------------------------------------------------------
132   // const size_t theExternMA = 111; // to mark external MA edges
133
134   // bool isExternal( const TVDEdge* edge )
135   // {
136   //   return ( SMESH_MAT2d::Branch::getBndSegment( edge ) == theExternMA );
137   // }
138
139   // // mark external MA edges
140   // void markExternalEdges( const TVDEdge* edge )
141   // {
142   //   if ( isExternal( edge ))
143   //     return;
144   //   SMESH_MAT2d::Branch::setBndSegment( theExternMA, edge );
145   //   SMESH_MAT2d::Branch::setBndSegment( theExternMA, edge->twin() );
146   //   if ( edge->is_primary() && edge->vertex1() )
147   //   {
148   //     const TVDVertex * v = edge->vertex1();
149   //     edge = v->incident_edge();
150   //     do {
151   //       markExternalEdges( edge );
152   //       edge = edge->rot_next();
153   //     } while ( edge != v->incident_edge() );
154   //   }
155   // }
156
157   // -------------------------------------------------------------------------------------
158 #ifdef _MYDEBUG_
159   // writes segments into a txt file readable by voronoi_visualizer
160   void inSegmentsToFile( vector< InSegment>& inSegments)
161   {
162     if ( inSegments.size() > 1000 )
163       return;
164     const char* fileName = "/misc/dn25/salome/eap/salome/misc/Code/C++/MAdebug.txt";
165     const char*     user = getenv("USER");
166     if ( !user || strcmp( user, "eap" )) return;
167     SMESH_File file(fileName, false );
168     file.remove();
169     file.openForWriting();
170     SMESH_Comment text;
171     text << "0\n"; // nb points
172     text << inSegments.size() << "\n"; // nb segments
173     for ( size_t i = 0; i < inSegments.size(); ++i )
174     {
175       text << inSegments[i]._p0->_a << " "
176            << inSegments[i]._p0->_b << " "
177            << inSegments[i]._p1->_a << " "
178            << inSegments[i]._p1->_b << "\n";
179     }
180     text << "\n";
181     file.write( text.c_str(), text.size() );
182     cout << "Write " << fileName << endl;
183   }
184   void dumpEdge( const TVDEdge* edge )
185   {
186     cout << "*Edge_" << edge;
187     if ( !edge->vertex0() )
188       cout << " ( INF, INF";
189     else
190       cout << " ( " << edge->vertex0()->x() << ", " << edge->vertex0()->y();
191     if ( !edge->vertex1() )
192       cout << ") -> ( INF, INF";
193     else
194       cout << ") -> ( " << edge->vertex1()->x() << ", " << edge->vertex1()->y();
195     cout << ")\t cell=" << edge->cell()
196          << " iBnd=" << edge->color()
197          << " twin=" << edge->twin()
198          << " twin_cell=" << edge->twin()->cell()
199          << " prev=" << edge->prev() << " next=" << edge->next()
200          << ( edge->is_primary() ? " MA " : " SCND" )
201          << ( edge->is_linear() ? " LIN " : " CURV" )
202          << endl;
203   }
204   void dumpCell( const TVDCell* cell )
205   {
206     cout << "**Cell_" << cell << " GEOM=" << cell->color() << " ";
207     cout << ( cell->contains_segment() ? " SEG " : " PNT " );
208     if ( cell-> is_degenerate() )
209       cout << " degen ";
210     else
211     {
212       cout << endl;
213       const TVDEdge* edge = cell->incident_edge();
214       size_t i = 0;
215       do {
216         edge = edge->next();
217         cout << "   - " << ++i << " ";
218         dumpEdge( edge );
219       } while (edge != cell->incident_edge());
220     }
221   }
222 #else
223   #define inSegmentsToFile(arg) {}
224   //void dumpEdge( const TVDEdge* edge ) {}
225   //void dumpCell( const TVDCell* cell ) {}
226 #endif
227 }
228 // -------------------------------------------------------------------------------------
229
230 namespace boost {
231   namespace polygon {
232
233     template <>
234     struct geometry_concept<InPoint> {
235       typedef point_concept type;
236     };
237     template <>
238     struct point_traits<InPoint> {
239       typedef int coordinate_type;
240
241       static inline coordinate_type get(const InPoint& point, orientation_2d orient) {
242         return (orient == HORIZONTAL) ? point._a : point._b;
243       }
244     };
245
246     template <>
247     struct geometry_concept<InSegment> {
248       typedef segment_concept type;
249     };
250
251     template <>
252     struct segment_traits<InSegment> {
253       typedef int coordinate_type;
254       typedef InPoint point_type;
255
256       static inline point_type get(const InSegment& segment, direction_1d dir) {
257         return *(dir.to_int() ? segment._p1 : segment._p0);
258       }
259     };
260   }  // namespace polygon
261 } // namespace boost
262   // -------------------------------------------------------------------------------------
263
264 namespace
265 {
266   const int    theNoBrachID = 0;
267   double       theScale[2]; // scale used in bndSegsToMesh()
268   const size_t theNoEdgeID = std::numeric_limits<size_t>::max() / 1000;
269
270   // -------------------------------------------------------------------------------------
271   /*!
272    * \brief Intermediate DS to create InPoint's
273    */
274   struct UVU
275   {
276     gp_Pnt2d _uv;
277     double   _u;
278     UVU( gp_Pnt2d uv, double u ): _uv(uv), _u(u) {}
279     InPoint getInPoint( double scale[2] )
280     {
281       return InPoint( int( _uv.X() * scale[0]), int( _uv.Y() * scale[1]), _u );
282     }
283   };
284   // -------------------------------------------------------------------------------------
285   /*!
286    * \brief Segment of EDGE, used to create BndPoints
287    */
288   struct BndSeg
289   {
290     InSegment*       _inSeg;
291     const TVDEdge*   _edge;
292     double           _uLast;
293     BndSeg*          _prev; // previous BndSeg in FACE boundary
294     int              _branchID; // negative ID means reverse direction
295
296     BndSeg( InSegment* seg, const TVDEdge* edge, double u ):
297       _inSeg(seg), _edge(edge), _uLast(u), _prev(0), _branchID( theNoBrachID ) {}
298
299     void setIndexToEdge( size_t id )
300     {
301       SMESH_MAT2d::Branch::setBndSegment( id, _edge );
302     }
303
304     int branchID() const { return Abs( _branchID ); }
305
306     size_t geomEdge() const { return _inSeg->_geomEdgeInd; }
307
308     static BndSeg* getBndSegOfEdge( const TVDEdge*              edge,
309                                     vector< vector< BndSeg > >& bndSegsPerEdge )
310     {
311       BndSeg* seg = 0;
312       if ( edge )
313       {
314         size_t oppSegIndex  = SMESH_MAT2d::Branch::getBndSegment( edge );
315         size_t oppEdgeIndex = SMESH_MAT2d::Branch::getGeomEdge  ( edge );
316         if ( oppEdgeIndex < bndSegsPerEdge.size() &&
317              oppSegIndex < bndSegsPerEdge[ oppEdgeIndex ].size() )
318         {
319           seg = & bndSegsPerEdge[ oppEdgeIndex ][ oppSegIndex ];
320         }
321       }
322       return seg;
323     }
324
325     void setBranch( int branchID, vector< vector< BndSeg > >& bndSegsPerEdge )
326     {
327       _branchID = branchID;
328
329       // pass branch to an opposite BndSeg
330       if ( _edge )
331         if ( BndSeg* oppSeg = getBndSegOfEdge( _edge->twin(), bndSegsPerEdge ))
332         {
333           if ( oppSeg->_branchID == theNoBrachID )
334             oppSeg->_branchID = -branchID;
335         }
336     }
337     bool hasOppositeEdge()
338     {
339       if ( !_edge ) return false;
340       return ( _inSeg->getGeomEdge( _edge->twin()->cell() ) != theNoEdgeID );
341     }
342
343     // check a next segment in CCW order
344     bool isSameBranch( const BndSeg& seg2 )
345     {
346       if ( !_edge || !seg2._edge )
347         return true;
348
349       if ( _edge->twin() == seg2._edge )
350         return true;
351
352       const TVDCell* cell1 = this->_edge->twin()->cell();
353       const TVDCell* cell2 = seg2. _edge->twin()->cell();
354       if ( cell1 == cell2 )
355         return true;
356
357       const TVDEdge* edgeMedium1 = this->_edge->twin()->next();
358       const TVDEdge* edgeMedium2 = seg2. _edge->twin()->prev();
359
360       if ( edgeMedium1->is_secondary() && edgeMedium2->is_secondary() )
361       {
362         if ( edgeMedium1->twin() == edgeMedium2 )
363           return true;
364         // edgeMedium's are edges whose twin()->cell is built on an end point of inSegment
365         // and is located between cell1 and cell2
366         if ( edgeMedium1->twin() == edgeMedium2->twin() ) // is this possible???
367           return true;
368         if ( edgeMedium1->twin() == edgeMedium2->twin()->next() &&
369              edgeMedium1->twin()->cell()->contains_point() )
370           return true;
371       }
372       else if ( edgeMedium1->is_primary() && edgeMedium2->is_primary() )
373       {
374         if ( edgeMedium1->twin() == edgeMedium2 &&
375              SMESH_MAT2d::Branch::getGeomEdge( edgeMedium1 ) ==
376              SMESH_MAT2d::Branch::getGeomEdge( edgeMedium2 ))
377           // this is an ignored MA edge between inSegment's on one EDGE forming a convex corner
378           return true;
379       }
380
381       return false;
382     }
383   }; // struct BndSeg
384
385   // -------------------------------------------------------------------------------------
386   /*!
387    * \brief Iterator 
388    */
389   struct BranchIterator
390   {
391     int                                 _i, _size;
392     const std::vector<const TVDEdge*> & _edges;
393     bool                                _closed;
394
395     BranchIterator(const std::vector<const TVDEdge*> & edges, int i )
396       :_i( i ), _size( edges.size() ), _edges( edges )
397     {
398       _closed = ( edges[0]->vertex1() == edges.back()->vertex0() || // closed branch
399                   edges[0]->vertex0() == edges.back()->vertex1() );
400     }
401     const TVDEdge* operator++() { ++_i; return edge(); }
402     const TVDEdge* operator--() { --_i; return edge(); }
403     bool operator<( const BranchIterator& other ) { return _i < other._i; }
404     BranchIterator& operator=( const BranchIterator& other ) { _i = other._i; return *this; }
405     void set(int i) { _i = i; }
406     int  index() const { return _i; }
407     int  indexMod() const { return ( _i + _size ) % _size; }
408     const TVDEdge* edge() const {
409       return _closed ? _edges[ indexMod() ] : ( _i < 0 || _i >= _size ) ? 0 : _edges[ _i ];
410     }
411     const TVDEdge* edgePrev() { --_i; const TVDEdge* e = edge(); ++_i; return e; }
412     const TVDEdge* edgeNext() { ++_i; const TVDEdge* e = edge(); --_i; return e; }
413   };
414
415   //================================================================================
416   /*!
417    * \brief debug: to visually check found MA edges
418    */
419   //================================================================================
420
421   void bndSegsToMesh( const vector< vector< BndSeg > >& bndSegsPerEdge )
422   {
423 #ifdef _MYDEBUG_
424     if ( !getenv("bndSegsToMesh")) return;
425     map< const TVDVertex *, int > v2Node;
426     map< const TVDVertex *, int >::iterator v2n;
427     set< const TVDEdge* > addedEdges;
428
429     const char* fileName = "/misc/dn25/salome/eap/salome/misc/Code/C++/MAedges.py";
430     SMESH_File file(fileName, false );
431     file.remove();
432     file.openForWriting();
433     SMESH_Comment text;
434     text << "import salome, SMESH\n";
435     text << "salome.salome_init()\n";
436     text << "from salome.smesh import smeshBuilder\n";
437     text << "smesh = smeshBuilder.New()\n";
438     text << "m=smesh.Mesh()\n";
439     for ( size_t iE = 0; iE < bndSegsPerEdge.size(); ++iE )
440     {
441       const vector< BndSeg >& bndSegs = bndSegsPerEdge[ iE ];
442       for ( size_t i = 0; i < bndSegs.size(); ++i )
443       {
444         if ( !bndSegs[i]._edge )
445           text << "# E=" << iE << " i=" << i << " NULL edge\n";
446         else if ( !bndSegs[i]._edge->vertex0() ||
447                   !bndSegs[i]._edge->vertex1() )
448           text << "# E=" << iE << " i=" << i << " INFINITE edge\n";
449         else if ( addedEdges.insert( bndSegs[i]._edge ).second &&
450                   addedEdges.insert( bndSegs[i]._edge->twin() ).second )
451         {
452           v2n = v2Node.insert( make_pair( bndSegs[i]._edge->vertex0(), v2Node.size() + 1 )).first;
453           size_t n0 = v2n->second;
454           if ( n0 == v2Node.size() )
455             text << "n" << n0 << " = m.AddNode( "
456                  << bndSegs[i]._edge->vertex0()->x() / theScale[0] << ", "
457                  << bndSegs[i]._edge->vertex0()->y() / theScale[1] << ", 0 )\n";
458
459           v2n = v2Node.insert( make_pair( bndSegs[i]._edge->vertex1(), v2Node.size() + 1 )).first;
460           size_t n1 = v2n->second;
461           if ( n1 == v2Node.size() )
462             text << "n" << n1 << " = m.AddNode( "
463                  << bndSegs[i]._edge->vertex1()->x() / theScale[0] << ", "
464                  << bndSegs[i]._edge->vertex1()->y() / theScale[1] << ", 0 )\n";
465
466           text << "e" << i << " = m.AddEdge([ n" << n0 << ", n" << n1 << " ])\n";
467         }
468       }
469     }
470     text << "\n";
471     file.write( text.c_str(), text.size() );
472     cout << fileName << endl;
473 #endif
474   }
475
476   //================================================================================
477   /*!
478    * \brief Computes length of a TVDEdge
479    */
480   //================================================================================
481
482   double length( const TVDEdge* edge )
483   {
484     gp_XY d( edge->vertex0()->x() - edge->vertex1()->x(),
485              edge->vertex0()->y() - edge->vertex1()->y() );
486     return d.Modulus();
487   }
488
489   //================================================================================
490   /*!
491    * \brief Compute scale to have the same 2d proportions as in 3d
492    */
493   //================================================================================
494
495   void computeProportionScale( const TopoDS_Face& face,
496                                const Bnd_B2d&     uvBox,
497                                double             scale[2])
498   {
499     scale[0] = scale[1] = 1.;
500     if ( uvBox.IsVoid() ) return;
501
502     TopLoc_Location loc;
503     Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
504
505     const int nbDiv = 30;
506     gp_XY uvMin = uvBox.CornerMin(), uvMax = uvBox.CornerMax();
507     gp_XY uvMid = 0.5 * ( uvMin + uvMax );
508     double du = ( uvMax.X() - uvMin.X() ) / nbDiv;
509     double dv = ( uvMax.Y() - uvMin.Y() ) / nbDiv;
510
511     double uLen3d = 0, vLen3d = 0;
512     gp_Pnt uPrevP = surface->Value( uvMin.X(), uvMid.Y() );
513     gp_Pnt vPrevP = surface->Value( uvMid.X(), uvMin.Y() );
514     for (int i = 1; i <= nbDiv; i++)
515     {
516       double u = uvMin.X() + du * i;
517       double v = uvMin.Y() + dv * i;
518       gp_Pnt uP = surface->Value( u, uvMid.Y() );
519       gp_Pnt vP = surface->Value( uvMid.X(), v );
520       uLen3d += uP.Distance( uPrevP );
521       vLen3d += vP.Distance( vPrevP );
522       uPrevP = uP;
523       vPrevP = vP;
524     }
525     scale[0] = uLen3d / ( uvMax.X() - uvMin.X() );
526     scale[1] = vLen3d / ( uvMax.Y() - uvMin.Y() );
527   }
528
529   //================================================================================
530   /*!
531    * \brief Fill input data for construct_voronoi()
532    */
533   //================================================================================
534
535   bool makeInputData(const TopoDS_Face&                face,
536                      const std::vector< TopoDS_Edge >& edges,
537                      const double                      minSegLen,
538                      vector< InPoint >&                inPoints,
539                      vector< InSegment>&               inSegments,
540                      double                            scale[2])
541   {
542     const double theDiscrCoef = 0.5; // to decrease minSegLen for discretization
543     TopLoc_Location loc;
544
545     // discretize the EDGEs to get 2d points and segments
546
547     vector< vector< UVU > > uvuVec( edges.size() );
548     Bnd_B2d uvBox;
549     for ( size_t iE = 0; iE < edges.size(); ++iE )
550     {
551       vector< UVU > & points = uvuVec[ iE ];
552
553       double f,l;
554       Handle(Geom_Curve)   c3d = BRep_Tool::Curve         ( edges[ iE ], loc, f, l );
555       Handle(Geom2d_Curve) c2d = BRep_Tool::CurveOnSurface( edges[ iE ], face, f, l );
556       if ( c2d.IsNull() ) return false;
557
558       points.push_back( UVU( c2d->Value( f ), f ));
559       uvBox.Add( points.back()._uv );
560
561       Geom2dAdaptor_Curve c2dAdaptor (c2d, f,l );
562       double curDeflect = 0.3; //0.01;  //Curvature deflection
563       double angDeflect = 0.2; // 0.09; //Angular deflection
564
565       GCPnts_TangentialDeflection discret(c2dAdaptor, angDeflect, curDeflect);
566       // if ( discret.NbPoints() > 2 )
567       // {
568       //   cout << endl;
569       //   do
570       //   {
571       //     discret.Initialize( c2dAdaptor, 100, curDeflect );
572       //     cout << "C " << curDeflect << " " << discret.NbPoints() << endl;
573       //     curDeflect *= 1.5;
574       //   }
575       //   while ( discret.NbPoints() > 5 );
576       //   cout << endl;
577       //   do
578       //   {
579       //     discret.Initialize( c2dAdaptor, angDeflect, 100 );
580       //     cout << "A " << angDeflect << " " << discret.NbPoints() << endl;
581       //     angDeflect *= 1.5;
582       //   }
583       //   while ( discret.NbPoints() > 5 );
584       // }
585       gp_Pnt p, pPrev;
586       if ( !c3d.IsNull() )
587         pPrev = c3d->Value( f );
588       if ( discret.NbPoints() > 2 )
589         for ( int i = 2; i <= discret.NbPoints(); i++ ) // skip the 1st point
590         {
591           double u = discret.Parameter(i);
592           if ( !c3d.IsNull() )
593           {
594             p = c3d->Value( u );
595             int nbDiv = int( p.Distance( pPrev ) / minSegLen / theDiscrCoef );
596             double dU = ( u - points.back()._u ) / nbDiv;
597             for ( int iD = 1; iD < nbDiv; ++iD )
598             {
599               double uD = points.back()._u + dU;
600               points.push_back( UVU( c2d->Value( uD ), uD ));
601             }
602             pPrev = p;
603           }
604           points.push_back( UVU( c2d->Value( u ), u ));
605           uvBox.Add( points.back()._uv );
606         }
607       // if ( !c3d.IsNull() )
608       // {
609       //   vector<double> params;
610       //   GeomAdaptor_Curve c3dAdaptor( c3d,f,l );
611       //   if ( useDefl )
612       //   {
613       //     const double deflection = minSegLen * 0.1;
614       //     GCPnts_UniformDeflection discret( c3dAdaptor, deflection, f, l, true );
615       //     if ( !discret.IsDone() )
616       //       return false;
617       //     int nbP = discret.NbPoints();
618       //     for ( int i = 2; i < nbP; i++ ) // skip 1st and last points
619       //       params.push_back( discret.Parameter(i) );
620       //   }
621       //   else
622       //   {
623       //     double   eLen = GCPnts_AbscissaPoint::Length( c3dAdaptor );
624       //     int     nbSeg = Max( 1, int( eLen / minSegLen / theDiscrCoef ));
625       //     double segLen = eLen / nbSeg;
626       //     GCPnts_UniformAbscissa discret( c3dAdaptor, segLen, f, l );
627       //     int nbP = Min( discret.NbPoints(), nbSeg + 1 );
628       //     for ( int i = 2; i < nbP; i++ ) // skip 1st and last points
629       //       params.push_back( discret.Parameter(i) );
630       //   }
631       //   for ( size_t i = 0; i < params.size(); ++i )
632       //   {
633       //     points.push_back( UVU( c2d->Value( params[i] ), params[i] ));
634       //     uvBox.Add( points.back()._uv );
635       //   }
636       // }
637       if ( points.size() < 2 )
638       {
639         points.push_back( UVU( c2d->Value( l ), l ));
640         uvBox.Add( points.back()._uv );
641       }
642       if ( edges[ iE ].Orientation() == TopAbs_REVERSED )
643         std::reverse( points.begin(), points.end() );
644     }
645
646     // make connected EDGEs have same UV at shared VERTEX
647     TopoDS_Vertex vShared;
648     for ( size_t iE = 0; iE < edges.size(); ++iE )
649     {
650       size_t iE2 = (iE+1) % edges.size();
651       if ( !TopExp::CommonVertex( edges[iE], edges[iE2], vShared )) // FACE with several WIREs?
652         for ( size_t i = 1; i < edges.size(); ++i )
653         {
654           iE2 = (iE2+1) % edges.size();
655           if ( iE != iE2 &&
656                TopExp::CommonVertex( edges[iE], edges[iE2], vShared ) &&
657                vShared.IsSame( TopExp::LastVertex( edges[iE], true )))
658             break;
659         }
660       if ( !vShared.IsSame( TopExp::LastVertex( edges[iE], true )))
661         continue;
662         //return false;
663       vector< UVU > & points1 = uvuVec[ iE ];
664       vector< UVU > & points2 = uvuVec[ iE2 ];
665       gp_Pnt2d & uv1 = points1.back() ._uv;
666       gp_Pnt2d & uv2 = points2.front()._uv;
667       uv1 = uv2 = 0.5 * ( uv1.XY() + uv2.XY() );
668     }
669
670     // get scale to have the same 2d proportions as in 3d
671     computeProportionScale( face, uvBox, scale );
672
673     // make 'scale' such that to have coordinates precise enough when converted to int
674
675     gp_XY uvMin = uvBox.CornerMin(), uvMax = uvBox.CornerMax();
676     uvMin *= gp_XY( scale[0], scale[1] );
677     uvMax *= gp_XY( scale[0], scale[1] );
678     double vMax[2] = { Max( Abs( uvMin.X() ), Abs( uvMax.X() )),
679                        Max( Abs( uvMin.Y() ), Abs( uvMax.Y() )) };
680     int iMax = ( vMax[0] > vMax[1] ) ? 0 : 1;
681     const double precision = Min( 1e-5, Min( minSegLen * 1e-2, vMax[iMax] * 1e-5 ));
682     double preciScale = Min( vMax[iMax] / precision,
683                              std::numeric_limits<int>::max() / vMax[iMax] );
684     preciScale /= scale[iMax];
685     double roundedScale = 10; // to ease debug
686     while ( roundedScale * 10 < preciScale )
687       roundedScale *= 10.;
688     scale[0] *= roundedScale;
689     scale[1] *= roundedScale;
690
691     // create input points and segments
692
693     inPoints.clear();
694     inSegments.clear();
695     size_t nbPnt = 0;
696     for ( size_t iE = 0; iE < uvuVec.size(); ++iE )
697       nbPnt += uvuVec[ iE ].size();
698     inPoints.resize( nbPnt );
699     inSegments.reserve( nbPnt );
700
701     size_t iP = 0;
702     if ( face.Orientation() == TopAbs_REVERSED )
703     {
704       for ( int iE = uvuVec.size()-1; iE >= 0; --iE )
705       {
706         vector< UVU > & points = uvuVec[ iE ];
707         inPoints[ iP++ ] = points.back().getInPoint( scale );
708         for ( size_t i = points.size()-1; i >= 1; --i )
709         {
710           inPoints[ iP++ ] = points[i-1].getInPoint( scale );
711           inSegments.push_back( InSegment( & inPoints[ iP-2 ], & inPoints[ iP-1 ], iE ));
712           if ( inPoints[ iP-2 ] == inPoints[ iP-1 ])
713             return false; // too short segment
714         }
715       }
716     }
717     else
718     {
719       for ( size_t iE = 0; iE < uvuVec.size(); ++iE )
720       {
721         vector< UVU > & points = uvuVec[ iE ];
722         inPoints[ iP++ ] = points[0].getInPoint( scale );
723         for ( size_t i = 1; i < points.size(); ++i )
724         {
725           inPoints[ iP++ ] = points[i].getInPoint( scale );
726           inSegments.push_back( InSegment( & inPoints[ iP-2 ], & inPoints[ iP-1 ], iE ));
727           if ( inPoints[ iP-2 ] == inPoints[ iP-1 ])
728             return false; // too short segment
729         }
730       }
731     }
732     // debug
733     theScale[0] = scale[0];
734     theScale[1] = scale[1];
735
736     return true;
737   }
738
739   //================================================================================
740   /*!
741    * \brief Update a branch joined to another one
742    */
743   //================================================================================
744
745   void updateJoinedBranch( vector< const TVDEdge* > &   branchEdges,
746                            const size_t                 newID,
747                            vector< vector< BndSeg > > & bndSegs,
748                            const bool                   reverse)
749   {
750     BndSeg *seg1, *seg2;
751     if ( reverse )
752     {
753       for ( size_t i = 0; i < branchEdges.size(); ++i )
754       {
755         if (( seg1 = BndSeg::getBndSegOfEdge( branchEdges[i],         bndSegs )) &&
756             ( seg2 = BndSeg::getBndSegOfEdge( branchEdges[i]->twin(), bndSegs )))
757         {
758           seg1->_branchID /= seg1->branchID();
759           seg2->_branchID /= seg2->branchID();
760           seg1->_branchID *= -newID;
761           seg2->_branchID *= -newID;
762           branchEdges[i] = branchEdges[i]->twin();
763         }
764       }
765       std::reverse( branchEdges.begin(), branchEdges.end() );
766     }
767     else
768     {
769       for ( size_t i = 0; i < branchEdges.size(); ++i )
770       {
771         if (( seg1 = BndSeg::getBndSegOfEdge( branchEdges[i],         bndSegs )) &&
772             ( seg2 = BndSeg::getBndSegOfEdge( branchEdges[i]->twin(), bndSegs )))
773         {
774           seg1->_branchID /= seg1->branchID();
775           seg2->_branchID /= seg2->branchID();
776           seg1->_branchID *= newID;
777           seg2->_branchID *= newID;
778         }
779       }
780     }
781   }
782
783   //================================================================================
784   /*!
785    * \brief Create MA branches and FACE boundary data
786    *  \param [in] vd - voronoi diagram of \a inSegments
787    *  \param [in] inPoints - FACE boundary points
788    *  \param [in,out] inSegments - FACE boundary segments
789    *  \param [out] branch - MA branches to fill
790    *  \param [out] branchEnd - ends of MA branches to fill
791    *  \param [out] boundary - FACE boundary to fill
792    */
793   //================================================================================
794
795   void makeMA( const TVD&                               vd,
796                const bool                               ignoreCorners,
797                vector< InPoint >&                       inPoints,
798                vector< InSegment > &                    inSegments,
799                vector< SMESH_MAT2d::Branch >&           branch,
800                vector< const SMESH_MAT2d::BranchEnd* >& branchPnt,
801                SMESH_MAT2d::Boundary&                   boundary )
802   {
803     // Associate MA cells with geom EDGEs
804     for (TVD::const_cell_iterator it = vd.cells().begin(); it != vd.cells().end(); ++it)
805     {
806       const TVDCell* cell = &(*it);
807       if ( cell->is_degenerate() )
808       {
809         std::cerr << "SMESH_MAT2d: encounter degenerate voronoi_cell. Invalid input data?"
810                   << std::endl;
811         return;
812       }
813       if ( cell->contains_segment() )
814       {
815         InSegment& seg = inSegments[ cell->source_index() ];
816         seg._cell = cell;
817         seg.setGeomEdgeToCell( cell, seg._geomEdgeInd );
818       }
819       else
820       {
821         InSegment::setGeomEdgeToCell( cell, theNoEdgeID );
822       }
823     }
824
825     vector< bool > inPntChecked( inPoints.size(), false );
826
827     // Find MA edges of each inSegment
828
829     for ( size_t i = 0; i < inSegments.size(); ++i )
830     {
831       InSegment& inSeg = inSegments[i];
832
833       // get edges around the cell lying on MA
834       bool hasSecondary = false;
835       const TVDEdge* edge = inSeg._cell->incident_edge();
836       do {
837         edge = edge->next(); // Returns the CCW next edge within the cell.
838         if ( edge->is_primary() && !inSeg.isExternal( edge ) )
839           inSeg._edges.push_back( edge ); // edge equidistant from two InSegments
840         else
841           hasSecondary = true;
842       } while (edge != inSeg._cell->incident_edge());
843
844       // there can be several continuous MA edges but maEdges can begin in the middle of
845       // a chain of continuous MA edges. Make the chain continuous.
846       list< const TVDEdge* >& maEdges = inSeg._edges;
847       if ( maEdges.empty() )
848         continue;
849       if ( hasSecondary )
850         while ( maEdges.back()->next() == maEdges.front() )
851           maEdges.splice( maEdges.end(), maEdges, maEdges.begin() );
852
853       // remove maEdges equidistant from two neighbor InSegments of the same geom EDGE
854       list< const TVDEdge* >::iterator e = maEdges.begin();
855       while ( e != maEdges.end() )
856       {
857         const TVDCell* cell2 = (*e)->twin()->cell(); // cell on the other side of a MA edge
858         size_t         geoE2 = InSegment::getGeomEdge( cell2 );
859         bool        toRemove = ( inSeg._geomEdgeInd == geoE2 && inSeg.isConnected( *e ));
860         if ( toRemove )
861           e = maEdges.erase( e );
862         else
863           ++e;
864       }
865       if ( maEdges.empty() )
866         continue;
867
868       // add MA edges corresponding to concave InPoints
869       for ( int is2nd = 0; is2nd < 2; ++is2nd ) // loop on two ends of inSeg
870       {
871         InPoint& inPnt = *( is2nd ? inSeg._p1 : inSeg._p0 );
872         size_t    pInd = inPnt.index( inPoints );
873         if ( inPntChecked[ pInd ] )
874           continue;
875         if ( pInd > 0 &&
876              inPntChecked[ pInd-1 ] &&
877              inPoints[ pInd-1 ] == inPnt )
878           continue;
879         inPntChecked[ pInd ] = true;
880
881         const TVDEdge* maE = is2nd ? maEdges.front() : maEdges.back();
882         if ( inPnt == ( is2nd ? maE->vertex0() : maE->vertex1() ))
883           continue;
884         const TVDEdge* edge =  // a secondary TVDEdge connecting inPnt and maE
885           is2nd ? maE->prev() : maE->next();
886         while ( inSeg.isConnected( edge ))
887         {
888           if ( edge->is_primary() ) break; // this should not happen
889           const TVDEdge* edge2 = edge->twin(); // we are in a neighbor cell, add MA edges to inPnt
890           if ( inSeg.getGeomEdge( edge2->cell() ) != theNoEdgeID )
891             break; // cell of an InSegment
892           bool hasInfinite = false;
893           list< const TVDEdge* > pointEdges;
894           edge = edge2;
895           do
896           {
897             edge = edge->next(); // Returns the CCW next edge within the cell.
898             if ( edge->is_infinite() )
899               hasInfinite = true;
900             else if ( edge->is_primary() && !inSeg.isExternal( edge ))
901               pointEdges.push_back( edge );
902           }
903           while ( edge != edge2 && !hasInfinite );
904
905           if ( hasInfinite || pointEdges.empty() )
906             break;
907           inPnt._edges.splice( inPnt._edges.end(), pointEdges );
908           inSeg.setGeomEdgeToCell( edge->cell(), inSeg._geomEdgeInd );
909
910           edge = is2nd ? inPnt._edges.front()->prev() : inPnt._edges.back()->next();
911         }
912       } // add MA edges corresponding to concave InPoints
913
914     } // loop on inSegments to find corresponding MA edges
915
916
917     // -------------------------------------------
918     // Create Branches and BndPoints for each EDGE
919     // -------------------------------------------
920
921     if ( inPoints.front() == inPoints.back() /*&& !inPoints[0]._edges.empty()*/ )
922     {
923       inPntChecked[0] = false; // do not use the 1st point twice
924       //InSegment::setGeomEdgeToCell( inPoints[0]._edges.back()->cell(), theNoEdgeID );
925       inPoints[0]._edges.clear();
926     }
927
928     // Divide InSegment's into BndSeg's (so that each BndSeg corresponds to one MA edge)
929
930     vector< vector< BndSeg > > bndSegsPerEdge( boundary.nbEdges() ); // all BndSeg's
931     {
932       vector< BndSeg > bndSegs; // bndSeg's of a current EDGE
933       size_t prevGeomEdge = theNoEdgeID;
934
935       list< const TVDEdge* >::reverse_iterator e;
936       for ( size_t i = 0; i < inSegments.size(); ++i )
937       {
938         InSegment& inSeg = inSegments[i];
939
940         if ( inSeg._geomEdgeInd != prevGeomEdge )
941         {
942           if ( !bndSegs.empty() )
943             bndSegsPerEdge[ prevGeomEdge ].swap( bndSegs );
944           prevGeomEdge = inSeg._geomEdgeInd;
945         }
946
947         // segments around 1st concave point
948         size_t ip0 = inSeg._p0->index( inPoints );
949         if ( inPntChecked[ ip0 ] )
950           for ( e = inSeg._p0->_edges.rbegin(); e != inSeg._p0->_edges.rend(); ++e )
951             bndSegs.push_back( BndSeg( &inSeg, *e, inSeg._p0->_param ));
952         inPntChecked[ ip0 ] = false;
953
954         // segments of InSegment's
955         const size_t nbMaEdges = inSeg._edges.size();
956         switch ( nbMaEdges ) {
957         case 0: // "around" circle center
958           bndSegs.push_back( BndSeg( &inSeg, 0, inSeg._p1->_param )); break;
959         case 1:
960           bndSegs.push_back( BndSeg( &inSeg, inSeg._edges.back(), inSeg._p1->_param )); break;
961         default:
962           gp_XY inSegDir( inSeg._p1->_a - inSeg._p0->_a,
963                           inSeg._p1->_b - inSeg._p0->_b );
964           const double inSegLen2 = inSegDir.SquareModulus();
965           e = inSeg._edges.rbegin();
966           for ( size_t iE = 1; iE < nbMaEdges; ++e, ++iE )
967           {
968             gp_XY toMA( (*e)->vertex0()->x() - inSeg._p0->_a,
969                         (*e)->vertex0()->y() - inSeg._p0->_b );
970             double r = toMA * inSegDir / inSegLen2;
971             double u = r * inSeg._p1->_param + ( 1. - r ) * inSeg._p0->_param;
972             bndSegs.push_back( BndSeg( &inSeg, *e, u ));
973           }
974           bndSegs.push_back( BndSeg( &inSeg, *e, inSeg._p1->_param ));
975         }
976         // segments around 2nd concave point
977         size_t ip1 = inSeg._p1->index( inPoints );
978         if ( inPntChecked[ ip1 ] )
979           for ( e = inSeg._p1->_edges.rbegin(); e != inSeg._p1->_edges.rend(); ++e )
980             bndSegs.push_back( BndSeg( &inSeg, *e, inSeg._p1->_param ));
981         inPntChecked[ ip1 ] = false;
982       }
983       if ( !bndSegs.empty() )
984         bndSegsPerEdge[ prevGeomEdge ].swap( bndSegs );
985     }
986
987     // prepare to MA branch search
988     for ( size_t iE = 0; iE < bndSegsPerEdge.size(); ++iE )
989     {
990       // 1) make TVDEdge's know it's BndSeg to enable passing branchID to
991       // an opposite BndSeg in BndSeg::setBranch(); geom EDGE ID is known from TVDCell
992       // 2) connect bndSegs via BndSeg::_prev
993
994       vector< BndSeg >& bndSegs = bndSegsPerEdge[ iE ];
995       if ( bndSegs.empty() ) continue;
996
997       for ( size_t i = 1; i < bndSegs.size(); ++i )
998       {
999         bndSegs[i]._prev = & bndSegs[i-1];
1000         bndSegs[i].setIndexToEdge( i );
1001       }
1002       // look for the last bndSeg of previous EDGE to set bndSegs[0]._prev
1003       const InPoint& p0 = bndSegs[0]._inSeg->point0();
1004       for ( size_t iE2 = 0; iE2 < bndSegsPerEdge.size(); ++iE2 )
1005         if ( p0 == bndSegsPerEdge[ iE2 ].back()._inSeg->point1() )
1006         {
1007           bndSegs[0]._prev = & bndSegsPerEdge[ iE2 ].back();
1008           break;
1009         }
1010       bndSegs[0].setIndexToEdge( 0 );
1011     }
1012
1013     bndSegsToMesh( bndSegsPerEdge ); // debug: visually check found MA edges
1014
1015
1016     // Find TVDEdge's of Branches and associate them with bndSegs
1017
1018     vector< vector<const TVDEdge*> > branchEdges;
1019     branchEdges.reserve( boundary.nbEdges() * 4 );
1020
1021     map< const TVDVertex*, SMESH_MAT2d::BranchEndType > endType;
1022
1023     int branchID = 1; // we code orientation as branchID sign
1024     branchEdges.resize( branchID );
1025
1026     vector< std::pair< int, const TVDVertex* > > branchesToCheckEnd;
1027
1028     for ( size_t iE = 0; iE < bndSegsPerEdge.size(); ++iE )
1029     {
1030       vector< BndSeg >& bndSegs = bndSegsPerEdge[ iE ];
1031       for ( size_t i = 0; i < bndSegs.size(); ++i )
1032       {
1033         if ( bndSegs[i].branchID() )
1034         {
1035           if ( bndSegs[i]._prev &&
1036                bndSegs[i]._branchID == -bndSegs[i]._prev->_branchID &&
1037                bndSegs[i]._edge )
1038           {
1039             SMESH_MAT2d::BranchEndType type =
1040               ( bndSegs[i]._inSeg->isConnected( bndSegs[i]._edge ) ?
1041                 SMESH_MAT2d::BE_ON_VERTEX :
1042                 SMESH_MAT2d::BE_END );
1043             endType.insert( make_pair( bndSegs[i]._edge->vertex1(), type ));
1044           }
1045           continue;
1046         }
1047         if ( !bndSegs[i]._prev &&
1048              !bndSegs[i].hasOppositeEdge() )
1049           continue;
1050
1051         if ( !bndSegs[i]._prev ||
1052              !bndSegs[i]._prev->isSameBranch( bndSegs[i] ))
1053         {
1054           branchEdges.resize(( branchID = branchEdges.size()) + 1 );
1055           if ( bndSegs[i]._edge && bndSegs[i]._prev )
1056           {
1057             endType.insert( make_pair( bndSegs[i]._edge->vertex1(), SMESH_MAT2d::BE_BRANCH_POINT ));
1058             if ( bndSegs[i]._prev->_branchID < 0 )
1059               // 0023404: a branch-point is inside a branch
1060               branchesToCheckEnd.push_back( make_pair( bndSegs[i]._prev->branchID(),
1061                                                        bndSegs[i]._edge->vertex1() ));
1062           }
1063         }
1064         else if ( bndSegs[i]._prev->_branchID )
1065         {
1066           branchID = bndSegs[i]._prev->_branchID;  // with sign
1067         }
1068         else if ( bndSegs[i]._edge ) // 1st bndSeg of a WIRE
1069         {
1070           branchEdges.resize(( branchID = branchEdges.size()) + 1 );
1071           if ( bndSegs[i]._inSeg->isConnected( bndSegs[i]._edge ))
1072           {
1073             if ( bndSegs[i]._inSeg->point0() == bndSegs[i]._edge->vertex1() )
1074               endType.insert( make_pair( bndSegs[i]._edge->vertex1(), SMESH_MAT2d::BE_ON_VERTEX ));
1075             else
1076               endType.insert( make_pair( bndSegs[i]._edge->vertex0(), SMESH_MAT2d::BE_ON_VERTEX ));
1077           }
1078         }
1079
1080         else // 2D_mesh_QuadranglePreference_00/A1, bos20144.brep
1081         {
1082           continue; // bndSegs.size() == 1
1083         }
1084
1085         bndSegs[i].setBranch( branchID, bndSegsPerEdge ); // set to i-th and to the opposite bndSeg
1086         if ( bndSegs[i].hasOppositeEdge() )
1087           branchEdges[ bndSegs[i].branchID() ].push_back( bndSegs[i]._edge );
1088       }
1089     }
1090
1091     if ( !ignoreCorners && !branchesToCheckEnd.empty() )
1092     {
1093       // split branches having branch-point inside
1094       // (a branch-point was not detected since another branch is joined at the opposite side)
1095       for ( size_t i = 0; i < branchesToCheckEnd.size(); ++i )
1096       {
1097         vector<const TVDEdge*> & branch = branchEdges[ branchesToCheckEnd[i].first ];
1098         const TVDVertex*    branchPoint = branchesToCheckEnd[i].second;
1099         if ( branch.front()->vertex1() == branchPoint ||
1100              branch.back ()->vertex0() == branchPoint )
1101           continue; // OK - branchPoint is at a branch end
1102
1103         // find a MA edge where another branch begins
1104         size_t iE;
1105         for ( iE = 0; iE < branch.size(); ++iE )
1106           if ( branch[iE]->vertex1() == branchPoint )
1107             break;
1108         if ( iE < branch.size() )
1109         {
1110           // split the branch
1111           branchEdges.resize(( branchID = branchEdges.size()) + 1 );
1112           vector<const TVDEdge*> & branch2 = branchEdges[ branchID ];
1113           branch2.assign( branch.begin()+iE, branch.end() );
1114           branch.resize( iE );
1115           for ( iE = 0; iE < branch2.size(); ++iE )
1116             if ( BndSeg* bs = BndSeg::getBndSegOfEdge( branch2[iE], bndSegsPerEdge ))
1117               bs->setBranch( branchID, bndSegsPerEdge );
1118         }
1119       }
1120     }
1121
1122     // join the 1st and the last branch edges if it is the same branch
1123     // if ( bndSegs.back().branchID() != bndSegs.front().branchID() &&
1124     //      bndSegs.back().isSameBranch( bndSegs.front() ))
1125     // {
1126     //   vector<const TVDEdge*> & br1 = branchEdges[ bndSegs.front().branchID() ];
1127     //   vector<const TVDEdge*> & br2 = branchEdges[ bndSegs.back().branchID()  ];
1128     //   br1.insert( br1.begin(), br2.begin(), br2.end() );
1129     //   br2.clear();
1130     // }
1131
1132     // remove branches ending at BE_ON_VERTEX and BE_END
1133
1134     vector<bool> isBranchRemoved( branchEdges.size(), false );
1135
1136     std::set< SMESH_MAT2d::BranchEndType > endTypeToRm;
1137     endTypeToRm.insert( SMESH_MAT2d::BE_ON_VERTEX );
1138     endTypeToRm.insert( SMESH_MAT2d::BE_END );
1139
1140     if ( ignoreCorners && branchEdges.size() > 2 && !branchEdges[2].empty() )
1141     {
1142       // find branches to remove
1143       map< const TVDVertex*, SMESH_MAT2d::BranchEndType >::iterator v2et;
1144       for ( size_t iB = 1; iB < branchEdges.size(); ++iB )
1145       {
1146         if ( branchEdges[iB].empty() )
1147           continue;
1148         const TVDVertex* v0 = branchEdges[iB][0]->vertex1();
1149         const TVDVertex* v1 = branchEdges[iB].back()->vertex0();
1150         v2et = endType.find( v0 );
1151         if ( v2et != endType.end() && endTypeToRm.count( v2et->second ))
1152           isBranchRemoved[ iB ] = true;
1153         v2et = endType.find( v1 );
1154         if ( v2et != endType.end() && endTypeToRm.count( v2et->second ))
1155           isBranchRemoved[ iB ] = true;
1156       }
1157       // try to join not removed branches into one
1158       for ( size_t iB = 1; iB < branchEdges.size(); ++iB )
1159       {
1160         if ( branchEdges[iB].empty() || isBranchRemoved[iB] )
1161           continue;
1162         const TVDVertex* v0 = branchEdges[iB][0]->vertex1();
1163         const TVDVertex* v1 = branchEdges[iB].back()->vertex0();
1164         v2et = endType.find( v0 );
1165         if ( v2et == endType.end() || v2et->second != SMESH_MAT2d::BE_BRANCH_POINT )
1166           v0 = 0;
1167         v2et = endType.find( v1 );
1168         if ( v2et == endType.end() || v2et->second != SMESH_MAT2d::BE_BRANCH_POINT )
1169           v1 = 0;
1170         if ( !v0 && !v1 )
1171           continue;
1172
1173         for ( int isV0 = 0; isV0 < 2; ++isV0 )
1174         {
1175           const TVDVertex* v = isV0 ? v0 : v1;
1176           size_t iBrToJoin = 0;
1177           for ( size_t iB2 = 1; iB2 < branchEdges.size(); ++iB2 )
1178           {
1179             if ( branchEdges[iB2].empty() || isBranchRemoved[iB2] || iB == iB2 )
1180               continue;
1181             const TVDVertex* v02 = branchEdges[iB2][0]->vertex1();
1182             const TVDVertex* v12 = branchEdges[iB2].back()->vertex0();
1183             if ( v == v02 || v == v12 )
1184             {
1185               if ( iBrToJoin > 0 )
1186               {
1187                 iBrToJoin = 0;
1188                 break; // more than 2 not removed branches meat at a TVDVertex
1189               }
1190               iBrToJoin = iB2;
1191             }
1192           }
1193           if ( iBrToJoin > 0 )
1194           {
1195             vector<const TVDEdge*>& branch = branchEdges[ iBrToJoin ];
1196             const TVDVertex* v02 = branch[0]->vertex1();
1197             const TVDVertex* v12 = branch.back()->vertex0();
1198             updateJoinedBranch( branch, iB, bndSegsPerEdge, /*reverse=*/(v0 == v02 || v1 == v12 ));
1199             if ( v0 == v02 || v0 == v12 )
1200               branchEdges[iB].insert( branchEdges[iB].begin(), branch.begin(), branch.end() );
1201             else
1202               branchEdges[iB].insert( branchEdges[iB].end(),   branch.begin(), branch.end() );
1203             branch.clear();
1204           }
1205         }
1206       } // loop on branchEdges
1207     } // if ( ignoreCorners )
1208
1209     // associate branchIDs and the input branch vector (arg)
1210     vector< SMESH_MAT2d::Branch* > branchByID( branchEdges.size(), 0 );
1211     int nbBranches = 0;
1212     for ( size_t i = 0; i < branchEdges.size(); ++i )
1213     {
1214       nbBranches += ( !branchEdges[i].empty() );
1215     }
1216     branch.resize( nbBranches );
1217     size_t iBr = 0;
1218     for ( size_t brID = 1; brID < branchEdges.size(); ++brID ) // 1st - not removed
1219     {
1220       if ( !branchEdges[ brID ].empty() && !isBranchRemoved[ brID ])
1221         branchByID[ brID ] = & branch[ iBr++ ];
1222     }
1223     for ( size_t brID = 1; brID < branchEdges.size(); ++brID ) // then - removed
1224     {
1225       if ( !branchEdges[ brID ].empty() && isBranchRemoved[ brID ])
1226         branchByID[ brID ] = & branch[ iBr++ ];
1227     }
1228
1229     // Fill in BndPoints of each EDGE of the boundary
1230
1231     //size_t iSeg = 0;
1232     int edgeInd = -1, dInd = 0;
1233     for ( size_t iE = 0; iE < bndSegsPerEdge.size(); ++iE )
1234     {
1235       vector< BndSeg >&          bndSegs = bndSegsPerEdge[ iE ];
1236       SMESH_MAT2d::BndPoints & bndPoints = boundary.getPoints( iE );
1237
1238       // make TVDEdge know an index of bndSegs within BndPoints
1239       for ( size_t i = 0; i < bndSegs.size(); ++i )
1240         if ( bndSegs[i]._edge )
1241           SMESH_MAT2d::Branch::setBndSegment( i, bndSegs[i]._edge );
1242
1243       // parameters on EDGE
1244
1245       bndPoints._params.reserve( bndSegs.size() + 1 );
1246       bndPoints._params.push_back( bndSegs[ 0 ]._inSeg->_p0->_param );
1247
1248       for ( size_t i = 0; i < bndSegs.size(); ++i )
1249         bndPoints._params.push_back( bndSegs[ i ]._uLast );
1250
1251       // MA edges
1252
1253       bndPoints._maEdges.reserve( bndSegs.size() );
1254
1255       for ( size_t i = 0; i < bndSegs.size(); ++i )
1256       {
1257         const size_t              brID = bndSegs[ i ].branchID();
1258         const SMESH_MAT2d::Branch*  br = branchByID[ brID ];
1259
1260         if ( bndSegs[ i ]._edge && !branchEdges[ brID ].empty() )
1261         {
1262           edgeInd += dInd;
1263
1264           if (( edgeInd < 0 ||
1265                 edgeInd >= (int) branchEdges[ brID ].size() ) ||
1266               ( branchEdges[ brID ][ edgeInd ]         != bndSegs[ i ]._edge &&
1267                 branchEdges[ brID ][ edgeInd ]->twin() != bndSegs[ i ]._edge ))
1268           {
1269             if ( bndSegs[ i ]._branchID < 0 )
1270             {
1271               dInd = -1;
1272               for ( edgeInd = branchEdges[ brID ].size() - 1; edgeInd > 0; --edgeInd )
1273                 if ( branchEdges[ brID ][ edgeInd ]->twin() == bndSegs[ i ]._edge )
1274                   break;
1275             }
1276             else // bndSegs[ i ]._branchID > 0
1277             {
1278               dInd = +1;
1279               for ( edgeInd = 0; edgeInd < (int)branchEdges[ brID ].size(); ++edgeInd )
1280                 if ( branchEdges[ brID ][ edgeInd ] == bndSegs[ i ]._edge )
1281                   break;
1282             }
1283           }
1284         }
1285         else
1286         {
1287           // no MA edge, bndSeg corresponds to an end point of a branch
1288           if ( bndPoints._maEdges.empty() )
1289             edgeInd = 0;
1290           else
1291             edgeInd = branchEdges[ brID ].size();
1292           dInd = bndSegs[ i ]._branchID > 0 ? +1 : -1;
1293         }
1294
1295         bndPoints._maEdges.push_back( make_pair( br, ( 1 + edgeInd ) * dInd ));
1296
1297       } // loop on bndSegs of an EDGE
1298     } // loop on all bndSegs to construct Boundary
1299
1300     // Initialize branches
1301
1302     // find a not removed branch
1303     size_t iBrNorRemoved = 0;
1304     for ( size_t brID = 1; brID < branchEdges.size(); ++brID )
1305       if ( !branchEdges[brID].empty() && !isBranchRemoved[brID] )
1306       {
1307         iBrNorRemoved = brID;
1308         break;
1309       }
1310     // fill the branches with MA edges
1311     for ( size_t brID = 1; brID < branchEdges.size(); ++brID )
1312       if ( !branchEdges[brID].empty() )
1313       {
1314         branchByID[ brID ]->init( branchEdges[brID], & boundary, endType );
1315       }
1316     // mark removed branches
1317     for ( size_t brID = 1; brID < branchEdges.size(); ++brID )
1318       if ( isBranchRemoved[brID] && iBrNorRemoved > 0 )
1319       {
1320         SMESH_MAT2d::Branch* branch     = branchByID[ brID ];
1321         SMESH_MAT2d::Branch* mainBranch = branchByID[ iBrNorRemoved ];
1322         bool is1stBrPnt = ( branch->getEnd(0)->_type == SMESH_MAT2d::BE_BRANCH_POINT );
1323         const TVDVertex* branchVextex = 
1324           is1stBrPnt ? branch->getEnd(0)->_vertex : branch->getEnd(1)->_vertex;
1325         SMESH_MAT2d::BranchPoint bp = mainBranch->getPoint( branchVextex );
1326         branch->setRemoved( bp );
1327       }
1328     // set branches to branch ends
1329     for ( size_t i = 0; i < branch.size(); ++i )
1330       if ( !branch[i].isRemoved() )
1331         branch[i].setBranchesToEnds( branch );
1332
1333     // fill branchPnt arg
1334     map< const TVDVertex*, const SMESH_MAT2d::BranchEnd* > v2end;
1335     for ( size_t i = 0; i < branch.size(); ++i )
1336     {
1337       if ( branch[i].getEnd(0)->_branches.size() > 2 )
1338         v2end.insert( make_pair( branch[i].getEnd(0)->_vertex, branch[i].getEnd(0) ));
1339       if ( branch[i].getEnd(1)->_branches.size() > 2 )
1340         v2end.insert( make_pair( branch[i].getEnd(1)->_vertex, branch[i].getEnd(1) ));
1341     }
1342     branchPnt.resize( v2end.size() );
1343     map< const TVDVertex*, const SMESH_MAT2d::BranchEnd* >::iterator v2e = v2end.begin();
1344     for ( size_t i = 0; v2e != v2end.end(); ++v2e, ++i )
1345       branchPnt[ i ] = v2e->second;
1346
1347   } // makeMA()
1348
1349 } // namespace
1350
1351 //================================================================================
1352 /*!
1353  * \brief MedialAxis constructor
1354  *  \param [in] face - a face to create MA for
1355  *  \param [in] edges - edges of the face (possibly not all) on the order they
1356  *              encounter in the face boundary.
1357  *  \param [in] minSegLen - minimal length of a mesh segment used to discretize
1358  *              the edges. It is used to define precision of MA approximation
1359  */
1360 //================================================================================
1361
1362 SMESH_MAT2d::MedialAxis::MedialAxis(const TopoDS_Face&                face,
1363                                     const std::vector< TopoDS_Edge >& edges,
1364                                     const double                      minSegLen,
1365                                     const bool                        ignoreCorners):
1366   _face( face ), _boundary( edges.size() )
1367 {
1368   // input to construct_voronoi()
1369   vector< InPoint >  inPoints;
1370   vector< InSegment> inSegments;
1371   if ( !makeInputData( face, edges, minSegLen, inPoints, inSegments, _scale ))
1372     return;
1373
1374   inSegmentsToFile( inSegments );
1375
1376   // build voronoi diagram
1377   construct_voronoi( inSegments.begin(), inSegments.end(), &_vd );
1378
1379   // make MA data
1380   makeMA( _vd, ignoreCorners, inPoints, inSegments, _branch, _branchPnt, _boundary );
1381
1382   // count valid branches
1383   _nbBranches = _branch.size();
1384   for ( size_t i = 0; i < _branch.size(); ++i )
1385     if ( _branch[i].isRemoved() )
1386       --_nbBranches;
1387 }
1388
1389 //================================================================================
1390 /*!
1391  * \brief Returns the i-th branch
1392  */
1393 //================================================================================
1394
1395 const SMESH_MAT2d::Branch* SMESH_MAT2d::MedialAxis::getBranch(size_t i) const
1396 {
1397   return i < _nbBranches ? &_branch[i] : 0;
1398 }
1399
1400 //================================================================================
1401 /*!
1402  * \brief Return UVs of ends of MA edges of a branch
1403  */
1404 //================================================================================
1405
1406 void SMESH_MAT2d::MedialAxis::getPoints( const Branch*         branch,
1407                                          std::vector< gp_XY >& points) const
1408 {
1409   branch->getPoints( points, _scale );
1410 }
1411
1412 //================================================================================
1413 /*!
1414  * \brief Returns a BranchPoint corresponding to a given point on a geom EDGE
1415  *  \param [in] iEdge - index of geom EDGE within a vector passed at MA construction
1416  *  \param [in] u - parameter of the point on EDGE curve
1417  *  \param [out] p - the found BranchPoint
1418  *  \return bool - is OK
1419  */
1420 //================================================================================
1421
1422 bool SMESH_MAT2d::Boundary::getBranchPoint( const std::size_t iEdge,
1423                                             double            u,
1424                                             BranchPoint&      p ) const
1425 {
1426   if ( iEdge >= _pointsPerEdge.size() || _pointsPerEdge[iEdge]._params.empty() )
1427     return false;
1428
1429   const BndPoints& points = _pointsPerEdge[ iEdge ];
1430   const bool  edgeReverse = ( points._params[0] > points._params.back() );
1431
1432   if ( u < ( edgeReverse ? points._params.back() : points._params[0] ))
1433     u = edgeReverse ? points._params.back() : points._params[0];
1434   else if ( u > ( edgeReverse ? points._params[0] : points._params.back()) )
1435     u = edgeReverse ? points._params[0] : points._params.back();
1436
1437   double r = ( u - points._params[0] ) / ( points._params.back() - points._params[0] );
1438   int    i = int( r * double( points._maEdges.size()-1 ));
1439   if ( edgeReverse )
1440   {
1441     while ( points._params[i  ] < u ) --i;
1442     while ( points._params[i+1] > u ) ++i;
1443   }
1444   else
1445   {
1446     while ( points._params[i  ] > u ) --i;
1447     while ( points._params[i+1] < u ) ++i;
1448   }
1449
1450   if ( points._params[i] == points._params[i+1] ) // coincident points at some end
1451   {
1452     int di = ( points._params[0] == points._params[i] ) ? +1 : -1;
1453     while ( points._params[i] == points._params[i+1] )
1454       i += di;
1455     if ( i < 0 || i+1 >= (int)points._params.size() )
1456       i = 0;
1457   }
1458
1459   double edgeParam = ( u - points._params[i] ) / ( points._params[i+1] - points._params[i] );
1460
1461   if ( !points._maEdges[ i ].second ) // no branch at the EDGE end, look for a closest branch
1462   {
1463     if ( i < (int)points._maEdges.size() / 2 ) // near 1st point
1464     {
1465       while ( i < (int)points._maEdges.size()-1 && !points._maEdges[ i ].second )
1466         ++i;
1467       edgeParam = edgeReverse;
1468     }
1469     else // near last point
1470     {
1471       while ( i > 0 && !points._maEdges[ i ].second )
1472         --i;
1473       edgeParam = !edgeReverse;
1474     }
1475   }
1476   const std::pair< const Branch*, int >& maE = points._maEdges[ i ];
1477   bool maReverse = ( maE.second < 0 );
1478
1479   p._branch    = maE.first;
1480   p._iEdge     = ( maReverse ? -maE.second : maE.second ) - 1; // countered from 1 to store sign
1481   p._edgeParam = ( maE.first && maReverse ) ? ( 1. - edgeParam ) : edgeParam;
1482
1483   return true;
1484 }
1485
1486 //================================================================================
1487 /*!
1488  * \brief Returns a BranchPoint corresponding to a given BoundaryPoint on a geom EDGE
1489  *  \param [in] bp - the BoundaryPoint
1490  *  \param [out] p - the found BranchPoint
1491  *  \return bool - is OK
1492  */
1493 //================================================================================
1494
1495 bool SMESH_MAT2d::Boundary::getBranchPoint( const BoundaryPoint& bp,
1496                                             BranchPoint&         p ) const
1497 {
1498   return getBranchPoint( bp._edgeIndex, bp._param, p );
1499 }
1500
1501 //================================================================================
1502 /*!
1503  * \brief Check if a given boundary segment is a null-length segment on a concave
1504  *        boundary corner.
1505  *  \param [in] iEdge - index of a geom EDGE
1506  *  \param [in] iSeg - index of a boundary segment
1507  *  \return bool - true if the segment is on concave corner
1508  */
1509 //================================================================================
1510
1511 bool SMESH_MAT2d::Boundary::isConcaveSegment( std::size_t iEdge, std::size_t iSeg ) const
1512 {
1513   if ( iEdge >= _pointsPerEdge.size() || _pointsPerEdge[iEdge]._params.empty() )
1514     return false;
1515
1516   const BndPoints& points = _pointsPerEdge[ iEdge ];
1517   if ( points._params.size() <= iSeg+1 )
1518     return false;
1519
1520   return Abs( points._params[ iSeg ] - points._params[ iSeg+1 ]) < 1e-20;
1521 }
1522
1523 //================================================================================
1524 /*!
1525  * \brief Moves (changes _param) a given BoundaryPoint to a closest EDGE end
1526  */
1527 //================================================================================
1528
1529 bool SMESH_MAT2d::Boundary::moveToClosestEdgeEnd( BoundaryPoint& bp ) const
1530 {
1531   if ( bp._edgeIndex >= _pointsPerEdge.size() )
1532     return false;
1533
1534   const BndPoints& points = _pointsPerEdge[ bp._edgeIndex ];
1535   if ( Abs( bp._param - points._params[0]) < Abs( points._params.back() - bp._param ))
1536     bp._param = points._params[0];
1537   else 
1538     bp._param = points._params.back();
1539
1540   return true;
1541 }
1542
1543 //================================================================================
1544 /*!
1545  * \brief Creates a 3d curve corresponding to a Branch
1546  *  \param [in] branch - the Branch
1547  *  \return Adaptor3d_Curve* - the new curve the caller is to delete
1548  */
1549 //================================================================================
1550
1551 Adaptor3d_Curve* SMESH_MAT2d::MedialAxis::make3DCurve(const Branch& branch) const
1552 {
1553   Handle(Geom_Surface) surface = BRep_Tool::Surface( _face );
1554   if ( surface.IsNull() )
1555     return 0;
1556
1557   vector< gp_XY > uv;
1558   branch.getPoints( uv, _scale );
1559   if ( uv.size() < 2 )
1560     return 0;
1561
1562   vector< TopoDS_Vertex > vertex( uv.size() );
1563   for ( size_t i = 0; i < uv.size(); ++i )
1564     vertex[i] = BRepBuilderAPI_MakeVertex( surface->Value( uv[i].X(), uv[i].Y() ));
1565
1566   TopoDS_Wire aWire;
1567   BRep_Builder aBuilder;
1568   aBuilder.MakeWire(aWire);
1569   for ( size_t i = 1; i < vertex.size(); ++i )
1570   {
1571     TopoDS_Edge edge = BRepBuilderAPI_MakeEdge( vertex[i-1], vertex[i] );
1572     aBuilder.Add( aWire, edge );
1573   }
1574
1575   // if ( myEdge.size() == 2 && FirstVertex().IsSame( LastVertex() ))
1576   //   aWire.Closed(true); // issue 0021141
1577
1578   return new BRepAdaptor_CompCurve( aWire );
1579 }
1580
1581 //================================================================================
1582 /*!
1583  * \brief Copy points of an EDGE
1584  */
1585 //================================================================================
1586
1587 void SMESH_MAT2d::Branch::init( vector<const TVDEdge*>&                 maEdges,
1588                                 const Boundary*                         boundary,
1589                                 map< const TVDVertex*, BranchEndType >& endType )
1590 {
1591   if ( maEdges.empty() ) return;
1592
1593   _boundary = boundary;
1594   _maEdges.swap( maEdges );
1595
1596
1597   _params.reserve( _maEdges.size() + 1 );
1598   _params.push_back( 0. );
1599   for ( size_t i = 0; i < _maEdges.size(); ++i )
1600     _params.push_back( _params.back() + length( _maEdges[i] ));
1601   
1602   for ( size_t i = 1; i < _params.size(); ++i )
1603     _params[i] /= _params.back();
1604
1605
1606   _endPoint1._vertex = _maEdges.front()->vertex1();
1607   _endPoint2._vertex = _maEdges.back ()->vertex0();
1608
1609   if ( endType.count( _endPoint1._vertex ))
1610     _endPoint1._type = endType[ _endPoint1._vertex ];
1611   if ( endType.count( _endPoint2._vertex ))
1612     _endPoint2._type = endType[ _endPoint2._vertex ];
1613 }
1614
1615 //================================================================================
1616 /*!
1617  * \brief fills BranchEnd::_branches of its ends
1618  */
1619 //================================================================================
1620
1621 void SMESH_MAT2d::Branch::setBranchesToEnds( const vector< Branch >& branches )
1622 {
1623   for ( size_t i = 0; i < branches.size(); ++i )
1624   {
1625     if ( this->_endPoint1._vertex == branches[i]._endPoint1._vertex ||
1626          this->_endPoint1._vertex == branches[i]._endPoint2._vertex )
1627       this->_endPoint1._branches.push_back( &branches[i] );
1628
1629     if ( this->_endPoint2._vertex == branches[i]._endPoint1._vertex ||
1630          this->_endPoint2._vertex == branches[i]._endPoint2._vertex )
1631       this->_endPoint2._branches.push_back( &branches[i] );
1632   }
1633 }
1634
1635 //================================================================================
1636 /*!
1637  * \brief returns a BranchPoint corresponding to a TVDVertex
1638  */
1639 //================================================================================
1640
1641 SMESH_MAT2d::BranchPoint SMESH_MAT2d::Branch::getPoint( const TVDVertex* vertex ) const
1642 {
1643   BranchPoint p;
1644   p._branch = this;
1645   p._iEdge  = 0;
1646
1647   if ( vertex == _maEdges[0]->vertex1() )
1648   {
1649     p._edgeParam = 0;
1650   }
1651   else
1652   {
1653     for ( ; p._iEdge < _maEdges.size(); ++p._iEdge )
1654       if ( vertex == _maEdges[ p._iEdge ]->vertex0() )
1655       {
1656         p._edgeParam = _params[ p._iEdge ];
1657         break;
1658       }
1659   }
1660   return p;
1661 }
1662
1663 //================================================================================
1664 /*!
1665  * \brief Sets a proxy point for a removed branch
1666  *  \param [in] proxyPoint - a point of another branch to which all points of this
1667  *         branch are mapped
1668  */
1669 //================================================================================
1670
1671 void SMESH_MAT2d::Branch::setRemoved( const BranchPoint& proxyPoint )
1672 {
1673   _proxyPoint = proxyPoint;
1674 }
1675
1676 //================================================================================
1677 /*!
1678  * \brief Returns points on two EDGEs, equidistant from a given point of this Branch
1679  *  \param [in] param - [0;1] normalized param on the Branch
1680  *  \param [out] bp1 - BoundaryPoint on EDGE with a lower index
1681  *  \param [out] bp2 - BoundaryPoint on EDGE with a higher index
1682  *  \return bool - true if the BoundaryPoint's found
1683  */
1684 //================================================================================
1685
1686 bool SMESH_MAT2d::Branch::getBoundaryPoints(double         param,
1687                                             BoundaryPoint& bp1,
1688                                             BoundaryPoint& bp2 ) const
1689 {
1690   if ( param < _params[0] || param > _params.back() )
1691     return false;
1692
1693   // look for an index of a MA edge by param
1694   double ip = param * _params.size();
1695   size_t  i = size_t( Min( int( _maEdges.size()-1), int( ip )));
1696
1697   while ( param < _params[i  ] ) --i;
1698   while ( param > _params[i+1] ) ++i;
1699
1700   double r = ( param - _params[i] ) / ( _params[i+1] - _params[i] );
1701
1702   return getBoundaryPoints( i, r, bp1, bp2 );
1703 }
1704
1705 //================================================================================
1706 /*!
1707  * \brief Returns points on two EDGEs, equidistant from a given point of this Branch
1708  *  \param [in] iMAEdge - index of a MA edge within this Branch
1709  *  \param [in] maEdgeParam - [0;1] normalized param on the \a iMAEdge
1710  *  \param [out] bp1 - BoundaryPoint on EDGE with a lower index
1711  *  \param [out] bp2 - BoundaryPoint on EDGE with a higher index
1712  *  \return bool - true if the BoundaryPoint's found
1713  */
1714 //================================================================================
1715
1716 bool SMESH_MAT2d::Branch::getBoundaryPoints(std::size_t    iMAEdge,
1717                                             double         maEdgeParam,
1718                                             BoundaryPoint& bp1,
1719                                             BoundaryPoint& bp2 ) const
1720 {
1721   if ( isRemoved() )
1722     return _proxyPoint._branch->getBoundaryPoints( _proxyPoint, bp1, bp2 );
1723
1724   if ( iMAEdge > _maEdges.size() )
1725     return false;
1726   if ( iMAEdge == _maEdges.size() )
1727     iMAEdge = _maEdges.size() - 1;
1728
1729   size_t iGeom1 = getGeomEdge( _maEdges[ iMAEdge ] );
1730   size_t iGeom2 = getGeomEdge( _maEdges[ iMAEdge ]->twin() );
1731   size_t iSeg1  = getBndSegment( _maEdges[ iMAEdge ] );
1732   size_t iSeg2  = getBndSegment( _maEdges[ iMAEdge ]->twin() );
1733
1734   return ( _boundary->getPoint( iGeom1, iSeg1, maEdgeParam, bp1 ) &&
1735            _boundary->getPoint( iGeom2, iSeg2, maEdgeParam, bp2 ));
1736 }
1737
1738 //================================================================================
1739 /*!
1740  * \brief Returns points on two EDGEs, equidistant from a given point of this Branch
1741  */
1742 //================================================================================
1743
1744 bool SMESH_MAT2d::Branch::getBoundaryPoints(const BranchPoint& p,
1745                                             BoundaryPoint&     bp1,
1746                                             BoundaryPoint&     bp2 ) const
1747 {
1748   return ( p._branch ? p._branch : this )->getBoundaryPoints( p._iEdge, p._edgeParam, bp1, bp2 );
1749 }
1750
1751 //================================================================================
1752 /*!
1753  * \brief Return a parameter of a BranchPoint normalized within this Branch
1754  */
1755 //================================================================================
1756
1757 bool SMESH_MAT2d::Branch::getParameter(const BranchPoint & p, double & u ) const
1758 {
1759   if ( this != p._branch && p._branch )
1760     return p._branch->getParameter( p, u );
1761
1762   if ( isRemoved() )
1763     return _proxyPoint._branch->getParameter( _proxyPoint, u );
1764
1765   if ( p._iEdge > _params.size()-1 )
1766     return false;
1767   if ( p._iEdge == _params.size()-1 )
1768     return ( u = 1. );
1769
1770   u = ( _params[ p._iEdge   ] * ( 1 - p._edgeParam ) +
1771         _params[ p._iEdge+1 ] * p._edgeParam );
1772
1773   return true;
1774 }
1775
1776 //================================================================================
1777 /*!
1778  * \brief Check type of both ends
1779  */
1780 //================================================================================
1781
1782 bool SMESH_MAT2d::Branch::hasEndOfType(BranchEndType type) const
1783 {
1784   return ( _endPoint1._type == type || _endPoint2._type == type );
1785 }
1786
1787 //================================================================================
1788 /*!
1789  * \brief Returns MA points
1790  *  \param [out] points - the 2d points
1791  *  \param [in] scale - the scale that was used to scale the 2d space of MA
1792  */
1793 //================================================================================
1794
1795 void SMESH_MAT2d::Branch::getPoints( std::vector< gp_XY >& points,
1796                                      const double          scale[2]) const
1797 {
1798   points.resize( _maEdges.size() + 1 );
1799
1800   points[0].SetCoord( _maEdges[0]->vertex1()->x() / scale[0], // CCW order! -> vertex1 not vertex0
1801                       _maEdges[0]->vertex1()->y() / scale[1] );
1802
1803   for ( size_t i = 0; i < _maEdges.size(); ++i )
1804     points[i+1].SetCoord( _maEdges[i]->vertex0()->x() / scale[0],
1805                           _maEdges[i]->vertex0()->y() / scale[1] );
1806 }
1807
1808 //================================================================================
1809 /*!
1810  * \brief Return indices of EDGEs equidistant from this branch
1811  */
1812 //================================================================================
1813
1814 void SMESH_MAT2d::Branch::getGeomEdges( std::vector< std::size_t >& edgeIDs1,
1815                                         std::vector< std::size_t >& edgeIDs2 ) const
1816 {
1817   edgeIDs1.push_back( getGeomEdge( _maEdges[0] ));
1818   edgeIDs2.push_back( getGeomEdge( _maEdges[0]->twin() ));
1819
1820   for ( size_t i = 1; i < _maEdges.size(); ++i )
1821   {
1822     size_t ie1 = getGeomEdge( _maEdges[i] );
1823     size_t ie2 = getGeomEdge( _maEdges[i]->twin() );
1824
1825     if ( edgeIDs1.back() != ie1 ) edgeIDs1.push_back( ie1 );
1826     if ( edgeIDs2.back() != ie2 ) edgeIDs2.push_back( ie2 );
1827   }
1828 }
1829
1830 //================================================================================
1831 /*!
1832  * \brief Looks for a BranchPoint position around a concave VERTEX
1833  */
1834 //================================================================================
1835
1836 bool SMESH_MAT2d::Branch::addDivPntForConcaVertex( std::vector< std::size_t >&   edgeIDs1,
1837                                                    std::vector< std::size_t >&   edgeIDs2,
1838                                                    std::vector< BranchPoint >&   divPoints,
1839                                                    const vector<const TVDEdge*>& maEdges,
1840                                                    const vector<const TVDEdge*>& maEdgesTwin,
1841                                                    int &                         i) const
1842 {
1843   // if there is a concave vertex between EDGEs
1844   // then position of a dividing BranchPoint is undefined, it is somewhere
1845   // on an arc-shaped part of the Branch around the concave vertex.
1846   // Chose this position by a VERTEX of the opposite EDGE, or put it in the middle
1847   // of the arc if there is no opposite VERTEX.
1848   // All null-length segments around a VERTEX belong to one of EDGEs.
1849
1850   BranchPoint divisionPnt;
1851   divisionPnt._branch = this;
1852
1853   BranchIterator iCur( maEdges, i );
1854
1855   size_t ie1 = getGeomEdge( maEdges    [i] );
1856   size_t ie2 = getGeomEdge( maEdgesTwin[i] );
1857
1858   size_t iSeg1  = getBndSegment( iCur.edgePrev() );
1859   size_t iSeg2  = getBndSegment( iCur.edge() );
1860   bool isConcaPrev = _boundary->isConcaveSegment( edgeIDs1.back(), iSeg1 );
1861   bool isConcaNext = _boundary->isConcaveSegment( ie1,             iSeg2 );
1862   if ( !isConcaNext && !isConcaPrev )
1863     return false;
1864
1865   bool isConcaveV = false;
1866
1867   const TVDEdge* maE;
1868   BranchIterator iPrev( maEdges, i ), iNext( maEdges, i );
1869    --iPrev;
1870   if ( isConcaNext ) // all null-length segments follow
1871   {
1872     // look for a VERTEX of the opposite EDGE
1873     // iNext - next after all null-length segments
1874     while (( maE = ++iNext ))
1875     {
1876       iSeg2 = getBndSegment( maE );
1877       if ( !_boundary->isConcaveSegment( ie1, iSeg2 ))
1878         break;
1879     }
1880     bool vertexFound = false;
1881     for ( ++iCur; iCur < iNext; ++iCur )
1882     {
1883       ie2 = getGeomEdge( maEdgesTwin[ iCur.indexMod() ] );
1884       if ( ie2 != edgeIDs2.back() )
1885       {
1886         // opposite VERTEX found
1887         divisionPnt._iEdge = iCur.indexMod();
1888         divisionPnt._edgeParam = 0;
1889         divPoints.push_back( divisionPnt );
1890         edgeIDs1.push_back( ie1 );
1891         edgeIDs2.push_back( ie2 );
1892         vertexFound = true;
1893       }
1894     }
1895     if ( vertexFound )
1896     {
1897       --iNext;
1898       iPrev = iNext; // not to add a BP in the moddle
1899       i = iNext.indexMod();
1900       isConcaveV = true;
1901     }
1902   }
1903   else if ( isConcaPrev )
1904   {
1905     // all null-length segments passed, find their beginning
1906     while (( maE = iPrev.edgePrev() ))
1907     {
1908       iSeg1 = getBndSegment( maE );
1909       if ( _boundary->isConcaveSegment( edgeIDs1.back(), iSeg1 ))
1910         --iPrev;
1911       else
1912         break;
1913     }
1914   }
1915
1916   if ( iPrev.index() < i-1 || iNext.index() > i )
1917   {
1918     // no VERTEX on the opposite EDGE, put the Branch Point in the middle
1919     divisionPnt._iEdge = iPrev.indexMod();
1920     ++iPrev;
1921     double   par1 = _params[ iPrev.indexMod() ], par2 = _params[ iNext.indexMod() ];
1922     double midPar = 0.5 * ( par1 + par2 );
1923     for ( ; _params[ iPrev.indexMod() ] < midPar; ++iPrev )
1924       divisionPnt._iEdge = iPrev.indexMod();
1925     divisionPnt._edgeParam =
1926       ( _params[ iPrev.indexMod() ] - midPar ) /
1927       ( _params[ iPrev.indexMod() ] - _params[ divisionPnt._iEdge ] );
1928     divPoints.push_back( divisionPnt );
1929     isConcaveV = true;
1930   }
1931
1932   return isConcaveV;
1933 }
1934
1935 //================================================================================
1936 /*!
1937  * \brief Return indices of opposite parts of EDGEs equidistant from this branch
1938  *  \param [out] edgeIDs1 - EDGE index opposite to the edgeIDs2[i]-th EDGE
1939  *  \param [out] edgeIDs2 - EDGE index opposite to the edgeIDs1[i]-th EDGE
1940  *  \param [out] divPoints - BranchPoint's located between two successive unique
1941  *         pairs of EDGE indices. A \a divPoints[i] can separate e.g. two following pairs
1942  *         of EDGE indices < 0, 2 > and < 0, 1 >. Number of \a divPoints is one less
1943  *         than number of \a edgeIDs
1944  */
1945 //================================================================================
1946
1947 void SMESH_MAT2d::Branch::getOppositeGeomEdges( std::vector< std::size_t >& edgeIDs1,
1948                                                 std::vector< std::size_t >& edgeIDs2,
1949                                                 std::vector< BranchPoint >& divPoints) const
1950 {
1951   edgeIDs1.clear();
1952   edgeIDs2.clear();
1953   divPoints.clear();
1954
1955   std::vector<const TVDEdge*> twins( _maEdges.size() );
1956   for ( size_t i = 0; i < _maEdges.size(); ++i )
1957     twins[i] = _maEdges[i]->twin();
1958
1959   BranchIterator maIter ( _maEdges, 0 );
1960   BranchIterator twIter ( twins, 0 );
1961   // size_t lastConcaE1 = _boundary.nbEdges();
1962   // size_t lastConcaE2 = _boundary.nbEdges();
1963
1964   // if ( maIter._closed ) // closed branch
1965   // {
1966   //   edgeIDs1.push_back( getGeomEdge( _maEdges.back() ));
1967   //   edgeIDs2.push_back( getGeomEdge( _maEdges.back()->twin() ));
1968   // }
1969   // else
1970   {
1971     edgeIDs1.push_back( getGeomEdge( maIter.edge() ));
1972     edgeIDs2.push_back( getGeomEdge( twIter.edge() ));
1973   }
1974
1975   BranchPoint divisionPnt;
1976   divisionPnt._branch = this;
1977
1978   for ( ++maIter, ++twIter; maIter.index() < (int)_maEdges.size(); ++maIter, ++twIter )
1979   {
1980     size_t ie1 = getGeomEdge( maIter.edge() );
1981     size_t ie2 = getGeomEdge( twIter.edge() );
1982
1983     bool otherE1 = ( edgeIDs1.back() != ie1 );
1984     bool otherE2 = ( edgeIDs2.back() != ie2 );
1985
1986     if ( !otherE1 && !otherE2 && maIter._closed )
1987     {
1988       int iSegPrev1 = getBndSegment( maIter.edgePrev() );
1989       int iSegCur1  = getBndSegment( maIter.edge() );
1990       otherE1 = Abs( iSegPrev1 - iSegCur1 ) != 1;
1991       int iSegPrev2 = getBndSegment( twIter.edgePrev() );
1992       int iSegCur2  = getBndSegment( twIter.edge() );
1993       otherE2 = Abs( iSegPrev2 - iSegCur2 ) != 1;
1994     }
1995
1996     if ( otherE1 || otherE2 )
1997     {
1998       bool isConcaveV = false;
1999       if ( otherE1 && !otherE2 )
2000       {
2001         isConcaveV = addDivPntForConcaVertex( edgeIDs1, edgeIDs2, divPoints,
2002                                               _maEdges, twins, maIter._i );
2003       }
2004       if ( !otherE1 && otherE2 )
2005       {
2006         isConcaveV = addDivPntForConcaVertex( edgeIDs2, edgeIDs1, divPoints,
2007                                               twins, _maEdges, maIter._i );
2008       }
2009
2010       if ( isConcaveV )
2011       {
2012         ie1 = getGeomEdge( maIter.edge() );
2013         ie2 = getGeomEdge( twIter.edge() );
2014       }
2015       if ( !isConcaveV || otherE1 || otherE2 )
2016       {
2017         edgeIDs1.push_back( ie1 );
2018         edgeIDs2.push_back( ie2 );
2019       }
2020       if ( divPoints.size() < edgeIDs1.size() - 1 )
2021       {
2022         divisionPnt._iEdge = maIter.index();
2023         divisionPnt._edgeParam = 0;
2024         divPoints.push_back( divisionPnt );
2025       }
2026
2027     } // if ( edgeIDs1.back() != ie1 || edgeIDs2.back() != ie2 )
2028   } // loop on _maEdges
2029 }
2030
2031 //================================================================================
2032 /*!
2033  * \brief Store data of boundary segments in TVDEdge
2034  */
2035 //================================================================================
2036
2037 void SMESH_MAT2d::Branch::setGeomEdge( std::size_t geomIndex, const TVDEdge* maEdge )
2038 {
2039   if ( maEdge ) maEdge->cell()->color( geomIndex );
2040 }
2041 std::size_t SMESH_MAT2d::Branch::getGeomEdge( const TVDEdge* maEdge )
2042 {
2043   return maEdge ? maEdge->cell()->color() : std::string::npos;
2044 }
2045 void SMESH_MAT2d::Branch::setBndSegment( std::size_t segIndex, const TVDEdge* maEdge )
2046 {
2047   if ( maEdge ) maEdge->color( segIndex );
2048 }
2049 std::size_t SMESH_MAT2d::Branch::getBndSegment( const TVDEdge* maEdge )
2050 {
2051   return maEdge ? maEdge->color() : std::string::npos;
2052 }
2053
2054 //================================================================================
2055 /*!
2056  * \brief Returns a boundary point on a given EDGE
2057  *  \param [in] iEdge - index of the EDGE within MedialAxis
2058  *  \param [in] iSeg - index of a boundary segment within this Branch
2059  *  \param [in] u - [0;1] normalized param within \a iSeg-th segment
2060  *  \param [out] bp - the found BoundaryPoint
2061  *  \return bool - true if the BoundaryPoint is found
2062  */
2063 //================================================================================
2064
2065 bool SMESH_MAT2d::Boundary::getPoint( std::size_t    iEdge,
2066                                       std::size_t    iSeg,
2067                                       double         u,
2068                                       BoundaryPoint& bp ) const
2069 {
2070   if ( iEdge >= _pointsPerEdge.size() )
2071     return false;
2072   if ( iSeg+1 >= _pointsPerEdge[ iEdge ]._params.size() )
2073     return false;
2074
2075   // This method is called by Branch that can have an opposite orientation,
2076   // hence u is inverted depending on orientation coded as a sign of _maEdge index
2077   bool isReverse = ( _pointsPerEdge[ iEdge ]._maEdges[ iSeg ].second < 0 );
2078   if ( isReverse )
2079     u = 1. - u;
2080
2081   double p0 = _pointsPerEdge[ iEdge ]._params[ iSeg ];
2082   double p1 = _pointsPerEdge[ iEdge ]._params[ iSeg+1 ];
2083
2084   bp._param = p0 * ( 1. - u ) + p1 * u;
2085   bp._edgeIndex = iEdge;
2086
2087   return true;
2088 }
2089