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