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