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