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