Salome HOME
try to cope with invalid node params on edges
[modules/smesh.git] / src / SMESH / SMESH_Pattern.cxx
1 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
3 // 
4 //  This library is free software; you can redistribute it and/or 
5 //  modify it under the terms of the GNU Lesser General Public 
6 //  License as published by the Free Software Foundation; either 
7 //  version 2.1 of the License. 
8 // 
9 //  This library is distributed in the hope that it will be useful, 
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 //  Lesser General Public License for more details. 
13 // 
14 //  You should have received a copy of the GNU Lesser General Public 
15 //  License along with this library; if not, write to the Free Software 
16 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
17 // 
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19
20 // File      : SMESH_Pattern.hxx
21 // Created   : Mon Aug  2 10:30:00 2004
22 // Author    : Edward AGAPOV (eap)
23
24 using namespace std;
25
26 #include "SMESH_Pattern.hxx"
27
28 #include <BRepAdaptor_Curve.hxx>
29 #include <BRepTools.hxx>
30 #include <BRepTools_WireExplorer.hxx>
31 #include <BRep_Tool.hxx>
32 #include <Bnd_Box.hxx>
33 #include <Bnd_Box2d.hxx>
34 #include <ElSLib.hxx>
35 #include <Extrema_ExtPC.hxx>
36 #include <Extrema_GenExtPS.hxx>
37 #include <Extrema_POnSurf.hxx>
38 #include <Geom2d_Curve.hxx>
39 #include <GeomAdaptor_Surface.hxx>
40 #include <Geom_Curve.hxx>
41 #include <Geom_Surface.hxx>
42 #include <TopAbs_ShapeEnum.hxx>
43 #include <TopExp.hxx>
44 #include <TopExp_Explorer.hxx>
45 #include <TopLoc_Location.hxx>
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopoDS.hxx>
48 #include <TopoDS_Edge.hxx>
49 #include <TopoDS_Face.hxx>
50 #include <TopoDS_Iterator.hxx>
51 #include <TopoDS_Shell.hxx>
52 #include <TopoDS_Vertex.hxx>
53 #include <TopoDS_Wire.hxx>
54 #include <gp_Ax2.hxx>
55 #include <gp_Lin2d.hxx>
56 #include <gp_Pnt2d.hxx>
57 #include <gp_Trsf.hxx>
58 #include <gp_XY.hxx>
59 #include <gp_XYZ.hxx>
60
61 #include "SMDS_EdgePosition.hxx"
62 #include "SMDS_FacePosition.hxx"
63 #include "SMDS_MeshElement.hxx"
64 #include "SMDS_MeshFace.hxx"
65 #include "SMDS_MeshNode.hxx"
66 #include "SMDS_VolumeTool.hxx"
67 #include "SMESHDS_Group.hxx"
68 #include "SMESHDS_Mesh.hxx"
69 #include "SMESHDS_SubMesh.hxx"
70 #include "SMESH_Block.hxx"
71 #include "SMESH_Mesh.hxx"
72 #include "SMESH_MeshEditor.hxx"
73 #include "SMESH_subMesh.hxx"
74
75 #include "utilities.h"
76
77 using namespace std;
78
79 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
80
81 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
82
83 //=======================================================================
84 //function : SMESH_Pattern
85 //purpose  : 
86 //=======================================================================
87
88 SMESH_Pattern::SMESH_Pattern ()
89 {
90 }
91 //=======================================================================
92 //function : getInt
93 //purpose  : 
94 //=======================================================================
95
96 static inline int getInt( const char * theSring )
97 {
98   if ( *theSring < '0' || *theSring > '9' )
99     return -1;
100
101   char *ptr;
102   int val = strtol( theSring, &ptr, 10 );
103   if ( ptr == theSring ||
104       // there must not be neither '.' nor ',' nor 'E' ...
105       (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
106     return -1;
107
108   return val;
109 }
110
111 //=======================================================================
112 //function : getDouble
113 //purpose  : 
114 //=======================================================================
115
116 static inline double getDouble( const char * theSring )
117 {
118   char *ptr;
119   return strtod( theSring, &ptr );
120 }
121
122 //=======================================================================
123 //function : readLine
124 //purpose  : Put token starting positions in theFields until '\n' or '\0'
125 //           Return the number of the found tokens
126 //=======================================================================
127
128 static int readLine (list <const char*> & theFields,
129                      const char*        & theLineBeg,
130                      const bool           theClearFields )
131 {
132   if ( theClearFields )
133     theFields.clear();
134
135   //  algo:
136   /*  loop                                                       */
137   /*    switch ( symbol ) {                                      */
138   /*    case white-space:                                        */
139   /*      look for a non-space symbol;                           */
140   /*    case string-end:                                         */
141   /*    case line-end:                                           */
142   /*      exit;                                                  */
143   /*    case comment beginning:                                  */
144   /*      skip all till a line-end;                              */
145   /*    case a number                                            */
146   /*      put its position in theFields, skip till a white-space;*/
147   /*    default:                                                 */
148   /*      abort;                                                 */
149   /*  till line-end                                              */
150
151   int nbRead = 0;
152   bool stopReading = false;
153   do {
154     bool goOn = true;
155     bool isNumber = false;
156     switch ( *theLineBeg )
157     {
158     case ' ':  // white space
159     case '\t': // tab
160     case 13:   // ^M
161       break;
162
163     case '\n': // a line ends
164       stopReading = ( nbRead > 0 );
165       break;
166
167     case '!':  // comment
168       do theLineBeg++;
169       while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
170       goOn = false;
171       break;
172
173     case '\0': // file ends
174       return nbRead;
175
176     case '-': // real number
177     case '+':
178     case '.':
179       isNumber = true;
180     default: // data
181       isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
182       if ( isNumber ) {
183         theFields.push_back( theLineBeg );
184         nbRead++;
185         do theLineBeg++;
186         while (*theLineBeg != ' ' &&
187                *theLineBeg != '\n' &&
188                *theLineBeg != '\0');
189         goOn = false;
190       }
191       else
192         return 0; // incorrect file format
193     }
194
195     if ( goOn )
196       theLineBeg++;
197
198   } while ( !stopReading );
199
200   return nbRead;
201 }
202
203 //=======================================================================
204 //function : Load
205 //purpose  : Load a pattern from <theFile>
206 //=======================================================================
207
208 bool SMESH_Pattern::Load (const char* theFileContents)
209 {
210   MESSAGE("Load( file ) ");
211
212   // file structure:
213
214   // ! This is a comment
215   // NB_POINTS               ! 1 integer - the number of points in the pattern.
216   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
217   //   X2 Y2 [Z2]            ! the pattern dimention is defined by the number of coordinates
218   //   ...
219   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
220   // ! elements description goes after all
221   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
222   // ...
223
224   Clear();
225
226   const char* lineBeg = theFileContents;
227   list <const char*> fields;
228   const bool clearFields = true;
229
230   // NB_POINTS               ! 1 integer - the number of points in the pattern.
231
232   if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
233     MESSAGE("Error reading NB_POINTS");
234     return setErrorCode( ERR_READ_NB_POINTS );
235   }
236   int nbPoints = getInt( fields.front() );
237
238   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
239
240   // read the first point coordinates to define pattern dimention
241   int dim = readLine( fields, lineBeg, clearFields );
242   if ( dim == 2 )
243     myIs2D = true;
244   else if ( dim == 3 )
245     myIs2D = false;
246   else {
247     MESSAGE("Error reading points: wrong nb of coordinates");
248     return setErrorCode( ERR_READ_POINT_COORDS );
249   }
250   if ( nbPoints <= dim ) {
251     MESSAGE(" Too few points ");
252     return setErrorCode( ERR_READ_TOO_FEW_POINTS );
253   }
254     
255   // read the rest points
256   int iPoint;
257   for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
258     if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
259       MESSAGE("Error reading  points : wrong nb of coordinates ");
260       return setErrorCode( ERR_READ_POINT_COORDS );
261     }
262   // store point coordinates
263   myPoints.resize( nbPoints );
264   list <const char*>::iterator fIt = fields.begin();
265   for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
266   {
267     TPoint & p = myPoints[ iPoint ];
268     for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
269     {
270       double coord = getDouble( *fIt );
271       if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
272         MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
273         Clear();
274         return setErrorCode( ERR_READ_3D_COORD );
275       }
276       p.myInitXYZ.SetCoord( iCoord, coord );
277       if ( myIs2D )
278         p.myInitUV.SetCoord( iCoord, coord );
279     }
280   }
281
282   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
283   if ( myIs2D )
284   {
285     if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
286       MESSAGE("Error: missing key-points");
287       Clear();
288       return setErrorCode( ERR_READ_NO_KEYPOINT );
289     }
290     set<int> idSet;
291     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
292     {
293       int pointIndex = getInt( *fIt );
294       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
295         MESSAGE("Error: invalid point index " << pointIndex );
296         Clear();
297         return setErrorCode( ERR_READ_BAD_INDEX );
298       }
299       if ( idSet.insert( pointIndex ).second ) // unique?
300         myKeyPointIDs.push_back( pointIndex );
301     }
302   }
303
304   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
305
306   while ( readLine( fields, lineBeg, clearFields ))
307   {
308     myElemPointIDs.push_back( TElemDef() );
309     TElemDef& elemPoints = myElemPointIDs.back();
310     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
311     {
312       int pointIndex = getInt( *fIt );
313       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
314         MESSAGE("Error: invalid point index " << pointIndex );
315         Clear();
316         return setErrorCode( ERR_READ_BAD_INDEX );
317       }
318       elemPoints.push_back( pointIndex );
319     }
320     // check the nb of nodes in element
321     bool Ok = true;
322     switch ( elemPoints.size() ) {
323     case 3: if ( !myIs2D ) Ok = false; break;
324     case 4: break;
325     case 5:
326     case 6:
327     case 8: if ( myIs2D ) Ok = false; break;
328     default: Ok = false;
329     }
330     if ( !Ok ) {
331       MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
332       Clear();
333       return setErrorCode( ERR_READ_ELEM_POINTS );
334     }
335   }
336   if ( myElemPointIDs.empty() ) {
337     MESSAGE("Error: no elements");
338     Clear();
339     return setErrorCode( ERR_READ_NO_ELEMS );
340   }
341
342   findBoundaryPoints(); // sort key-points
343
344   return setErrorCode( ERR_OK );
345 }
346
347 //=======================================================================
348 //function : Save
349 //purpose  : Save the loaded pattern into the file <theFileName>
350 //=======================================================================
351
352 bool SMESH_Pattern::Save (ostream& theFile)
353 {
354   MESSAGE(" ::Save(file) " );
355   if ( !IsLoaded() ) {
356     MESSAGE(" Pattern not loaded ");
357     return setErrorCode( ERR_SAVE_NOT_LOADED );
358   }
359
360   theFile << "!!! SALOME Mesh Pattern file" << endl;
361   theFile << "!!!" << endl;
362   theFile << "!!! Nb of points:" << endl;
363   theFile << myPoints.size() << endl;
364
365   // point coordinates
366   const int width = 8;
367 //  theFile.width( 8 );
368 //  theFile.setf(ios::fixed);// use 123.45 floating notation
369 //  theFile.setf(ios::right);
370 //  theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
371 //   theFile.setf(ios::showpoint); // do not show trailing zeros
372   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
373   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
374     const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
375     theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
376     if ( !myIs2D ) theFile  << " " << setw( width ) << xyz.Z();
377     theFile  << "  !- " << i << endl; // point id to ease reading by a human being
378   }
379   // key-points
380   if ( myIs2D ) {
381     theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
382     list< int >::const_iterator kpIt = myKeyPointIDs.begin();
383     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
384       theFile << " " << *kpIt;
385     if ( !myKeyPointIDs.empty() )
386       theFile << endl;
387   }
388   // elements
389   theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
390   list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
391   for ( ; epIt != myElemPointIDs.end(); epIt++ )
392   {
393     const TElemDef & elemPoints = *epIt;
394     TElemDef::const_iterator iIt = elemPoints.begin();
395     for ( ; iIt != elemPoints.end(); iIt++ )
396       theFile << " " << *iIt;
397     theFile << endl;
398   }
399
400   theFile << endl;
401   
402   return setErrorCode( ERR_OK );
403 }
404
405 //=======================================================================
406 //function : sortBySize
407 //purpose  : sort theListOfList by size
408 //=======================================================================
409
410 template<typename T> struct TSizeCmp {
411   bool operator ()( const list < T > & l1, const list < T > & l2 )
412     const { return l1.size() < l2.size(); }
413 };
414
415 template<typename T> void sortBySize( list< list < T > > & theListOfList )
416 {
417   if ( theListOfList.size() > 2 ) {
418     TSizeCmp< T > SizeCmp;
419     theListOfList.sort( SizeCmp );
420   }
421 }
422
423 //=======================================================================
424 //function : project
425 //purpose  : 
426 //=======================================================================
427
428 static gp_XY project (const SMDS_MeshNode* theNode,
429                       Extrema_GenExtPS &   theProjectorPS)
430 {
431   gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
432   theProjectorPS.Perform( P );
433   if ( !theProjectorPS.IsDone() ) {
434     MESSAGE( "SMESH_Pattern: point projection FAILED");
435     return gp_XY(0.,0.);
436   }
437   double u, v, minVal = DBL_MAX;
438   for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
439     if ( theProjectorPS.Value( i ) < minVal ) {
440       minVal = theProjectorPS.Value( i );
441       theProjectorPS.Point( i ).Parameter( u, v );
442     }
443   return gp_XY( u, v );
444 }
445
446 //=======================================================================
447 //function : areNodesBound
448 //purpose  : true if all nodes of faces are bound to shapes
449 //=======================================================================
450
451 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
452 {
453   while ( faceItr->more() )
454   {
455     SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
456     while ( nIt->more() )
457     {
458       const SMDS_MeshNode* node = smdsNode( nIt->next() );
459       SMDS_PositionPtr pos = node->GetPosition();
460       if ( !pos || !pos->GetShapeId() ) {
461         return false;
462       }
463     }
464   }
465   return true;
466 }
467
468 //=======================================================================
469 //function : isMeshBoundToShape
470 //purpose  : return true if all 2d elements are bound to shape
471 //           if aFaceSubmesh != NULL, then check faces bound to it
472 //           else check all faces in aMeshDS
473 //=======================================================================
474
475 static bool isMeshBoundToShape(SMESHDS_Mesh *     aMeshDS,
476                                SMESHDS_SubMesh *  aFaceSubmesh,
477                                const bool         isMainShape)
478 {
479   if ( isMainShape ) {
480     // check that all faces are bound to aFaceSubmesh
481     if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
482       return false;
483   }
484
485   // check face nodes binding
486   if ( aFaceSubmesh ) {
487     SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
488     return areNodesBound( fIt );
489   }
490   SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
491   return areNodesBound( fIt );
492 }
493
494 //=======================================================================
495 //function : Load
496 //purpose  : Create a pattern from the mesh built on <theFace>.
497 //           <theProject>==true makes override nodes positions
498 //           on <theFace> computed by mesher
499 //=======================================================================
500
501 bool SMESH_Pattern::Load (SMESH_Mesh*        theMesh,
502                           const TopoDS_Face& theFace,
503                           bool               theProject)
504 {
505   MESSAGE(" ::Load(face) " );
506   Clear();
507   myIs2D = true;
508
509   SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
510   SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
511   SMESH_MesherHelper helper( *theMesh );
512   helper.SetSubShape( theFace );
513
514   int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
515   int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
516   if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
517   {
518     MESSAGE( "No elements bound to the face");
519     return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
520   }
521
522   TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
523
524   // check that face is not closed
525   bool isClosed = helper.HasSeam();
526   TopoDS_Vertex bidon;
527   list<TopoDS_Edge> eList;
528   list<TopoDS_Edge>::iterator elIt;
529   SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
530
531   // check that requested or needed projection is possible
532   bool isMainShape = theMesh->IsMainShape( face );
533   bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
534   bool canProject  = ( nbElems ? true : isMainShape );
535   if ( isClosed )
536     canProject = false; // so far
537
538   if ( ( theProject || needProject ) && !canProject )
539     return setErrorCode( ERR_LOADF_CANT_PROJECT );
540
541   Extrema_GenExtPS projector;
542   GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
543   if ( theProject || needProject )
544     projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
545
546   int iPoint = 0;
547   TNodePointIDMap nodePointIDMap;
548   TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
549
550   if ( needProject )
551   {
552     MESSAGE("Project the submesh");
553     // ---------------------------------------------------------------
554     // The case where the submesh is projected to theFace
555     // ---------------------------------------------------------------
556
557     // get all faces
558     list< const SMDS_MeshElement* > faces;
559     if ( nbElems > 0 ) {
560       SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
561       while ( fIt->more() ) {
562         const SMDS_MeshElement* f = fIt->next();
563         if ( f && f->GetType() == SMDSAbs_Face )
564           faces.push_back( f );
565       }
566     }
567     else {
568       SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
569       while ( fIt->more() )
570         faces.push_back( fIt->next() );
571     }
572
573     // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
574     list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
575     for ( ; fIt != faces.end(); ++fIt )
576     {
577       myElemPointIDs.push_back( TElemDef() );
578       TElemDef& elemPoints = myElemPointIDs.back();
579       SMDS_ElemIteratorPtr nIt = (*fIt)->nodesIterator();
580       while ( nIt->more() )
581       {
582         const SMDS_MeshElement* node = nIt->next();
583         TNodePointIDMap::iterator nIdIt = nodePointIDMap.find( node );
584         if ( nIdIt == nodePointIDMap.end() )
585         {
586           elemPoints.push_back( iPoint );
587           nodePointIDMap.insert( make_pair( node, iPoint++ ));
588         }
589         else
590           elemPoints.push_back( (*nIdIt).second );
591       }
592     }
593     myPoints.resize( iPoint );
594
595     // project all nodes of 2d elements to theFace
596     TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
597     for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
598     {
599       const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
600       TPoint * p = & myPoints[ (*nIdIt).second ];
601       p->myInitUV = project( node, projector );
602       p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
603     }
604     // find key-points: the points most close to UV of vertices
605     TopExp_Explorer vExp( face, TopAbs_VERTEX );
606     set<int> foundIndices;
607     for ( ; vExp.More(); vExp.Next() ) {
608       const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
609       gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
610       double minDist = DBL_MAX;
611       int index;
612       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
613       for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
614         double dist = uv.SquareDistance( (*pVecIt).myInitUV );
615         if ( dist < minDist ) {
616           minDist = dist;
617           index = iPoint;
618         }
619       }
620       if ( foundIndices.insert( index ).second ) // unique?
621         myKeyPointIDs.push_back( index );
622     }
623     myIsBoundaryPointsFound = false;
624
625   }
626   else
627   {
628     // ---------------------------------------------------------------------
629     // The case where a pattern is being made from the mesh built by mesher
630     // ---------------------------------------------------------------------
631
632     // Load shapes in the consequent order and count nb of points
633
634     // vertices
635     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
636       myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
637       if ( BRep_Tool::IsClosed( *elIt, theFace ) )
638         myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));
639       SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt );
640       if ( eSubMesh )
641         nbNodes += eSubMesh->NbNodes() + 1;
642     }
643     // edges
644     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
645       myShapeIDMap.Add( *elIt );
646     // the face
647     myShapeIDMap.Add( face );
648
649     myPoints.resize( nbNodes );
650
651     // Load U of points on edges
652
653     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
654     {
655       TopoDS_Edge & edge = *elIt;
656       list< TPoint* > & ePoints = getShapePoints( edge );
657       double f, l;
658       Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
659       bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
660
661       TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
662       TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
663       // to make adjacent edges share key-point, we make v2 FORWARD too
664       // (as we have different points for same shape with different orienation)
665       v2.Reverse();
666
667       // on closed face we must have REVERSED some of seam vertices
668       bool isSeam = helper.IsSeamShape( edge );
669       if ( isClosed ) {
670         if ( isSeam ) { // reverse on reversed SEAM edge
671           if ( !isForward ) {
672             v1.Reverse();
673             v2.Reverse();
674           }
675         }
676         else { // on CLOSED edge
677           for ( int is2 = 0; is2 < 2; ++is2 ) {
678             TopoDS_Shape & v = is2 ? v2 : v1;
679             if ( helper.IsSeamShape( v ) ) {
680               // reverse or not depending on orientation of adjacent seam
681               TopoDS_Edge seam;
682               list<TopoDS_Edge>::iterator eIt2 = elIt;
683               if ( is2 )
684                 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
685               else
686                 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
687               if ( seam.Orientation() == TopAbs_REVERSED )
688                 v.Reverse();
689             }
690           }
691         }
692       }
693
694       // the forward key-point
695       list< TPoint* > * vPoint = & getShapePoints( v1 );
696       if ( vPoint->empty() )
697       {
698         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
699         if ( vSubMesh && vSubMesh->NbNodes() ) {
700           myKeyPointIDs.push_back( iPoint );
701           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
702           const SMDS_MeshNode* node = nIt->next();
703           if ( v1.Orientation() == TopAbs_REVERSED )
704             closeNodePointIDMap.insert( make_pair( node, iPoint ));
705           else
706             nodePointIDMap.insert( make_pair( node, iPoint ));
707
708           TPoint* keyPoint = &myPoints[ iPoint++ ];
709           vPoint->push_back( keyPoint );
710           if ( theProject )
711             keyPoint->myInitUV = project( node, projector );
712           else
713             keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
714           keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
715         }
716       }
717       if ( !vPoint->empty() )
718         ePoints.push_back( vPoint->front() );
719
720       // on-edge points
721       SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
722       if ( eSubMesh && eSubMesh->NbNodes() )
723       {
724         // loop on nodes of an edge: sort them by param on edge
725         typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
726         TParamNodeMap paramNodeMap;
727         SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
728         while ( nIt->more() )
729         {
730           const SMDS_MeshNode* node = smdsNode( nIt->next() );
731           const SMDS_EdgePosition* epos =
732             static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
733           double u = epos->GetUParameter();
734           paramNodeMap.insert( make_pair( u, node ));
735         }
736         if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
737           // wrong U on edge, project
738           Extrema_ExtPC proj;
739           BRepAdaptor_Curve aCurve( edge );
740           proj.Initialize( aCurve, f, l );
741           paramNodeMap.clear();
742           nIt = eSubMesh->GetNodes();
743           for ( int iNode = 0; nIt->more(); ++iNode ) {
744             const SMDS_MeshNode* node = smdsNode( nIt->next() );
745             proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
746             double u = 0;
747             if ( proj.IsDone() ) {
748               for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
749                 if ( proj.IsMin( i )) {
750                   u = proj.Point( i ).Parameter();
751                   break;
752                 }
753             } else {
754               u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
755             }
756             paramNodeMap.insert( make_pair( u, node ));
757           }
758         }
759         // put U in [0,1] so that the first key-point has U==0
760         double du = l - f;
761         TParamNodeMap::iterator         unIt  = paramNodeMap.begin();
762         TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
763         while ( unIt != paramNodeMap.end() )
764         {
765           TPoint* p = & myPoints[ iPoint ];
766           ePoints.push_back( p );
767           const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
768           if ( isSeam && !isForward )
769             closeNodePointIDMap.insert( make_pair( node, iPoint ));
770           else
771             nodePointIDMap.insert ( make_pair( node, iPoint ));
772
773           if ( theProject )
774             p->myInitUV = project( node, projector );
775           else {
776             double u = isForward ? (*unIt).first : (*unRIt).first;
777             p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
778             p->myInitUV = C2d->Value( u ).XY();
779           }
780           p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
781           unIt++; unRIt++;
782           iPoint++;
783         }
784       }
785       // the reverse key-point
786       vPoint = & getShapePoints( v2 );
787       if ( vPoint->empty() )
788       {
789         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
790         if ( vSubMesh && vSubMesh->NbNodes() ) {
791           myKeyPointIDs.push_back( iPoint );
792           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
793           const SMDS_MeshNode* node = nIt->next();
794           if ( v2.Orientation() == TopAbs_REVERSED )
795             closeNodePointIDMap.insert( make_pair( node, iPoint ));
796           else
797             nodePointIDMap.insert( make_pair( node, iPoint ));
798
799           TPoint* keyPoint = &myPoints[ iPoint++ ];
800           vPoint->push_back( keyPoint );
801           if ( theProject )
802             keyPoint->myInitUV = project( node, projector );
803           else
804             keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
805           keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
806         }
807       }
808       if ( !vPoint->empty() )
809         ePoints.push_back( vPoint->front() );
810
811       // compute U of edge-points
812       if ( theProject )
813       {
814         double totalDist = 0;
815         list< TPoint* >::iterator pIt = ePoints.begin();
816         TPoint* prevP = *pIt;
817         prevP->myInitU = totalDist;
818         for ( pIt++; pIt != ePoints.end(); pIt++ ) {
819           TPoint* p = *pIt;
820           totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
821           p->myInitU = totalDist;
822           prevP = p;
823         }
824         if ( totalDist > DBL_MIN)
825           for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
826             TPoint* p = *pIt;
827             p->myInitU /= totalDist;
828           }
829       }
830     } // loop on edges of a wire
831
832     // Load in-face points and elements
833
834     if ( fSubMesh && fSubMesh->NbElements() )
835     {
836       list< TPoint* > & fPoints = getShapePoints( face );
837       SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
838       while ( nIt->more() )
839       {
840         const SMDS_MeshNode* node = smdsNode( nIt->next() );
841         nodePointIDMap.insert( make_pair( node, iPoint ));
842         TPoint* p = &myPoints[ iPoint++ ];
843         fPoints.push_back( p );
844         if ( theProject )
845           p->myInitUV = project( node, projector );
846         else {
847           const SMDS_FacePosition* pos =
848             static_cast<const SMDS_FacePosition*>(node->GetPosition().get());
849           p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
850         }
851         p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
852       }
853       // load elements
854       SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
855       while ( elemIt->more() )
856       {
857         const SMDS_MeshElement* elem = elemIt->next();
858         SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
859         myElemPointIDs.push_back( TElemDef() );
860         TElemDef& elemPoints = myElemPointIDs.back();
861         // find point indices corresponding to element nodes
862         while ( nIt->more() )
863         {
864           const SMDS_MeshNode* node = smdsNode( nIt->next() );
865           iPoint = nodePointIDMap[ node ]; // point index of interest
866           // for a node on a seam edge there are two points
867           TNodePointIDMap::iterator n_id = closeNodePointIDMap.end();
868           if ( helper.IsSeamShape( node->GetPosition()->GetShapeId() ))
869             n_id = closeNodePointIDMap.find( node );
870           if ( n_id != closeNodePointIDMap.end() )
871           {
872             TPoint & p1 = myPoints[ iPoint ];
873             TPoint & p2 = myPoints[ n_id->second ];
874             // Select point closest to the rest nodes of element in UV space
875             SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
876             const SMDS_MeshNode* notSeamNode = 0;
877             // find node not on a seam edge
878             while ( nIt2->more() && !notSeamNode ) {
879               const SMDS_MeshNode* n = smdsNode( nIt2->next() );
880               if ( !helper.IsSeamShape( n->GetPosition()->GetShapeId() ))
881                 notSeamNode = n;
882             }
883             gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
884             double dist1 = uv.SquareDistance( p1.myInitUV );
885             double dist2 = uv.SquareDistance( p2.myInitUV );
886             if ( dist2 < dist1 )
887               iPoint = n_id->second;
888           }
889           elemPoints.push_back( iPoint );
890         }
891       }
892     }
893
894     myIsBoundaryPointsFound = true;
895   }
896
897   // Assure that U range is proportional to V range
898
899   Bnd_Box2d bndBox;
900   vector< TPoint >::iterator pVecIt = myPoints.begin();
901   for ( ; pVecIt != myPoints.end(); pVecIt++ )
902     bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
903   double minU, minV, maxU, maxV;
904   bndBox.Get( minU, minV, maxU, maxV );
905   double dU = maxU - minU, dV = maxV - minV;
906   if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
907     Clear();
908     bndBox.SetVoid();
909     // define where is the problem, in the face or in the mesh
910     TopExp_Explorer vExp( face, TopAbs_VERTEX );
911     for ( ; vExp.More(); vExp.Next() ) {
912       gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
913       bndBox.Add( uv );
914     }
915     bndBox.Get( minU, minV, maxU, maxV );
916     dU = maxU - minU, dV = maxV - minV;
917     if ( dU <= DBL_MIN || dV <= DBL_MIN )
918       // face problem
919       return setErrorCode( ERR_LOADF_NARROW_FACE );
920     else
921       // mesh is projected onto a line, e.g.
922       return setErrorCode( ERR_LOADF_CANT_PROJECT );
923   }
924   double ratio = dU / dV, maxratio = 3, scale;
925   int iCoord = 0;
926   if ( ratio > maxratio ) {
927     scale = ratio / maxratio;
928     iCoord = 2;
929   }
930   else if ( ratio < 1./maxratio ) {
931     scale = maxratio / ratio;
932     iCoord = 1;
933   }
934   if ( iCoord ) {
935     SCRUTE( scale );
936     for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
937       TPoint & p = *pVecIt;
938       p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
939       p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
940     }
941   }
942   if ( myElemPointIDs.empty() ) {
943     MESSAGE( "No elements bound to the face");
944     return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
945   }
946
947   return setErrorCode( ERR_OK );
948 }
949
950 //=======================================================================
951 //function : computeUVOnEdge
952 //purpose  : compute coordinates of points on theEdge
953 //=======================================================================
954
955 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge&      theEdge,
956                                      const list< TPoint* > & ePoints )
957 {
958   bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
959   double f, l;
960   Handle(Geom2d_Curve) C2d =
961     BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
962
963   ePoints.back()->myInitU = 1.0;
964   list< TPoint* >::const_iterator pIt = ePoints.begin();
965   for ( pIt++; pIt != ePoints.end(); pIt++ )
966   {
967     TPoint* point = *pIt;
968     // U
969     double du = ( isForward ? point->myInitU : 1 - point->myInitU );
970     point->myU = ( f * ( 1 - du ) + l * du );
971     // UV
972     point->myUV = C2d->Value( point->myU ).XY();
973   }
974 }
975
976 //=======================================================================
977 //function : intersectIsolines
978 //purpose  : 
979 //=======================================================================
980
981 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
982                               const gp_XY& uv21, const gp_XY& uv22, const double r2,
983                               gp_XY& resUV,
984                               bool& isDeformed)
985 {
986   gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
987   gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
988   resUV = 0.5 * ( loc1 + loc2 );
989   //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
990   // SKL 26.07.2007 for NPAL16567
991   double d1 = (uv11-uv12).Modulus();
992   double d2 = (uv21-uv22).Modulus();
993   // double delta = d1*d2*1e-6; PAL17233
994   double delta = min( d1, d2 ) / 10.;
995   isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
996
997 //   double len1 = ( uv11 - uv12 ).Modulus();
998 //   double len2 = ( uv21 - uv22 ).Modulus();
999 //   resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1000 //  return true;
1001
1002   
1003 //   gp_Lin2d line1( uv11, uv12 - uv11 );
1004 //   gp_Lin2d line2( uv21, uv22 - uv21 );
1005 //   double angle = Abs( line1.Angle( line2 ) );
1006
1007 //     IntAna2d_AnaIntersection inter;
1008 //     inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1009 //     if ( inter.IsDone() && inter.NbPoints() == 1 )
1010 //     {
1011 //       gp_Pnt2d interUV = inter.Point(1).Value();
1012 //       resUV += interUV.XY();
1013 //   inter.Perform( line1, line2 );
1014 //   interUV = inter.Point(1).Value();
1015 //   resUV += interUV.XY();
1016   
1017 //   resUV /= 2.;
1018 //     }
1019   if ( isDeformed ) {
1020     MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1021             ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1022   }
1023   return true;
1024 }
1025
1026 //=======================================================================
1027 //function : compUVByIsoIntersection
1028 //purpose  : 
1029 //=======================================================================
1030
1031 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1032                                              const gp_XY&                   theInitUV,
1033                                              gp_XY&                         theUV,
1034                                              bool &                         theIsDeformed )
1035 {
1036   // compute UV by intersection of 2 iso lines
1037   //gp_Lin2d isoLine[2];
1038   gp_XY uv1[2], uv2[2];
1039   double ratio[2];
1040   const double zero = DBL_MIN;
1041   for ( int iIso = 0; iIso < 2; iIso++ )
1042   {
1043     // to build an iso line:
1044     // find 2 pairs of consequent edge-points such that the range of their
1045     // initial parameters encloses the in-face point initial parameter
1046     gp_XY UV[2], initUV[2];
1047     int nbUV = 0, iCoord = iIso + 1;
1048     double initParam = theInitUV.Coord( iCoord );
1049
1050     list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1051     for ( ; bndIt != theBndPoints.end(); bndIt++ )
1052     {
1053       const list< TPoint* > & bndPoints = * bndIt;
1054       TPoint* prevP = bndPoints.back(); // this is the first point
1055       list< TPoint* >::const_iterator pIt = bndPoints.begin();
1056       bool coincPrev = false; 
1057       // loop on the edge-points
1058       for ( ; pIt != bndPoints.end(); pIt++ )
1059       {
1060         double paramDiff     = initParam - (*pIt)->myInitUV.Coord( iCoord );
1061         double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1062         double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1063         if (!coincPrev && // ignore if initParam coincides with prev point param
1064             sumOfDiff > zero && // ignore if both points coincide with initParam
1065             prevParamDiff * paramDiff <= zero )
1066         {
1067           // find UV in parametric space of theFace
1068           double r = Abs(prevParamDiff) / sumOfDiff;
1069           gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1070           int i = nbUV++;
1071           if ( i >= 2 ) {
1072             // throw away uv most distant from <theInitUV>
1073             gp_XY vec0 = initUV[0] - theInitUV;
1074             gp_XY vec1 = initUV[1] - theInitUV;
1075             gp_XY vec  = uvInit    - theInitUV;
1076             bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1077             double dist0 = vec0.SquareModulus();
1078             double dist1 = vec1.SquareModulus();
1079             double dist  = vec .SquareModulus();
1080             if ( !isBetween || dist < dist0 || dist < dist1 ) {
1081               i = ( dist0 < dist1 ? 1 : 0 );
1082               if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1083                 i = 3; // theInitUV must remain between
1084             }
1085           }
1086           if ( i < 2 ) {
1087             initUV[ i ] = uvInit;
1088             UV[ i ]     = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1089           }
1090           coincPrev = ( Abs(paramDiff) <= zero );
1091         }
1092         else
1093           coincPrev = false;
1094         prevP = *pIt;
1095       }
1096     }
1097     if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1098       MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1099               ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1100       return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1101     }
1102     // an iso line should be normal to UV[0] - UV[1] direction
1103     // and be located at the same relative distance as from initial ends
1104     //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1105     double r =
1106       (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1107     //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1108     //isoLine[ iIso ] = iso.Normal( isoLoc );
1109     uv1[ iIso ] = UV[0];
1110     uv2[ iIso ] = UV[1];
1111     ratio[ iIso ] = r;
1112   }
1113   if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1114                           uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1115     MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1116     return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1117   }
1118
1119   return true;
1120 }
1121
1122
1123 // ==========================================================
1124 // structure representing a node of a grid of iso-poly-lines
1125 // ==========================================================
1126
1127 struct TIsoNode {
1128   bool   myIsMovable;
1129   gp_XY  myInitUV;
1130   gp_XY  myUV;
1131   double myRatio[2];
1132   gp_Dir2d  myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1133   TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1134   TIsoNode* myBndNodes[4];     // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1135   TIsoNode(double initU, double initV):
1136     myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1137   { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1138   bool IsUVComputed() const
1139   { return myUV.X() != 1e100; }
1140   bool IsMovable() const
1141   { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1142   void SetNotMovable()
1143   { myIsMovable = false; }
1144   void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1145   { myBndNodes[ iDir + i * 2 ] = node; }
1146   TIsoNode* GetBoundaryNode(int iDir, int i)
1147   { return myBndNodes[ iDir + i * 2 ]; }
1148   void SetNext(TIsoNode* node, int iDir, int isForward)
1149   { myNext[ iDir + isForward  * 2 ] = node; }
1150   TIsoNode* GetNext(int iDir, int isForward)
1151   { return myNext[ iDir + isForward * 2 ]; }
1152 };
1153
1154 //=======================================================================
1155 //function : getNextNode
1156 //purpose  : 
1157 //=======================================================================
1158
1159 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1160 {
1161   TIsoNode* n = node->myNext[ dir ];
1162   if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1163     n = 0;//node->myBndNodes[ dir ];
1164 //     MESSAGE("getNextNode: use bnd for node "<<
1165 //             node->myInitUV.X()<<" "<<node->myInitUV.Y());
1166   }
1167   return n;
1168 }
1169 //=======================================================================
1170 //function : checkQuads
1171 //purpose  : check if newUV destortes quadrangles around node,
1172 //           and if ( crit == FIX_OLD ) fix newUV in this case
1173 //=======================================================================
1174
1175 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1176
1177 static bool checkQuads (const TIsoNode* node,
1178                         gp_XY&          newUV,
1179                         const bool      reversed,
1180                         const int       crit = FIX_OLD,
1181                         double          fixSize = 0.)
1182 {
1183   gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1184   int nbOldFix = 0, nbOldImpr = 0;
1185   double newBadRate = 0, oldBadRate = 0;
1186   bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1187   int i, dir1 = 0, dir2 = 3;
1188   for ( ; dir1 < 4; dir1++, dir2++ )  // loop on 4 quadrangles around <node>
1189   {
1190     if ( dir2 > 3 ) dir2 = 0;
1191     TIsoNode* n[3];
1192     // walking counterclockwise around a quad,
1193     // nodes are in the order: node, n[0], n[1], n[2]
1194     n[0] = getNextNode( node, dir1 );
1195     n[2] = getNextNode( node, dir2 );
1196     if ( !n[0] || !n[2] ) continue;
1197     n[1] = getNextNode( n[0], dir2 );
1198     if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1199     bool isTriangle = ( !n[1] );
1200     if ( reversed ) {
1201       TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1202     }
1203 //     if ( fixSize != 0 ) {
1204 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1205 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1206 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1207 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1208 // }
1209     // check if a quadrangle is degenerated
1210     if ( !isTriangle &&
1211         ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1212          (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1213       isTriangle = true;
1214     if ( isTriangle &&
1215         ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1216       continue;
1217
1218     // find min size of the diagonal node-n[1]
1219     double minDiag = fixSize;
1220     if ( minDiag == 0. ) {
1221       double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1222       if ( !isTriangle ) {
1223         maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1224         maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1225       }
1226       maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1227       minDiag = sqrt( maxLen2 ) * PI / 60.; // ~ maxLen * Sin( 3 deg )
1228     }
1229
1230     // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1231     // ( behind means "to the right of")
1232     // it is OK if
1233     // 1. newUV is not behind 01 and 12 dirs
1234     // 2. or newUV is not behind 02 dir and n[2] is convex
1235     bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1236     bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1237     gp_Vec2d moveVec[3], outVec[3];
1238     for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1239     {
1240       bool isDiag = ( i == 2 );
1241       if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1242         break;
1243       gp_Vec2d sideDir;
1244       if ( isDiag )
1245         sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1246       else
1247         sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1248
1249       gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1250       outDir.Normalize();
1251       gp_Vec2d newDir( n[i]->myUV, newUV );
1252       gp_Vec2d oldDir( n[i]->myUV, oldUV );
1253       outVec[i] = outDir;
1254       if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1255       if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1256       if ( crit == FIX_OLD ) {
1257         wasIn[i] = ( outDir * oldDir < 0 );
1258         wasOk[i] = ( outDir * oldDir < -minDiag );
1259         if ( !newOk[i] )
1260           newBadRate += outDir * newDir;
1261         if ( !wasOk[i] )
1262           oldBadRate += outDir * oldDir;
1263         // push node inside
1264         if ( !wasOk[i] ) {
1265           double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1266           //               double r = ( l1 - minDiag ) / ( l1 + l2 );
1267           //               moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1268           moveVec[i] = ( oldDist - minDiag ) * outDir;
1269         }
1270       }
1271     }
1272
1273     // check if n[2] is convex
1274     bool convex = true;
1275     if ( !isTriangle )
1276       convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1277
1278     bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1279     bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1280     newIsOk = ( newIsOk && isNewOk );
1281     newIsIn = ( newIsIn && isNewIn );
1282
1283     if ( crit != FIX_OLD ) {
1284       if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1285       if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1286       continue;
1287     }
1288
1289     bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1290     bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1291     oldIsIn = ( oldIsIn && isOldIn );
1292     oldIsOk = ( oldIsOk && isOldIn );
1293
1294
1295     if ( !isOldIn ) { // node is outside a quadrangle
1296       // move newUV inside a quadrangle
1297 //MESSAGE("Quad "<< dir1 << "  WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1298       // node and newUV are outside: push newUV inside
1299       gp_XY uv;
1300       if ( convex || isTriangle ) {
1301         uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1302       }
1303       else {
1304         gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1305         double outSize = out.Magnitude();
1306         if ( outSize > DBL_MIN )
1307           out /= outSize;
1308         else
1309           out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1310         uv = n[1]->myUV - minDiag * out.XY();
1311       }
1312       oldUVFixed[ nbOldFix++ ] = uv;
1313       //node->myUV = newUV;
1314     }
1315     else if ( !isOldOk )  {
1316       // try to fix old UV: move node inside as less as possible
1317 //MESSAGE("Quad "<< dir1 << "  old is BAD, try to fix old, minDiag: "<< minDiag);
1318       gp_XY uv1, uv2 = node->myUV;
1319       for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1320         if ( wasOk[i] )
1321           moveVec[ i ].SetCoord( 1, 2e100); // not use this vector 
1322       while ( !isOldOk ) {
1323         // find the least moveVec
1324         int i, iMin = 4;
1325         double minMove2 = 1e100;
1326         for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1327         {
1328           if ( moveVec[i].Coord(1) < 1e100 ) {
1329             double move2 = moveVec[i].SquareMagnitude();
1330             if ( move2 < minMove2 ) {
1331               minMove2 = move2;
1332               iMin = i;
1333             }
1334           }
1335         }
1336         if ( iMin == 4 ) {
1337           break;
1338         }
1339         // move node to newUV
1340         uv1 = node->myUV + moveVec[ iMin ].XY();
1341         uv2 += moveVec[ iMin ].XY();
1342         moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1343         // check if uv1 is ok
1344         for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1345           wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1346         isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1347         if ( isOldOk )
1348           oldUVImpr[ nbOldImpr++ ] = uv1;
1349         else {
1350           // check if uv2 is ok
1351           for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1352             wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1353           isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1354           if ( isOldOk )
1355             oldUVImpr[ nbOldImpr++ ] = uv2;
1356         }
1357       }
1358     }
1359
1360   } // loop on 4 quadrangles around <node>
1361
1362   if ( crit == CHECK_NEW_OK  )
1363     return newIsOk;
1364   if ( crit == CHECK_NEW_IN  )
1365     return newIsIn;
1366
1367   if ( newIsOk )
1368     return true;
1369
1370   if ( oldIsOk )
1371     newUV = oldUV;
1372   else {
1373     if ( oldIsIn && nbOldImpr ) {
1374 //       MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1375 //               " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1376       gp_XY uv = oldUVImpr[ 0 ];
1377       for ( int i = 1; i < nbOldImpr; i++ )
1378         uv += oldUVImpr[ i ];
1379       uv /= nbOldImpr;
1380       if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1381         newUV = uv;
1382         return false;
1383       }
1384       else {
1385         //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1386       }
1387     }
1388     if ( !oldIsIn && nbOldFix ) {
1389 //       MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1390 //               " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1391       gp_XY uv = oldUVFixed[ 0 ];
1392       for ( int i = 1; i < nbOldFix; i++ )
1393         uv += oldUVFixed[ i ];
1394       uv /= nbOldFix;
1395       if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1396         newUV = uv;
1397         return false;
1398       }
1399       else {
1400         //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1401       }
1402     }
1403     if ( newIsIn && oldIsIn )
1404       newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1405     else if ( !newIsIn )
1406       newUV = oldUV;
1407   }
1408
1409   return false;
1410 }
1411
1412 //=======================================================================
1413 //function : compUVByElasticIsolines
1414 //purpose  : compute UV as nodes of iso-poly-lines consisting of
1415 //           segments keeping relative size as in the pattern
1416 //=======================================================================
1417 //#define DEB_COMPUVBYELASTICISOLINES
1418 bool SMESH_Pattern::
1419   compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1420                           const list< TPoint* >&         thePntToCompute)
1421 {
1422   return false; // PAL17233
1423 //cout << "============================== KEY POINTS =============================="<<endl;
1424 //   list< int >::iterator kpIt = myKeyPointIDs.begin();
1425 //   for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1426 //     TPoint& p = myPoints[ *kpIt ];
1427 //     cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1428 //       " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1429 //  }
1430 //cout << "=============================="<<endl;
1431
1432   // Define parameters of iso-grid nodes in U and V dir
1433
1434   set< double > paramSet[ 2 ];
1435   list< list< TPoint* > >::const_iterator pListIt;
1436   list< TPoint* >::const_iterator pIt;
1437   for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1438     const list< TPoint* > & pList = * pListIt;
1439     for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1440       paramSet[0].insert( (*pIt)->myInitUV.X() );
1441       paramSet[1].insert( (*pIt)->myInitUV.Y() );
1442     }
1443   }
1444   for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1445     paramSet[0].insert( (*pIt)->myInitUV.X() );
1446     paramSet[1].insert( (*pIt)->myInitUV.Y() );
1447   }
1448   // unite close parameters and split too long segments
1449   int iDir;
1450   double tol[ 2 ];
1451   for ( iDir = 0; iDir < 2; iDir++ )
1452   {
1453     set< double > & params = paramSet[ iDir ];
1454     double range = ( *params.rbegin() - *params.begin() );
1455     double toler = range / 1e6;
1456     tol[ iDir ] = toler;
1457 //    double maxSegment = range / params.size() / 2.;
1458 //
1459 //     set< double >::iterator parIt = params.begin();
1460 //     double prevPar = *parIt;
1461 //     for ( parIt++; parIt != params.end(); parIt++ )
1462 //     {
1463 //       double segLen = (*parIt) - prevPar;
1464 //       if ( segLen < toler )
1465 //         ;//params.erase( prevPar ); // unite
1466 //       else if ( segLen > maxSegment )
1467 //         params.insert( prevPar + 0.5 * segLen ); // split
1468 //       prevPar = (*parIt);
1469 //     }
1470   }
1471
1472   // Make nodes of a grid of iso-poly-lines
1473
1474   list < TIsoNode > nodes;
1475   typedef list < TIsoNode *> TIsoLine;
1476   map < double, TIsoLine > isoMap[ 2 ];
1477
1478   set< double > & params0 = paramSet[ 0 ];
1479   set< double >::iterator par0It = params0.begin();
1480   for ( ; par0It != params0.end(); par0It++ )
1481   {
1482     TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1483     set< double > & params1 = paramSet[ 1 ];
1484     set< double >::iterator par1It = params1.begin();
1485     for ( ; par1It != params1.end(); par1It++ )
1486     {
1487       nodes.push_back( TIsoNode( *par0It, *par1It ) );
1488       isoLine0.push_back( & nodes.back() );
1489       isoMap[1][ *par1It ].push_back( & nodes.back() );
1490     }
1491   }
1492
1493   // Compute intersections of boundaries with iso-lines:
1494   // only boundary nodes will have computed UV so far
1495
1496   Bnd_Box2d uvBnd;
1497   list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1498   list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1499   for ( ; bndIt != theBndPoints.end(); bndIt++ )
1500   {
1501     const list< TPoint* > & bndPoints = * bndIt;
1502     TPoint* prevP = bndPoints.back(); // this is the first point
1503     list< TPoint* >::const_iterator pIt = bndPoints.begin();
1504     // loop on the edge-points
1505     for ( ; pIt != bndPoints.end(); pIt++ )
1506     {
1507       TPoint* point = *pIt;
1508       for ( iDir = 0; iDir < 2; iDir++ )
1509       {
1510         const int iCoord = iDir + 1;
1511         const int iOtherCoord = 2 - iDir;
1512         double par1 = prevP->myInitUV.Coord( iCoord );
1513         double par2 = point->myInitUV.Coord( iCoord );
1514         double parDif = par2 - par1;
1515         if ( Abs( parDif ) <= DBL_MIN )
1516           continue;
1517         // find iso-lines intersecting a bounadry
1518         double toler = tol[ 1 - iDir ];
1519         double minPar = Min ( par1, par2 );
1520         double maxPar = Max ( par1, par2 );
1521         map < double, TIsoLine >& isos = isoMap[ iDir ];
1522         map < double, TIsoLine >::iterator isoIt = isos.begin();
1523         for ( ; isoIt != isos.end(); isoIt++ )
1524         {
1525           double isoParam = (*isoIt).first;
1526           if ( isoParam < minPar || isoParam > maxPar )
1527             continue;
1528           double r = ( isoParam - par1 ) / parDif;
1529           gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1530           gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1531           double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1532           // find existing node with otherPar or insert a new one
1533           TIsoLine & isoLine = (*isoIt).second;
1534           double nodePar;
1535           TIsoLine::iterator nIt = isoLine.begin();
1536           for ( ; nIt != isoLine.end(); nIt++ ) {
1537             nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1538             if ( nodePar >= otherPar )
1539               break;
1540           }
1541           TIsoNode * node;
1542           if ( Abs( nodePar - otherPar ) <= toler )
1543             node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1544           else {
1545             nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1546             node = & nodes.back();
1547             isoLine.insert( nIt, node );
1548           }
1549           node->SetNotMovable();
1550           node->myUV = uv;
1551           uvBnd.Add( gp_Pnt2d( uv ));
1552 //  cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1553           // tangent dir
1554           gp_XY tgt( point->myUV - prevP->myUV );
1555           if ( ::IsEqual( r, 1. ))
1556             node->myDir[ 0 ] = tgt;
1557           else if ( ::IsEqual( r, 0. ))
1558             node->myDir[ 1 ] = tgt;
1559           else
1560             node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1561           // keep boundary nodes corresponding to boundary points
1562           if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1563             if ( bndNodes.empty() || bndNodes.back() != node )
1564               bndNodes.push_back( node );
1565         } // loop on isolines
1566       } // loop on 2 directions
1567       prevP = point;
1568     } // loop on boundary points
1569   } // loop on boundaries
1570
1571   // Define orientation
1572
1573   // find the point with the least X
1574   double leastX = DBL_MAX;
1575   TIsoNode * leftNode;
1576   list < TIsoNode >::iterator nodeIt = nodes.begin();
1577   for ( ; nodeIt != nodes.end(); nodeIt++  ) {
1578     TIsoNode & node = *nodeIt;
1579     if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1580       leastX = node.myUV.X();
1581       leftNode = &node;
1582     }
1583 // if ( node.IsUVComputed() ) {
1584 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1585 //   node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1586 //    " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1587 //      " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1588 // }
1589   }
1590   bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1591   //SCRUTE( reversed );
1592
1593   // Prepare internal nodes:
1594   // 1. connect nodes
1595   // 2. compute ratios
1596   // 3. find boundary nodes for each node
1597   // 4. remove nodes out of the boundary
1598   for ( iDir = 0; iDir < 2; iDir++ )
1599   {
1600     const int iCoord = 2 - iDir; // coord changing along an isoline
1601     map < double, TIsoLine >& isos = isoMap[ iDir ];
1602     map < double, TIsoLine >::iterator isoIt = isos.begin();
1603     for ( ; isoIt != isos.end(); isoIt++ )
1604     {
1605       TIsoLine & isoLine = (*isoIt).second;
1606       bool firstCompNodeFound = false;
1607       TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1608       nPrevIt = nIt = nNextIt = isoLine.begin();
1609       nIt++;
1610       nNextIt++; nNextIt++;
1611       while ( nIt != isoLine.end() )
1612       {
1613         // 1. connect prev - cur
1614         TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1615         if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1616           firstCompNodeFound = true;
1617           lastCompNodePos = nPrevIt;
1618         }
1619         if ( firstCompNodeFound ) {
1620           node->SetNext( prevNode, iDir, 0 );
1621           prevNode->SetNext( node, iDir, 1 );
1622         }
1623         // 2. compute ratio
1624         if ( nNextIt != isoLine.end() ) {
1625           double par1 = prevNode->myInitUV.Coord( iCoord );
1626           double par2 = node->myInitUV.Coord( iCoord );
1627           double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1628           node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1629         }
1630         // 3. find boundary nodes
1631         if ( node->IsUVComputed() )
1632           lastCompNodePos = nIt;
1633         else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1634           TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1635           for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1636             if ( (*nIt2)->IsUVComputed() )
1637               break;
1638           if ( nIt2 != isoLine.end() ) {
1639             bndNode2 = *nIt2;
1640             node->SetBoundaryNode( bndNode1, iDir, 0 );
1641             node->SetBoundaryNode( bndNode2, iDir, 1 );
1642 // cout << "--------------------------------------------------"<<endl;
1643 //  cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1644 //   " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1645 //     " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1646 //  cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1647 //   " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1648 //     " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1649           }
1650           else {
1651             /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1652             node->SetBoundaryNode( 0, iDir, 0 );
1653             node->SetBoundaryNode( 0, iDir, 1 );
1654           }
1655         }
1656         nIt++; nPrevIt++;
1657         if ( nNextIt != isoLine.end() ) nNextIt++;
1658         // 4. remove nodes out of the boundary
1659         if ( !firstCompNodeFound )
1660           isoLine.pop_front();
1661       } // loop on isoLine nodes
1662
1663       // remove nodes after the boundary
1664 //       for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1665 //         (*nIt)->SetNotMovable();
1666       isoLine.erase( ++lastCompNodePos, isoLine.end() );
1667     } // loop on isolines
1668   } // loop on 2 directions
1669
1670   // Compute local isoline direction for internal nodes
1671
1672   /*
1673   map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1674   map < double, TIsoLine >::iterator isoIt = isos.begin();
1675   for ( ; isoIt != isos.end(); isoIt++ )
1676   {
1677     TIsoLine & isoLine = (*isoIt).second;
1678     TIsoLine::iterator nIt = isoLine.begin();
1679     for ( ; nIt != isoLine.end(); nIt++ )
1680     {
1681       TIsoNode* node = *nIt;
1682       if ( node->IsUVComputed() || !node->IsMovable() )
1683         continue;
1684       gp_Vec2d aTgt[2], aNorm[2];
1685       double ratio[2];
1686       bool OK = true;
1687       for ( iDir = 0; iDir < 2; iDir++ )
1688       {
1689         TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1690         TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1691         if ( !bndNode1 || !bndNode2 ) {
1692           OK = false;
1693           break;
1694         }
1695         const int iCoord = 2 - iDir; // coord changing along an isoline
1696         double par1 = bndNode1->myInitUV.Coord( iCoord );
1697         double par2 = node->myInitUV.Coord( iCoord );
1698         double par3 = bndNode2->myInitUV.Coord( iCoord );
1699         ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1700
1701         gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1702         gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1703         if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1704         else                            tgt1.Reverse();
1705 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1706
1707         if ( ratio[ iDir ] < 0.5 )
1708           aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1709         else
1710           aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1711         if ( iDir == 1 )
1712           aNorm[ iDir ].Reverse();  // along iDir isoline
1713
1714         double angle = tgt1.Angle( tgt2 ); //  [-PI, PI]
1715         // maybe angle is more than |PI|
1716         if ( Abs( angle ) > PI / 2. ) {
1717           // check direction of the last but one perpendicular isoline
1718           TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1719           bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1720           bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1721           gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1722           if ( isoDir * tgt2 < 0 )
1723             isoDir.Reverse();
1724           double angle2 = tgt1.Angle( isoDir );
1725           //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1726           if (angle2 * angle < 0 && // check the sign of an angle close to PI
1727               Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1728             //MESSAGE("REVERSE ANGLE");
1729             angle = -angle;
1730           }
1731           if ( Abs( angle2 ) > Abs( angle ) ||
1732               ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1733             //MESSAGE("Add PI");
1734             // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1735             // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1736             // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1737             // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1738             // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<"  "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1739             angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1740           }
1741         }
1742         aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1743       } // loop on 2 dir
1744
1745       if ( OK ) {
1746         for ( iDir = 0; iDir < 2; iDir++ )
1747         {
1748           aTgt[iDir].Normalize();
1749           aNorm[1-iDir].Normalize();
1750           double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1751           r *= r;
1752           
1753           node->myDir[iDir] = //aTgt[iDir];
1754             aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1755         }
1756 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1757 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1758 //  cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<"  |  "
1759 //    << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1760       }
1761     } // loop on iso nodes
1762   } // loop on isolines
1763 */
1764   // Find nodes to start computing UV from
1765
1766   list< TIsoNode* > startNodes;
1767   list< TIsoNode* >::iterator nIt = bndNodes.end();
1768   TIsoNode* node = *(--nIt);
1769   TIsoNode* prevNode = *(--nIt);
1770   for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1771   {
1772     TIsoNode* nextNode = *nIt;
1773     gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1774     gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1775     double initAngle = initTgt1.Angle( initTgt2 );
1776     double angle = node->myDir[0].Angle( node->myDir[1] );
1777     if ( reversed ) angle = -angle;
1778     if ( initAngle > angle && initAngle - angle > PI / 2.1 ) {
1779       // find a close internal node
1780       TIsoNode* nClose = 0;
1781       list< TIsoNode* > testNodes;
1782       testNodes.push_back( node );
1783       list< TIsoNode* >::iterator it = testNodes.begin();
1784       for ( ; !nClose && it != testNodes.end(); it++ )
1785       {
1786         for (int i = 0; i < 4; i++ )
1787         {
1788           nClose = (*it)->myNext[ i ];
1789           if ( nClose ) {
1790             if ( !nClose->IsUVComputed() )
1791               break;
1792             else {
1793               testNodes.push_back( nClose );
1794               nClose = 0;
1795             }
1796           }
1797         }
1798       }
1799       startNodes.push_back( nClose );
1800 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1801 //   node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1802 //   "initAngle: " << initAngle << " angle: " << angle << endl;
1803 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1804 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1805 //    node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1806 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1807     }
1808     prevNode = node;
1809     node = nextNode;
1810   }
1811
1812   // Compute starting UV of internal nodes
1813
1814   list < TIsoNode* > internNodes;
1815   bool needIteration = true;
1816   if ( startNodes.empty() ) {
1817     MESSAGE( " Starting UV by compUVByIsoIntersection()");
1818     needIteration = false;
1819     map < double, TIsoLine >& isos = isoMap[ 0 ];
1820     map < double, TIsoLine >::iterator isoIt = isos.begin();
1821     for ( ; isoIt != isos.end(); isoIt++ )
1822     {
1823       TIsoLine & isoLine = (*isoIt).second;
1824       TIsoLine::iterator nIt = isoLine.begin();
1825       for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1826       {
1827         TIsoNode* node = *nIt;
1828         if ( !node->IsUVComputed() && node->IsMovable() ) {
1829           internNodes.push_back( node );
1830           //bool isDeformed;
1831           if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1832                                         node->myUV, needIteration ))
1833             node->myUV = node->myInitUV;
1834         }
1835       }
1836     }
1837     if ( needIteration )
1838       for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1839       {
1840         TIsoNode* node = *nIt, *nClose = 0;
1841         list< TIsoNode* > testNodes;
1842         testNodes.push_back( node );
1843         list< TIsoNode* >::iterator it = testNodes.begin();
1844         for ( ; !nClose && it != testNodes.end(); it++ )
1845         {
1846           for (int i = 0; i < 4; i++ )
1847           {
1848             nClose = (*it)->myNext[ i ];
1849             if ( nClose ) {
1850               if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1851                 break;
1852               else {
1853                 testNodes.push_back( nClose );
1854                 nClose = 0;
1855               }
1856             }
1857           }
1858         }
1859         startNodes.push_back( nClose );
1860       }
1861   }
1862
1863   double aMin[2], aMax[2], step[2];
1864   uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1865   double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1866   step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1867   step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1868 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1869
1870   for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1871   {
1872     TIsoNode* prevN[2], *node = *nIt;
1873     if ( node->IsUVComputed() || !node->IsMovable() )
1874       continue;
1875     gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1876     int nbComp = 0, nbPrev = 0;
1877     for ( iDir = 0; iDir < 2; iDir++ )
1878     {
1879       TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1880       TIsoNode* n = node->GetNext( iDir, 0 );
1881       if ( n->IsUVComputed() )
1882         prevNode1 = n;
1883       else
1884         startNodes.push_back( n );
1885       n = node->GetNext( iDir, 1 );
1886       if ( n->IsUVComputed() )
1887         prevNode2 = n;
1888       else
1889         startNodes.push_back( n );
1890       if ( !prevNode1 ) {
1891         prevNode1 = prevNode2;
1892         prevNode2 = 0;
1893       }
1894       if ( prevNode1 ) nbPrev++;
1895       if ( prevNode2 ) nbPrev++;
1896       if ( prevNode1 ) {
1897         gp_XY dir;
1898           double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1899           double par = node->myInitUV.Coord( 2 - iDir );
1900           bool isEnd = ( prevPar > par );
1901 //          dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1902         //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1903           TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1904           if ( !bndNode ) {
1905             MESSAGE("Why we are here?");
1906             continue;
1907           }
1908           gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1909           dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1910           dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1911         //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1912           //  cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1913           //     bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1914           //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1915             //" par: " << prevPar << endl;
1916           //           cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1917         //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1918         if ( prevNode2 ) {
1919           //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1920           gp_XY & uv1 = prevNode1->myUV;
1921           gp_XY & uv2 = prevNode2->myUV;
1922 //           dir = ( uv2 - uv1 );
1923 //           double len = dir.Modulus();
1924 //           if ( len > DBL_MIN )
1925 //             dir /= len * 0.5;
1926           double r = node->myRatio[ iDir ];
1927           newUV += uv1 * ( 1 - r ) + uv2 * r;
1928         }
1929         else {
1930           newUV += prevNode1->myUV + dir * step[ iDir ];
1931         }
1932         sumDir += dir;
1933         prevN[ iDir ] = prevNode1;
1934         nbComp++;
1935       }
1936     }
1937     if ( !nbComp ) continue;
1938     newUV /= nbComp;
1939     node->myUV = newUV;
1940     //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1941
1942     // check if a quadrangle is not distorted
1943     if ( nbPrev > 1 ) {
1944       //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1945       if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1946       //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1947       //  cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1948         node->myUV = newUV;
1949       }
1950     }
1951     internNodes.push_back( node );
1952   }
1953   
1954   // Move nodes
1955
1956   static int maxNbIter = 100;
1957 #ifdef DEB_COMPUVBYELASTICISOLINES
1958 //   maxNbIter++;
1959   bool useNbMoveNode = 0;
1960   static int maxNbNodeMove = 100;
1961   maxNbNodeMove++;
1962   int nbNodeMove = 0;
1963   if ( !useNbMoveNode )
1964     maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1965 #endif    
1966   double maxMove;
1967   int nbIter = 0;
1968   do {
1969     if ( !needIteration) break;
1970 #ifdef DEB_COMPUVBYELASTICISOLINES
1971     if ( nbIter >= maxNbIter ) break;
1972 #endif
1973     maxMove = 0.0;
1974     list < TIsoNode* >::iterator nIt = internNodes.begin();
1975     for ( ; nIt != internNodes.end(); nIt++  ) {
1976 #ifdef DEB_COMPUVBYELASTICISOLINES
1977       if (useNbMoveNode )
1978         cout << nbNodeMove <<" =================================================="<<endl;
1979 #endif
1980       TIsoNode * node = *nIt;
1981       // make lines
1982       //gp_Lin2d line[2];
1983       gp_XY loc[2];
1984       for ( iDir = 0; iDir < 2; iDir++ )
1985       {
1986         gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
1987         gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
1988         double r = node->myRatio[ iDir ];
1989         loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
1990 //         line[ iDir ].SetLocation( loc[ iDir ] );
1991 //         line[ iDir ].SetDirection( node->myDir[ iDir ] );
1992       }
1993       // define ratio
1994       bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
1995       double locR[2] = { 0, 0 };
1996       for ( iDir = 0; iDir < 2; iDir++ )
1997       {
1998         const int iCoord = 2 - iDir; // coord changing along an isoline
1999         TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2000         TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2001         if ( !bndNode1 || !bndNode2 ) {
2002           ok = false; break;
2003         }
2004         double par1 = bndNode1->myInitUV.Coord( iCoord );
2005         double par2 = node->myInitUV.Coord( iCoord );
2006         double par3 = bndNode2->myInitUV.Coord( iCoord );
2007         double r = ( par2 - par1 ) / ( par3 - par1 );
2008         r = Abs ( r - 0.5 ) * 2.0;  // [0,1] - distance from the middle
2009         locR[ iDir ] = ( 1 - r * r ) * 0.25;
2010       }
2011       //locR[0] = locR[1] = 0.25;
2012       // intersect the 2 lines and move a node
2013       //IntAna2d_AnaIntersection inter( line[0], line[1] );
2014       if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2015       {
2016 //         double intR = 1 - locR[0] - locR[1];
2017 //         gp_XY newUV = inter.Point(1).Value().XY();
2018 //         if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2019 //           newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2020 //         else
2021 //           newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2022         gp_XY newUV = 0.5 * ( loc[0] +  loc[1] );
2023         // avoid parallel isolines intersection
2024         checkQuads( node, newUV, reversed );
2025
2026         maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2027         node->myUV = newUV;
2028       } // intersection found
2029 #ifdef DEB_COMPUVBYELASTICISOLINES
2030       if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2031 #endif
2032     } // loop on internal nodes
2033 #ifdef DEB_COMPUVBYELASTICISOLINES
2034     if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2035 #endif
2036   } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2037
2038   MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2039
2040   if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2041     MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2042 #ifndef DEB_COMPUVBYELASTICISOLINES
2043     return false;
2044 #endif
2045   }
2046
2047   // Set computed UV to points
2048
2049   for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2050     TPoint* point = *pIt;
2051     //gp_XY oldUV = point->myUV;
2052     double minDist = DBL_MAX;
2053     list < TIsoNode >::iterator nIt = nodes.begin();
2054     for ( ; nIt != nodes.end(); nIt++ ) {
2055       double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2056       if ( dist < minDist ) {
2057         minDist = dist;
2058         point->myUV = (*nIt).myUV;
2059       }
2060     }
2061   }
2062       
2063     
2064   return true;
2065 }
2066
2067
2068 //=======================================================================
2069 //function : setFirstEdge
2070 //purpose  : choose the best first edge of theWire; return the summary distance
2071 //           between point UV computed by isolines intersection and
2072 //           eventual UV got from edge p-curves
2073 //=======================================================================
2074
2075 //#define DBG_SETFIRSTEDGE
2076 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2077 {
2078   int iE, nbEdges = theWire.size();
2079   if ( nbEdges == 1 )
2080     return 0;
2081
2082   // Transform UVs computed by iso to fit bnd box of a wire
2083
2084   // max nb of points on an edge
2085   int maxNbPnt = 0;
2086   int eID = theFirstEdgeID;
2087   for ( iE = 0; iE < nbEdges; iE++ )
2088     maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2089   
2090   // compute bnd boxes
2091   TopoDS_Face face = TopoDS::Face( myShape );
2092   Bnd_Box2d bndBox, eBndBox;
2093   eID = theFirstEdgeID;
2094   list< TopoDS_Edge >::iterator eIt;
2095   list< TPoint* >::iterator pIt;
2096   for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2097   {
2098     // UV by isos stored in TPoint.myXYZ
2099     list< TPoint* > & ePoints = getShapePoints( eID++ );
2100     for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2101       TPoint* p = (*pIt);
2102       bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2103     }
2104     // UV by an edge p-curve
2105     double f, l;
2106     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2107     double dU = ( l - f ) / ( maxNbPnt - 1 );
2108     for ( int i = 0; i < maxNbPnt; i++ )
2109       eBndBox.Add( C2d->Value( f + i * dU ));
2110   }
2111
2112   // transform UVs by isos
2113   double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2114   bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2115   eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2116 #ifdef DBG_SETFIRSTEDGE
2117   cout << "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2118     << eMinPar[1] << " - " << eMaxPar[1] << endl;
2119 #endif
2120   for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2121   {
2122     double dMin = eMinPar[i] - minPar[i];
2123     double dMax = eMaxPar[i] - maxPar[i];
2124     double dPar = maxPar[i] - minPar[i];
2125     eID = theFirstEdgeID;
2126     for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2127     {
2128       list< TPoint* > & ePoints = getShapePoints( eID++ );
2129       for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2130       {
2131         double par = (*pIt)->myXYZ.Coord( iC );
2132         double r = ( par - minPar[i] ) / dPar;
2133         par += ( 1 - r ) * dMin + r * dMax;
2134         (*pIt)->myXYZ.SetCoord( iC, par );
2135       }
2136     }
2137   }
2138
2139   TopoDS_Edge eBest;
2140   double minDist = DBL_MAX;
2141   for ( iE = 0 ; iE < nbEdges; iE++ )
2142   {
2143 #ifdef DBG_SETFIRSTEDGE
2144     cout << " VARIANT " << iE << endl;
2145 #endif
2146     // evaluate the distance between UV computed by the 2 methods:
2147     // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2148     double dist = 0;
2149     int eID = theFirstEdgeID;
2150     for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2151     {
2152       list< TPoint* > & ePoints = getShapePoints( eID++ );
2153       computeUVOnEdge( *eIt, ePoints );
2154       for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2155         TPoint* p = (*pIt);
2156         dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2157 #ifdef DBG_SETFIRSTEDGE
2158         cout << " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2159           p->myUV.X() << ", " << p->myUV.Y() << ") " << endl;
2160 #endif
2161       }
2162     }
2163 #ifdef DBG_SETFIRSTEDGE
2164     cout << "dist -- " << dist << endl;
2165 #endif
2166     if ( dist < minDist ) {
2167       minDist = dist;
2168       eBest = theWire.front();
2169     }
2170     // check variant with another first edge
2171     theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2172   }
2173   // put the best first edge to the theWire front
2174   if ( eBest != theWire.front() ) {
2175     eIt = find ( theWire.begin(), theWire.end(), eBest );
2176     theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2177   }
2178
2179   return minDist;
2180 }
2181
2182 //=======================================================================
2183 //function : sortSameSizeWires
2184 //purpose  : sort wires in theWireList from theFromWire until theToWire,
2185 //           the wires are set in the order to correspond to the order
2186 //           of boundaries; after sorting, edges in the wires are put
2187 //           in a good order, point UVs on edges are computed and points
2188 //           are appended to theEdgesPointsList
2189 //=======================================================================
2190
2191 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList &                theWireList,
2192                                        const TListOfEdgesList::iterator& theFromWire,
2193                                        const TListOfEdgesList::iterator& theToWire,
2194                                        const int                         theFirstEdgeID,
2195                                        list< list< TPoint* > >&          theEdgesPointsList )
2196 {
2197   TopoDS_Face F = TopoDS::Face( myShape );
2198   int iW, nbWires = 0;
2199   TListOfEdgesList::iterator wlIt = theFromWire;
2200   while ( wlIt++ != theToWire )
2201     nbWires++;
2202
2203   // Recompute key-point UVs by isolines intersection,
2204   // compute CG of key-points for each wire and bnd boxes of GCs
2205
2206   bool aBool;
2207   gp_XY orig( gp::Origin2d().XY() );
2208   vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2209   Bnd_Box2d bndBox, vBndBox;
2210   int eID = theFirstEdgeID;
2211   list< TopoDS_Edge >::iterator eIt;
2212   for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2213   {
2214     list< TopoDS_Edge > & wire = *wlIt;
2215     for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2216     {
2217       list< TPoint* > & ePoints = getShapePoints( eID++ );
2218       TPoint* p = ePoints.front();
2219       if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2220         MESSAGE("cant sortSameSizeWires()");
2221         return false;
2222       }
2223       gcVec[iW] += p->myUV;
2224       bndBox.Add( gp_Pnt2d( p->myUV ));
2225       TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2226       gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2227       vGcVec[iW] += vXY.XY();
2228       vBndBox.Add( vXY );
2229       // keep the computed UV to compare against by setFirstEdge()
2230       p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2231     }
2232     gcVec[iW] /= nbWires;
2233     vGcVec[iW] /= nbWires;
2234 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2235 //   " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2236   }
2237
2238   // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2239
2240   double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2241   bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2242   vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2243   for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2244   {
2245     double dMin = vMinPar[i] - minPar[i];
2246     double dMax = vMaxPar[i] - maxPar[i];
2247     double dPar = maxPar[i] - minPar[i];
2248     if ( Abs( dPar ) <= DBL_MIN )
2249       continue;
2250     for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2251       double par = gcVec[iW].Coord( iC );
2252       double r = ( par - minPar[i] ) / dPar;
2253       par += ( 1 - r ) * dMin + r * dMax;
2254       gcVec[iW].SetCoord( iC, par );
2255     }
2256   }
2257
2258   // Define boundary - wire correspondence by GC closeness
2259
2260   TListOfEdgesList tmpWList;
2261   tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2262   typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2263   TIntWirePosMap bndIndWirePosMap;
2264   vector< bool > bndFound( nbWires, false );
2265   for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2266   {
2267 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2268 //   " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2269     double minDist = DBL_MAX;
2270     gp_XY & wGc = vGcVec[ iW ];
2271     int bIndex;
2272     for ( int iB = 0; iB < nbWires; iB++ ) {
2273       if ( bndFound[ iB ] ) continue;
2274       double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2275       if ( dist < minDist ) {
2276         minDist = dist;
2277         bIndex = iB;
2278       }
2279     }
2280     bndFound[ bIndex ] = true;
2281     bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2282   }
2283
2284   // Treat each wire  
2285
2286   TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2287   eID = theFirstEdgeID;
2288   for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2289   {
2290     TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2291     list < TopoDS_Edge > & wire = ( *wirePos );
2292
2293     // choose the best first edge of a wire
2294     setFirstEdge( wire, eID );
2295     
2296     // compute eventual UV and fill theEdgesPointsList
2297     theEdgesPointsList.push_back( list< TPoint* >() );
2298     list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2299     for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2300     {
2301       list< TPoint* > & ePoints = getShapePoints( eID++ );
2302       computeUVOnEdge( *eIt, ePoints );
2303       edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2304     }
2305     // put wire back to theWireList
2306     wlIt = wirePos++;
2307     theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2308   }
2309
2310   return true;
2311 }
2312
2313 //=======================================================================
2314 //function : Apply
2315 //purpose  : Compute  nodes coordinates applying
2316 //           the loaded pattern to <theFace>. The first key-point
2317 //           will be mapped into <theVertexOnKeyPoint1>
2318 //=======================================================================
2319
2320 bool SMESH_Pattern::Apply (const TopoDS_Face&   theFace,
2321                            const TopoDS_Vertex& theVertexOnKeyPoint1,
2322                            const bool           theReverse)
2323 {
2324   MESSAGE(" ::Apply(face) " );
2325   TopoDS_Face face  = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2326   if ( !setShapeToMesh( face ))
2327     return false;
2328
2329   // find points on edges, it fills myNbKeyPntInBoundary
2330   if ( !findBoundaryPoints() )
2331     return false;
2332
2333   // Define the edges order so that the first edge starts at
2334   // theVertexOnKeyPoint1
2335
2336   list< TopoDS_Edge > eList;
2337   list< int >         nbVertexInWires;
2338   int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2339   if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2340   {
2341     MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2342     return setErrorCode( ERR_APPLF_BAD_VERTEX );
2343   }
2344   // check nb wires and edges
2345   list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2346   l1.sort(); l2.sort();
2347   if ( l1 != l2 )
2348   {
2349     MESSAGE( "Wrong nb vertices in wires" );
2350     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2351   }
2352
2353   // here shapes get IDs, for the outer wire IDs are OK
2354   list<TopoDS_Edge>::iterator elIt = eList.begin();
2355   for ( ; elIt != eList.end(); elIt++ ) {
2356     myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2357     if ( BRep_Tool::IsClosed( *elIt, theFace ) )
2358       myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));
2359   }
2360   int nbVertices = myShapeIDMap.Extent();
2361
2362   for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2363     myShapeIDMap.Add( *elIt );
2364
2365   myShapeIDMap.Add( face );
2366
2367   if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent()/* + nbSeamShapes*/ ) {
2368     MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2369     return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2370   }
2371
2372   // points on edges to be used for UV computation of in-face points
2373   list< list< TPoint* > > edgesPointsList;
2374   edgesPointsList.push_back( list< TPoint* >() );
2375   list< TPoint* > * edgesPoints = & edgesPointsList.back();
2376   list< TPoint* >::iterator pIt;
2377
2378   // compute UV of points on the outer wire
2379   int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2380   for (iE = 0, elIt = eList.begin();
2381        iE < nbEdgesInOuterWire && elIt != eList.end();
2382        iE++, elIt++ )
2383   {
2384     list< TPoint* > & ePoints = getShapePoints( *elIt );
2385     // compute UV
2386     computeUVOnEdge( *elIt, ePoints );
2387     // collect on-edge points (excluding the last one)
2388     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2389   }
2390
2391   // If there are several wires, define the order of edges of inner wires:
2392   // compute UV of inner edge-points using 2 methods: the one for in-face points
2393   // and the one for on-edge points and then choose the best edge order
2394   // by the best correspondance of the 2 results
2395   if ( nbWires > 1 )
2396   {
2397     // compute UV of inner edge-points using the method for in-face points
2398     // and devide eList into a list of separate wires
2399     bool aBool;
2400     list< list< TopoDS_Edge > > wireList;
2401     list<TopoDS_Edge>::iterator eIt = elIt;
2402     list<int>::iterator nbEIt = nbVertexInWires.begin();
2403     for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2404     {
2405       int nbEdges = *nbEIt;
2406       wireList.push_back( list< TopoDS_Edge >() );
2407       list< TopoDS_Edge > & wire = wireList.back();
2408       for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2409       {
2410         list< TPoint* > & ePoints = getShapePoints( *eIt );
2411         pIt = ePoints.begin();
2412         for (  pIt++; pIt != ePoints.end(); pIt++ ) {
2413           TPoint* p = (*pIt);
2414           if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2415             MESSAGE("cant Apply(face)");
2416             return false;
2417           }
2418           // keep the computed UV to compare against by setFirstEdge()
2419           p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2420         }
2421         wire.push_back( *eIt );
2422       }
2423     }
2424     // remove inner edges from eList
2425     eList.erase( elIt, eList.end() );
2426
2427     // sort wireList by nb edges in a wire
2428     sortBySize< TopoDS_Edge > ( wireList );
2429
2430     // an ID of the first edge of a boundary
2431     int id1 = nbVertices + nbEdgesInOuterWire + 1;
2432 //     if ( nbSeamShapes > 0 )
2433 //       id1 += 2; // 2 vertices more
2434
2435     // find points - edge correspondence for wires of unique size,
2436     // edge order within a wire should be defined only
2437
2438     list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2439     while ( wlIt != wireList.end() )
2440     {
2441       list< TopoDS_Edge >& wire = (*wlIt);
2442       int nbEdges = wire.size();
2443       wlIt++;
2444       if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2445       {
2446         // choose the best first edge of a wire
2447         setFirstEdge( wire, id1 );
2448
2449         // compute eventual UV and collect on-edge points
2450         edgesPointsList.push_back( list< TPoint* >() );
2451         edgesPoints = & edgesPointsList.back();
2452         int eID = id1;
2453         for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2454         {
2455           list< TPoint* > & ePoints = getShapePoints( eID++ );
2456           computeUVOnEdge( *eIt, ePoints );
2457           edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2458         }
2459       }
2460       id1 += nbEdges;
2461     }
2462
2463     // find boundary - wire correspondence for several wires of same size
2464     
2465     id1 = nbVertices + nbEdgesInOuterWire + 1;
2466     wlIt = wireList.begin();
2467     while ( wlIt != wireList.end() )
2468     {
2469       int nbSameSize = 0, nbEdges = (*wlIt).size();
2470       list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2471       wlIt2++;
2472       while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2473         nbSameSize++;
2474         wlIt2++;
2475       }
2476       if ( nbSameSize > 0 )
2477         if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2478           return false;
2479       wlIt = wlIt2;
2480       id1 += nbEdges * ( nbSameSize + 1 );
2481     }
2482
2483     // add well-ordered edges to eList
2484     
2485     for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2486     {
2487       list< TopoDS_Edge >& wire = (*wlIt);
2488       eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2489     }
2490
2491     // re-fill myShapeIDMap - all shapes get good IDs
2492
2493     myShapeIDMap.Clear();
2494     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2495       myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2496     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2497       myShapeIDMap.Add( *elIt );
2498     myShapeIDMap.Add( face );
2499     
2500   } // there are inner wires
2501
2502   // Compute XYZ of on-edge points
2503
2504   TopLoc_Location loc;
2505   for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2506   {
2507     BRepAdaptor_Curve C3d( *elIt );
2508     list< TPoint* > & ePoints = getShapePoints( iE++ );
2509     pIt = ePoints.begin();
2510     for ( pIt++; pIt != ePoints.end(); pIt++ )
2511     {
2512       TPoint* point = *pIt;
2513       point->myXYZ = C3d.Value( point->myU );
2514     }
2515   }
2516
2517   // Compute UV and XYZ of in-face points
2518
2519   // try to use a simple algo
2520   list< TPoint* > & fPoints = getShapePoints( face );
2521   bool isDeformed = false;
2522   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2523     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2524                                   (*pIt)->myUV, isDeformed )) {
2525       MESSAGE("cant Apply(face)");
2526       return false;
2527     }
2528   // try to use a complex algo if it is a difficult case
2529   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2530   {
2531     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2532       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2533                                     (*pIt)->myUV, isDeformed )) {
2534         MESSAGE("cant Apply(face)");
2535         return false;
2536       }
2537   }
2538
2539   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2540   const gp_Trsf & aTrsf = loc.Transformation();
2541   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2542   {
2543     TPoint * point = *pIt;
2544     point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2545     if ( !loc.IsIdentity() )
2546       aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2547   }
2548
2549   myIsComputed = true;
2550
2551   return setErrorCode( ERR_OK );
2552 }
2553
2554 //=======================================================================
2555 //function : Apply
2556 //purpose  : Compute nodes coordinates applying
2557 //           the loaded pattern to <theFace>. The first key-point
2558 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
2559 //=======================================================================
2560
2561 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2562                            const int            theNodeIndexOnKeyPoint1,
2563                            const bool           theReverse)
2564 {
2565 //  MESSAGE(" ::Apply(MeshFace) " );
2566
2567   if ( !IsLoaded() ) {
2568     MESSAGE( "Pattern not loaded" );
2569     return setErrorCode( ERR_APPL_NOT_LOADED );
2570   }
2571
2572   // check nb of nodes
2573   if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2574     MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2575     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2576   }
2577
2578   // find points on edges, it fills myNbKeyPntInBoundary
2579   if ( !findBoundaryPoints() )
2580     return false;
2581
2582   // check that there are no holes in a pattern
2583   if (myNbKeyPntInBoundary.size() > 1 ) {
2584     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2585   }
2586
2587   // Define the nodes order
2588
2589   list< const SMDS_MeshNode* > nodes;
2590   list< const SMDS_MeshNode* >::iterator n = nodes.end();
2591   SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2592   int iSub = 0;
2593   while ( noIt->more() ) {
2594     const SMDS_MeshNode* node = smdsNode( noIt->next() );
2595     nodes.push_back( node );
2596     if ( iSub++ == theNodeIndexOnKeyPoint1 )
2597       n = --nodes.end();
2598   }
2599   if ( n != nodes.end() ) {
2600     if ( theReverse ) {
2601       if ( n != --nodes.end() )
2602         nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2603       nodes.reverse();
2604     }
2605     else if ( n != nodes.begin() )
2606       nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2607   }
2608   list< gp_XYZ > xyzList;
2609   myOrderedNodes.resize( theFace->NbNodes() );
2610   for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2611     xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2612     myOrderedNodes[ iSub++] = *n;
2613   }
2614
2615   // Define a face plane
2616
2617   list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2618   gp_Pnt P ( *xyzIt++ );
2619   gp_Vec Vx( P, *xyzIt++ ), N;
2620   do {
2621     N = Vx ^ gp_Vec( P, *xyzIt++ );
2622   } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2623   if ( N.SquareMagnitude() <= DBL_MIN )
2624     return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2625   gp_Ax2 pos( P, N, Vx );
2626
2627   // Compute UV of key-points on a plane
2628   for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2629   {
2630     gp_Vec vec ( pos.Location(), *xyzIt );
2631     TPoint* p = getShapePoints( iSub ).front();
2632     p->myUV.SetX( vec * pos.XDirection() );
2633     p->myUV.SetY( vec * pos.YDirection() );
2634     p->myXYZ = *xyzIt;
2635   }
2636
2637   // points on edges to be used for UV computation of in-face points
2638   list< list< TPoint* > > edgesPointsList;
2639   edgesPointsList.push_back( list< TPoint* >() );
2640   list< TPoint* > * edgesPoints = & edgesPointsList.back();
2641   list< TPoint* >::iterator pIt;
2642
2643   // compute UV and XYZ of points on edges
2644
2645   for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2646   {
2647     gp_XYZ& xyz1 = *xyzIt++;
2648     gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2649     
2650     list< TPoint* > & ePoints = getShapePoints( iSub );
2651     ePoints.back()->myInitU = 1.0;
2652     list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2653     while ( *pIt != ePoints.back() )
2654     {
2655       TPoint* p = *pIt++;
2656       p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2657       gp_Vec vec ( pos.Location(), p->myXYZ );
2658       p->myUV.SetX( vec * pos.XDirection() );
2659       p->myUV.SetY( vec * pos.YDirection() );
2660     }
2661     // collect on-edge points (excluding the last one)
2662     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2663   }
2664
2665   // Compute UV and XYZ of in-face points
2666
2667   // try to use a simple algo to compute UV
2668   list< TPoint* > & fPoints = getShapePoints( iSub );
2669   bool isDeformed = false;
2670   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2671     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2672                                   (*pIt)->myUV, isDeformed )) {
2673       MESSAGE("cant Apply(face)");
2674       return false;
2675     }
2676   // try to use a complex algo if it is a difficult case
2677   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2678   {
2679     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2680       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2681                                     (*pIt)->myUV, isDeformed )) {
2682         MESSAGE("cant Apply(face)");
2683         return false;
2684       }
2685   }
2686
2687   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2688   {
2689     (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2690   }
2691
2692   myIsComputed = true;
2693
2694   return setErrorCode( ERR_OK );
2695 }
2696
2697 //=======================================================================
2698 //function : Apply
2699 //purpose  : Compute nodes coordinates applying
2700 //           the loaded pattern to <theFace>. The first key-point
2701 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
2702 //=======================================================================
2703
2704 bool SMESH_Pattern::Apply (SMESH_Mesh*          theMesh,
2705                            const SMDS_MeshFace* theFace,
2706                            const TopoDS_Shape&  theSurface,
2707                            const int            theNodeIndexOnKeyPoint1,
2708                            const bool           theReverse)
2709 {
2710 //  MESSAGE(" ::Apply(MeshFace) " );
2711   if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2712     return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2713   }
2714   const TopoDS_Face& face = TopoDS::Face( theSurface );
2715   TopLoc_Location loc;
2716   Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2717   const gp_Trsf & aTrsf = loc.Transformation();
2718
2719   if ( !IsLoaded() ) {
2720     MESSAGE( "Pattern not loaded" );
2721     return setErrorCode( ERR_APPL_NOT_LOADED );
2722   }
2723
2724   // check nb of nodes
2725   if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2726     MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2727     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2728   }
2729
2730   // find points on edges, it fills myNbKeyPntInBoundary
2731   if ( !findBoundaryPoints() )
2732     return false;
2733
2734   // check that there are no holes in a pattern
2735   if (myNbKeyPntInBoundary.size() > 1 ) {
2736     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2737   }
2738
2739   // Define the nodes order
2740
2741   list< const SMDS_MeshNode* > nodes;
2742   list< const SMDS_MeshNode* >::iterator n = nodes.end();
2743   SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2744   int iSub = 0;
2745   while ( noIt->more() ) {
2746     const SMDS_MeshNode* node = smdsNode( noIt->next() );
2747     nodes.push_back( node );
2748     if ( iSub++ == theNodeIndexOnKeyPoint1 )
2749       n = --nodes.end();
2750   }
2751   if ( n != nodes.end() ) {
2752     if ( theReverse ) {
2753       if ( n != --nodes.end() )
2754         nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2755       nodes.reverse();
2756     }
2757     else if ( n != nodes.begin() )
2758       nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2759   }
2760
2761   // find a node not on a seam edge, if necessary
2762   SMESH_MesherHelper helper( *theMesh );
2763   helper.SetSubShape( theSurface );
2764   const SMDS_MeshNode* inFaceNode = 0;
2765   if ( helper.GetNodeUVneedInFaceNode() )
2766   {
2767     SMESH_MeshEditor editor( theMesh );
2768     for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2769       int shapeID = editor.FindShape( *n );
2770       if ( !shapeID )
2771         return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2772       if ( !helper.IsSeamShape( shapeID ))
2773         inFaceNode = *n;
2774     }
2775   }
2776
2777   // Set UV of key-points (i.e. of nodes of theFace )
2778   vector< gp_XY > keyUV( theFace->NbNodes() );
2779   myOrderedNodes.resize( theFace->NbNodes() );
2780   for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2781   {
2782     TPoint* p = getShapePoints( iSub ).front();
2783     p->myUV  = helper.GetNodeUV( face, *n, inFaceNode );
2784     p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2785
2786     keyUV[ iSub-1 ] = p->myUV;
2787     myOrderedNodes[ iSub-1 ] = *n;
2788   }
2789
2790   // points on edges to be used for UV computation of in-face points
2791   list< list< TPoint* > > edgesPointsList;
2792   edgesPointsList.push_back( list< TPoint* >() );
2793   list< TPoint* > * edgesPoints = & edgesPointsList.back();
2794   list< TPoint* >::iterator pIt;
2795
2796   // compute UV and XYZ of points on edges
2797
2798   for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2799   {
2800     gp_XY& uv1 = keyUV[ i ];
2801     gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2802
2803     list< TPoint* > & ePoints = getShapePoints( iSub );
2804     ePoints.back()->myInitU = 1.0;
2805     list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2806     while ( *pIt != ePoints.back() )
2807     {
2808       TPoint* p = *pIt++;
2809       p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2810       p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2811       if ( !loc.IsIdentity() )
2812         aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2813     }
2814     // collect on-edge points (excluding the last one)
2815     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2816   }
2817
2818   // Compute UV and XYZ of in-face points
2819
2820   // try to use a simple algo to compute UV
2821   list< TPoint* > & fPoints = getShapePoints( iSub );
2822   bool isDeformed = false;
2823   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2824     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2825                                   (*pIt)->myUV, isDeformed )) {
2826       MESSAGE("cant Apply(face)");
2827       return false;
2828     }
2829   // try to use a complex algo if it is a difficult case
2830   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2831   {
2832     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2833       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2834                                     (*pIt)->myUV, isDeformed )) {
2835         MESSAGE("cant Apply(face)");
2836         return false;
2837       }
2838   }
2839
2840   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2841   {
2842     TPoint * point = *pIt;
2843     point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2844     if ( !loc.IsIdentity() )
2845       aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2846   }
2847
2848   myIsComputed = true;
2849
2850   return setErrorCode( ERR_OK );
2851 }
2852
2853 //=======================================================================
2854 //function : undefinedXYZ
2855 //purpose  : 
2856 //=======================================================================
2857
2858 static const gp_XYZ& undefinedXYZ()
2859 {
2860   static gp_XYZ xyz( 1.e100, 0., 0. );
2861   return xyz;
2862 }
2863
2864 //=======================================================================
2865 //function : isDefined
2866 //purpose  : 
2867 //=======================================================================
2868
2869 inline static bool isDefined(const gp_XYZ& theXYZ)
2870 {
2871   return theXYZ.X() < 1.e100;
2872 }
2873
2874 //=======================================================================
2875 //function : Apply
2876 //purpose  : Compute nodes coordinates applying
2877 //           the loaded pattern to <theFaces>. The first key-point
2878 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
2879 //=======================================================================
2880
2881 bool SMESH_Pattern::Apply (SMESH_Mesh*                     theMesh,
2882                            std::set<const SMDS_MeshFace*>& theFaces,
2883                            const int                       theNodeIndexOnKeyPoint1,
2884                            const bool                      theReverse)
2885 {
2886   MESSAGE(" ::Apply(set<MeshFace>) " );
2887
2888   if ( !IsLoaded() ) {
2889     MESSAGE( "Pattern not loaded" );
2890     return setErrorCode( ERR_APPL_NOT_LOADED );
2891   }
2892
2893   // find points on edges, it fills myNbKeyPntInBoundary
2894   if ( !findBoundaryPoints() )
2895     return false;
2896
2897   // check that there are no holes in a pattern
2898   if (myNbKeyPntInBoundary.size() > 1 ) {
2899     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2900   }
2901
2902   myShape.Nullify();
2903   myXYZ.clear();
2904   myElemXYZIDs.clear();
2905   myXYZIdToNodeMap.clear();
2906   myElements.clear();
2907   myIdsOnBoundary.clear();
2908   myReverseConnectivity.clear();
2909
2910   myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2911   myElements.reserve( theFaces.size() );
2912
2913   // to find point index
2914   map< TPoint*, int > pointIndex;
2915   for ( int i = 0; i < myPoints.size(); i++ )
2916     pointIndex.insert( make_pair( & myPoints[ i ], i ));
2917
2918   int ind1 = 0; // lowest point index for a face
2919
2920   // meshed geometry
2921   TopoDS_Shape shape;
2922 //   int          shapeID = 0;
2923 //   SMESH_MeshEditor editor( theMesh ); 
2924
2925   // apply to each face in theFaces set
2926   set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2927   for ( ; face != theFaces.end(); ++face )
2928   {
2929 //     int curShapeId = editor.FindShape( *face );
2930 //     if ( curShapeId != shapeID ) {
2931 //       if ( curShapeId )
2932 //         shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2933 //       else
2934 //         shape.Nullify();
2935 //       shapeID = curShapeId;
2936 //     }
2937     bool ok;
2938     if ( shape.IsNull() )
2939       ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2940     else
2941       ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2942     if ( !ok ) {
2943       MESSAGE( "Failed on " << *face );
2944       continue;
2945     }
2946     myElements.push_back( *face );
2947
2948     // store computed points belonging to elements
2949     list< TElemDef >::iterator ll = myElemPointIDs.begin();
2950     for ( ; ll != myElemPointIDs.end(); ++ll )
2951     {
2952       myElemXYZIDs.push_back(TElemDef());
2953       TElemDef& xyzIds = myElemXYZIDs.back();
2954       TElemDef& pIds = *ll;
2955       for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
2956         int pIndex = *id + ind1;
2957         xyzIds.push_back( pIndex );
2958         myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
2959         myReverseConnectivity[ pIndex ].push_back( & xyzIds );
2960       }
2961     }
2962     // put points on links to myIdsOnBoundary,
2963     // they will be used to sew new elements on adjacent refined elements
2964     int nbNodes = (*face)->NbNodes(), eID = nbNodes + 1;
2965     for ( int i = 0; i < nbNodes; i++ )
2966     {
2967       list< TPoint* > & linkPoints = getShapePoints( eID++ );
2968       const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
2969       const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
2970       // make a link and a node set
2971       TNodeSet linkSet, node1Set;
2972       linkSet.insert( n1 );
2973       linkSet.insert( n2 );
2974       node1Set.insert( n1 );
2975       list< TPoint* >::iterator p = linkPoints.begin();
2976       {
2977         // map the first link point to n1
2978         int nId = pointIndex[ *p ] + ind1;
2979         myXYZIdToNodeMap[ nId ] = n1;
2980         list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
2981         groups.push_back(list< int > ());
2982         groups.back().push_back( nId );
2983       }
2984       // add the linkSet to the map
2985       list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
2986       groups.push_back(list< int > ());
2987       list< int >& indList = groups.back();
2988       // add points to the map excluding the end points
2989       for ( p++; *p != linkPoints.back(); p++ )
2990         indList.push_back( pointIndex[ *p ] + ind1 );
2991     }
2992     ind1 += myPoints.size();
2993   }
2994
2995   return !myElemXYZIDs.empty();
2996 }
2997
2998 //=======================================================================
2999 //function : Apply
3000 //purpose  : Compute nodes coordinates applying
3001 //           the loaded pattern to <theVolumes>. The (0,0,0) key-point
3002 //           will be mapped into <theNode000Index>-th node. The
3003 //           (0,0,1) key-point will be mapped into <theNode000Index>-th
3004 //           node.
3005 //=======================================================================
3006
3007 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3008                            const int                          theNode000Index,
3009                            const int                          theNode001Index)
3010 {
3011   MESSAGE(" ::Apply(set<MeshVolumes>) " );
3012
3013   if ( !IsLoaded() ) {
3014     MESSAGE( "Pattern not loaded" );
3015     return setErrorCode( ERR_APPL_NOT_LOADED );
3016   }
3017
3018    // bind ID to points
3019   if ( !findBoundaryPoints() )
3020     return false;
3021
3022   // check that there are no holes in a pattern
3023   if (myNbKeyPntInBoundary.size() > 1 ) {
3024     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3025   }
3026
3027   myShape.Nullify();
3028   myXYZ.clear();
3029   myElemXYZIDs.clear();
3030   myXYZIdToNodeMap.clear();
3031   myElements.clear();
3032   myIdsOnBoundary.clear();
3033   myReverseConnectivity.clear();
3034
3035   myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3036   myElements.reserve( theVolumes.size() );
3037
3038   // to find point index
3039   map< TPoint*, int > pointIndex;
3040   for ( int i = 0; i < myPoints.size(); i++ )
3041     pointIndex.insert( make_pair( & myPoints[ i ], i ));
3042
3043   int ind1 = 0; // lowest point index for an element
3044
3045   // apply to each element in theVolumes set
3046   set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3047   for ( ; vol != theVolumes.end(); ++vol )
3048   {
3049     if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3050       MESSAGE( "Failed on " << *vol );
3051       continue;
3052     }
3053     myElements.push_back( *vol );
3054
3055     // store computed points belonging to elements
3056     list< TElemDef >::iterator ll = myElemPointIDs.begin();
3057     for ( ; ll != myElemPointIDs.end(); ++ll )
3058     {
3059       myElemXYZIDs.push_back(TElemDef());
3060       TElemDef& xyzIds = myElemXYZIDs.back();
3061       TElemDef& pIds = *ll;
3062       for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3063         int pIndex = *id + ind1;
3064         xyzIds.push_back( pIndex );
3065         myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3066         myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3067       }
3068     }
3069     // put points on edges and faces to myIdsOnBoundary,
3070     // they will be used to sew new elements on adjacent refined elements
3071     for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3072     {
3073       // make a set of sub-points
3074       TNodeSet subNodes;
3075       vector< int > subIDs;
3076       if ( SMESH_Block::IsVertexID( Id )) {
3077         subNodes.insert( myOrderedNodes[ Id - 1 ]);
3078       }
3079       else if ( SMESH_Block::IsEdgeID( Id )) {
3080         SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3081         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3082         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3083       }
3084       else {
3085         SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3086         int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3087         SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3088         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3089         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3090         SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3091         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3092         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3093       }
3094       // add points
3095       list< TPoint* > & points = getShapePoints( Id );
3096       list< TPoint* >::iterator p = points.begin();
3097       list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3098       groups.push_back(list< int > ());
3099       list< int >& indList = groups.back();
3100       for ( ; p != points.end(); p++ )
3101         indList.push_back( pointIndex[ *p ] + ind1 );
3102       if ( subNodes.size() == 1 ) // vertex case
3103         myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3104     }
3105     ind1 += myPoints.size();
3106   }
3107
3108   return !myElemXYZIDs.empty();
3109 }
3110
3111 //=======================================================================
3112 //function : Load
3113 //purpose  : Create a pattern from the mesh built on <theBlock>
3114 //=======================================================================
3115
3116 bool SMESH_Pattern::Load (SMESH_Mesh*         theMesh,
3117                           const TopoDS_Shell& theBlock)
3118 {
3119   MESSAGE(" ::Load(volume) " );
3120   Clear();
3121   myIs2D = false;
3122   SMESHDS_SubMesh * aSubMesh;
3123
3124   // load shapes in myShapeIDMap
3125   SMESH_Block block;
3126   TopoDS_Vertex v1, v2;
3127   if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3128     return setErrorCode( ERR_LOADV_BAD_SHAPE );
3129
3130   // count nodes
3131   int nbNodes = 0, shapeID;
3132   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3133   {
3134     const TopoDS_Shape& S = myShapeIDMap( shapeID );
3135     aSubMesh = getSubmeshWithElements( theMesh, S );
3136     if ( aSubMesh )
3137       nbNodes += aSubMesh->NbNodes();
3138   }
3139   myPoints.resize( nbNodes );
3140
3141   // load U of points on edges
3142   TNodePointIDMap nodePointIDMap;
3143   int iPoint = 0;
3144   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3145   {
3146     const TopoDS_Shape& S = myShapeIDMap( shapeID );
3147     list< TPoint* > & shapePoints = getShapePoints( shapeID );
3148     aSubMesh = getSubmeshWithElements( theMesh, S );
3149     if ( ! aSubMesh ) continue;
3150     SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3151     if ( !nIt->more() ) continue;
3152
3153       // store a node and a point
3154     while ( nIt->more() ) {
3155       const SMDS_MeshNode* node = smdsNode( nIt->next() );
3156       nodePointIDMap.insert( make_pair( node, iPoint ));
3157       if ( block.IsVertexID( shapeID ))
3158         myKeyPointIDs.push_back( iPoint );
3159       TPoint* p = & myPoints[ iPoint++ ];
3160       shapePoints.push_back( p );
3161       p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3162       p->myInitXYZ.SetCoord( 0,0,0 );
3163     }
3164     list< TPoint* >::iterator pIt = shapePoints.begin();
3165
3166     // compute init XYZ
3167     switch ( S.ShapeType() )
3168     {
3169     case TopAbs_VERTEX:
3170     case TopAbs_EDGE: {
3171
3172       for ( ; pIt != shapePoints.end(); pIt++ ) {
3173         double * coef = block.GetShapeCoef( shapeID );
3174         for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3175           if ( coef[ iCoord - 1] > 0 )
3176             (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3177       }
3178       if ( S.ShapeType() == TopAbs_VERTEX )
3179         break;
3180
3181       const TopoDS_Edge& edge = TopoDS::Edge( S );
3182       double f,l;
3183       BRep_Tool::Range( edge, f, l );
3184       int iCoord     = SMESH_Block::GetCoordIndOnEdge( shapeID );
3185       bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3186       pIt = shapePoints.begin();
3187       nIt = aSubMesh->GetNodes();
3188       for ( ; nIt->more(); pIt++ )
3189       {
3190         const SMDS_MeshNode* node = smdsNode( nIt->next() );
3191         const SMDS_EdgePosition* epos =
3192           static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
3193         double u = ( epos->GetUParameter() - f ) / ( l - f );
3194         (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3195       }
3196       break;
3197     }
3198     default:
3199       for ( ; pIt != shapePoints.end(); pIt++ )
3200       {
3201         if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3202           MESSAGE( "!block.ComputeParameters()" );
3203           return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3204         }
3205       }
3206     }
3207   } // loop on block sub-shapes
3208
3209   // load elements
3210
3211   aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3212   if ( aSubMesh )
3213   {
3214     SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3215     while ( elemIt->more() ) {
3216       SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
3217       myElemPointIDs.push_back( TElemDef() );
3218       TElemDef& elemPoints = myElemPointIDs.back();
3219       while ( nIt->more() )
3220         elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
3221     }
3222   }
3223
3224   myIsBoundaryPointsFound = true;
3225
3226   return setErrorCode( ERR_OK );
3227 }
3228
3229 //=======================================================================
3230 //function : getSubmeshWithElements
3231 //purpose  : return submesh containing elements bound to theBlock in theMesh
3232 //=======================================================================
3233
3234 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh*         theMesh,
3235                                                         const TopoDS_Shape& theShape)
3236 {
3237   SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3238   if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3239     return aSubMesh;
3240
3241   if ( theShape.ShapeType() == TopAbs_SHELL )
3242   {
3243     // look for submesh of VOLUME
3244     TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3245     for (; it.More(); it.Next()) {
3246       aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3247       if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3248         return aSubMesh;
3249     }
3250   }
3251   return 0;
3252 }
3253
3254
3255 //=======================================================================
3256 //function : Apply
3257 //purpose  : Compute nodes coordinates applying
3258 //           the loaded pattern to <theBlock>. The (0,0,0) key-point
3259 //           will be mapped into <theVertex000>. The (0,0,1)
3260 //           fifth key-point will be mapped into <theVertex001>.
3261 //=======================================================================
3262
3263 bool SMESH_Pattern::Apply (const TopoDS_Shell&  theBlock,
3264                            const TopoDS_Vertex& theVertex000,
3265                            const TopoDS_Vertex& theVertex001)
3266 {
3267   MESSAGE(" ::Apply(volume) " );
3268
3269   if (!findBoundaryPoints()     || // bind ID to points
3270       !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3271     return false;
3272
3273   SMESH_Block block;  // bind ID to shape
3274   if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3275     return setErrorCode( ERR_APPLV_BAD_SHAPE );
3276
3277   // compute XYZ of points on shapes
3278
3279   for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3280   {
3281     list< TPoint* > & shapePoints = getShapePoints( shapeID );
3282     list< TPoint* >::iterator pIt = shapePoints.begin();
3283     const TopoDS_Shape& S = myShapeIDMap( shapeID );
3284     switch ( S.ShapeType() )
3285     {
3286     case TopAbs_VERTEX: {
3287
3288       for ( ; pIt != shapePoints.end(); pIt++ )
3289         block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3290       break;
3291     }
3292     case TopAbs_EDGE: {
3293
3294       for ( ; pIt != shapePoints.end(); pIt++ )
3295         block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3296       break;
3297     }
3298     case TopAbs_FACE: {
3299
3300       for ( ; pIt != shapePoints.end(); pIt++ )
3301         block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3302       break;
3303     }
3304     default:
3305       for ( ; pIt != shapePoints.end(); pIt++ )
3306         block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3307     }
3308   } // loop on block sub-shapes
3309
3310   myIsComputed = true;
3311
3312   return setErrorCode( ERR_OK );
3313 }
3314
3315 //=======================================================================
3316 //function : Apply
3317 //purpose  : Compute nodes coordinates applying
3318 //           the loaded pattern to <theVolume>. The (0,0,0) key-point
3319 //           will be mapped into <theNode000Index>-th node. The
3320 //           (0,0,1) key-point will be mapped into <theNode000Index>-th
3321 //           node.
3322 //=======================================================================
3323
3324 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3325                            const int              theNode000Index,
3326                            const int              theNode001Index)
3327 {
3328   //MESSAGE(" ::Apply(MeshVolume) " );
3329
3330   if (!findBoundaryPoints()) // bind ID to points
3331     return false;
3332
3333   SMESH_Block block;  // bind ID to shape
3334   if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3335     return setErrorCode( ERR_APPLV_BAD_SHAPE );
3336   // compute XYZ of points on shapes
3337
3338   for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3339   {
3340     list< TPoint* > & shapePoints = getShapePoints( ID );
3341     list< TPoint* >::iterator pIt = shapePoints.begin();
3342
3343     if ( block.IsVertexID( ID ))
3344       for ( ; pIt != shapePoints.end(); pIt++ ) {
3345         block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3346       }
3347     else if ( block.IsEdgeID( ID ))
3348       for ( ; pIt != shapePoints.end(); pIt++ ) {
3349         block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3350       }
3351     else if ( block.IsFaceID( ID ))
3352       for ( ; pIt != shapePoints.end(); pIt++ ) {
3353         block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3354       }
3355     else
3356       for ( ; pIt != shapePoints.end(); pIt++ )
3357         block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3358   } // loop on block sub-shapes
3359
3360   myIsComputed = true;
3361
3362   return setErrorCode( ERR_OK );
3363 }
3364
3365 //=======================================================================
3366 //function : mergePoints
3367 //purpose  : Merge XYZ on edges and/or faces.
3368 //=======================================================================
3369
3370 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3371 {
3372   map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3373   for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3374   {
3375     list<list< int > >& groups = idListIt->second;
3376     if ( groups.size() < 2 )
3377       continue;
3378
3379     // find tolerance
3380     const TNodeSet& nodes = idListIt->first;
3381     double tol2 = 1.e-10;
3382     if ( nodes.size() > 1 ) {
3383       Bnd_Box box;
3384       TNodeSet::const_iterator n = nodes.begin();
3385       for ( ; n != nodes.end(); ++n )
3386         box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3387       double x, y, z, X, Y, Z;
3388       box.Get( x, y, z, X, Y, Z );
3389       gp_Pnt p( x, y, z ), P( X, Y, Z );
3390       tol2 = 1.e-4 * p.SquareDistance( P );
3391     }
3392
3393     // to unite groups on link
3394     bool unite = ( uniteGroups && nodes.size() == 2 );
3395     map< double, int > distIndMap;
3396     const SMDS_MeshNode* node = *nodes.begin();
3397     gp_Pnt P( node->X(), node->Y(), node->Z() );
3398
3399     // compare points, replace indices
3400
3401     list< int >::iterator ind1, ind2;
3402     list< list< int > >::iterator grpIt1, grpIt2;
3403     for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3404     {
3405       list< int >& indices1 = *grpIt1;
3406       grpIt2 = grpIt1;
3407       for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3408       {
3409         list< int >& indices2 = *grpIt2;
3410         for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3411         {
3412           gp_XYZ& p1 = myXYZ[ *ind1 ];
3413           ind2 = indices2.begin();
3414           while ( ind2 != indices2.end() )
3415           {
3416             gp_XYZ& p2 = myXYZ[ *ind2 ];
3417             //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3418             if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3419             {
3420               ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3421               list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3422               list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3423               for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3424               {
3425                 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3426                 myXYZ[ *ind2 ] = undefinedXYZ();
3427                 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3428               }
3429               ind2 = indices2.erase( ind2 );
3430             }
3431             else
3432               ind2++;
3433           }
3434         }
3435       }
3436       if ( unite ) { // sort indices using distIndMap
3437         for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3438         {
3439           ASSERT( isDefined( myXYZ[ *ind1 ] ));
3440           double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3441           distIndMap.insert( make_pair( dist, *ind1 ));
3442         }
3443       }
3444     }
3445     if ( unite ) { // put all sorted indices into the first group
3446       list< int >& g = groups.front();
3447       g.clear();
3448       map< double, int >::iterator dist_ind = distIndMap.begin();
3449       for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3450         g.push_back( dist_ind->second );
3451     }
3452   } // loop on myIdsOnBoundary
3453 }
3454
3455 //=======================================================================
3456 //function : makePolyElements
3457 //purpose  : prepare intermediate data to create Polygons and Polyhedrons
3458 //=======================================================================
3459
3460 void SMESH_Pattern::
3461   makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3462                    const bool                            toCreatePolygons,
3463                    const bool                            toCreatePolyedrs)
3464 {
3465   myPolyElemXYZIDs.clear();
3466   myPolyElems.clear();
3467   myPolyElems.reserve( myIdsOnBoundary.size() );
3468
3469   // make a set of refined elements
3470   TIDSortedElemSet avoidSet, elemSet;
3471   std::vector<const SMDS_MeshElement*>::iterator itv =  myElements.begin();
3472   for(; itv!=myElements.end(); itv++) {
3473     const SMDS_MeshElement* el = (*itv);
3474     avoidSet.insert( el );
3475   }
3476   //avoidSet.insert( myElements.begin(), myElements.end() );
3477
3478   map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3479
3480   if ( toCreatePolygons )
3481   {
3482     int lastFreeId = myXYZ.size();
3483
3484     // loop on links of refined elements
3485     indListIt = myIdsOnBoundary.begin();
3486     for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3487     {
3488       const TNodeSet & linkNodes = indListIt->first;
3489       if ( linkNodes.size() != 2 )
3490         continue; // skip face
3491       const SMDS_MeshNode* n1 = * linkNodes.begin();
3492       const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3493
3494       list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3495       if ( idGroups.empty() || idGroups.front().empty() )
3496         continue;
3497
3498       // find not refined face having n1-n2 link
3499
3500       while (true)
3501       {
3502         const SMDS_MeshElement* face =
3503           SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3504         if ( face )
3505         {
3506           avoidSet.insert ( face );
3507           myPolyElems.push_back( face );
3508
3509           // some links of <face> are split;
3510           // make list of xyz for <face>
3511           myPolyElemXYZIDs.push_back(TElemDef());
3512           TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3513           // loop on links of a <face>
3514           SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3515           int i = 0, nbNodes = face->NbNodes();
3516           vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3517           while ( nIt->more() )
3518             nodes[ i++ ] = smdsNode( nIt->next() );
3519           nodes[ i ] = nodes[ 0 ];
3520           for ( i = 0; i < nbNodes; ++i )
3521           {
3522             // look for point mapped on a link
3523             TNodeSet faceLinkNodes;
3524             faceLinkNodes.insert( nodes[ i ] );
3525             faceLinkNodes.insert( nodes[ i + 1 ] );
3526             if ( faceLinkNodes == linkNodes )
3527               nn_IdList = indListIt;
3528             else
3529               nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3530             // add face point ids
3531             faceNodeIds.push_back( ++lastFreeId );
3532             myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3533             if ( nn_IdList != myIdsOnBoundary.end() )
3534             {
3535               // there are points mapped on a link
3536               list< int >& mappedIds = nn_IdList->second.front();
3537               if ( isReversed( nodes[ i ], mappedIds ))
3538                 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3539               else
3540                 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3541             }
3542           } // loop on links of a <face>
3543         } // if ( face )
3544         else
3545           break;
3546       } // while (true)
3547
3548       if ( myIs2D && idGroups.size() > 1 ) {
3549
3550         // sew new elements on 2 refined elements sharing n1-n2 link
3551
3552         list< int >& idsOnLink = idGroups.front();
3553         // temporarily add ids of link nodes to idsOnLink
3554         bool rev = isReversed( n1, idsOnLink );
3555         for ( int i = 0; i < 2; ++i )
3556         {
3557           TNodeSet nodeSet;
3558           nodeSet.insert( i ? n2 : n1 );
3559           ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3560           list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3561           int nodeId = groups.front().front();
3562           bool append = i;
3563           if ( rev ) append = !append;
3564           if ( append )
3565             idsOnLink.push_back( nodeId );
3566           else
3567             idsOnLink.push_front( nodeId );
3568         }
3569         list< int >::iterator id = idsOnLink.begin();
3570         for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3571         {
3572           list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3573           list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3574           for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3575           {
3576             TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3577             // look for <id> in element definition
3578             TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3579             ASSERT ( idDef != pIdList->end() );
3580             // look for 2 neighbour ids of <id> in element definition
3581             for ( int prev = 0; prev < 2; ++prev ) {
3582               TElemDef::iterator idDef2 = idDef;
3583               if ( prev )
3584                 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3585               else
3586                 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3587               // look for idDef2 on a link starting from id
3588               list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3589               if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3590                 // insert ids located on link between <id> and <id2>
3591                 // into the element definition between idDef and idDef2
3592                 if ( prev )
3593                   for ( ; id2 != id; --id2 )
3594                     pIdList->insert( idDef, *id2 );
3595                 else {
3596                   list< int >::iterator id1 = id;
3597                   for ( ++id1, ++id2; id1 != id2; ++id1 )
3598                     pIdList->insert( idDef2, *id1 );
3599                 }
3600               }
3601             }
3602           }
3603         }
3604         // remove ids of link nodes
3605         idsOnLink.pop_front();
3606         idsOnLink.pop_back();
3607       }
3608     } // loop on myIdsOnBoundary
3609   } // if ( toCreatePolygons )
3610
3611   if ( toCreatePolyedrs )
3612   {
3613     // check volumes adjacent to the refined elements
3614     SMDS_VolumeTool volTool;
3615     vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3616     for ( ; refinedElem != myElements.end(); ++refinedElem )
3617     {
3618       // loop on nodes of refinedElem
3619       SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3620       while ( nIt->more() ) {
3621         const SMDS_MeshNode* node = smdsNode( nIt->next() );
3622         // loop on inverse elements of node
3623         SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3624         while ( eIt->more() )
3625         {
3626           const SMDS_MeshElement* elem = eIt->next();
3627           if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3628             continue; // skip faces or refined elements
3629           // add polyhedron definition
3630           myPolyhedronQuantities.push_back(vector<int> ());
3631           myPolyElemXYZIDs.push_back(TElemDef());
3632           vector<int>& quantity = myPolyhedronQuantities.back();
3633           TElemDef &   elemDef  = myPolyElemXYZIDs.back();
3634           // get definitions of new elements on volume faces
3635           bool makePoly = false;
3636           for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3637           {
3638             if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3639                                     volTool.NbFaceNodes( iF ),
3640                                     theNodes, elemDef, quantity))
3641               makePoly = true;
3642           }
3643           if ( makePoly )
3644             myPolyElems.push_back( elem );
3645           else {
3646             myPolyhedronQuantities.pop_back();
3647             myPolyElemXYZIDs.pop_back();
3648           }
3649         }
3650       }
3651     }
3652   }
3653 }
3654
3655 //=======================================================================
3656 //function : getFacesDefinition
3657 //purpose  : return faces definition for a volume face defined by theBndNodes
3658 //=======================================================================
3659
3660 bool SMESH_Pattern::
3661   getFacesDefinition(const SMDS_MeshNode**                 theBndNodes,
3662                      const int                             theNbBndNodes,
3663                      const vector< const SMDS_MeshNode* >& theNodes,
3664                      list< int >&                          theFaceDefs,
3665                      vector<int>&                          theQuantity)
3666 {
3667   bool makePoly = false;
3668 //   cout << "FROM FACE NODES: " <<endl;
3669 //   for ( int i = 0; i < theNbBndNodes; ++i )
3670 //     cout << theBndNodes[ i ];
3671
3672   set< const SMDS_MeshNode* > bndNodeSet;
3673   for ( int i = 0; i < theNbBndNodes; ++i )
3674     bndNodeSet.insert( theBndNodes[ i ]);
3675
3676   map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3677
3678   // make a set of all nodes on a face
3679   set< int > ids;
3680   if ( !myIs2D ) { // for 2D, merge only edges
3681     nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3682     if ( nn_IdList != myIdsOnBoundary.end() ) {
3683       makePoly = true;
3684       list< int > & faceIds = nn_IdList->second.front();
3685       ids.insert( faceIds.begin(), faceIds.end() );
3686     }
3687   }
3688   //bool hasIdsInFace = !ids.empty();
3689
3690   // add ids on links and bnd nodes
3691   int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3692   TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3693   for ( int iN = 0; iN < theNbBndNodes; ++iN )
3694   {
3695     // add id of iN-th bnd node
3696     TNodeSet nSet;
3697     nSet.insert( theBndNodes[ iN ] );
3698     nn_IdList = myIdsOnBoundary.find( nSet );
3699     int bndId = ++lastFreeId;
3700     if ( nn_IdList != myIdsOnBoundary.end() ) {
3701       bndId = nn_IdList->second.front().front();
3702       ids.insert( bndId );
3703     }
3704     else 
3705       myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3706     faceDef.push_back( bndId );
3707     // add ids on a link
3708     TNodeSet linkNodes;
3709     linkNodes.insert( theBndNodes[ iN ]);
3710     linkNodes.insert( theBndNodes[ iN + 1 == theNbBndNodes ? 0 : iN + 1 ]);
3711     nn_IdList = myIdsOnBoundary.find( linkNodes );
3712     if ( nn_IdList != myIdsOnBoundary.end() ) {
3713       makePoly = true;
3714       list< int > & linkIds = nn_IdList->second.front();
3715       ids.insert( linkIds.begin(), linkIds.end() );
3716       if ( isReversed( theBndNodes[ iN ], linkIds ))
3717         faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3718       else
3719         faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3720     }
3721   }
3722
3723   // find faces definition of new volumes
3724
3725   bool defsAdded = false;
3726   if ( !myIs2D ) { // for 2D, merge only edges
3727     SMDS_VolumeTool vol;
3728     set< TElemDef* > checkedVolDefs;
3729     set< int >::iterator id = ids.begin();
3730     for ( ; id != ids.end(); ++id )
3731     {
3732       // definitions of volumes sharing id
3733       list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3734       ASSERT( !defList.empty() );
3735       // loop on volume definitions
3736       list< TElemDef* >::iterator pIdList = defList.begin();
3737       for ( ; pIdList != defList.end(); ++pIdList)
3738       {
3739         if ( !checkedVolDefs.insert( *pIdList ).second )
3740           continue; // skip already checked volume definition
3741         vector< int > idVec;
3742         idVec.reserve( (*pIdList)->size() );
3743         idVec.insert( idVec.begin(), (*pIdList)->begin(), (*pIdList)->end() );
3744         // loop on face defs of a volume
3745         SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3746         if ( volType == SMDS_VolumeTool::UNKNOWN )
3747           continue;
3748         int nbFaces = vol.NbFaces( volType );
3749         for ( int iF = 0; iF < nbFaces; ++iF )
3750         {
3751           const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3752           int iN, nbN = vol.NbFaceNodes( volType, iF );
3753           // check if all nodes of a faces are in <ids>
3754           bool all = true;
3755           for ( iN = 0; iN < nbN && all; ++iN ) {
3756             int nodeId = idVec[ nodeInds[ iN ]];
3757             all = ( ids.find( nodeId ) != ids.end() );
3758           }
3759           if ( all ) {
3760             // store a face definition
3761             for ( iN = 0; iN < nbN; ++iN ) {
3762               theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3763             }
3764             theQuantity.push_back( nbN );
3765             defsAdded = true;
3766           }
3767         }
3768       }
3769     }
3770   }
3771   if ( !defsAdded ) {
3772     theQuantity.push_back( faceDef.size() );
3773     theFaceDefs.splice( theFaceDefs.end(), faceDef, faceDef.begin(), faceDef.end() );
3774   }
3775
3776   return makePoly;
3777 }
3778
3779 //=======================================================================
3780 //function : clearSubMesh
3781 //purpose  : 
3782 //=======================================================================
3783
3784 static bool clearSubMesh( SMESH_Mesh*         theMesh,
3785                           const TopoDS_Shape& theShape)
3786 {
3787   bool removed = false;
3788   if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3789   {
3790     if ( aSubMesh->GetSubMeshDS() ) {
3791       removed =
3792         aSubMesh->GetSubMeshDS()->NbElements() || aSubMesh->GetSubMeshDS()->NbNodes();
3793       aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3794     }
3795   }
3796   else {
3797     SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3798     if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3799     {
3800       SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3801       removed = eIt->more();
3802       while ( eIt->more() )
3803         aMeshDS->RemoveElement( eIt->next() );
3804       SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3805       removed = removed || nIt->more();
3806       while ( nIt->more() )
3807         aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3808     }
3809   }
3810   return removed;
3811 }
3812
3813 //=======================================================================
3814 //function : clearMesh
3815 //purpose  : clear mesh elements existing on myShape in theMesh
3816 //=======================================================================
3817
3818 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3819 {
3820
3821   if ( !myShape.IsNull() )
3822   {
3823     if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3824       TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3825       for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3826       {
3827         clearSubMesh( theMesh, it.Value() );
3828       }
3829     }
3830   }
3831 }
3832
3833 //=======================================================================
3834 //function : MakeMesh
3835 //purpose  : Create nodes and elements in <theMesh> using nodes
3836 //           coordinates computed by either of Apply...() methods
3837 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3838 //           it does not care of nodes and elements already existing on
3839 //           subshapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3840 //=======================================================================
3841
3842 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3843                              const bool  toCreatePolygons,
3844                              const bool  toCreatePolyedrs)
3845 {
3846   MESSAGE(" ::MakeMesh() " );
3847   if ( !myIsComputed )
3848     return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3849
3850   mergePoints( toCreatePolygons );
3851
3852   SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3853
3854   // clear elements and nodes existing on myShape
3855   clearMesh(theMesh);
3856
3857   bool onMeshElements = ( !myElements.empty() );
3858
3859   // Create missing nodes
3860
3861   vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3862   if ( onMeshElements )
3863   {
3864     nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3865     map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3866     for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3867       nodesVector[ i_node->first ] = i_node->second;
3868     }
3869     for ( int i = 0; i < myXYZ.size(); ++i ) {
3870       if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3871         nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3872                                              myXYZ[ i ].Y(),
3873                                              myXYZ[ i ].Z());
3874     }
3875   }
3876   else
3877   {
3878     nodesVector.resize( myPoints.size(), 0 );
3879
3880     // to find point index
3881     map< TPoint*, int > pointIndex;
3882     for ( int i = 0; i < myPoints.size(); i++ )
3883       pointIndex.insert( make_pair( & myPoints[ i ], i ));
3884
3885     // loop on sub-shapes of myShape: create nodes
3886     map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3887     for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3888     {
3889       TopoDS_Shape S;
3890       //SMESHDS_SubMesh * subMeshDS = 0;
3891       if ( !myShapeIDMap.IsEmpty() ) {
3892         S = myShapeIDMap( idPointIt->first );
3893         //subMeshDS = aMeshDS->MeshElements( S );
3894       }
3895       list< TPoint* > & points = idPointIt->second;
3896       list< TPoint* >::iterator pIt = points.begin();
3897       for ( ; pIt != points.end(); pIt++ )
3898       {
3899         TPoint* point = *pIt;
3900         int pIndex = pointIndex[ point ];
3901         if ( nodesVector [ pIndex ] )
3902           continue;
3903         SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3904                                                 point->myXYZ.Y(),
3905                                                 point->myXYZ.Z());
3906         nodesVector [ pIndex ] = node;
3907
3908         if ( true /*subMeshDS*/ ) {
3909           // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3910           switch ( S.ShapeType() ) {
3911           case TopAbs_VERTEX: {
3912             aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3913           }
3914           case TopAbs_EDGE: {
3915             aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3916           }
3917           case TopAbs_FACE: {
3918             aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3919                                     point->myUV.X(), point->myUV.Y() ); break;
3920           }
3921           default:
3922             aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3923           }
3924         }
3925       }
3926     }
3927   }
3928
3929   // create elements
3930
3931   if ( onMeshElements )
3932   {
3933     // prepare data to create poly elements
3934     makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3935
3936     // refine elements
3937     createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3938     // sew old and new elements
3939     createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3940   }
3941   else
3942   {
3943     createElements( theMesh, nodesVector, myElemPointIDs, myElements );
3944   }
3945
3946 //   const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
3947 //   map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
3948 //   for ( ; i_sm != sm.end(); i_sm++ )
3949 //   {
3950 //     cout << " SM " << i_sm->first << " ";
3951 //     TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
3952 //     //SMDS_ElemIteratorPtr GetElements();
3953 //     SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
3954 //     while ( nit->more() )
3955 //       cout << nit->next()->GetID() << " ";
3956 //     cout << endl;
3957 //   }
3958   return setErrorCode( ERR_OK );
3959 }
3960
3961 //=======================================================================
3962 //function : createElements
3963 //purpose  : add elements to the mesh
3964 //=======================================================================
3965
3966 void SMESH_Pattern::createElements(SMESH_Mesh*                            theMesh,
3967                                    const vector<const SMDS_MeshNode* >&   theNodesVector,
3968                                    const list< TElemDef > &               theElemNodeIDs,
3969                                    const vector<const SMDS_MeshElement*>& theElements)
3970 {
3971   SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3972   SMESH_MeshEditor editor( theMesh ); 
3973
3974   bool onMeshElements = !theElements.empty();
3975
3976   // shapes and groups theElements are on
3977   vector< int > shapeIDs;
3978   vector< list< SMESHDS_Group* > > groups;
3979   set< const SMDS_MeshNode* > shellNodes;
3980   if ( onMeshElements )
3981   {
3982     shapeIDs.resize( theElements.size() );
3983     groups.resize( theElements.size() );
3984     const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
3985     set<SMESHDS_GroupBase*>::const_iterator grIt;
3986     for ( int i = 0; i < theElements.size(); i++ )
3987     {
3988       shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
3989       for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
3990         SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
3991         if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
3992           groups[ i ].push_back( group );
3993       }
3994     }
3995     // get all nodes bound to shells because their SpacePosition is not set
3996     // by SMESHDS_Mesh::SetNodeInVolume()
3997     TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
3998     if ( !aMainShape.IsNull() ) {
3999       TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4000       for ( ; shellExp.More(); shellExp.Next() )
4001       {
4002         SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4003         if ( sm ) {
4004           SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4005           while ( nIt->more() )
4006             shellNodes.insert( nIt->next() );
4007         }
4008       }
4009     }
4010   }
4011    // nb new elements per a refined element
4012   int nbNewElemsPerOld = 1;
4013   if ( onMeshElements )
4014     nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4015
4016   bool is2d = myIs2D;
4017
4018   list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4019   list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4020   for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4021   {
4022     const TElemDef & elemNodeInd = *enIt;
4023     // retrieve nodes
4024     vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4025     TElemDef::const_iterator id = elemNodeInd.begin();
4026     int nbNodes;
4027     for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4028       if ( *id < theNodesVector.size() )
4029         nodes[ nbNodes++ ] = theNodesVector[ *id ];
4030       else
4031         nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4032     }
4033     // dim of refined elem
4034     int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4035     if ( onMeshElements ) {
4036       is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4037     }
4038     // add an element
4039     const SMDS_MeshElement* elem = 0;
4040     if ( is2d ) {
4041       switch ( nbNodes ) {
4042       case 3:
4043         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4044       case 4:
4045         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4046       case 6:
4047         if ( !onMeshElements ) {// create a quadratic face
4048           elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4049                                    nodes[4], nodes[5] ); break;
4050         } // else do not break but create a polygon
4051       case 8:
4052         if ( !onMeshElements ) {// create a quadratic face
4053           elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4054                                    nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4055         } // else do not break but create a polygon
4056       default:
4057         elem = aMeshDS->AddPolygonalFace( nodes );
4058       }
4059     }
4060     else {
4061       switch ( nbNodes ) {
4062       case 4:
4063         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4064       case 5:
4065         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4066                                    nodes[4] ); break;
4067       case 6:
4068         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4069                                    nodes[4], nodes[5] ); break;
4070       case 8:
4071         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4072                                    nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4073       default:
4074         elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4075       }
4076     }
4077     // set element on a shape
4078     if ( elem && onMeshElements ) // applied to mesh elements
4079     {
4080       int shapeID = shapeIDs[ elemIndex ];
4081       if ( shapeID > 0 ) {
4082         aMeshDS->SetMeshElementOnShape( elem, shapeID );
4083         // set nodes on a shape
4084         TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4085         if ( S.ShapeType() == TopAbs_SOLID ) {
4086           TopoDS_Iterator shellIt( S );
4087           if ( shellIt.More() )
4088             shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4089         }
4090         SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4091         while ( noIt->more() ) {
4092           SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4093           if (!node->GetPosition()->GetShapeId() &&
4094               shellNodes.find( node ) == shellNodes.end() ) {
4095             if ( S.ShapeType() == TopAbs_FACE )
4096               aMeshDS->SetNodeOnFace( node, shapeID );
4097             else {
4098               aMeshDS->SetNodeInVolume( node, shapeID );
4099               shellNodes.insert( node );
4100             }
4101           }
4102         }
4103       }
4104       // add elem in groups
4105       list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4106       for ( ; g != groups[ elemIndex ].end(); ++g )
4107         (*g)->SMDSGroup().Add( elem );
4108     }
4109     if ( elem && !myShape.IsNull() ) // applied to shape
4110       aMeshDS->SetMeshElementOnShape( elem, myShape );
4111   }
4112
4113   // make that SMESH_subMesh::_computeState == COMPUTE_OK
4114   // so that operations with hypotheses will erase the mesh being built
4115
4116   SMESH_subMesh * subMesh;
4117   if ( !myShape.IsNull() ) {
4118     subMesh = theMesh->GetSubMesh( myShape );
4119     if ( subMesh )
4120       subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4121   }
4122   if ( onMeshElements ) {
4123     list< int > elemIDs;
4124     for ( int i = 0; i < theElements.size(); i++ )
4125     {
4126       subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4127       if ( subMesh )
4128         subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4129
4130       elemIDs.push_back( theElements[ i ]->GetID() );
4131     }
4132     // remove refined elements
4133     editor.Remove( elemIDs, false );
4134   }
4135 }
4136
4137 //=======================================================================
4138 //function : isReversed
4139 //purpose  : check xyz ids order in theIdsList taking into account
4140 //           theFirstNode on a link
4141 //=======================================================================
4142
4143 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4144                                const list< int >&   theIdsList) const
4145 {
4146   if ( theIdsList.size() < 2 )
4147     return false;
4148
4149   gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4150   gp_Pnt P[2];
4151   list<int>::const_iterator id = theIdsList.begin();
4152   for ( int i = 0; i < 2; ++i, ++id ) {
4153     if ( *id < myXYZ.size() )
4154       P[ i ] = myXYZ[ *id ];
4155     else {
4156       map< int, const SMDS_MeshNode*>::const_iterator i_n;
4157       i_n = myXYZIdToNodeMap.find( *id );
4158       ASSERT( i_n != myXYZIdToNodeMap.end() );
4159       const SMDS_MeshNode* n = i_n->second;
4160       P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4161     }
4162   }
4163   return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4164 }
4165
4166
4167 //=======================================================================
4168 //function : arrangeBoundaries
4169 //purpose  : if there are several wires, arrange boundaryPoints so that
4170 //           the outer wire goes first and fix inner wires orientation
4171 //           update myKeyPointIDs to correspond to the order of key-points
4172 //           in boundaries; sort internal boundaries by the nb of key-points
4173 //=======================================================================
4174
4175 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4176 {
4177   typedef list< list< TPoint* > >::iterator TListOfListIt;
4178   TListOfListIt bndIt;
4179   list< TPoint* >::iterator pIt;
4180
4181   int nbBoundaries = boundaryList.size();
4182   if ( nbBoundaries > 1 )
4183   {
4184     // sort boundaries by nb of key-points
4185     if ( nbBoundaries > 2 )
4186     {
4187       // move boundaries in tmp list
4188       list< list< TPoint* > > tmpList; 
4189       tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4190       // make a map nb-key-points to boundary-position-in-tmpList,
4191       // boundary-positions get ordered in it
4192       typedef map< int, TListOfListIt > TNbKpBndPosMap;
4193       TNbKpBndPosMap nbKpBndPosMap;
4194       bndIt = tmpList.begin();
4195       list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4196       for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4197         int nb = *nbKpIt * nbBoundaries;
4198         while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4199           nb++;
4200         nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4201       }
4202       // move boundaries back to boundaryList
4203       TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4204       for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4205         TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4206         TListOfListIt bndPos1 = bndPos2++;
4207         boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4208       }
4209     }
4210
4211     // Look for the outer boundary: the one with the point with the least X
4212     double leastX = DBL_MAX;
4213     TListOfListIt outerBndPos;
4214     for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4215     {
4216       list< TPoint* >& boundary = (*bndIt);
4217       for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4218       {
4219         TPoint* point = *pIt;
4220         if ( point->myInitXYZ.X() < leastX ) {
4221           leastX = point->myInitXYZ.X();
4222           outerBndPos = bndIt;
4223         }
4224       }
4225     }
4226
4227     if ( outerBndPos != boundaryList.begin() )
4228       boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4229
4230   } // if nbBoundaries > 1
4231                  
4232   // Check boundaries orientation and re-fill myKeyPointIDs
4233
4234   set< TPoint* > keyPointSet;
4235   list< int >::iterator kpIt = myKeyPointIDs.begin();
4236   for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4237     keyPointSet.insert( & myPoints[ *kpIt ]);
4238   myKeyPointIDs.clear();
4239
4240   // update myNbKeyPntInBoundary also
4241   list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4242
4243   for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4244   {
4245     // find the point with the least X
4246     double leastX = DBL_MAX;
4247     list< TPoint* >::iterator xpIt;
4248     list< TPoint* >& boundary = (*bndIt);
4249     for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4250     {
4251       TPoint* point = *pIt;
4252       if ( point->myInitXYZ.X() < leastX ) {
4253         leastX = point->myInitXYZ.X();
4254         xpIt = pIt;
4255       }
4256     }
4257     // find points next to the point with the least X
4258     TPoint* p = *xpIt, *pPrev, *pNext;
4259     if ( p == boundary.front() )
4260       pPrev = *(++boundary.rbegin());
4261     else {
4262       xpIt--;
4263       pPrev = *xpIt;
4264       xpIt++;
4265     }
4266     if ( p == boundary.back() )
4267       pNext = *(++boundary.begin());
4268     else {
4269       xpIt++;
4270       pNext = *xpIt;
4271     }
4272     // vectors of boundary direction near <p>
4273     gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4274     double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4275     if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4276       double yPrev = v1.Y() / sqrt( sqMag1 );
4277       double yNext = v2.Y() / sqrt( sqMag2 );
4278       double sumY = yPrev + yNext;
4279       bool reverse;
4280       if ( bndIt == boundaryList.begin() ) // outer boundary
4281         reverse = sumY > 0;
4282       else
4283         reverse = sumY < 0;
4284       if ( reverse )
4285         boundary.reverse();
4286     }
4287
4288     // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4289     (*nbKpIt) = 0; // count nb of key-points again
4290     pIt = boundary.begin();
4291     for ( ; pIt != boundary.end(); pIt++)
4292     {
4293       TPoint* point = *pIt;
4294       if ( keyPointSet.find( point ) == keyPointSet.end() )
4295         continue;
4296       // find an index of a keypoint
4297       int index = 0;
4298       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4299       for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4300         if ( &(*pVecIt) == point )
4301           break;
4302       myKeyPointIDs.push_back( index );
4303       (*nbKpIt)++;
4304     }
4305     myKeyPointIDs.pop_back(); // remove the first key-point from the back
4306     (*nbKpIt)--;
4307
4308   } // loop on a list of boundaries
4309
4310   ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4311 }
4312
4313 //=======================================================================
4314 //function : findBoundaryPoints
4315 //purpose  : if loaded from file, find points to map on edges and faces and
4316 //           compute their parameters
4317 //=======================================================================
4318
4319 bool SMESH_Pattern::findBoundaryPoints()
4320 {
4321   if ( myIsBoundaryPointsFound ) return true;
4322
4323   MESSAGE(" findBoundaryPoints() ");
4324
4325   myNbKeyPntInBoundary.clear();
4326
4327   if ( myIs2D )
4328   {
4329     set< TPoint* > pointsInElems;
4330
4331     // Find free links of elements:
4332     // put links of all elements in a set and remove links encountered twice
4333
4334     typedef pair< TPoint*, TPoint*> TLink;
4335     set< TLink > linkSet;
4336     list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4337     for ( ; epIt != myElemPointIDs.end(); epIt++ )
4338     {
4339       TElemDef & elemPoints = *epIt;
4340       TElemDef::iterator pIt = elemPoints.begin();
4341       int prevP = elemPoints.back();
4342       for ( ; pIt != elemPoints.end(); pIt++ ) {
4343         TPoint* p1 = & myPoints[ prevP ];
4344         TPoint* p2 = & myPoints[ *pIt ];
4345         TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4346         ASSERT( link.first != link.second );
4347         pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4348         if ( !itUniq.second )
4349           linkSet.erase( itUniq.first );
4350         prevP = *pIt;
4351
4352         pointsInElems.insert( p1 );
4353       }
4354     }
4355     // Now linkSet contains only free links,
4356     // find the points order that they have in boundaries
4357
4358     // 1. make a map of key-points
4359     set< TPoint* > keyPointSet;
4360     list< int >::iterator kpIt = myKeyPointIDs.begin();
4361     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4362       keyPointSet.insert( & myPoints[ *kpIt ]);
4363
4364     // 2. chain up boundary points
4365     list< list< TPoint* > > boundaryList;
4366     boundaryList.push_back( list< TPoint* >() );
4367     list< TPoint* > * boundary = & boundaryList.back();
4368
4369     TPoint *point1, *point2, *keypoint1;
4370     kpIt = myKeyPointIDs.begin();
4371     point1 = keypoint1 = & myPoints[ *kpIt++ ];
4372     // loop on free links: look for the next point
4373     int iKeyPoint = 0;
4374     set< TLink >::iterator lIt = linkSet.begin();
4375     while ( lIt != linkSet.end() )
4376     {
4377       if ( (*lIt).first == point1 )
4378         point2 = (*lIt).second;
4379       else if ( (*lIt).second == point1 )
4380         point2 = (*lIt).first;
4381       else {
4382         lIt++;
4383         continue;
4384       }
4385       linkSet.erase( lIt );
4386       lIt = linkSet.begin();
4387
4388       if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4389       {
4390         boundary->push_back( point2 );
4391       }
4392       else // a key-point found
4393       {
4394         keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4395         iKeyPoint++;
4396         if ( point2 != keypoint1 ) // its not the boundary end
4397         {
4398           boundary->push_back( point2 );
4399         }
4400         else  // the boundary end reached
4401         {
4402           boundary->push_front( keypoint1 );
4403           boundary->push_back( keypoint1 );
4404           myNbKeyPntInBoundary.push_back( iKeyPoint );
4405           if ( keyPointSet.empty() )
4406             break; // all boundaries containing key-points are found
4407
4408           // prepare to search for the next boundary
4409           boundaryList.push_back( list< TPoint* >() );
4410           boundary = & boundaryList.back();
4411           point2 = keypoint1 = (*keyPointSet.begin());
4412         }
4413       }
4414       point1 = point2;
4415     } // loop on the free links set
4416
4417     if ( boundary->empty() ) {
4418       MESSAGE(" a separate key-point");
4419       return setErrorCode( ERR_READ_BAD_KEY_POINT );
4420     }
4421
4422     // if there are several wires, arrange boundaryPoints so that
4423     // the outer wire goes first and fix inner wires orientation;
4424     // sort myKeyPointIDs to correspond to the order of key-points
4425     // in boundaries
4426     arrangeBoundaries( boundaryList );
4427
4428     // Find correspondence shape ID - points,
4429     // compute points parameter on edge
4430
4431     keyPointSet.clear();
4432     for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4433       keyPointSet.insert( & myPoints[ *kpIt ]);
4434
4435     set< TPoint* > edgePointSet; // to find in-face points
4436     int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4437     int edgeID = myKeyPointIDs.size() + 1;
4438
4439     list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4440     for ( ; bndIt != boundaryList.end(); bndIt++ )
4441     {
4442       boundary = & (*bndIt);
4443       double edgeLength = 0;
4444       list< TPoint* >::iterator pIt = boundary->begin();
4445       getShapePoints( edgeID ).push_back( *pIt );
4446       getShapePoints( vertexID++ ).push_back( *pIt );
4447       for ( pIt++; pIt != boundary->end(); pIt++)
4448       {
4449         list< TPoint* > & edgePoints = getShapePoints( edgeID );
4450         TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4451         TPoint* point = *pIt;
4452         edgePointSet.insert( point );
4453         if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4454         {
4455           edgePoints.push_back( point );
4456           edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4457           point->myInitU = edgeLength;
4458         }
4459         else // a key-point
4460         {
4461           // treat points on the edge which ends up: compute U [0,1]
4462           edgePoints.push_back( point );
4463           if ( edgePoints.size() > 2 ) {
4464             edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4465             list< TPoint* >::iterator epIt = edgePoints.begin();
4466             for ( ; epIt != edgePoints.end(); epIt++ )
4467               (*epIt)->myInitU /= edgeLength;
4468           }
4469           // begin the next edge treatment
4470           edgeLength = 0;
4471           edgeID++;
4472           if ( point != boundary->front() ) { // not the first key-point again
4473             getShapePoints( edgeID ).push_back( point );
4474             getShapePoints( vertexID++ ).push_back( point );
4475           }
4476         }
4477       }
4478     }
4479
4480     // find in-face points
4481     list< TPoint* > & facePoints = getShapePoints( edgeID );
4482     vector< TPoint >::iterator pVecIt = myPoints.begin();
4483     for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4484       TPoint* point = &(*pVecIt);
4485       if ( edgePointSet.find( point ) == edgePointSet.end() &&
4486           pointsInElems.find( point ) != pointsInElems.end())
4487         facePoints.push_back( point );
4488     }
4489
4490   } // 2D case
4491
4492   else // 3D case
4493   {
4494     // bind points to shapes according to point parameters
4495     vector< TPoint >::iterator pVecIt = myPoints.begin();
4496     for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4497       TPoint* point = &(*pVecIt);
4498       int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4499       getShapePoints( shapeID ).push_back( point );
4500       // detect key-points
4501       if ( SMESH_Block::IsVertexID( shapeID ))
4502         myKeyPointIDs.push_back( i );        
4503     }
4504   }
4505
4506   myIsBoundaryPointsFound = true;
4507   return myIsBoundaryPointsFound;
4508 }
4509
4510 //=======================================================================
4511 //function : Clear
4512 //purpose  : clear fields
4513 //=======================================================================
4514
4515 void SMESH_Pattern::Clear()
4516 {
4517   myIsComputed = myIsBoundaryPointsFound = false;
4518
4519   myPoints.clear();
4520   myKeyPointIDs.clear();
4521   myElemPointIDs.clear();
4522   myShapeIDToPointsMap.clear();
4523   myShapeIDMap.Clear();
4524   myShape.Nullify();
4525   myNbKeyPntInBoundary.clear();
4526 }
4527
4528 //=======================================================================
4529 //function : setShapeToMesh
4530 //purpose  : set a shape to be meshed. Return True if meshing is possible
4531 //=======================================================================
4532
4533 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4534 {
4535   if ( !IsLoaded() ) {
4536     MESSAGE( "Pattern not loaded" );
4537     return setErrorCode( ERR_APPL_NOT_LOADED );
4538   }
4539
4540   TopAbs_ShapeEnum aType = theShape.ShapeType();
4541   bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4542   if ( !dimOk ) {
4543     MESSAGE( "Pattern dimention mismatch" );
4544     return setErrorCode( ERR_APPL_BAD_DIMENTION );
4545   }
4546
4547   // check if a face is closed
4548   int nbNodeOnSeamEdge = 0;
4549   if ( myIs2D ) {
4550     TopoDS_Face face = TopoDS::Face( theShape );
4551     TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4552     for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() )
4553       if ( BRep_Tool::IsClosed( TopoDS::Edge( eExp.Current() ), face ))
4554         nbNodeOnSeamEdge = 2;
4555   }
4556     
4557   // check nb of vertices
4558   TopTools_IndexedMapOfShape vMap;
4559   TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4560   if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4561     MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4562     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4563   }
4564
4565   myElements.clear(); // not refine elements
4566   myElemXYZIDs.clear();
4567
4568   myShapeIDMap.Clear();
4569   myShape = theShape;
4570   return true;
4571 }
4572
4573 //=======================================================================
4574 //function : GetMappedPoints
4575 //purpose  : Return nodes coordinates computed by Apply() method
4576 //=======================================================================
4577
4578 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4579 {
4580   thePoints.clear();
4581   if ( !myIsComputed )
4582     return false;
4583
4584   if ( myElements.empty() ) { // applied to shape
4585     vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4586     for ( ; pVecIt != myPoints.end(); pVecIt++ )
4587       thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4588   }
4589   else { // applied to mesh elements
4590     const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4591     vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4592     for ( ; xyz != myXYZ.end(); ++xyz )
4593       if ( !isDefined( *xyz ))
4594         thePoints.push_back( definedXYZ );
4595       else
4596         thePoints.push_back( & (*xyz) );
4597   }
4598   return !thePoints.empty();
4599 }
4600
4601
4602 //=======================================================================
4603 //function : GetPoints
4604 //purpose  : Return nodes coordinates of the pattern
4605 //=======================================================================
4606
4607 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4608 {
4609   thePoints.clear();
4610
4611   if ( !IsLoaded() )
4612     return false;
4613
4614   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4615   for ( ; pVecIt != myPoints.end(); pVecIt++ )
4616     thePoints.push_back( & (*pVecIt).myInitXYZ );
4617
4618   return ( thePoints.size() > 0 );
4619 }
4620
4621 //=======================================================================
4622 //function : getShapePoints
4623 //purpose  : return list of points located on theShape
4624 //=======================================================================
4625
4626 list< SMESH_Pattern::TPoint* > &
4627   SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4628 {
4629   int aShapeID;
4630   if ( !myShapeIDMap.Contains( theShape ))
4631     aShapeID = myShapeIDMap.Add( theShape );
4632   else
4633     aShapeID = myShapeIDMap.FindIndex( theShape );
4634
4635   return myShapeIDToPointsMap[ aShapeID ];
4636 }
4637
4638 //=======================================================================
4639 //function : getShapePoints
4640 //purpose  : return list of points located on the shape
4641 //=======================================================================
4642
4643 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4644 {
4645   return myShapeIDToPointsMap[ theShapeID ];
4646 }
4647
4648 //=======================================================================
4649 //function : DumpPoints
4650 //purpose  : Debug
4651 //=======================================================================
4652
4653 void SMESH_Pattern::DumpPoints() const
4654 {
4655 #ifdef _DEBUG_
4656   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4657   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4658     cout << i << ": " << *pVecIt;
4659 #endif
4660 }
4661
4662 //=======================================================================
4663 //function : TPoint()
4664 //purpose  : 
4665 //=======================================================================
4666
4667 SMESH_Pattern::TPoint::TPoint()
4668 {
4669 #ifdef _DEBUG_
4670   myInitXYZ.SetCoord(0,0,0);
4671   myInitUV.SetCoord(0.,0.);
4672   myInitU = 0;
4673   myXYZ.SetCoord(0,0,0);
4674   myUV.SetCoord(0.,0.);
4675   myU = 0;
4676 #endif
4677 }
4678
4679 //=======================================================================
4680 //function : operator <<
4681 //purpose  : 
4682 //=======================================================================
4683
4684 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4685 {
4686   gp_XYZ xyz = p.myInitXYZ;
4687   OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4688   gp_XY xy = p.myInitUV;
4689   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
4690   double u = p.myInitU;
4691   OS << " u( " <<  u << " )) " << &p << endl;
4692   xyz = p.myXYZ.XYZ();
4693   OS << "\t    ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4694   xy = p.myUV;
4695   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
4696   u = p.myU;
4697   OS << " u( " <<  u << " ))" << endl;
4698   
4699   return OS;
4700 }