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