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