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