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