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