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