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