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