Back to index

salome-smesh  6.5.0
SMESH_Pattern.cxx
Go to the documentation of this file.
00001 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00002 //
00003 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
00004 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
00005 //
00006 // This library is free software; you can redistribute it and/or
00007 // modify it under the terms of the GNU Lesser General Public
00008 // License as published by the Free Software Foundation; either
00009 // version 2.1 of the License.
00010 //
00011 // This library is distributed in the hope that it will be useful,
00012 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00013 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014 // Lesser General Public License for more details.
00015 //
00016 // You should have received a copy of the GNU Lesser General Public
00017 // License along with this library; if not, write to the Free Software
00018 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00019 //
00020 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00021 //
00022 
00023 // File      : SMESH_Pattern.hxx
00024 // Created   : Mon Aug  2 10:30:00 2004
00025 // Author    : Edward AGAPOV (eap)
00026 
00027 #include "SMESH_Pattern.hxx"
00028 
00029 #include <BRepAdaptor_Curve.hxx>
00030 #include <BRepTools.hxx>
00031 #include <BRepTools_WireExplorer.hxx>
00032 #include <BRep_Tool.hxx>
00033 #include <Bnd_Box.hxx>
00034 #include <Bnd_Box2d.hxx>
00035 #include <ElSLib.hxx>
00036 #include <Extrema_ExtPC.hxx>
00037 #include <Extrema_GenExtPS.hxx>
00038 #include <Extrema_POnSurf.hxx>
00039 #include <Geom2d_Curve.hxx>
00040 #include <GeomAdaptor_Surface.hxx>
00041 #include <Geom_Curve.hxx>
00042 #include <Geom_Surface.hxx>
00043 #include <Precision.hxx>
00044 #include <TopAbs_ShapeEnum.hxx>
00045 #include <TopExp.hxx>
00046 #include <TopExp_Explorer.hxx>
00047 #include <TopLoc_Location.hxx>
00048 #include <TopTools_ListIteratorOfListOfShape.hxx>
00049 #include <TopoDS.hxx>
00050 #include <TopoDS_Edge.hxx>
00051 #include <TopoDS_Face.hxx>
00052 #include <TopoDS_Iterator.hxx>
00053 #include <TopoDS_Shell.hxx>
00054 #include <TopoDS_Vertex.hxx>
00055 #include <TopoDS_Wire.hxx>
00056 #include <gp_Ax2.hxx>
00057 #include <gp_Lin2d.hxx>
00058 #include <gp_Pnt2d.hxx>
00059 #include <gp_Trsf.hxx>
00060 #include <gp_XY.hxx>
00061 #include <gp_XYZ.hxx>
00062 
00063 #include "SMDS_EdgePosition.hxx"
00064 #include "SMDS_FacePosition.hxx"
00065 #include "SMDS_MeshElement.hxx"
00066 #include "SMDS_MeshFace.hxx"
00067 #include "SMDS_MeshNode.hxx"
00068 #include "SMDS_VolumeTool.hxx"
00069 #include "SMESHDS_Group.hxx"
00070 #include "SMESHDS_Mesh.hxx"
00071 #include "SMESHDS_SubMesh.hxx"
00072 #include "SMESH_Block.hxx"
00073 #include "SMESH_Mesh.hxx"
00074 #include "SMESH_MesherHelper.hxx"
00075 #include "SMESH_subMesh.hxx"
00076 
00077 #include <Basics_OCCTVersion.hxx>
00078 
00079 #include <Basics_Utils.hxx>
00080 #include "utilities.h"
00081 
00082 using namespace std;
00083 
00084 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
00085 
00086 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
00087 
00088 //=======================================================================
00089 //function : SMESH_Pattern
00090 //purpose  : 
00091 //=======================================================================
00092 
00093 SMESH_Pattern::SMESH_Pattern ()
00094 {
00095 }
00096 //=======================================================================
00097 //function : getInt
00098 //purpose  : 
00099 //=======================================================================
00100 
00101 static inline int getInt( const char * theSring )
00102 {
00103   if ( *theSring < '0' || *theSring > '9' )
00104     return -1;
00105 
00106   char *ptr;
00107   int val = strtol( theSring, &ptr, 10 );
00108   if ( ptr == theSring ||
00109       // there must not be neither '.' nor ',' nor 'E' ...
00110       (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
00111     return -1;
00112 
00113   return val;
00114 }
00115 
00116 //=======================================================================
00117 //function : getDouble
00118 //purpose  : 
00119 //=======================================================================
00120 
00121 static inline double getDouble( const char * theSring )
00122 {
00123   char *ptr;
00124   return strtod( theSring, &ptr );
00125 }
00126 
00127 //=======================================================================
00128 //function : readLine
00129 //purpose  : Put token starting positions in theFields until '\n' or '\0'
00130 //           Return the number of the found tokens
00131 //=======================================================================
00132 
00133 static int readLine (list <const char*> & theFields,
00134                      const char*        & theLineBeg,
00135                      const bool           theClearFields )
00136 {
00137   if ( theClearFields )
00138     theFields.clear();
00139 
00140   //  algo:
00141   /*  loop                                                       */
00142   /*    switch ( symbol ) {                                      */
00143   /*    case white-space:                                        */
00144   /*      look for a non-space symbol;                           */
00145   /*    case string-end:                                         */
00146   /*    case line-end:                                           */
00147   /*      exit;                                                  */
00148   /*    case comment beginning:                                  */
00149   /*      skip all till a line-end;                              */
00150   /*    case a number                                            */
00151   /*      put its position in theFields, skip till a white-space;*/
00152   /*    default:                                                 */
00153   /*      abort;                                                 */
00154   /*  till line-end                                              */
00155 
00156   int nbRead = 0;
00157   bool stopReading = false;
00158   do {
00159     bool goOn = true;
00160     bool isNumber = false;
00161     switch ( *theLineBeg )
00162     {
00163     case ' ':  // white space
00164     case '\t': // tab
00165     case 13:   // ^M
00166       break;
00167 
00168     case '\n': // a line ends
00169       stopReading = ( nbRead > 0 );
00170       break;
00171 
00172     case '!':  // comment
00173       do theLineBeg++;
00174       while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
00175       goOn = false;
00176       break;
00177 
00178     case '\0': // file ends
00179       return nbRead;
00180 
00181     case '-': // real number
00182     case '+':
00183     case '.':
00184       isNumber = true;
00185     default: // data
00186       isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
00187       if ( isNumber ) {
00188         theFields.push_back( theLineBeg );
00189         nbRead++;
00190         do theLineBeg++;
00191         while (*theLineBeg != ' ' &&
00192                *theLineBeg != '\n' &&
00193                *theLineBeg != '\0');
00194         goOn = false;
00195       }
00196       else
00197         return 0; // incorrect file format
00198     }
00199 
00200     if ( goOn )
00201       theLineBeg++;
00202 
00203   } while ( !stopReading );
00204 
00205   return nbRead;
00206 }
00207 
00208 //=======================================================================
00209 //function : Load
00210 //purpose  : Load a pattern from <theFile>
00211 //=======================================================================
00212 
00213 bool SMESH_Pattern::Load (const char* theFileContents)
00214 {
00215   MESSAGE("Load( file ) ");
00216 
00217   Kernel_Utils::Localizer loc;
00218   
00219   // file structure:
00220 
00221   // ! This is a comment
00222   // NB_POINTS               ! 1 integer - the number of points in the pattern.
00223   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
00224   //   X2 Y2 [Z2]            ! the pattern dimention is defined by the number of coordinates
00225   //   ...
00226   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
00227   // ! elements description goes after all
00228   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
00229   // ...
00230 
00231   Clear();
00232 
00233   const char* lineBeg = theFileContents;
00234   list <const char*> fields;
00235   const bool clearFields = true;
00236 
00237   // NB_POINTS               ! 1 integer - the number of points in the pattern.
00238 
00239   if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
00240     MESSAGE("Error reading NB_POINTS");
00241     return setErrorCode( ERR_READ_NB_POINTS );
00242   }
00243   int nbPoints = getInt( fields.front() );
00244 
00245   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
00246 
00247   // read the first point coordinates to define pattern dimention
00248   int dim = readLine( fields, lineBeg, clearFields );
00249   if ( dim == 2 )
00250     myIs2D = true;
00251   else if ( dim == 3 )
00252     myIs2D = false;
00253   else {
00254     MESSAGE("Error reading points: wrong nb of coordinates");
00255     return setErrorCode( ERR_READ_POINT_COORDS );
00256   }
00257   if ( nbPoints <= dim ) {
00258     MESSAGE(" Too few points ");
00259     return setErrorCode( ERR_READ_TOO_FEW_POINTS );
00260   }
00261 
00262   // read the rest points
00263   int iPoint;
00264   for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
00265     if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
00266       MESSAGE("Error reading  points : wrong nb of coordinates ");
00267       return setErrorCode( ERR_READ_POINT_COORDS );
00268     }
00269   // store point coordinates
00270   myPoints.resize( nbPoints );
00271   list <const char*>::iterator fIt = fields.begin();
00272   for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
00273   {
00274     TPoint & p = myPoints[ iPoint ];
00275     for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
00276     {
00277       double coord = getDouble( *fIt );
00278       if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
00279         MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
00280         Clear();
00281         return setErrorCode( ERR_READ_3D_COORD );
00282       }
00283       p.myInitXYZ.SetCoord( iCoord, coord );
00284       if ( myIs2D )
00285         p.myInitUV.SetCoord( iCoord, coord );
00286     }
00287   }
00288 
00289   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
00290   if ( myIs2D )
00291   {
00292     if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
00293       MESSAGE("Error: missing key-points");
00294       Clear();
00295       return setErrorCode( ERR_READ_NO_KEYPOINT );
00296     }
00297     set<int> idSet;
00298     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
00299     {
00300       int pointIndex = getInt( *fIt );
00301       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
00302         MESSAGE("Error: invalid point index " << pointIndex );
00303         Clear();
00304         return setErrorCode( ERR_READ_BAD_INDEX );
00305       }
00306       if ( idSet.insert( pointIndex ).second ) // unique?
00307         myKeyPointIDs.push_back( pointIndex );
00308     }
00309   }
00310 
00311   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
00312 
00313   while ( readLine( fields, lineBeg, clearFields ))
00314   {
00315     myElemPointIDs.push_back( TElemDef() );
00316     TElemDef& elemPoints = myElemPointIDs.back();
00317     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
00318     {
00319       int pointIndex = getInt( *fIt );
00320       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
00321         MESSAGE("Error: invalid point index " << pointIndex );
00322         Clear();
00323         return setErrorCode( ERR_READ_BAD_INDEX );
00324       }
00325       elemPoints.push_back( pointIndex );
00326     }
00327     // check the nb of nodes in element
00328     bool Ok = true;
00329     switch ( elemPoints.size() ) {
00330     case 3: if ( !myIs2D ) Ok = false; break;
00331     case 4: break;
00332     case 5:
00333     case 6:
00334     case 8: if ( myIs2D ) Ok = false; break;
00335     default: Ok = false;
00336     }
00337     if ( !Ok ) {
00338       MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
00339       Clear();
00340       return setErrorCode( ERR_READ_ELEM_POINTS );
00341     }
00342   }
00343   if ( myElemPointIDs.empty() ) {
00344     MESSAGE("Error: no elements");
00345     Clear();
00346     return setErrorCode( ERR_READ_NO_ELEMS );
00347   }
00348 
00349   findBoundaryPoints(); // sort key-points
00350 
00351   return setErrorCode( ERR_OK );
00352 }
00353 
00354 //=======================================================================
00355 //function : Save
00356 //purpose  : Save the loaded pattern into the file <theFileName>
00357 //=======================================================================
00358 
00359 bool SMESH_Pattern::Save (ostream& theFile)
00360 {
00361   MESSAGE(" ::Save(file) " );
00362   
00363   Kernel_Utils::Localizer loc;
00364     
00365   if ( !IsLoaded() ) {
00366     MESSAGE(" Pattern not loaded ");
00367     return setErrorCode( ERR_SAVE_NOT_LOADED );
00368   }
00369 
00370   theFile << "!!! SALOME Mesh Pattern file" << endl;
00371   theFile << "!!!" << endl;
00372   theFile << "!!! Nb of points:" << endl;
00373   theFile << myPoints.size() << endl;
00374 
00375   // point coordinates
00376   const int width = 8;
00377 //  theFile.width( 8 );
00378 //  theFile.setf(ios::fixed);// use 123.45 floating notation
00379 //  theFile.setf(ios::right);
00380 //  theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
00381 //   theFile.setf(ios::showpoint); // do not show trailing zeros
00382   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
00383   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
00384     const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
00385     theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
00386     if ( !myIs2D ) theFile  << " " << setw( width ) << xyz.Z();
00387     theFile  << "  !- " << i << endl; // point id to ease reading by a human being
00388   }
00389   // key-points
00390   if ( myIs2D ) {
00391     theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
00392     list< int >::const_iterator kpIt = myKeyPointIDs.begin();
00393     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
00394       theFile << " " << *kpIt;
00395     if ( !myKeyPointIDs.empty() )
00396       theFile << endl;
00397   }
00398   // elements
00399   theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
00400   list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
00401   for ( ; epIt != myElemPointIDs.end(); epIt++ )
00402   {
00403     const TElemDef & elemPoints = *epIt;
00404     TElemDef::const_iterator iIt = elemPoints.begin();
00405     for ( ; iIt != elemPoints.end(); iIt++ )
00406       theFile << " " << *iIt;
00407     theFile << endl;
00408   }
00409 
00410   theFile << endl;
00411 
00412   return setErrorCode( ERR_OK );
00413 }
00414 
00415 //=======================================================================
00416 //function : sortBySize
00417 //purpose  : sort theListOfList by size
00418 //=======================================================================
00419 
00420 template<typename T> struct TSizeCmp {
00421   bool operator ()( const list < T > & l1, const list < T > & l2 )
00422     const { return l1.size() < l2.size(); }
00423 };
00424 
00425 template<typename T> void sortBySize( list< list < T > > & theListOfList )
00426 {
00427   if ( theListOfList.size() > 2 ) {
00428     TSizeCmp< T > SizeCmp;
00429     theListOfList.sort( SizeCmp );
00430   }
00431 }
00432 
00433 //=======================================================================
00434 //function : project
00435 //purpose  : 
00436 //=======================================================================
00437 
00438 static gp_XY project (const SMDS_MeshNode* theNode,
00439                       Extrema_GenExtPS &   theProjectorPS)
00440 {
00441   gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
00442   theProjectorPS.Perform( P );
00443   if ( !theProjectorPS.IsDone() ) {
00444     MESSAGE( "SMESH_Pattern: point projection FAILED");
00445     return gp_XY(0.,0.);
00446   }
00447   double u, v, minVal = DBL_MAX;
00448   for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
00449 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
00450     if ( theProjectorPS.SquareDistance( i ) < minVal ) {
00451       minVal = theProjectorPS.SquareDistance( i );
00452 #else
00453     if ( theProjectorPS.Value( i ) < minVal ) {
00454       minVal = theProjectorPS.Value( i );
00455 #endif
00456       theProjectorPS.Point( i ).Parameter( u, v );
00457     }
00458   return gp_XY( u, v );
00459 }
00460 
00461 //=======================================================================
00462 //function : areNodesBound
00463 //purpose  : true if all nodes of faces are bound to shapes
00464 //=======================================================================
00465 
00466 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
00467 {
00468   while ( faceItr->more() )
00469   {
00470     SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
00471     while ( nIt->more() )
00472     {
00473       const SMDS_MeshNode* node = smdsNode( nIt->next() );
00474       if (node->getshapeId() <1) {
00475         return false;
00476       }
00477     }
00478   }
00479   return true;
00480 }
00481 
00482 //=======================================================================
00483 //function : isMeshBoundToShape
00484 //purpose  : return true if all 2d elements are bound to shape
00485 //           if aFaceSubmesh != NULL, then check faces bound to it
00486 //           else check all faces in aMeshDS
00487 //=======================================================================
00488 
00489 static bool isMeshBoundToShape(SMESHDS_Mesh *     aMeshDS,
00490                                SMESHDS_SubMesh *  aFaceSubmesh,
00491                                const bool         isMainShape)
00492 {
00493   if ( isMainShape ) {
00494     // check that all faces are bound to aFaceSubmesh
00495     if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
00496       return false;
00497   }
00498 
00499   // check face nodes binding
00500   if ( aFaceSubmesh ) {
00501     SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
00502     return areNodesBound( fIt );
00503   }
00504   SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
00505   return areNodesBound( fIt );
00506 }
00507 
00508 //=======================================================================
00509 //function : Load
00510 //purpose  : Create a pattern from the mesh built on <theFace>.
00511 //           <theProject>==true makes override nodes positions
00512 //           on <theFace> computed by mesher
00513 //=======================================================================
00514 
00515 bool SMESH_Pattern::Load (SMESH_Mesh*        theMesh,
00516                           const TopoDS_Face& theFace,
00517                           bool               theProject)
00518 {
00519   MESSAGE(" ::Load(face) " );
00520   Clear();
00521   myIs2D = true;
00522 
00523   SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
00524   SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
00525   const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
00526   SMESH_MesherHelper helper( *theMesh );
00527   helper.SetSubShape( theFace );
00528 
00529   int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
00530   int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
00531   if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
00532   {
00533     MESSAGE( "No elements bound to the face");
00534     return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
00535   }
00536 
00537   TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
00538 
00539   // check if face is closed
00540   bool isClosed = helper.HasSeam();
00541   TopoDS_Vertex bidon;
00542   list<TopoDS_Edge> eList;
00543   list<TopoDS_Edge>::iterator elIt;
00544   SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
00545 
00546   // check that requested or needed projection is possible
00547   bool isMainShape = theMesh->IsMainShape( face );
00548   bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
00549   bool canProject  = ( nbElems ? true : isMainShape );
00550   if ( isClosed )
00551     canProject = false; // so far
00552 
00553   if ( ( theProject || needProject ) && !canProject )
00554     return setErrorCode( ERR_LOADF_CANT_PROJECT );
00555 
00556   Extrema_GenExtPS projector;
00557   GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
00558   if ( theProject || needProject )
00559     projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
00560 
00561   int iPoint = 0;
00562   TNodePointIDMap nodePointIDMap;
00563   TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
00564 
00565   if ( needProject )
00566   {
00567     MESSAGE("Project the submesh");
00568     // ---------------------------------------------------------------
00569     // The case where the submesh is projected to theFace
00570     // ---------------------------------------------------------------
00571 
00572     // get all faces
00573     list< const SMDS_MeshElement* > faces;
00574     if ( nbElems > 0 ) {
00575       SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
00576       while ( fIt->more() ) {
00577         const SMDS_MeshElement* f = fIt->next();
00578         if ( f && f->GetType() == SMDSAbs_Face )
00579           faces.push_back( f );
00580       }
00581     }
00582     else {
00583       SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
00584       while ( fIt->more() )
00585         faces.push_back( fIt->next() );
00586     }
00587 
00588     // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
00589     list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
00590     for ( ; fIt != faces.end(); ++fIt )
00591     {
00592       myElemPointIDs.push_back( TElemDef() );
00593       TElemDef& elemPoints = myElemPointIDs.back();
00594       int nbNodes = (*fIt)->NbCornerNodes();
00595       for ( int i = 0;i < nbNodes; ++i )
00596       {
00597         const SMDS_MeshElement* node = (*fIt)->GetNode( i );
00598         TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
00599         if ( nIdIt->second == -1 )
00600         {
00601           elemPoints.push_back( iPoint );
00602           nIdIt->second = iPoint++;
00603         }
00604         else
00605           elemPoints.push_back( (*nIdIt).second );
00606       }
00607     }
00608     myPoints.resize( iPoint );
00609 
00610     // project all nodes of 2d elements to theFace
00611     TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
00612     for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
00613     {
00614       const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
00615       TPoint * p = & myPoints[ (*nIdIt).second ];
00616       p->myInitUV = project( node, projector );
00617       p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
00618     }
00619     // find key-points: the points most close to UV of vertices
00620     TopExp_Explorer vExp( face, TopAbs_VERTEX );
00621     set<int> foundIndices;
00622     for ( ; vExp.More(); vExp.Next() ) {
00623       const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
00624       gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
00625       double minDist = DBL_MAX;
00626       int index;
00627       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
00628       for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
00629         double dist = uv.SquareDistance( (*pVecIt).myInitUV );
00630         if ( dist < minDist ) {
00631           minDist = dist;
00632           index = iPoint;
00633         }
00634       }
00635       if ( foundIndices.insert( index ).second ) // unique?
00636         myKeyPointIDs.push_back( index );
00637     }
00638     myIsBoundaryPointsFound = false;
00639 
00640   }
00641   else
00642   {
00643     // ---------------------------------------------------------------------
00644     // The case where a pattern is being made from the mesh built by mesher
00645     // ---------------------------------------------------------------------
00646 
00647     // Load shapes in the consequent order and count nb of points
00648 
00649     // vertices
00650     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
00651       int nbV = myShapeIDMap.Extent();
00652       myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
00653       bool added = ( nbV < myShapeIDMap.Extent() );
00654       if ( !added ) { // vertex encountered twice
00655         // a seam vertex have two corresponding key points
00656         myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ).Reversed());
00657         ++nbNodes;
00658       }
00659       if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
00660         nbNodes += eSubMesh->NbNodes() + 1;
00661     }
00662     // edges
00663     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
00664       myShapeIDMap.Add( *elIt );
00665     // the face
00666     myShapeIDMap.Add( face );
00667 
00668     myPoints.resize( nbNodes );
00669 
00670     // Load U of points on edges
00671 
00672     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
00673     {
00674       TopoDS_Edge & edge = *elIt;
00675       list< TPoint* > & ePoints = getShapePoints( edge );
00676       double f, l;
00677       Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
00678       bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
00679 
00680       TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
00681       TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
00682       // to make adjacent edges share key-point, we make v2 FORWARD too
00683       // (as we have different points for same shape with different orienation)
00684       v2.Reverse();
00685 
00686       // on closed face we must have REVERSED some of seam vertices
00687       if ( isClosed ) {
00688         if ( helper.IsSeamShape( edge ) ) {
00689           if ( helper.IsRealSeam( edge ) && !isForward ) {
00690             // reverse on reversed SEAM edge
00691             v1.Reverse();
00692             v2.Reverse();
00693           }
00694         }
00695         else { // on CLOSED edge (i.e. having one vertex with different orienations)
00696           for ( int is2 = 0; is2 < 2; ++is2 ) {
00697             TopoDS_Shape & v = is2 ? v2 : v1;
00698             if ( helper.IsRealSeam( v ) ) {
00699               // reverse or not depending on orientation of adjacent seam
00700               TopoDS_Edge seam;
00701               list<TopoDS_Edge>::iterator eIt2 = elIt;
00702               if ( is2 )
00703                 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
00704               else
00705                 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
00706               if ( seam.Orientation() == TopAbs_REVERSED )
00707                 v.Reverse();
00708             }
00709           }
00710         }
00711       }
00712 
00713       // the forward key-point
00714       list< TPoint* > * vPoint = & getShapePoints( v1 );
00715       if ( vPoint->empty() )
00716       {
00717         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
00718         if ( vSubMesh && vSubMesh->NbNodes() ) {
00719           myKeyPointIDs.push_back( iPoint );
00720           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
00721           const SMDS_MeshNode* node = nIt->next();
00722           if ( v1.Orientation() == TopAbs_REVERSED )
00723             closeNodePointIDMap.insert( make_pair( node, iPoint ));
00724           else
00725             nodePointIDMap.insert( make_pair( node, iPoint ));
00726 
00727           TPoint* keyPoint = &myPoints[ iPoint++ ];
00728           vPoint->push_back( keyPoint );
00729           if ( theProject )
00730             keyPoint->myInitUV = project( node, projector );
00731           else
00732             keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
00733           keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
00734         }
00735       }
00736       if ( !vPoint->empty() )
00737         ePoints.push_back( vPoint->front() );
00738 
00739       // on-edge points
00740       SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
00741       if ( eSubMesh && eSubMesh->NbNodes() )
00742       {
00743         // loop on nodes of an edge: sort them by param on edge
00744         typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
00745         TParamNodeMap paramNodeMap;
00746         int nbMeduimNodes = 0;
00747         SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
00748         while ( nIt->more() )
00749         {
00750           const SMDS_MeshNode* node = nIt->next();
00751           if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
00752             ++nbMeduimNodes;
00753             continue;
00754           }
00755           const SMDS_EdgePosition* epos =
00756             static_cast<const SMDS_EdgePosition*>(node->GetPosition());
00757           double u = epos->GetUParameter();
00758           paramNodeMap.insert( make_pair( u, node ));
00759         }
00760         if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
00761           // wrong U on edge, project
00762           Extrema_ExtPC proj;
00763           BRepAdaptor_Curve aCurve( edge );
00764           proj.Initialize( aCurve, f, l );
00765           paramNodeMap.clear();
00766           nIt = eSubMesh->GetNodes();
00767           for ( int iNode = 0; nIt->more(); ++iNode ) {
00768             const SMDS_MeshNode* node = nIt->next();
00769             if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
00770               continue;
00771             proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
00772             double u = 0;
00773             if ( proj.IsDone() ) {
00774               for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
00775                 if ( proj.IsMin( i )) {
00776                   u = proj.Point( i ).Parameter();
00777                   break;
00778                 }
00779             } else {
00780               u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
00781             }
00782             paramNodeMap.insert( make_pair( u, node ));
00783           }
00784 
00785           //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
00786           if ( paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
00787             return setErrorCode(ERR_UNEXPECTED);
00788         }
00789 
00790         // put U in [0,1] so that the first key-point has U==0
00791         bool isSeam = helper.IsRealSeam( edge );
00792         double du = l - f;
00793         TParamNodeMap::iterator         unIt  = paramNodeMap.begin();
00794         TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
00795         while ( unIt != paramNodeMap.end() )
00796         {
00797           TPoint* p = & myPoints[ iPoint ];
00798           ePoints.push_back( p );
00799           const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
00800           if ( isSeam && !isForward )
00801             closeNodePointIDMap.insert( make_pair( node, iPoint ));
00802           else
00803             nodePointIDMap.insert ( make_pair( node, iPoint ));
00804 
00805           if ( theProject )
00806             p->myInitUV = project( node, projector );
00807           else {
00808             double u = isForward ? (*unIt).first : (*unRIt).first;
00809             p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
00810             p->myInitUV = C2d->Value( u ).XY();
00811           }
00812           p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
00813           unIt++; unRIt++;
00814           iPoint++;
00815         }
00816       }
00817       // the reverse key-point
00818       vPoint = & getShapePoints( v2 );
00819       if ( vPoint->empty() )
00820       {
00821         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
00822         if ( vSubMesh && vSubMesh->NbNodes() ) {
00823           myKeyPointIDs.push_back( iPoint );
00824           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
00825           const SMDS_MeshNode* node = nIt->next();
00826           if ( v2.Orientation() == TopAbs_REVERSED )
00827             closeNodePointIDMap.insert( make_pair( node, iPoint ));
00828           else
00829             nodePointIDMap.insert( make_pair( node, iPoint ));
00830 
00831           TPoint* keyPoint = &myPoints[ iPoint++ ];
00832           vPoint->push_back( keyPoint );
00833           if ( theProject )
00834             keyPoint->myInitUV = project( node, projector );
00835           else
00836             keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
00837           keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
00838         }
00839       }
00840       if ( !vPoint->empty() )
00841         ePoints.push_back( vPoint->front() );
00842 
00843       // compute U of edge-points
00844       if ( theProject )
00845       {
00846         double totalDist = 0;
00847         list< TPoint* >::iterator pIt = ePoints.begin();
00848         TPoint* prevP = *pIt;
00849         prevP->myInitU = totalDist;
00850         for ( pIt++; pIt != ePoints.end(); pIt++ ) {
00851           TPoint* p = *pIt;
00852           totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
00853           p->myInitU = totalDist;
00854           prevP = p;
00855         }
00856         if ( totalDist > DBL_MIN)
00857           for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
00858             TPoint* p = *pIt;
00859             p->myInitU /= totalDist;
00860           }
00861       }
00862     } // loop on edges of a wire
00863 
00864     // Load in-face points and elements
00865 
00866     if ( fSubMesh && fSubMesh->NbElements() )
00867     {
00868       list< TPoint* > & fPoints = getShapePoints( face );
00869       SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
00870       while ( nIt->more() )
00871       {
00872         const SMDS_MeshNode* node = nIt->next();
00873         if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
00874           continue;
00875         nodePointIDMap.insert( make_pair( node, iPoint ));
00876         TPoint* p = &myPoints[ iPoint++ ];
00877         fPoints.push_back( p );
00878         if ( theProject )
00879           p->myInitUV = project( node, projector );
00880         else {
00881           const SMDS_FacePosition* pos =
00882             static_cast<const SMDS_FacePosition*>(node->GetPosition());
00883           p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
00884         }
00885         p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
00886       }
00887       // load elements
00888       TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
00889       SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
00890       while ( elemIt->more() )
00891       {
00892         const SMDS_MeshElement* elem = elemIt->next();
00893         SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
00894         myElemPointIDs.push_back( TElemDef() );
00895         TElemDef& elemPoints = myElemPointIDs.back();
00896         // find point indices corresponding to element nodes
00897         while ( nIt->more() )
00898         {
00899           const SMDS_MeshNode* node = smdsNode( nIt->next() );
00900           n_id = nodePointIDMap.find( node );
00901           if ( n_id == nodePointIDMap.end() )
00902             continue; // medium node
00903           iPoint = n_id->second; // point index of interest
00904           // for a node on a seam edge there are two points
00905           if ( helper.IsRealSeam( node->getshapeId() ) &&
00906                ( n_id = closeNodePointIDMap.find( node )) != not_found )
00907           {
00908             TPoint & p1 = myPoints[ iPoint ];
00909             TPoint & p2 = myPoints[ n_id->second ];
00910             // Select point closest to the rest nodes of element in UV space
00911             SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
00912             const SMDS_MeshNode* notSeamNode = 0;
00913             // find node not on a seam edge
00914             while ( nIt2->more() && !notSeamNode ) {
00915               const SMDS_MeshNode* n = smdsNode( nIt2->next() );
00916               if ( !helper.IsSeamShape( n->getshapeId() ))
00917                 notSeamNode = n;
00918             }
00919             gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
00920             double dist1 = uv.SquareDistance( p1.myInitUV );
00921             double dist2 = uv.SquareDistance( p2.myInitUV );
00922             if ( dist2 < dist1 )
00923               iPoint = n_id->second;
00924           }
00925           elemPoints.push_back( iPoint );
00926         }
00927       }
00928     }
00929     myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
00930 
00931     myIsBoundaryPointsFound = true;
00932   }
00933 
00934   // Assure that U range is proportional to V range
00935 
00936   Bnd_Box2d bndBox;
00937   vector< TPoint >::iterator pVecIt = myPoints.begin();
00938   for ( ; pVecIt != myPoints.end(); pVecIt++ )
00939     bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
00940   double minU, minV, maxU, maxV;
00941   bndBox.Get( minU, minV, maxU, maxV );
00942   double dU = maxU - minU, dV = maxV - minV;
00943   if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
00944     Clear();
00945     bndBox.SetVoid();
00946     // define where is the problem, in the face or in the mesh
00947     TopExp_Explorer vExp( face, TopAbs_VERTEX );
00948     for ( ; vExp.More(); vExp.Next() ) {
00949       gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
00950       bndBox.Add( uv );
00951     }
00952     bndBox.Get( minU, minV, maxU, maxV );
00953     dU = maxU - minU, dV = maxV - minV;
00954     if ( dU <= DBL_MIN || dV <= DBL_MIN )
00955       // face problem
00956       return setErrorCode( ERR_LOADF_NARROW_FACE );
00957     else
00958       // mesh is projected onto a line, e.g.
00959       return setErrorCode( ERR_LOADF_CANT_PROJECT );
00960   }
00961   double ratio = dU / dV, maxratio = 3, scale;
00962   int iCoord = 0;
00963   if ( ratio > maxratio ) {
00964     scale = ratio / maxratio;
00965     iCoord = 2;
00966   }
00967   else if ( ratio < 1./maxratio ) {
00968     scale = maxratio / ratio;
00969     iCoord = 1;
00970   }
00971   if ( iCoord ) {
00972     SCRUTE( scale );
00973     for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
00974       TPoint & p = *pVecIt;
00975       p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
00976       p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
00977     }
00978   }
00979   if ( myElemPointIDs.empty() ) {
00980     MESSAGE( "No elements bound to the face");
00981     return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
00982   }
00983 
00984   return setErrorCode( ERR_OK );
00985 }
00986 
00987 //=======================================================================
00988 //function : computeUVOnEdge
00989 //purpose  : compute coordinates of points on theEdge
00990 //=======================================================================
00991 
00992 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge&      theEdge,
00993                                      const list< TPoint* > & ePoints )
00994 {
00995   bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
00996   double f, l;
00997   Handle(Geom2d_Curve) C2d =
00998     BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
00999 
01000   ePoints.back()->myInitU = 1.0;
01001   list< TPoint* >::const_iterator pIt = ePoints.begin();
01002   for ( pIt++; pIt != ePoints.end(); pIt++ )
01003   {
01004     TPoint* point = *pIt;
01005     // U
01006     double du = ( isForward ? point->myInitU : 1 - point->myInitU );
01007     point->myU = ( f * ( 1 - du ) + l * du );
01008     // UV
01009     point->myUV = C2d->Value( point->myU ).XY();
01010   }
01011 }
01012 
01013 //=======================================================================
01014 //function : intersectIsolines
01015 //purpose  : 
01016 //=======================================================================
01017 
01018 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
01019                               const gp_XY& uv21, const gp_XY& uv22, const double r2,
01020                               gp_XY& resUV,
01021                               bool& isDeformed)
01022 {
01023   gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
01024   gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
01025   resUV = 0.5 * ( loc1 + loc2 );
01026   //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
01027   // SKL 26.07.2007 for NPAL16567
01028   double d1 = (uv11-uv12).Modulus();
01029   double d2 = (uv21-uv22).Modulus();
01030   // double delta = d1*d2*1e-6; PAL17233
01031   double delta = min( d1, d2 ) / 10.;
01032   isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
01033 
01034 //   double len1 = ( uv11 - uv12 ).Modulus();
01035 //   double len2 = ( uv21 - uv22 ).Modulus();
01036 //   resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
01037 //  return true;
01038 
01039 
01040 //   gp_Lin2d line1( uv11, uv12 - uv11 );
01041 //   gp_Lin2d line2( uv21, uv22 - uv21 );
01042 //   double angle = Abs( line1.Angle( line2 ) );
01043 
01044 //     IntAna2d_AnaIntersection inter;
01045 //     inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
01046 //     if ( inter.IsDone() && inter.NbPoints() == 1 )
01047 //     {
01048 //       gp_Pnt2d interUV = inter.Point(1).Value();
01049 //       resUV += interUV.XY();
01050 //   inter.Perform( line1, line2 );
01051 //   interUV = inter.Point(1).Value();
01052 //   resUV += interUV.XY();
01053 
01054 //   resUV /= 2.;
01055 //     }
01056   if ( isDeformed ) {
01057     MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
01058             ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
01059   }
01060   return true;
01061 }
01062 
01063 //=======================================================================
01064 //function : compUVByIsoIntersection
01065 //purpose  : 
01066 //=======================================================================
01067 
01068 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
01069                                              const gp_XY&                   theInitUV,
01070                                              gp_XY&                         theUV,
01071                                              bool &                         theIsDeformed )
01072 {
01073   // compute UV by intersection of 2 iso lines
01074   //gp_Lin2d isoLine[2];
01075   gp_XY uv1[2], uv2[2];
01076   double ratio[2];
01077   const double zero = DBL_MIN;
01078   for ( int iIso = 0; iIso < 2; iIso++ )
01079   {
01080     // to build an iso line:
01081     // find 2 pairs of consequent edge-points such that the range of their
01082     // initial parameters encloses the in-face point initial parameter
01083     gp_XY UV[2], initUV[2];
01084     int nbUV = 0, iCoord = iIso + 1;
01085     double initParam = theInitUV.Coord( iCoord );
01086 
01087     list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
01088     for ( ; bndIt != theBndPoints.end(); bndIt++ )
01089     {
01090       const list< TPoint* > & bndPoints = * bndIt;
01091       TPoint* prevP = bndPoints.back(); // this is the first point
01092       list< TPoint* >::const_iterator pIt = bndPoints.begin();
01093       bool coincPrev = false;
01094       // loop on the edge-points
01095       for ( ; pIt != bndPoints.end(); pIt++ )
01096       {
01097         double paramDiff     = initParam - (*pIt)->myInitUV.Coord( iCoord );
01098         double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
01099         double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
01100         if (!coincPrev && // ignore if initParam coincides with prev point param
01101             sumOfDiff > zero && // ignore if both points coincide with initParam
01102             prevParamDiff * paramDiff <= zero )
01103         {
01104           // find UV in parametric space of theFace
01105           double r = Abs(prevParamDiff) / sumOfDiff;
01106           gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
01107           int i = nbUV++;
01108           if ( i >= 2 ) {
01109             // throw away uv most distant from <theInitUV>
01110             gp_XY vec0 = initUV[0] - theInitUV;
01111             gp_XY vec1 = initUV[1] - theInitUV;
01112             gp_XY vec  = uvInit    - theInitUV;
01113             bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
01114             double dist0 = vec0.SquareModulus();
01115             double dist1 = vec1.SquareModulus();
01116             double dist  = vec .SquareModulus();
01117             if ( !isBetween || dist < dist0 || dist < dist1 ) {
01118               i = ( dist0 < dist1 ? 1 : 0 );
01119               if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
01120                 i = 3; // theInitUV must remain between
01121             }
01122           }
01123           if ( i < 2 ) {
01124             initUV[ i ] = uvInit;
01125             UV[ i ]     = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
01126           }
01127           coincPrev = ( Abs(paramDiff) <= zero );
01128         }
01129         else
01130           coincPrev = false;
01131         prevP = *pIt;
01132       }
01133     }
01134     if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
01135       MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
01136               ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
01137       return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
01138     }
01139     // an iso line should be normal to UV[0] - UV[1] direction
01140     // and be located at the same relative distance as from initial ends
01141     //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
01142     double r =
01143       (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
01144     //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
01145     //isoLine[ iIso ] = iso.Normal( isoLoc );
01146     uv1[ iIso ] = UV[0];
01147     uv2[ iIso ] = UV[1];
01148     ratio[ iIso ] = r;
01149   }
01150   if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
01151                           uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
01152     MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
01153     return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
01154   }
01155 
01156   return true;
01157 }
01158 
01159 
01160 // ==========================================================
01161 // structure representing a node of a grid of iso-poly-lines
01162 // ==========================================================
01163 
01164 struct TIsoNode {
01165   bool   myIsMovable;
01166   gp_XY  myInitUV;
01167   gp_XY  myUV;
01168   double myRatio[2];
01169   gp_Dir2d  myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
01170   TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
01171   TIsoNode* myBndNodes[4];     // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
01172   TIsoNode(double initU, double initV):
01173     myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
01174   { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
01175   bool IsUVComputed() const
01176   { return myUV.X() != 1e100; }
01177   bool IsMovable() const
01178   { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
01179   void SetNotMovable()
01180   { myIsMovable = false; }
01181   void SetBoundaryNode(TIsoNode* node, int iDir, int i)
01182   { myBndNodes[ iDir + i * 2 ] = node; }
01183   TIsoNode* GetBoundaryNode(int iDir, int i)
01184   { return myBndNodes[ iDir + i * 2 ]; }
01185   void SetNext(TIsoNode* node, int iDir, int isForward)
01186   { myNext[ iDir + isForward  * 2 ] = node; }
01187   TIsoNode* GetNext(int iDir, int isForward)
01188   { return myNext[ iDir + isForward * 2 ]; }
01189 };
01190 
01191 //=======================================================================
01192 //function : getNextNode
01193 //purpose  : 
01194 //=======================================================================
01195 
01196 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
01197 {
01198   TIsoNode* n = node->myNext[ dir ];
01199   if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
01200     n = 0;//node->myBndNodes[ dir ];
01201 //     MESSAGE("getNextNode: use bnd for node "<<
01202 //             node->myInitUV.X()<<" "<<node->myInitUV.Y());
01203   }
01204   return n;
01205 }
01206 //=======================================================================
01207 //function : checkQuads
01208 //purpose  : check if newUV destortes quadrangles around node,
01209 //           and if ( crit == FIX_OLD ) fix newUV in this case
01210 //=======================================================================
01211 
01212 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
01213 
01214 static bool checkQuads (const TIsoNode* node,
01215                         gp_XY&          newUV,
01216                         const bool      reversed,
01217                         const int       crit = FIX_OLD,
01218                         double          fixSize = 0.)
01219 {
01220   gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
01221   int nbOldFix = 0, nbOldImpr = 0;
01222   double newBadRate = 0, oldBadRate = 0;
01223   bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
01224   int i, dir1 = 0, dir2 = 3;
01225   for ( ; dir1 < 4; dir1++, dir2++ )  // loop on 4 quadrangles around <node>
01226   {
01227     if ( dir2 > 3 ) dir2 = 0;
01228     TIsoNode* n[3];
01229     // walking counterclockwise around a quad,
01230     // nodes are in the order: node, n[0], n[1], n[2]
01231     n[0] = getNextNode( node, dir1 );
01232     n[2] = getNextNode( node, dir2 );
01233     if ( !n[0] || !n[2] ) continue;
01234     n[1] = getNextNode( n[0], dir2 );
01235     if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
01236     bool isTriangle = ( !n[1] );
01237     if ( reversed ) {
01238       TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
01239     }
01240 //     if ( fixSize != 0 ) {
01241 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
01242 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
01243 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
01244 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
01245 // }
01246     // check if a quadrangle is degenerated
01247     if ( !isTriangle &&
01248         ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
01249          (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
01250       isTriangle = true;
01251     if ( isTriangle &&
01252         ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
01253       continue;
01254 
01255     // find min size of the diagonal node-n[1]
01256     double minDiag = fixSize;
01257     if ( minDiag == 0. ) {
01258       double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
01259       if ( !isTriangle ) {
01260         maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
01261         maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
01262       }
01263       maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
01264       minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
01265     }
01266 
01267     // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
01268     // ( behind means "to the right of")
01269     // it is OK if
01270     // 1. newUV is not behind 01 and 12 dirs
01271     // 2. or newUV is not behind 02 dir and n[2] is convex
01272     bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
01273     bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
01274     gp_Vec2d moveVec[3], outVec[3];
01275     for ( i = isTriangle ? 2 : 0; i < 3; i++ )
01276     {
01277       bool isDiag = ( i == 2 );
01278       if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
01279         break;
01280       gp_Vec2d sideDir;
01281       if ( isDiag )
01282         sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
01283       else
01284         sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
01285 
01286       gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
01287       outDir.Normalize();
01288       gp_Vec2d newDir( n[i]->myUV, newUV );
01289       gp_Vec2d oldDir( n[i]->myUV, oldUV );
01290       outVec[i] = outDir;
01291       if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
01292       if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
01293       if ( crit == FIX_OLD ) {
01294         wasIn[i] = ( outDir * oldDir < 0 );
01295         wasOk[i] = ( outDir * oldDir < -minDiag );
01296         if ( !newOk[i] )
01297           newBadRate += outDir * newDir;
01298         if ( !wasOk[i] )
01299           oldBadRate += outDir * oldDir;
01300         // push node inside
01301         if ( !wasOk[i] ) {
01302           double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
01303           //               double r = ( l1 - minDiag ) / ( l1 + l2 );
01304           //               moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
01305           moveVec[i] = ( oldDist - minDiag ) * outDir;
01306         }
01307       }
01308     }
01309 
01310     // check if n[2] is convex
01311     bool convex = true;
01312     if ( !isTriangle )
01313       convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
01314 
01315     bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
01316     bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
01317     newIsOk = ( newIsOk && isNewOk );
01318     newIsIn = ( newIsIn && isNewIn );
01319 
01320     if ( crit != FIX_OLD ) {
01321       if ( crit == CHECK_NEW_OK && !newIsOk ) break;
01322       if ( crit == CHECK_NEW_IN && !newIsIn ) break;
01323       continue;
01324     }
01325 
01326     bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
01327     bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
01328     oldIsIn = ( oldIsIn && isOldIn );
01329     oldIsOk = ( oldIsOk && isOldIn );
01330 
01331 
01332     if ( !isOldIn ) { // node is outside a quadrangle
01333       // move newUV inside a quadrangle
01334 //MESSAGE("Quad "<< dir1 << "  WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
01335       // node and newUV are outside: push newUV inside
01336       gp_XY uv;
01337       if ( convex || isTriangle ) {
01338         uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
01339       }
01340       else {
01341         gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
01342         double outSize = out.Magnitude();
01343         if ( outSize > DBL_MIN )
01344           out /= outSize;
01345         else
01346           out.SetCoord( -outVec[1].Y(), outVec[1].X() );
01347         uv = n[1]->myUV - minDiag * out.XY();
01348       }
01349       oldUVFixed[ nbOldFix++ ] = uv;
01350       //node->myUV = newUV;
01351     }
01352     else if ( !isOldOk )  {
01353       // try to fix old UV: move node inside as less as possible
01354 //MESSAGE("Quad "<< dir1 << "  old is BAD, try to fix old, minDiag: "<< minDiag);
01355       gp_XY uv1, uv2 = node->myUV;
01356       for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
01357         if ( wasOk[i] )
01358           moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
01359       while ( !isOldOk ) {
01360         // find the least moveVec
01361         int i, iMin = 4;
01362         double minMove2 = 1e100;
01363         for ( i = isTriangle ? 2 : 0; i < 3; i++ )
01364         {
01365           if ( moveVec[i].Coord(1) < 1e100 ) {
01366             double move2 = moveVec[i].SquareMagnitude();
01367             if ( move2 < minMove2 ) {
01368               minMove2 = move2;
01369               iMin = i;
01370             }
01371           }
01372         }
01373         if ( iMin == 4 ) {
01374           break;
01375         }
01376         // move node to newUV
01377         uv1 = node->myUV + moveVec[ iMin ].XY();
01378         uv2 += moveVec[ iMin ].XY();
01379         moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
01380         // check if uv1 is ok
01381         for ( i = isTriangle ? 2 : 0; i < 3; i++ )
01382           wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
01383         isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
01384         if ( isOldOk )
01385           oldUVImpr[ nbOldImpr++ ] = uv1;
01386         else {
01387           // check if uv2 is ok
01388           for ( i = isTriangle ? 2 : 0; i < 3; i++ )
01389             wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
01390           isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
01391           if ( isOldOk )
01392             oldUVImpr[ nbOldImpr++ ] = uv2;
01393         }
01394       }
01395     }
01396 
01397   } // loop on 4 quadrangles around <node>
01398 
01399   if ( crit == CHECK_NEW_OK  )
01400     return newIsOk;
01401   if ( crit == CHECK_NEW_IN  )
01402     return newIsIn;
01403 
01404   if ( newIsOk )
01405     return true;
01406 
01407   if ( oldIsOk )
01408     newUV = oldUV;
01409   else {
01410     if ( oldIsIn && nbOldImpr ) {
01411 //       MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
01412 //               " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
01413       gp_XY uv = oldUVImpr[ 0 ];
01414       for ( int i = 1; i < nbOldImpr; i++ )
01415         uv += oldUVImpr[ i ];
01416       uv /= nbOldImpr;
01417       if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
01418         newUV = uv;
01419         return false;
01420       }
01421       else {
01422         //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
01423       }
01424     }
01425     if ( !oldIsIn && nbOldFix ) {
01426 //       MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
01427 //               " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
01428       gp_XY uv = oldUVFixed[ 0 ];
01429       for ( int i = 1; i < nbOldFix; i++ )
01430         uv += oldUVFixed[ i ];
01431       uv /= nbOldFix;
01432       if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
01433         newUV = uv;
01434         return false;
01435       }
01436       else {
01437         //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
01438       }
01439     }
01440     if ( newIsIn && oldIsIn )
01441       newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
01442     else if ( !newIsIn )
01443       newUV = oldUV;
01444   }
01445 
01446   return false;
01447 }
01448 
01449 //=======================================================================
01450 //function : compUVByElasticIsolines
01451 //purpose  : compute UV as nodes of iso-poly-lines consisting of
01452 //           segments keeping relative size as in the pattern
01453 //=======================================================================
01454 //#define DEB_COMPUVBYELASTICISOLINES
01455 bool SMESH_Pattern::
01456   compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
01457                           const list< TPoint* >&         thePntToCompute)
01458 {
01459   return false; // PAL17233
01460 //cout << "============================== KEY POINTS =============================="<<endl;
01461 //   list< int >::iterator kpIt = myKeyPointIDs.begin();
01462 //   for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
01463 //     TPoint& p = myPoints[ *kpIt ];
01464 //     cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
01465 //       " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
01466 //  }
01467 //cout << "=============================="<<endl;
01468 
01469   // Define parameters of iso-grid nodes in U and V dir
01470 
01471   set< double > paramSet[ 2 ];
01472   list< list< TPoint* > >::const_iterator pListIt;
01473   list< TPoint* >::const_iterator pIt;
01474   for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
01475     const list< TPoint* > & pList = * pListIt;
01476     for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
01477       paramSet[0].insert( (*pIt)->myInitUV.X() );
01478       paramSet[1].insert( (*pIt)->myInitUV.Y() );
01479     }
01480   }
01481   for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
01482     paramSet[0].insert( (*pIt)->myInitUV.X() );
01483     paramSet[1].insert( (*pIt)->myInitUV.Y() );
01484   }
01485   // unite close parameters and split too long segments
01486   int iDir;
01487   double tol[ 2 ];
01488   for ( iDir = 0; iDir < 2; iDir++ )
01489   {
01490     set< double > & params = paramSet[ iDir ];
01491     double range = ( *params.rbegin() - *params.begin() );
01492     double toler = range / 1e6;
01493     tol[ iDir ] = toler;
01494 //    double maxSegment = range / params.size() / 2.;
01495 //
01496 //     set< double >::iterator parIt = params.begin();
01497 //     double prevPar = *parIt;
01498 //     for ( parIt++; parIt != params.end(); parIt++ )
01499 //     {
01500 //       double segLen = (*parIt) - prevPar;
01501 //       if ( segLen < toler )
01502 //         ;//params.erase( prevPar ); // unite
01503 //       else if ( segLen > maxSegment )
01504 //         params.insert( prevPar + 0.5 * segLen ); // split
01505 //       prevPar = (*parIt);
01506 //     }
01507   }
01508 
01509   // Make nodes of a grid of iso-poly-lines
01510 
01511   list < TIsoNode > nodes;
01512   typedef list < TIsoNode *> TIsoLine;
01513   map < double, TIsoLine > isoMap[ 2 ];
01514 
01515   set< double > & params0 = paramSet[ 0 ];
01516   set< double >::iterator par0It = params0.begin();
01517   for ( ; par0It != params0.end(); par0It++ )
01518   {
01519     TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
01520     set< double > & params1 = paramSet[ 1 ];
01521     set< double >::iterator par1It = params1.begin();
01522     for ( ; par1It != params1.end(); par1It++ )
01523     {
01524       nodes.push_back( TIsoNode( *par0It, *par1It ) );
01525       isoLine0.push_back( & nodes.back() );
01526       isoMap[1][ *par1It ].push_back( & nodes.back() );
01527     }
01528   }
01529 
01530   // Compute intersections of boundaries with iso-lines:
01531   // only boundary nodes will have computed UV so far
01532 
01533   Bnd_Box2d uvBnd;
01534   list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
01535   list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
01536   for ( ; bndIt != theBndPoints.end(); bndIt++ )
01537   {
01538     const list< TPoint* > & bndPoints = * bndIt;
01539     TPoint* prevP = bndPoints.back(); // this is the first point
01540     list< TPoint* >::const_iterator pIt = bndPoints.begin();
01541     // loop on the edge-points
01542     for ( ; pIt != bndPoints.end(); pIt++ )
01543     {
01544       TPoint* point = *pIt;
01545       for ( iDir = 0; iDir < 2; iDir++ )
01546       {
01547         const int iCoord = iDir + 1;
01548         const int iOtherCoord = 2 - iDir;
01549         double par1 = prevP->myInitUV.Coord( iCoord );
01550         double par2 = point->myInitUV.Coord( iCoord );
01551         double parDif = par2 - par1;
01552         if ( Abs( parDif ) <= DBL_MIN )
01553           continue;
01554         // find iso-lines intersecting a bounadry
01555         double toler = tol[ 1 - iDir ];
01556         double minPar = Min ( par1, par2 );
01557         double maxPar = Max ( par1, par2 );
01558         map < double, TIsoLine >& isos = isoMap[ iDir ];
01559         map < double, TIsoLine >::iterator isoIt = isos.begin();
01560         for ( ; isoIt != isos.end(); isoIt++ )
01561         {
01562           double isoParam = (*isoIt).first;
01563           if ( isoParam < minPar || isoParam > maxPar )
01564             continue;
01565           double r = ( isoParam - par1 ) / parDif;
01566           gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
01567           gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
01568           double otherPar = initUV.Coord( iOtherCoord ); // along isoline
01569           // find existing node with otherPar or insert a new one
01570           TIsoLine & isoLine = (*isoIt).second;
01571           double nodePar;
01572           TIsoLine::iterator nIt = isoLine.begin();
01573           for ( ; nIt != isoLine.end(); nIt++ ) {
01574             nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
01575             if ( nodePar >= otherPar )
01576               break;
01577           }
01578           TIsoNode * node;
01579           if ( Abs( nodePar - otherPar ) <= toler )
01580             node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
01581           else {
01582             nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
01583             node = & nodes.back();
01584             isoLine.insert( nIt, node );
01585           }
01586           node->SetNotMovable();
01587           node->myUV = uv;
01588           uvBnd.Add( gp_Pnt2d( uv ));
01589 //  cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
01590           // tangent dir
01591           gp_XY tgt( point->myUV - prevP->myUV );
01592           if ( ::IsEqual( r, 1. ))
01593             node->myDir[ 0 ] = tgt;
01594           else if ( ::IsEqual( r, 0. ))
01595             node->myDir[ 1 ] = tgt;
01596           else
01597             node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
01598           // keep boundary nodes corresponding to boundary points
01599           if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
01600             if ( bndNodes.empty() || bndNodes.back() != node )
01601               bndNodes.push_back( node );
01602         } // loop on isolines
01603       } // loop on 2 directions
01604       prevP = point;
01605     } // loop on boundary points
01606   } // loop on boundaries
01607 
01608   // Define orientation
01609 
01610   // find the point with the least X
01611   double leastX = DBL_MAX;
01612   TIsoNode * leftNode;
01613   list < TIsoNode >::iterator nodeIt = nodes.begin();
01614   for ( ; nodeIt != nodes.end(); nodeIt++  ) {
01615     TIsoNode & node = *nodeIt;
01616     if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
01617       leastX = node.myUV.X();
01618       leftNode = &node;
01619     }
01620 // if ( node.IsUVComputed() ) {
01621 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
01622 //   node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
01623 //    " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
01624 //      " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
01625 // }
01626   }
01627   bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
01628   //SCRUTE( reversed );
01629 
01630   // Prepare internal nodes:
01631   // 1. connect nodes
01632   // 2. compute ratios
01633   // 3. find boundary nodes for each node
01634   // 4. remove nodes out of the boundary
01635   for ( iDir = 0; iDir < 2; iDir++ )
01636   {
01637     const int iCoord = 2 - iDir; // coord changing along an isoline
01638     map < double, TIsoLine >& isos = isoMap[ iDir ];
01639     map < double, TIsoLine >::iterator isoIt = isos.begin();
01640     for ( ; isoIt != isos.end(); isoIt++ )
01641     {
01642       TIsoLine & isoLine = (*isoIt).second;
01643       bool firstCompNodeFound = false;
01644       TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
01645       nPrevIt = nIt = nNextIt = isoLine.begin();
01646       nIt++;
01647       nNextIt++; nNextIt++;
01648       while ( nIt != isoLine.end() )
01649       {
01650         // 1. connect prev - cur
01651         TIsoNode* node = *nIt, * prevNode = *nPrevIt;
01652         if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
01653           firstCompNodeFound = true;
01654           lastCompNodePos = nPrevIt;
01655         }
01656         if ( firstCompNodeFound ) {
01657           node->SetNext( prevNode, iDir, 0 );
01658           prevNode->SetNext( node, iDir, 1 );
01659         }
01660         // 2. compute ratio
01661         if ( nNextIt != isoLine.end() ) {
01662           double par1 = prevNode->myInitUV.Coord( iCoord );
01663           double par2 = node->myInitUV.Coord( iCoord );
01664           double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
01665           node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
01666         }
01667         // 3. find boundary nodes
01668         if ( node->IsUVComputed() )
01669           lastCompNodePos = nIt;
01670         else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
01671           TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
01672           for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
01673             if ( (*nIt2)->IsUVComputed() )
01674               break;
01675           if ( nIt2 != isoLine.end() ) {
01676             bndNode2 = *nIt2;
01677             node->SetBoundaryNode( bndNode1, iDir, 0 );
01678             node->SetBoundaryNode( bndNode2, iDir, 1 );
01679 // cout << "--------------------------------------------------"<<endl;
01680 //  cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
01681 //   " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
01682 //     " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
01683 //  cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
01684 //   " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
01685 //     " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
01686           }
01687           else {
01689             node->SetBoundaryNode( 0, iDir, 0 );
01690             node->SetBoundaryNode( 0, iDir, 1 );
01691           }
01692         }
01693         nIt++; nPrevIt++;
01694         if ( nNextIt != isoLine.end() ) nNextIt++;
01695         // 4. remove nodes out of the boundary
01696         if ( !firstCompNodeFound )
01697           isoLine.pop_front();
01698       } // loop on isoLine nodes
01699 
01700       // remove nodes after the boundary
01701 //       for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
01702 //         (*nIt)->SetNotMovable();
01703       isoLine.erase( ++lastCompNodePos, isoLine.end() );
01704     } // loop on isolines
01705   } // loop on 2 directions
01706 
01707   // Compute local isoline direction for internal nodes
01708 
01709   /*
01710   map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
01711   map < double, TIsoLine >::iterator isoIt = isos.begin();
01712   for ( ; isoIt != isos.end(); isoIt++ )
01713   {
01714     TIsoLine & isoLine = (*isoIt).second;
01715     TIsoLine::iterator nIt = isoLine.begin();
01716     for ( ; nIt != isoLine.end(); nIt++ )
01717     {
01718       TIsoNode* node = *nIt;
01719       if ( node->IsUVComputed() || !node->IsMovable() )
01720         continue;
01721       gp_Vec2d aTgt[2], aNorm[2];
01722       double ratio[2];
01723       bool OK = true;
01724       for ( iDir = 0; iDir < 2; iDir++ )
01725       {
01726         TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
01727         TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
01728         if ( !bndNode1 || !bndNode2 ) {
01729           OK = false;
01730           break;
01731         }
01732         const int iCoord = 2 - iDir; // coord changing along an isoline
01733         double par1 = bndNode1->myInitUV.Coord( iCoord );
01734         double par2 = node->myInitUV.Coord( iCoord );
01735         double par3 = bndNode2->myInitUV.Coord( iCoord );
01736         ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
01737 
01738         gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
01739         gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
01740         if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
01741         else                            tgt1.Reverse();
01742 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
01743 
01744         if ( ratio[ iDir ] < 0.5 )
01745           aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
01746         else
01747           aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
01748         if ( iDir == 1 )
01749           aNorm[ iDir ].Reverse();  // along iDir isoline
01750 
01751         double angle = tgt1.Angle( tgt2 ); //  [-PI, PI]
01752         // maybe angle is more than |PI|
01753         if ( Abs( angle ) > PI / 2. ) {
01754           // check direction of the last but one perpendicular isoline
01755           TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
01756           bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
01757           bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
01758           gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
01759           if ( isoDir * tgt2 < 0 )
01760             isoDir.Reverse();
01761           double angle2 = tgt1.Angle( isoDir );
01762           //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
01763           if (angle2 * angle < 0 && // check the sign of an angle close to PI
01764               Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
01765             //MESSAGE("REVERSE ANGLE");
01766             angle = -angle;
01767           }
01768           if ( Abs( angle2 ) > Abs( angle ) ||
01769               ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
01770             //MESSAGE("Add PI");
01771             // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
01772             // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
01773             // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
01774             // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
01775             // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<"  "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
01776             angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
01777           }
01778         }
01779         aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
01780       } // loop on 2 dir
01781 
01782       if ( OK ) {
01783         for ( iDir = 0; iDir < 2; iDir++ )
01784         {
01785           aTgt[iDir].Normalize();
01786           aNorm[1-iDir].Normalize();
01787           double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
01788           r *= r;
01789 
01790           node->myDir[iDir] = //aTgt[iDir];
01791             aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
01792         }
01793 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
01794 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
01795 //  cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<"  |  "
01796 //    << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
01797       }
01798     } // loop on iso nodes
01799   } // loop on isolines
01800 */
01801   // Find nodes to start computing UV from
01802 
01803   list< TIsoNode* > startNodes;
01804   list< TIsoNode* >::iterator nIt = bndNodes.end();
01805   TIsoNode* node = *(--nIt);
01806   TIsoNode* prevNode = *(--nIt);
01807   for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
01808   {
01809     TIsoNode* nextNode = *nIt;
01810     gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
01811     gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
01812     double initAngle = initTgt1.Angle( initTgt2 );
01813     double angle = node->myDir[0].Angle( node->myDir[1] );
01814     if ( reversed ) angle = -angle;
01815     if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
01816       // find a close internal node
01817       TIsoNode* nClose = 0;
01818       list< TIsoNode* > testNodes;
01819       testNodes.push_back( node );
01820       list< TIsoNode* >::iterator it = testNodes.begin();
01821       for ( ; !nClose && it != testNodes.end(); it++ )
01822       {
01823         for (int i = 0; i < 4; i++ )
01824         {
01825           nClose = (*it)->myNext[ i ];
01826           if ( nClose ) {
01827             if ( !nClose->IsUVComputed() )
01828               break;
01829             else {
01830               testNodes.push_back( nClose );
01831               nClose = 0;
01832             }
01833           }
01834         }
01835       }
01836       startNodes.push_back( nClose );
01837 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
01838 //   node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
01839 //   "initAngle: " << initAngle << " angle: " << angle << endl;
01840 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
01841 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
01842 //    node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
01843 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
01844     }
01845     prevNode = node;
01846     node = nextNode;
01847   }
01848 
01849   // Compute starting UV of internal nodes
01850 
01851   list < TIsoNode* > internNodes;
01852   bool needIteration = true;
01853   if ( startNodes.empty() ) {
01854     MESSAGE( " Starting UV by compUVByIsoIntersection()");
01855     needIteration = false;
01856     map < double, TIsoLine >& isos = isoMap[ 0 ];
01857     map < double, TIsoLine >::iterator isoIt = isos.begin();
01858     for ( ; isoIt != isos.end(); isoIt++ )
01859     {
01860       TIsoLine & isoLine = (*isoIt).second;
01861       TIsoLine::iterator nIt = isoLine.begin();
01862       for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
01863       {
01864         TIsoNode* node = *nIt;
01865         if ( !node->IsUVComputed() && node->IsMovable() ) {
01866           internNodes.push_back( node );
01867           //bool isDeformed;
01868           if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
01869                                         node->myUV, needIteration ))
01870             node->myUV = node->myInitUV;
01871         }
01872       }
01873     }
01874     if ( needIteration )
01875       for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
01876       {
01877         TIsoNode* node = *nIt, *nClose = 0;
01878         list< TIsoNode* > testNodes;
01879         testNodes.push_back( node );
01880         list< TIsoNode* >::iterator it = testNodes.begin();
01881         for ( ; !nClose && it != testNodes.end(); it++ )
01882         {
01883           for (int i = 0; i < 4; i++ )
01884           {
01885             nClose = (*it)->myNext[ i ];
01886             if ( nClose ) {
01887               if ( !nClose->IsUVComputed() && nClose->IsMovable() )
01888                 break;
01889               else {
01890                 testNodes.push_back( nClose );
01891                 nClose = 0;
01892               }
01893             }
01894           }
01895         }
01896         startNodes.push_back( nClose );
01897       }
01898   }
01899 
01900   double aMin[2], aMax[2], step[2];
01901   uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
01902   double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
01903   step[0] = minUvSize / paramSet[ 0 ].size() / 10;
01904   step[1] = minUvSize / paramSet[ 1 ].size() / 10;
01905 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
01906 
01907   for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
01908   {
01909     TIsoNode *node = *nIt;
01910     if ( node->IsUVComputed() || !node->IsMovable() )
01911       continue;
01912     gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
01913     int nbComp = 0, nbPrev = 0;
01914     for ( iDir = 0; iDir < 2; iDir++ )
01915     {
01916       TIsoNode* prevNode1 = 0, *prevNode2 = 0;
01917       TIsoNode* n = node->GetNext( iDir, 0 );
01918       if ( n->IsUVComputed() )
01919         prevNode1 = n;
01920       else
01921         startNodes.push_back( n );
01922       n = node->GetNext( iDir, 1 );
01923       if ( n->IsUVComputed() )
01924         prevNode2 = n;
01925       else
01926         startNodes.push_back( n );
01927       if ( !prevNode1 ) {
01928         prevNode1 = prevNode2;
01929         prevNode2 = 0;
01930       }
01931       if ( prevNode1 ) nbPrev++;
01932       if ( prevNode2 ) nbPrev++;
01933       if ( prevNode1 ) {
01934         gp_XY dir;
01935           double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
01936           double par = node->myInitUV.Coord( 2 - iDir );
01937           bool isEnd = ( prevPar > par );
01938 //          dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
01939         //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
01940           TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
01941           if ( !bndNode ) {
01942             MESSAGE("Why we are here?");
01943             continue;
01944           }
01945           gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
01946           dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
01947           dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
01948         //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
01949           //  cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
01950           //     bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
01951           //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
01952             //" par: " << prevPar << endl;
01953           //           cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
01954         //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
01955         if ( prevNode2 ) {
01956           //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
01957           gp_XY & uv1 = prevNode1->myUV;
01958           gp_XY & uv2 = prevNode2->myUV;
01959 //           dir = ( uv2 - uv1 );
01960 //           double len = dir.Modulus();
01961 //           if ( len > DBL_MIN )
01962 //             dir /= len * 0.5;
01963           double r = node->myRatio[ iDir ];
01964           newUV += uv1 * ( 1 - r ) + uv2 * r;
01965         }
01966         else {
01967           newUV += prevNode1->myUV + dir * step[ iDir ];
01968         }
01969         sumDir += dir;
01970         nbComp++;
01971       }
01972     }
01973     if ( !nbComp ) continue;
01974     newUV /= nbComp;
01975     node->myUV = newUV;
01976     //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
01977 
01978     // check if a quadrangle is not distorted
01979     if ( nbPrev > 1 ) {
01980       //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
01981       if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
01982       //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
01983       //  cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
01984         node->myUV = newUV;
01985       }
01986     }
01987     internNodes.push_back( node );
01988   }
01989 
01990   // Move nodes
01991 
01992   static int maxNbIter = 100;
01993 #ifdef DEB_COMPUVBYELASTICISOLINES
01994 //   maxNbIter++;
01995   bool useNbMoveNode = 0;
01996   static int maxNbNodeMove = 100;
01997   maxNbNodeMove++;
01998   int nbNodeMove = 0;
01999   if ( !useNbMoveNode )
02000     maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
02001 #endif
02002   double maxMove;
02003   int nbIter = 0;
02004   do {
02005     if ( !needIteration) break;
02006 #ifdef DEB_COMPUVBYELASTICISOLINES
02007     if ( nbIter >= maxNbIter ) break;
02008 #endif
02009     maxMove = 0.0;
02010     list < TIsoNode* >::iterator nIt = internNodes.begin();
02011     for ( ; nIt != internNodes.end(); nIt++  ) {
02012 #ifdef DEB_COMPUVBYELASTICISOLINES
02013       if (useNbMoveNode )
02014         cout << nbNodeMove <<" =================================================="<<endl;
02015 #endif
02016       TIsoNode * node = *nIt;
02017       // make lines
02018       //gp_Lin2d line[2];
02019       gp_XY loc[2];
02020       for ( iDir = 0; iDir < 2; iDir++ )
02021       {
02022         gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
02023         gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
02024         double r = node->myRatio[ iDir ];
02025         loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
02026 //         line[ iDir ].SetLocation( loc[ iDir ] );
02027 //         line[ iDir ].SetDirection( node->myDir[ iDir ] );
02028       }
02029       // define ratio
02030       bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
02031 //      double locR[2] = { 0, 0 };
02032       for ( iDir = 0; iDir < 2; iDir++ )
02033       {
02034         const int iCoord = 2 - iDir; // coord changing along an isoline
02035         TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
02036         TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
02037         if ( !bndNode1 || !bndNode2 ) {
02038           ok = false; break;
02039         }
02040         double par1 = bndNode1->myInitUV.Coord( iCoord );
02041         double par2 = node->myInitUV.Coord( iCoord );
02042         double par3 = bndNode2->myInitUV.Coord( iCoord );
02043         double r = ( par2 - par1 ) / ( par3 - par1 );
02044         r = Abs ( r - 0.5 ) * 2.0;  // [0,1] - distance from the middle
02045 //        locR[ iDir ] = ( 1 - r * r ) * 0.25;
02046       }
02047       //locR[0] = locR[1] = 0.25;
02048       // intersect the 2 lines and move a node
02049       //IntAna2d_AnaIntersection inter( line[0], line[1] );
02050       if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
02051       {
02052 //         double intR = 1 - locR[0] - locR[1];
02053 //         gp_XY newUV = inter.Point(1).Value().XY();
02054 //         if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
02055 //           newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
02056 //         else
02057 //           newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
02058         gp_XY newUV = 0.5 * ( loc[0] +  loc[1] );
02059         // avoid parallel isolines intersection
02060         checkQuads( node, newUV, reversed );
02061 
02062         maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
02063         node->myUV = newUV;
02064       } // intersection found
02065 #ifdef DEB_COMPUVBYELASTICISOLINES
02066       if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
02067 #endif
02068     } // loop on internal nodes
02069 #ifdef DEB_COMPUVBYELASTICISOLINES
02070     if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
02071 #endif
02072   } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
02073 
02074   MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
02075 
02076   if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
02077     MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
02078 #ifndef DEB_COMPUVBYELASTICISOLINES
02079     return false;
02080 #endif
02081   }
02082 
02083   // Set computed UV to points
02084 
02085   for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
02086     TPoint* point = *pIt;
02087     //gp_XY oldUV = point->myUV;
02088     double minDist = DBL_MAX;
02089     list < TIsoNode >::iterator nIt = nodes.begin();
02090     for ( ; nIt != nodes.end(); nIt++ ) {
02091       double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
02092       if ( dist < minDist ) {
02093         minDist = dist;
02094         point->myUV = (*nIt).myUV;
02095       }
02096     }
02097   }
02098 
02099   return true;
02100 }
02101 
02102 
02103 //=======================================================================
02104 //function : setFirstEdge
02105 //purpose  : choose the best first edge of theWire; return the summary distance
02106 //           between point UV computed by isolines intersection and
02107 //           eventual UV got from edge p-curves
02108 //=======================================================================
02109 
02110 //#define DBG_SETFIRSTEDGE
02111 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
02112 {
02113   int iE, nbEdges = theWire.size();
02114   if ( nbEdges == 1 )
02115     return 0;
02116 
02117   // Transform UVs computed by iso to fit bnd box of a wire
02118 
02119   // max nb of points on an edge
02120   int maxNbPnt = 0;
02121   int eID = theFirstEdgeID;
02122   for ( iE = 0; iE < nbEdges; iE++ )
02123     maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
02124 
02125   // compute bnd boxes
02126   TopoDS_Face face = TopoDS::Face( myShape );
02127   Bnd_Box2d bndBox, eBndBox;
02128   eID = theFirstEdgeID;
02129   list< TopoDS_Edge >::iterator eIt;
02130   list< TPoint* >::iterator pIt;
02131   for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
02132   {
02133     // UV by isos stored in TPoint.myXYZ
02134     list< TPoint* > & ePoints = getShapePoints( eID++ );
02135     for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
02136       TPoint* p = (*pIt);
02137       bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
02138     }
02139     // UV by an edge p-curve
02140     double f, l;
02141     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
02142     double dU = ( l - f ) / ( maxNbPnt - 1 );
02143     for ( int i = 0; i < maxNbPnt; i++ )
02144       eBndBox.Add( C2d->Value( f + i * dU ));
02145   }
02146 
02147   // transform UVs by isos
02148   double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
02149   bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
02150   eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
02151 #ifdef DBG_SETFIRSTEDGE
02152   MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
02153          << eMinPar[1] << " - " << eMaxPar[1] );
02154 #endif
02155   for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
02156   {
02157     double dMin = eMinPar[i] - minPar[i];
02158     double dMax = eMaxPar[i] - maxPar[i];
02159     double dPar = maxPar[i] - minPar[i];
02160     eID = theFirstEdgeID;
02161     for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
02162     {
02163       list< TPoint* > & ePoints = getShapePoints( eID++ );
02164       for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
02165       {
02166         double par = (*pIt)->myXYZ.Coord( iC );
02167         double r = ( par - minPar[i] ) / dPar;
02168         par += ( 1 - r ) * dMin + r * dMax;
02169         (*pIt)->myXYZ.SetCoord( iC, par );
02170       }
02171     }
02172   }
02173 
02174   TopoDS_Edge eBest;
02175   double minDist = DBL_MAX;
02176   for ( iE = 0 ; iE < nbEdges; iE++ )
02177   {
02178 #ifdef DBG_SETFIRSTEDGE
02179     MESSAGE ( " VARIANT " << iE );
02180 #endif
02181     // evaluate the distance between UV computed by the 2 methods:
02182     // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
02183     double dist = 0;
02184     int eID = theFirstEdgeID;
02185     for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
02186     {
02187       list< TPoint* > & ePoints = getShapePoints( eID++ );
02188       computeUVOnEdge( *eIt, ePoints );
02189       for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
02190         TPoint* p = (*pIt);
02191         dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
02192 #ifdef DBG_SETFIRSTEDGE
02193         MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
02194                   p->myUV.X() << ", " << p->myUV.Y() << ") " );
02195 #endif
02196       }
02197     }
02198 #ifdef DBG_SETFIRSTEDGE
02199     MESSAGE ( "dist -- " << dist );
02200 #endif
02201     if ( dist < minDist ) {
02202       minDist = dist;
02203       eBest = theWire.front();
02204     }
02205     // check variant with another first edge
02206     theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
02207   }
02208   // put the best first edge to the theWire front
02209   if ( eBest != theWire.front() ) {
02210     eIt = find ( theWire.begin(), theWire.end(), eBest );
02211     theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
02212   }
02213 
02214   return minDist;
02215 }
02216 
02217 //=======================================================================
02218 //function : sortSameSizeWires
02219 //purpose  : sort wires in theWireList from theFromWire until theToWire,
02220 //           the wires are set in the order to correspond to the order
02221 //           of boundaries; after sorting, edges in the wires are put
02222 //           in a good order, point UVs on edges are computed and points
02223 //           are appended to theEdgesPointsList
02224 //=======================================================================
02225 
02226 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList &                theWireList,
02227                                        const TListOfEdgesList::iterator& theFromWire,
02228                                        const TListOfEdgesList::iterator& theToWire,
02229                                        const int                         theFirstEdgeID,
02230                                        list< list< TPoint* > >&          theEdgesPointsList )
02231 {
02232   TopoDS_Face F = TopoDS::Face( myShape );
02233   int iW, nbWires = 0;
02234   TListOfEdgesList::iterator wlIt = theFromWire;
02235   while ( wlIt++ != theToWire )
02236     nbWires++;
02237 
02238   // Recompute key-point UVs by isolines intersection,
02239   // compute CG of key-points for each wire and bnd boxes of GCs
02240 
02241   bool aBool;
02242   gp_XY orig( gp::Origin2d().XY() );
02243   vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
02244   Bnd_Box2d bndBox, vBndBox;
02245   int eID = theFirstEdgeID;
02246   list< TopoDS_Edge >::iterator eIt;
02247   for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
02248   {
02249     list< TopoDS_Edge > & wire = *wlIt;
02250     for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
02251     {
02252       list< TPoint* > & ePoints = getShapePoints( eID++ );
02253       TPoint* p = ePoints.front();
02254       if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
02255         MESSAGE("cant sortSameSizeWires()");
02256         return false;
02257       }
02258       gcVec[iW] += p->myUV;
02259       bndBox.Add( gp_Pnt2d( p->myUV ));
02260       TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
02261       gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
02262       vGcVec[iW] += vXY.XY();
02263       vBndBox.Add( vXY );
02264       // keep the computed UV to compare against by setFirstEdge()
02265       p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
02266     }
02267     gcVec[iW] /= nbWires;
02268     vGcVec[iW] /= nbWires;
02269 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
02270 //   " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
02271   }
02272 
02273   // Transform GCs computed by isos to fit in bnd box of GCs by vertices
02274 
02275   double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
02276   bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
02277   vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
02278   for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
02279   {
02280     double dMin = vMinPar[i] - minPar[i];
02281     double dMax = vMaxPar[i] - maxPar[i];
02282     double dPar = maxPar[i] - minPar[i];
02283     if ( Abs( dPar ) <= DBL_MIN )
02284       continue;
02285     for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
02286       double par = gcVec[iW].Coord( iC );
02287       double r = ( par - minPar[i] ) / dPar;
02288       par += ( 1 - r ) * dMin + r * dMax;
02289       gcVec[iW].SetCoord( iC, par );
02290     }
02291   }
02292 
02293   // Define boundary - wire correspondence by GC closeness
02294 
02295   TListOfEdgesList tmpWList;
02296   tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
02297   typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
02298   TIntWirePosMap bndIndWirePosMap;
02299   vector< bool > bndFound( nbWires, false );
02300   for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
02301   {
02302 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
02303 //   " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
02304     double minDist = DBL_MAX;
02305     gp_XY & wGc = vGcVec[ iW ];
02306     int bIndex;
02307     for ( int iB = 0; iB < nbWires; iB++ ) {
02308       if ( bndFound[ iB ] ) continue;
02309       double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
02310       if ( dist < minDist ) {
02311         minDist = dist;
02312         bIndex = iB;
02313       }
02314     }
02315     bndFound[ bIndex ] = true;
02316     bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
02317   }
02318 
02319   // Treat each wire
02320 
02321   TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
02322   eID = theFirstEdgeID;
02323   for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
02324   {
02325     TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
02326     list < TopoDS_Edge > & wire = ( *wirePos );
02327 
02328     // choose the best first edge of a wire
02329     setFirstEdge( wire, eID );
02330 
02331     // compute eventual UV and fill theEdgesPointsList
02332     theEdgesPointsList.push_back( list< TPoint* >() );
02333     list< TPoint* > & edgesPoints = theEdgesPointsList.back();
02334     for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
02335     {
02336       list< TPoint* > & ePoints = getShapePoints( eID++ );
02337       computeUVOnEdge( *eIt, ePoints );
02338       edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
02339     }
02340     // put wire back to theWireList
02341     wlIt = wirePos++;
02342     theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
02343   }
02344 
02345   return true;
02346 }
02347 
02348 //=======================================================================
02349 //function : Apply
02350 //purpose  : Compute  nodes coordinates applying
02351 //           the loaded pattern to <theFace>. The first key-point
02352 //           will be mapped into <theVertexOnKeyPoint1>
02353 //=======================================================================
02354 
02355 bool SMESH_Pattern::Apply (const TopoDS_Face&   theFace,
02356                            const TopoDS_Vertex& theVertexOnKeyPoint1,
02357                            const bool           theReverse)
02358 {
02359   MESSAGE(" ::Apply(face) " );
02360   TopoDS_Face face  = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
02361   if ( !setShapeToMesh( face ))
02362     return false;
02363 
02364   // find points on edges, it fills myNbKeyPntInBoundary
02365   if ( !findBoundaryPoints() )
02366     return false;
02367 
02368   // Define the edges order so that the first edge starts at
02369   // theVertexOnKeyPoint1
02370 
02371   list< TopoDS_Edge > eList;
02372   list< int >         nbVertexInWires;
02373   int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
02374   if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
02375   {
02376     MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
02377     return setErrorCode( ERR_APPLF_BAD_VERTEX );
02378   }
02379   // check nb wires and edges
02380   list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
02381   l1.sort(); l2.sort();
02382   if ( l1 != l2 )
02383   {
02384     MESSAGE( "Wrong nb vertices in wires" );
02385     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
02386   }
02387 
02388   // here shapes get IDs, for the outer wire IDs are OK
02389   list<TopoDS_Edge>::iterator elIt = eList.begin();
02390   for ( ; elIt != eList.end(); elIt++ ) {
02391     myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
02392     bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
02393     // BEGIN: jfa for bug 0019943
02394     if (isClosed1) {
02395       isClosed1 = false;
02396       for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
02397         const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
02398         int nbe = 0;
02399         for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
02400           if (we.Current().IsSame(*elIt)) {
02401             nbe++;
02402             if (nbe == 2) isClosed1 = true;
02403           }
02404         }
02405       }
02406     }
02407     // END: jfa for bug 0019943
02408     if (isClosed1)
02409       myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
02410   }
02411   int nbVertices = myShapeIDMap.Extent();
02412 
02413   for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
02414     myShapeIDMap.Add( *elIt );
02415 
02416   myShapeIDMap.Add( face );
02417 
02418   if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
02419     MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
02420     return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
02421   }
02422 
02423   // points on edges to be used for UV computation of in-face points
02424   list< list< TPoint* > > edgesPointsList;
02425   edgesPointsList.push_back( list< TPoint* >() );
02426   list< TPoint* > * edgesPoints = & edgesPointsList.back();
02427   list< TPoint* >::iterator pIt;
02428 
02429   // compute UV of points on the outer wire
02430   int iE, nbEdgesInOuterWire = nbVertexInWires.front();
02431   for (iE = 0, elIt = eList.begin();
02432        iE < nbEdgesInOuterWire && elIt != eList.end();
02433        iE++, elIt++ )
02434   {
02435     list< TPoint* > & ePoints = getShapePoints( *elIt );
02436     // compute UV
02437     computeUVOnEdge( *elIt, ePoints );
02438     // collect on-edge points (excluding the last one)
02439     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
02440   }
02441 
02442   // If there are several wires, define the order of edges of inner wires:
02443   // compute UV of inner edge-points using 2 methods: the one for in-face points
02444   // and the one for on-edge points and then choose the best edge order
02445   // by the best correspondance of the 2 results
02446   if ( nbWires > 1 )
02447   {
02448     // compute UV of inner edge-points using the method for in-face points
02449     // and devide eList into a list of separate wires
02450     bool aBool;
02451     list< list< TopoDS_Edge > > wireList;
02452     list<TopoDS_Edge>::iterator eIt = elIt;
02453     list<int>::iterator nbEIt = nbVertexInWires.begin();
02454     for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
02455     {
02456       int nbEdges = *nbEIt;
02457       wireList.push_back( list< TopoDS_Edge >() );
02458       list< TopoDS_Edge > & wire = wireList.back();
02459       for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
02460       {
02461         list< TPoint* > & ePoints = getShapePoints( *eIt );
02462         pIt = ePoints.begin();
02463         for (  pIt++; pIt != ePoints.end(); pIt++ ) {
02464           TPoint* p = (*pIt);
02465           if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
02466             MESSAGE("cant Apply(face)");
02467             return false;
02468           }
02469           // keep the computed UV to compare against by setFirstEdge()
02470           p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
02471         }
02472         wire.push_back( *eIt );
02473       }
02474     }
02475     // remove inner edges from eList
02476     eList.erase( elIt, eList.end() );
02477 
02478     // sort wireList by nb edges in a wire
02479     sortBySize< TopoDS_Edge > ( wireList );
02480 
02481     // an ID of the first edge of a boundary
02482     int id1 = nbVertices + nbEdgesInOuterWire + 1;
02483 //     if ( nbSeamShapes > 0 )
02484 //       id1 += 2; // 2 vertices more
02485 
02486     // find points - edge correspondence for wires of unique size,
02487     // edge order within a wire should be defined only
02488 
02489     list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
02490     while ( wlIt != wireList.end() )
02491     {
02492       list< TopoDS_Edge >& wire = (*wlIt);
02493       int nbEdges = wire.size();
02494       wlIt++;
02495       if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
02496       {
02497         // choose the best first edge of a wire
02498         setFirstEdge( wire, id1 );
02499 
02500         // compute eventual UV and collect on-edge points
02501         edgesPointsList.push_back( list< TPoint* >() );
02502         edgesPoints = & edgesPointsList.back();
02503         int eID = id1;
02504         for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
02505         {
02506           list< TPoint* > & ePoints = getShapePoints( eID++ );
02507           computeUVOnEdge( *eIt, ePoints );
02508           edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
02509         }
02510       }
02511       id1 += nbEdges;
02512     }
02513 
02514     // find boundary - wire correspondence for several wires of same size
02515 
02516     id1 = nbVertices + nbEdgesInOuterWire + 1;
02517     wlIt = wireList.begin();
02518     while ( wlIt != wireList.end() )
02519     {
02520       int nbSameSize = 0, nbEdges = (*wlIt).size();
02521       list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
02522       wlIt2++;
02523       while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
02524         nbSameSize++;
02525         wlIt2++;
02526       }
02527       if ( nbSameSize > 0 )
02528         if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
02529           return false;
02530       wlIt = wlIt2;
02531       id1 += nbEdges * ( nbSameSize + 1 );
02532     }
02533 
02534     // add well-ordered edges to eList
02535 
02536     for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
02537     {
02538       list< TopoDS_Edge >& wire = (*wlIt);
02539       eList.splice( eList.end(), wire, wire.begin(), wire.end() );
02540     }
02541 
02542     // re-fill myShapeIDMap - all shapes get good IDs
02543 
02544     myShapeIDMap.Clear();
02545     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
02546       myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
02547     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
02548       myShapeIDMap.Add( *elIt );
02549     myShapeIDMap.Add( face );
02550 
02551   } // there are inner wires
02552 
02553   // Compute XYZ of on-edge points
02554 
02555   TopLoc_Location loc;
02556   for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
02557   {
02558     BRepAdaptor_Curve C3d( *elIt );
02559     list< TPoint* > & ePoints = getShapePoints( iE++ );
02560     pIt = ePoints.begin();
02561     for ( pIt++; pIt != ePoints.end(); pIt++ )
02562     {
02563       TPoint* point = *pIt;
02564       point->myXYZ = C3d.Value( point->myU );
02565     }
02566   }
02567 
02568   // Compute UV and XYZ of in-face points
02569 
02570   // try to use a simple algo
02571   list< TPoint* > & fPoints = getShapePoints( face );
02572   bool isDeformed = false;
02573   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
02574     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
02575                                   (*pIt)->myUV, isDeformed )) {
02576       MESSAGE("cant Apply(face)");
02577       return false;
02578     }
02579   // try to use a complex algo if it is a difficult case
02580   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
02581   {
02582     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
02583       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
02584                                     (*pIt)->myUV, isDeformed )) {
02585         MESSAGE("cant Apply(face)");
02586         return false;
02587       }
02588   }
02589 
02590   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
02591   const gp_Trsf & aTrsf = loc.Transformation();
02592   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
02593   {
02594     TPoint * point = *pIt;
02595     point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
02596     if ( !loc.IsIdentity() )
02597       aTrsf.Transforms( point->myXYZ.ChangeCoord() );
02598   }
02599 
02600   myIsComputed = true;
02601 
02602   return setErrorCode( ERR_OK );
02603 }
02604 
02605 //=======================================================================
02606 //function : Apply
02607 //purpose  : Compute nodes coordinates applying
02608 //           the loaded pattern to <theFace>. The first key-point
02609 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
02610 //=======================================================================
02611 
02612 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
02613                            const int            theNodeIndexOnKeyPoint1,
02614                            const bool           theReverse)
02615 {
02616 //  MESSAGE(" ::Apply(MeshFace) " );
02617 
02618   if ( !IsLoaded() ) {
02619     MESSAGE( "Pattern not loaded" );
02620     return setErrorCode( ERR_APPL_NOT_LOADED );
02621   }
02622 
02623   // check nb of nodes
02624   const int nbFaceNodes = theFace->NbCornerNodes();
02625   if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
02626     MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
02627     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
02628   }
02629 
02630   // find points on edges, it fills myNbKeyPntInBoundary
02631   if ( !findBoundaryPoints() )
02632     return false;
02633 
02634   // check that there are no holes in a pattern
02635   if (myNbKeyPntInBoundary.size() > 1 ) {
02636     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
02637   }
02638 
02639   // Define the nodes order
02640 
02641   list< const SMDS_MeshNode* > nodes;
02642   list< const SMDS_MeshNode* >::iterator n = nodes.end();
02643   SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
02644   int iSub = 0;
02645   while ( noIt->more() && iSub < nbFaceNodes ) {
02646     const SMDS_MeshNode* node = smdsNode( noIt->next() );
02647     nodes.push_back( node );
02648     if ( iSub++ == theNodeIndexOnKeyPoint1 )
02649       n = --nodes.end();
02650   }
02651   if ( n != nodes.end() ) {
02652     if ( theReverse ) {
02653       if ( n != --nodes.end() )
02654         nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
02655       nodes.reverse();
02656     }
02657     else if ( n != nodes.begin() )
02658       nodes.splice( nodes.end(), nodes, nodes.begin(), n );
02659   }
02660   list< gp_XYZ > xyzList;
02661   myOrderedNodes.resize( nbFaceNodes );
02662   for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
02663     xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
02664     myOrderedNodes[ iSub++] = *n;
02665   }
02666 
02667   // Define a face plane
02668 
02669   list< gp_XYZ >::iterator xyzIt = xyzList.begin();
02670   gp_Pnt P ( *xyzIt++ );
02671   gp_Vec Vx( P, *xyzIt++ ), N;
02672   do {
02673     N = Vx ^ gp_Vec( P, *xyzIt++ );
02674   } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
02675   if ( N.SquareMagnitude() <= DBL_MIN )
02676     return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
02677   gp_Ax2 pos( P, N, Vx );
02678 
02679   // Compute UV of key-points on a plane
02680   for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
02681   {
02682     gp_Vec vec ( pos.Location(), *xyzIt );
02683     TPoint* p = getShapePoints( iSub ).front();
02684     p->myUV.SetX( vec * pos.XDirection() );
02685     p->myUV.SetY( vec * pos.YDirection() );
02686     p->myXYZ = *xyzIt;
02687   }
02688 
02689   // points on edges to be used for UV computation of in-face points
02690   list< list< TPoint* > > edgesPointsList;
02691   edgesPointsList.push_back( list< TPoint* >() );
02692   list< TPoint* > * edgesPoints = & edgesPointsList.back();
02693   list< TPoint* >::iterator pIt;
02694 
02695   // compute UV and XYZ of points on edges
02696 
02697   for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
02698   {
02699     gp_XYZ& xyz1 = *xyzIt++;
02700     gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
02701 
02702     list< TPoint* > & ePoints = getShapePoints( iSub );
02703     ePoints.back()->myInitU = 1.0;
02704     list< TPoint* >::const_iterator pIt = ++ePoints.begin();
02705     while ( *pIt != ePoints.back() )
02706     {
02707       TPoint* p = *pIt++;
02708       p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
02709       gp_Vec vec ( pos.Location(), p->myXYZ );
02710       p->myUV.SetX( vec * pos.XDirection() );
02711       p->myUV.SetY( vec * pos.YDirection() );
02712     }
02713     // collect on-edge points (excluding the last one)
02714     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
02715   }
02716 
02717   // Compute UV and XYZ of in-face points
02718 
02719   // try to use a simple algo to compute UV
02720   list< TPoint* > & fPoints = getShapePoints( iSub );
02721   bool isDeformed = false;
02722   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
02723     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
02724                                   (*pIt)->myUV, isDeformed )) {
02725       MESSAGE("cant Apply(face)");
02726       return false;
02727     }
02728   // try to use a complex algo if it is a difficult case
02729   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
02730   {
02731     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
02732       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
02733                                     (*pIt)->myUV, isDeformed )) {
02734         MESSAGE("cant Apply(face)");
02735         return false;
02736       }
02737   }
02738 
02739   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
02740   {
02741     (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
02742   }
02743 
02744   myIsComputed = true;
02745 
02746   return setErrorCode( ERR_OK );
02747 }
02748 
02749 //=======================================================================
02750 //function : Apply
02751 //purpose  : Compute nodes coordinates applying
02752 //           the loaded pattern to <theFace>. The first key-point
02753 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
02754 //=======================================================================
02755 
02756 bool SMESH_Pattern::Apply (SMESH_Mesh*          theMesh,
02757                            const SMDS_MeshFace* theFace,
02758                            const TopoDS_Shape&  theSurface,
02759                            const int            theNodeIndexOnKeyPoint1,
02760                            const bool           theReverse)
02761 {
02762 //  MESSAGE(" ::Apply(MeshFace) " );
02763   if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
02764     return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
02765   }
02766   const TopoDS_Face& face = TopoDS::Face( theSurface );
02767   TopLoc_Location loc;
02768   Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
02769   const gp_Trsf & aTrsf = loc.Transformation();
02770 
02771   if ( !IsLoaded() ) {
02772     MESSAGE( "Pattern not loaded" );
02773     return setErrorCode( ERR_APPL_NOT_LOADED );
02774   }
02775 
02776   // check nb of nodes
02777   if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
02778     MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
02779     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
02780   }
02781 
02782   // find points on edges, it fills myNbKeyPntInBoundary
02783   if ( !findBoundaryPoints() )
02784     return false;
02785 
02786   // check that there are no holes in a pattern
02787   if (myNbKeyPntInBoundary.size() > 1 ) {
02788     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
02789   }
02790 
02791   // Define the nodes order
02792 
02793   list< const SMDS_MeshNode* > nodes;
02794   list< const SMDS_MeshNode* >::iterator n = nodes.end();
02795   SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
02796   int iSub = 0;
02797   while ( noIt->more() ) {
02798     const SMDS_MeshNode* node = smdsNode( noIt->next() );
02799     nodes.push_back( node );
02800     if ( iSub++ == theNodeIndexOnKeyPoint1 )
02801       n = --nodes.end();
02802   }
02803   if ( n != nodes.end() ) {
02804     if ( theReverse ) {
02805       if ( n != --nodes.end() )
02806         nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
02807       nodes.reverse();
02808     }
02809     else if ( n != nodes.begin() )
02810       nodes.splice( nodes.end(), nodes, nodes.begin(), n );
02811   }
02812 
02813   // find a node not on a seam edge, if necessary
02814   SMESH_MesherHelper helper( *theMesh );
02815   helper.SetSubShape( theSurface );
02816   const SMDS_MeshNode* inFaceNode = 0;
02817   if ( helper.GetNodeUVneedInFaceNode() )
02818   {
02819     SMESH_MeshEditor editor( theMesh );
02820     for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
02821       int shapeID = editor.FindShape( *n );
02822       if ( !shapeID )
02823         return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
02824       if ( !helper.IsSeamShape( shapeID ))
02825         inFaceNode = *n;
02826     }
02827   }
02828 
02829   // Set UV of key-points (i.e. of nodes of theFace )
02830   vector< gp_XY > keyUV( theFace->NbNodes() );
02831   myOrderedNodes.resize( theFace->NbNodes() );
02832   for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
02833   {
02834     TPoint* p = getShapePoints( iSub ).front();
02835     p->myUV  = helper.GetNodeUV( face, *n, inFaceNode );
02836     p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
02837 
02838     keyUV[ iSub-1 ] = p->myUV;
02839     myOrderedNodes[ iSub-1 ] = *n;
02840   }
02841 
02842   // points on edges to be used for UV computation of in-face points
02843   list< list< TPoint* > > edgesPointsList;
02844   edgesPointsList.push_back( list< TPoint* >() );
02845   list< TPoint* > * edgesPoints = & edgesPointsList.back();
02846   list< TPoint* >::iterator pIt;
02847 
02848   // compute UV and XYZ of points on edges
02849 
02850   for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
02851   {
02852     gp_XY& uv1 = keyUV[ i ];
02853     gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
02854 
02855     list< TPoint* > & ePoints = getShapePoints( iSub );
02856     ePoints.back()->myInitU = 1.0;
02857     list< TPoint* >::const_iterator pIt = ++ePoints.begin();
02858     while ( *pIt != ePoints.back() )
02859     {
02860       TPoint* p = *pIt++;
02861       p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
02862       p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
02863       if ( !loc.IsIdentity() )
02864         aTrsf.Transforms( p->myXYZ.ChangeCoord() );
02865     }
02866     // collect on-edge points (excluding the last one)
02867     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
02868   }
02869 
02870   // Compute UV and XYZ of in-face points
02871 
02872   // try to use a simple algo to compute UV
02873   list< TPoint* > & fPoints = getShapePoints( iSub );
02874   bool isDeformed = false;
02875   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
02876     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
02877                                   (*pIt)->myUV, isDeformed )) {
02878       MESSAGE("cant Apply(face)");
02879       return false;
02880     }
02881   // try to use a complex algo if it is a difficult case
02882   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
02883   {
02884     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
02885       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
02886                                     (*pIt)->myUV, isDeformed )) {
02887         MESSAGE("cant Apply(face)");
02888         return false;
02889       }
02890   }
02891 
02892   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
02893   {
02894     TPoint * point = *pIt;
02895     point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
02896     if ( !loc.IsIdentity() )
02897       aTrsf.Transforms( point->myXYZ.ChangeCoord() );
02898   }
02899 
02900   myIsComputed = true;
02901 
02902   return setErrorCode( ERR_OK );
02903 }
02904 
02905 //=======================================================================
02906 //function : undefinedXYZ
02907 //purpose  : 
02908 //=======================================================================
02909 
02910 static const gp_XYZ& undefinedXYZ()
02911 {
02912   static gp_XYZ xyz( 1.e100, 0., 0. );
02913   return xyz;
02914 }
02915 
02916 //=======================================================================
02917 //function : isDefined
02918 //purpose  : 
02919 //=======================================================================
02920 
02921 inline static bool isDefined(const gp_XYZ& theXYZ)
02922 {
02923   return theXYZ.X() < 1.e100;
02924 }
02925 
02926 //=======================================================================
02927 //function : Apply
02928 //purpose  : Compute nodes coordinates applying
02929 //           the loaded pattern to <theFaces>. The first key-point
02930 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
02931 //=======================================================================
02932 
02933 bool SMESH_Pattern::Apply (SMESH_Mesh*                     theMesh,
02934                            std::set<const SMDS_MeshFace*>& theFaces,
02935                            const int                       theNodeIndexOnKeyPoint1,
02936                            const bool                      theReverse)
02937 {
02938   MESSAGE(" ::Apply(set<MeshFace>) " );
02939 
02940   if ( !IsLoaded() ) {
02941     MESSAGE( "Pattern not loaded" );
02942     return setErrorCode( ERR_APPL_NOT_LOADED );
02943   }
02944 
02945   // find points on edges, it fills myNbKeyPntInBoundary
02946   if ( !findBoundaryPoints() )
02947     return false;
02948 
02949   // check that there are no holes in a pattern
02950   if (myNbKeyPntInBoundary.size() > 1 ) {
02951     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
02952   }
02953 
02954   myShape.Nullify();
02955   myXYZ.clear();
02956   myElemXYZIDs.clear();
02957   myXYZIdToNodeMap.clear();
02958   myElements.clear();
02959   myIdsOnBoundary.clear();
02960   myReverseConnectivity.clear();
02961 
02962   myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
02963   myElements.reserve( theFaces.size() );
02964 
02965   // to find point index
02966   map< TPoint*, int > pointIndex;
02967   for ( int i = 0; i < myPoints.size(); i++ )
02968     pointIndex.insert( make_pair( & myPoints[ i ], i ));
02969 
02970   int ind1 = 0; // lowest point index for a face
02971 
02972   // meshed geometry
02973   TopoDS_Shape shape;
02974 //   int          shapeID = 0;
02975 //   SMESH_MeshEditor editor( theMesh );
02976 
02977   // apply to each face in theFaces set
02978   set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
02979   for ( ; face != theFaces.end(); ++face )
02980   {
02981 //     int curShapeId = editor.FindShape( *face );
02982 //     if ( curShapeId != shapeID ) {
02983 //       if ( curShapeId )
02984 //         shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
02985 //       else
02986 //         shape.Nullify();
02987 //       shapeID = curShapeId;
02988 //     }
02989     bool ok;
02990     if ( shape.IsNull() )
02991       ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
02992     else
02993       ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
02994     if ( !ok ) {
02995       MESSAGE( "Failed on " << *face );
02996       continue;
02997     }
02998     myElements.push_back( *face );
02999 
03000     // store computed points belonging to elements
03001     list< TElemDef >::iterator ll = myElemPointIDs.begin();
03002     for ( ; ll != myElemPointIDs.end(); ++ll )
03003     {
03004       myElemXYZIDs.push_back(TElemDef());
03005       TElemDef& xyzIds = myElemXYZIDs.back();
03006       TElemDef& pIds = *ll;
03007       for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
03008         int pIndex = *id + ind1;
03009         xyzIds.push_back( pIndex );
03010         myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
03011         myReverseConnectivity[ pIndex ].push_back( & xyzIds );
03012       }
03013     }
03014     // put points on links to myIdsOnBoundary,
03015     // they will be used to sew new elements on adjacent refined elements
03016     int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
03017     for ( int i = 0; i < nbNodes; i++ )
03018     {
03019       list< TPoint* > & linkPoints = getShapePoints( eID++ );
03020       const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
03021       const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
03022       // make a link and a node set
03023       TNodeSet linkSet, node1Set;
03024       linkSet.insert( n1 );
03025       linkSet.insert( n2 );
03026       node1Set.insert( n1 );
03027       list< TPoint* >::iterator p = linkPoints.begin();
03028       {
03029         // map the first link point to n1
03030         int nId = pointIndex[ *p ] + ind1;
03031         myXYZIdToNodeMap[ nId ] = n1;
03032         list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
03033         groups.push_back(list< int > ());
03034         groups.back().push_back( nId );
03035       }
03036       // add the linkSet to the map
03037       list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
03038       groups.push_back(list< int > ());
03039       list< int >& indList = groups.back();
03040       // add points to the map excluding the end points
03041       for ( p++; *p != linkPoints.back(); p++ )
03042         indList.push_back( pointIndex[ *p ] + ind1 );
03043     }
03044     ind1 += myPoints.size();
03045   }
03046 
03047   return !myElemXYZIDs.empty();
03048 }
03049 
03050 //=======================================================================
03051 //function : Apply
03052 //purpose  : Compute nodes coordinates applying
03053 //           the loaded pattern to <theVolumes>. The (0,0,0) key-point
03054 //           will be mapped into <theNode000Index>-th node. The
03055 //           (0,0,1) key-point will be mapped into <theNode000Index>-th
03056 //           node.
03057 //=======================================================================
03058 
03059 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
03060                            const int                          theNode000Index,
03061                            const int                          theNode001Index)
03062 {
03063   MESSAGE(" ::Apply(set<MeshVolumes>) " );
03064 
03065   if ( !IsLoaded() ) {
03066     MESSAGE( "Pattern not loaded" );
03067     return setErrorCode( ERR_APPL_NOT_LOADED );
03068   }
03069 
03070    // bind ID to points
03071   if ( !findBoundaryPoints() )
03072     return false;
03073 
03074   // check that there are no holes in a pattern
03075   if (myNbKeyPntInBoundary.size() > 1 ) {
03076     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
03077   }
03078 
03079   myShape.Nullify();
03080   myXYZ.clear();
03081   myElemXYZIDs.clear();
03082   myXYZIdToNodeMap.clear();
03083   myElements.clear();
03084   myIdsOnBoundary.clear();
03085   myReverseConnectivity.clear();
03086 
03087   myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
03088   myElements.reserve( theVolumes.size() );
03089 
03090   // to find point index
03091   map< TPoint*, int > pointIndex;
03092   for ( int i = 0; i < myPoints.size(); i++ )
03093     pointIndex.insert( make_pair( & myPoints[ i ], i ));
03094 
03095   int ind1 = 0; // lowest point index for an element
03096 
03097   // apply to each element in theVolumes set
03098   set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
03099   for ( ; vol != theVolumes.end(); ++vol )
03100   {
03101     if ( !Apply( *vol, theNode000Index, theNode001Index )) {
03102       MESSAGE( "Failed on " << *vol );
03103       continue;
03104     }
03105     myElements.push_back( *vol );
03106 
03107     // store computed points belonging to elements
03108     list< TElemDef >::iterator ll = myElemPointIDs.begin();
03109     for ( ; ll != myElemPointIDs.end(); ++ll )
03110     {
03111       myElemXYZIDs.push_back(TElemDef());
03112       TElemDef& xyzIds = myElemXYZIDs.back();
03113       TElemDef& pIds = *ll;
03114       for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
03115         int pIndex = *id + ind1;
03116         xyzIds.push_back( pIndex );
03117         myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
03118         myReverseConnectivity[ pIndex ].push_back( & xyzIds );
03119       }
03120     }
03121     // put points on edges and faces to myIdsOnBoundary,
03122     // they will be used to sew new elements on adjacent refined elements
03123     for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
03124     {
03125       // make a set of sub-points
03126       TNodeSet subNodes;
03127       vector< int > subIDs;
03128       if ( SMESH_Block::IsVertexID( Id )) {
03129         subNodes.insert( myOrderedNodes[ Id - 1 ]);
03130       }
03131       else if ( SMESH_Block::IsEdgeID( Id )) {
03132         SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
03133         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
03134         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
03135       }
03136       else {
03137         SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
03138         int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
03139         SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
03140         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
03141         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
03142         SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
03143         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
03144         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
03145       }
03146       // add points
03147       list< TPoint* > & points = getShapePoints( Id );
03148       list< TPoint* >::iterator p = points.begin();
03149       list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
03150       groups.push_back(list< int > ());
03151       list< int >& indList = groups.back();
03152       for ( ; p != points.end(); p++ )
03153         indList.push_back( pointIndex[ *p ] + ind1 );
03154       if ( subNodes.size() == 1 ) // vertex case
03155         myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
03156     }
03157     ind1 += myPoints.size();
03158   }
03159 
03160   return !myElemXYZIDs.empty();
03161 }
03162 
03163 //=======================================================================
03164 //function : Load
03165 //purpose  : Create a pattern from the mesh built on <theBlock>
03166 //=======================================================================
03167 
03168 bool SMESH_Pattern::Load (SMESH_Mesh*         theMesh,
03169                           const TopoDS_Shell& theBlock)
03170 {
03171   MESSAGE(" ::Load(volume) " );
03172   Clear();
03173   myIs2D = false;
03174   SMESHDS_SubMesh * aSubMesh;
03175 
03176   const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
03177 
03178   // load shapes in myShapeIDMap
03179   SMESH_Block block;
03180   TopoDS_Vertex v1, v2;
03181   if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
03182     return setErrorCode( ERR_LOADV_BAD_SHAPE );
03183 
03184   // count nodes
03185   int nbNodes = 0, shapeID;
03186   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
03187   {
03188     const TopoDS_Shape& S = myShapeIDMap( shapeID );
03189     aSubMesh = getSubmeshWithElements( theMesh, S );
03190     if ( aSubMesh )
03191       nbNodes += aSubMesh->NbNodes();
03192   }
03193   myPoints.resize( nbNodes );
03194 
03195   // load U of points on edges
03196   TNodePointIDMap nodePointIDMap;
03197   int iPoint = 0;
03198   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
03199   {
03200     const TopoDS_Shape& S = myShapeIDMap( shapeID );
03201     list< TPoint* > & shapePoints = getShapePoints( shapeID );
03202     aSubMesh = getSubmeshWithElements( theMesh, S );
03203     if ( ! aSubMesh ) continue;
03204     SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
03205     if ( !nIt->more() ) continue;
03206 
03207       // store a node and a point
03208     while ( nIt->more() ) {
03209       const SMDS_MeshNode* node = smdsNode( nIt->next() );
03210       if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
03211         continue;
03212       nodePointIDMap.insert( make_pair( node, iPoint ));
03213       if ( block.IsVertexID( shapeID ))
03214         myKeyPointIDs.push_back( iPoint );
03215       TPoint* p = & myPoints[ iPoint++ ];
03216       shapePoints.push_back( p );
03217       p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
03218       p->myInitXYZ.SetCoord( 0,0,0 );
03219     }
03220     list< TPoint* >::iterator pIt = shapePoints.begin();
03221 
03222     // compute init XYZ
03223     switch ( S.ShapeType() )
03224     {
03225     case TopAbs_VERTEX:
03226     case TopAbs_EDGE: {
03227 
03228       for ( ; pIt != shapePoints.end(); pIt++ ) {
03229         double * coef = block.GetShapeCoef( shapeID );
03230         for ( int iCoord = 1; iCoord <= 3; iCoord++ )
03231           if ( coef[ iCoord - 1] > 0 )
03232             (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
03233       }
03234       if ( S.ShapeType() == TopAbs_VERTEX )
03235         break;
03236 
03237       const TopoDS_Edge& edge = TopoDS::Edge( S );
03238       double f,l;
03239       BRep_Tool::Range( edge, f, l );
03240       int iCoord     = SMESH_Block::GetCoordIndOnEdge( shapeID );
03241       bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
03242       pIt = shapePoints.begin();
03243       nIt = aSubMesh->GetNodes();
03244       for ( ; nIt->more(); pIt++ )
03245       {
03246         const SMDS_MeshNode* node = nIt->next();
03247         if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
03248           continue;
03249         const SMDS_EdgePosition* epos =
03250           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
03251         double u = ( epos->GetUParameter() - f ) / ( l - f );
03252         (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
03253       }
03254       break;
03255     }
03256     default:
03257       for ( ; pIt != shapePoints.end(); pIt++ )
03258       {
03259         if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
03260           MESSAGE( "!block.ComputeParameters()" );
03261           return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
03262         }
03263       }
03264     }
03265   } // loop on block sub-shapes
03266 
03267   // load elements
03268 
03269   aSubMesh = getSubmeshWithElements( theMesh, theBlock );
03270   if ( aSubMesh )
03271   {
03272     SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
03273     while ( elemIt->more() ) {
03274       const SMDS_MeshElement* elem = elemIt->next();
03275       myElemPointIDs.push_back( TElemDef() );
03276       TElemDef& elemPoints = myElemPointIDs.back();
03277       int nbNodes = elem->NbCornerNodes();
03278       for ( int i = 0;i < nbNodes; ++i )
03279         elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
03280     }
03281   }
03282 
03283   myIsBoundaryPointsFound = true;
03284 
03285   return setErrorCode( ERR_OK );
03286 }
03287 
03288 //=======================================================================
03289 //function : getSubmeshWithElements
03290 //purpose  : return submesh containing elements bound to theBlock in theMesh
03291 //=======================================================================
03292 
03293 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh*         theMesh,
03294                                                         const TopoDS_Shape& theShape)
03295 {
03296   SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
03297   if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
03298     return aSubMesh;
03299 
03300   if ( theShape.ShapeType() == TopAbs_SHELL )
03301   {
03302     // look for submesh of VOLUME
03303     TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
03304     for (; it.More(); it.Next()) {
03305       aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
03306       if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
03307         return aSubMesh;
03308     }
03309   }
03310   return 0;
03311 }
03312 
03313 
03314 //=======================================================================
03315 //function : Apply
03316 //purpose  : Compute nodes coordinates applying
03317 //           the loaded pattern to <theBlock>. The (0,0,0) key-point
03318 //           will be mapped into <theVertex000>. The (0,0,1)
03319 //           fifth key-point will be mapped into <theVertex001>.
03320 //=======================================================================
03321 
03322 bool SMESH_Pattern::Apply (const TopoDS_Shell&  theBlock,
03323                            const TopoDS_Vertex& theVertex000,
03324                            const TopoDS_Vertex& theVertex001)
03325 {
03326   MESSAGE(" ::Apply(volume) " );
03327 
03328   if (!findBoundaryPoints()     || // bind ID to points
03329       !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
03330     return false;
03331 
03332   SMESH_Block block;  // bind ID to shape
03333   if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
03334     return setErrorCode( ERR_APPLV_BAD_SHAPE );
03335 
03336   // compute XYZ of points on shapes
03337 
03338   for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
03339   {
03340     list< TPoint* > & shapePoints = getShapePoints( shapeID );
03341     list< TPoint* >::iterator pIt = shapePoints.begin();
03342     const TopoDS_Shape& S = myShapeIDMap( shapeID );
03343     switch ( S.ShapeType() )
03344     {
03345     case TopAbs_VERTEX: {
03346 
03347       for ( ; pIt != shapePoints.end(); pIt++ )
03348         block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
03349       break;
03350     }
03351     case TopAbs_EDGE: {
03352 
03353       for ( ; pIt != shapePoints.end(); pIt++ )
03354         block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
03355       break;
03356     }
03357     case TopAbs_FACE: {
03358 
03359       for ( ; pIt != shapePoints.end(); pIt++ )
03360         block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
03361       break;
03362     }
03363     default:
03364       for ( ; pIt != shapePoints.end(); pIt++ )
03365         block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
03366     }
03367   } // loop on block sub-shapes
03368 
03369   myIsComputed = true;
03370 
03371   return setErrorCode( ERR_OK );
03372 }
03373 
03374 //=======================================================================
03375 //function : Apply
03376 //purpose  : Compute nodes coordinates applying
03377 //           the loaded pattern to <theVolume>. The (0,0,0) key-point
03378 //           will be mapped into <theNode000Index>-th node. The
03379 //           (0,0,1) key-point will be mapped into <theNode000Index>-th
03380 //           node.
03381 //=======================================================================
03382 
03383 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
03384                            const int              theNode000Index,
03385                            const int              theNode001Index)
03386 {
03387   //MESSAGE(" ::Apply(MeshVolume) " );
03388 
03389   if (!findBoundaryPoints()) // bind ID to points
03390     return false;
03391 
03392   SMESH_Block block;  // bind ID to shape
03393   if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
03394     return setErrorCode( ERR_APPLV_BAD_SHAPE );
03395   // compute XYZ of points on shapes
03396 
03397   for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
03398   {
03399     list< TPoint* > & shapePoints = getShapePoints( ID );
03400     list< TPoint* >::iterator pIt = shapePoints.begin();
03401 
03402     if ( block.IsVertexID( ID ))
03403       for ( ; pIt != shapePoints.end(); pIt++ ) {
03404         block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
03405       }
03406     else if ( block.IsEdgeID( ID ))
03407       for ( ; pIt != shapePoints.end(); pIt++ ) {
03408         block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
03409       }
03410     else if ( block.IsFaceID( ID ))
03411       for ( ; pIt != shapePoints.end(); pIt++ ) {
03412         block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
03413       }
03414     else
03415       for ( ; pIt != shapePoints.end(); pIt++ )
03416         block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
03417   } // loop on block sub-shapes
03418 
03419   myIsComputed = true;
03420 
03421   return setErrorCode( ERR_OK );
03422 }
03423 
03424 //=======================================================================
03425 //function : mergePoints
03426 //purpose  : Merge XYZ on edges and/or faces.
03427 //=======================================================================
03428 
03429 void SMESH_Pattern::mergePoints (const bool uniteGroups)
03430 {
03431   map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
03432   for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
03433   {
03434     list<list< int > >& groups = idListIt->second;
03435     if ( groups.size() < 2 )
03436       continue;
03437 
03438     // find tolerance
03439     const TNodeSet& nodes = idListIt->first;
03440     double tol2 = 1.e-10;
03441     if ( nodes.size() > 1 ) {
03442       Bnd_Box box;
03443       TNodeSet::const_iterator n = nodes.begin();
03444       for ( ; n != nodes.end(); ++n )
03445         box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
03446       double x, y, z, X, Y, Z;
03447       box.Get( x, y, z, X, Y, Z );
03448       gp_Pnt p( x, y, z ), P( X, Y, Z );
03449       tol2 = 1.e-4 * p.SquareDistance( P );
03450     }
03451 
03452     // to unite groups on link
03453     bool unite = ( uniteGroups && nodes.size() == 2 );
03454     map< double, int > distIndMap;
03455     const SMDS_MeshNode* node = *nodes.begin();
03456     gp_Pnt P( node->X(), node->Y(), node->Z() );
03457 
03458     // compare points, replace indices
03459 
03460     list< int >::iterator ind1, ind2;
03461     list< list< int > >::iterator grpIt1, grpIt2;
03462     for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
03463     {
03464       list< int >& indices1 = *grpIt1;
03465       grpIt2 = grpIt1;
03466       for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
03467       {
03468         list< int >& indices2 = *grpIt2;
03469         for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
03470         {
03471           gp_XYZ& p1 = myXYZ[ *ind1 ];
03472           ind2 = indices2.begin();
03473           while ( ind2 != indices2.end() )
03474           {
03475             gp_XYZ& p2 = myXYZ[ *ind2 ];
03476             //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
03477             if ( ( p1 - p2 ).SquareModulus() <= tol2 )
03478             {
03479               ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
03480               list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
03481               list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
03482               for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
03483               {
03484                 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
03485                 myXYZ[ *ind2 ] = undefinedXYZ();
03486                 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
03487               }
03488               ind2 = indices2.erase( ind2 );
03489             }
03490             else
03491               ind2++;
03492           }
03493         }
03494       }
03495       if ( unite ) { // sort indices using distIndMap
03496         for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
03497         {
03498           ASSERT( isDefined( myXYZ[ *ind1 ] ));
03499           double dist = P.SquareDistance( myXYZ[ *ind1 ]);
03500           distIndMap.insert( make_pair( dist, *ind1 ));
03501         }
03502       }
03503     }
03504     if ( unite ) { // put all sorted indices into the first group
03505       list< int >& g = groups.front();
03506       g.clear();
03507       map< double, int >::iterator dist_ind = distIndMap.begin();
03508       for ( ; dist_ind != distIndMap.end(); dist_ind++ )
03509         g.push_back( dist_ind->second );
03510     }
03511   } // loop on myIdsOnBoundary
03512 }
03513 
03514 //=======================================================================
03515 //function : makePolyElements
03516 //purpose  : prepare intermediate data to create Polygons and Polyhedrons
03517 //=======================================================================
03518 
03519 void SMESH_Pattern::
03520   makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
03521                    const bool                            toCreatePolygons,
03522                    const bool                            toCreatePolyedrs)
03523 {
03524   myPolyElemXYZIDs.clear();
03525   myPolyElems.clear();
03526   myPolyElems.reserve( myIdsOnBoundary.size() );
03527 
03528   // make a set of refined elements
03529   TIDSortedElemSet avoidSet, elemSet;
03530   std::vector<const SMDS_MeshElement*>::iterator itv =  myElements.begin();
03531   for(; itv!=myElements.end(); itv++) {
03532     const SMDS_MeshElement* el = (*itv);
03533     avoidSet.insert( el );
03534   }
03535   //avoidSet.insert( myElements.begin(), myElements.end() );
03536 
03537   map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
03538 
03539   if ( toCreatePolygons )
03540   {
03541     int lastFreeId = myXYZ.size();
03542 
03543     // loop on links of refined elements
03544     indListIt = myIdsOnBoundary.begin();
03545     for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
03546     {
03547       const TNodeSet & linkNodes = indListIt->first;
03548       if ( linkNodes.size() != 2 )
03549         continue; // skip face
03550       const SMDS_MeshNode* n1 = * linkNodes.begin();
03551       const SMDS_MeshNode* n2 = * linkNodes.rbegin();
03552 
03553       list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
03554       if ( idGroups.empty() || idGroups.front().empty() )
03555         continue;
03556 
03557       // find not refined face having n1-n2 link
03558 
03559       while (true)
03560       {
03561         const SMDS_MeshElement* face =
03562           SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
03563         if ( face )
03564         {
03565           avoidSet.insert ( face );
03566           myPolyElems.push_back( face );
03567 
03568           // some links of <face> are split;
03569           // make list of xyz for <face>
03570           myPolyElemXYZIDs.push_back(TElemDef());
03571           TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
03572           // loop on links of a <face>
03573           SMDS_ElemIteratorPtr nIt = face->nodesIterator();
03574           int i = 0, nbNodes = face->NbNodes();
03575           vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
03576           while ( nIt->more() )
03577             nodes[ i++ ] = smdsNode( nIt->next() );
03578           nodes[ i ] = nodes[ 0 ];
03579           for ( i = 0; i < nbNodes; ++i )
03580           {
03581             // look for point mapped on a link
03582             TNodeSet faceLinkNodes;
03583             faceLinkNodes.insert( nodes[ i ] );
03584             faceLinkNodes.insert( nodes[ i + 1 ] );
03585             if ( faceLinkNodes == linkNodes )
03586               nn_IdList = indListIt;
03587             else
03588               nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
03589             // add face point ids
03590             faceNodeIds.push_back( ++lastFreeId );
03591             myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
03592             if ( nn_IdList != myIdsOnBoundary.end() )
03593             {
03594               // there are points mapped on a link
03595               list< int >& mappedIds = nn_IdList->second.front();
03596               if ( isReversed( nodes[ i ], mappedIds ))
03597                 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
03598               else
03599                 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
03600             }
03601           } // loop on links of a <face>
03602         } // if ( face )
03603         else
03604           break;
03605       } // while (true)
03606 
03607       if ( myIs2D && idGroups.size() > 1 ) {
03608 
03609         // sew new elements on 2 refined elements sharing n1-n2 link
03610 
03611         list< int >& idsOnLink = idGroups.front();
03612         // temporarily add ids of link nodes to idsOnLink
03613         bool rev = isReversed( n1, idsOnLink );
03614         for ( int i = 0; i < 2; ++i )
03615         {
03616           TNodeSet nodeSet;
03617           nodeSet.insert( i ? n2 : n1 );
03618           ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
03619           list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
03620           int nodeId = groups.front().front();
03621           bool append = i;
03622           if ( rev ) append = !append;
03623           if ( append )
03624             idsOnLink.push_back( nodeId );
03625           else
03626             idsOnLink.push_front( nodeId );
03627         }
03628         list< int >::iterator id = idsOnLink.begin();
03629         for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
03630         {
03631           list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
03632           list< TElemDef* >::iterator pElemDef = elemDefs.begin();
03633           for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
03634           {
03635             TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
03636             // look for <id> in element definition
03637             TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
03638             ASSERT ( idDef != pIdList->end() );
03639             // look for 2 neighbour ids of <id> in element definition
03640             for ( int prev = 0; prev < 2; ++prev ) {
03641               TElemDef::iterator idDef2 = idDef;
03642               if ( prev )
03643                 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
03644               else
03645                 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
03646               // look for idDef2 on a link starting from id
03647               list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
03648               if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
03649                 // insert ids located on link between <id> and <id2>
03650                 // into the element definition between idDef and idDef2
03651                 if ( prev )
03652                   for ( ; id2 != id; --id2 )
03653                     pIdList->insert( idDef, *id2 );
03654                 else {
03655                   list< int >::iterator id1 = id;
03656                   for ( ++id1, ++id2; id1 != id2; ++id1 )
03657                     pIdList->insert( idDef2, *id1 );
03658                 }
03659               }
03660             }
03661           }
03662         }
03663         // remove ids of link nodes
03664         idsOnLink.pop_front();
03665         idsOnLink.pop_back();
03666       }
03667     } // loop on myIdsOnBoundary
03668   } // if ( toCreatePolygons )
03669 
03670   if ( toCreatePolyedrs )
03671   {
03672     // check volumes adjacent to the refined elements
03673     SMDS_VolumeTool volTool;
03674     vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
03675     for ( ; refinedElem != myElements.end(); ++refinedElem )
03676     {
03677       // loop on nodes of refinedElem
03678       SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
03679       while ( nIt->more() ) {
03680         const SMDS_MeshNode* node = smdsNode( nIt->next() );
03681         // loop on inverse elements of node
03682         SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
03683         while ( eIt->more() )
03684         {
03685           const SMDS_MeshElement* elem = eIt->next();
03686           if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
03687             continue; // skip faces or refined elements
03688           // add polyhedron definition
03689           myPolyhedronQuantities.push_back(vector<int> ());
03690           myPolyElemXYZIDs.push_back(TElemDef());
03691           vector<int>& quantity = myPolyhedronQuantities.back();
03692           TElemDef &   elemDef  = myPolyElemXYZIDs.back();
03693           // get definitions of new elements on volume faces
03694           bool makePoly = false;
03695           for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
03696           {
03697             if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
03698                                     volTool.NbFaceNodes( iF ),
03699                                     theNodes, elemDef, quantity))
03700               makePoly = true;
03701           }
03702           if ( makePoly )
03703             myPolyElems.push_back( elem );
03704           else {
03705             myPolyhedronQuantities.pop_back();
03706             myPolyElemXYZIDs.pop_back();
03707           }
03708         }
03709       }
03710     }
03711   }
03712 }
03713 
03714 //=======================================================================
03715 //function : getFacesDefinition
03716 //purpose  : return faces definition for a volume face defined by theBndNodes
03717 //=======================================================================
03718 
03719 bool SMESH_Pattern::
03720   getFacesDefinition(const SMDS_MeshNode**                 theBndNodes,
03721                      const int                             theNbBndNodes,
03722                      const vector< const SMDS_MeshNode* >& theNodes,
03723                      list< int >&                          theFaceDefs,
03724                      vector<int>&                          theQuantity)
03725 {
03726   bool makePoly = false;
03727 
03728   set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
03729 
03730   map< TNodeSet, list< list< int > > >::iterator nn_IdList;
03731 
03732   // make a set of all nodes on a face
03733   set< int > ids;
03734   if ( !myIs2D ) { // for 2D, merge only edges
03735     nn_IdList = myIdsOnBoundary.find( bndNodeSet );
03736     if ( nn_IdList != myIdsOnBoundary.end() ) {
03737       list< int > & faceIds = nn_IdList->second.front();
03738       if ( !faceIds.empty() ) {
03739         makePoly = true;
03740         ids.insert( faceIds.begin(), faceIds.end() );
03741       }
03742     }
03743   }
03744 
03745   // add ids on links and bnd nodes
03746   int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
03747   TElemDef faceDef; // definition for the case if there is no new adjacent volumes
03748   for ( int iN = 0; iN < theNbBndNodes; ++iN )
03749   {
03750     // add id of iN-th bnd node
03751     TNodeSet nSet;
03752     nSet.insert( theBndNodes[ iN ] );
03753     nn_IdList = myIdsOnBoundary.find( nSet );
03754     int bndId = ++lastFreeId;
03755     if ( nn_IdList != myIdsOnBoundary.end() ) {
03756       bndId = nn_IdList->second.front().front();
03757       ids.insert( bndId );
03758     }
03759     else {
03760       myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
03761     }
03762     faceDef.push_back( bndId );
03763     // add ids on a link
03764     TNodeSet linkNodes;
03765     linkNodes.insert( theBndNodes[ iN ]);
03766     linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
03767     nn_IdList = myIdsOnBoundary.find( linkNodes );
03768     if ( nn_IdList != myIdsOnBoundary.end() ) {
03769       list< int > & linkIds = nn_IdList->second.front();
03770       if ( !linkIds.empty() )
03771       {
03772         makePoly = true;
03773         ids.insert( linkIds.begin(), linkIds.end() );
03774         if ( isReversed( theBndNodes[ iN ], linkIds ))
03775           faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
03776         else
03777           faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
03778       }
03779     }
03780   }
03781 
03782   // find faces definition of new volumes
03783 
03784   bool defsAdded = false;
03785   if ( !myIs2D ) { // for 2D, merge only edges
03786     SMDS_VolumeTool vol;
03787     set< TElemDef* > checkedVolDefs;
03788     set< int >::iterator id = ids.begin();
03789     for ( ; id != ids.end(); ++id )
03790     {
03791       // definitions of volumes sharing id
03792       list< TElemDef* >& defList = myReverseConnectivity[ *id ];
03793       ASSERT( !defList.empty() );
03794       // loop on volume definitions
03795       list< TElemDef* >::iterator pIdList = defList.begin();
03796       for ( ; pIdList != defList.end(); ++pIdList)
03797       {
03798         if ( !checkedVolDefs.insert( *pIdList ).second )
03799           continue; // skip already checked volume definition
03800         vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
03801         // loop on face defs of a volume
03802         SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
03803         if ( volType == SMDS_VolumeTool::UNKNOWN )
03804           continue;
03805         int nbFaces = vol.NbFaces( volType );
03806         for ( int iF = 0; iF < nbFaces; ++iF )
03807         {
03808           const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
03809           int iN, nbN = vol.NbFaceNodes( volType, iF );
03810           // check if all nodes of a faces are in <ids>
03811           bool all = true;
03812           for ( iN = 0; iN < nbN && all; ++iN ) {
03813             int nodeId = idVec[ nodeInds[ iN ]];
03814             all = ( ids.find( nodeId ) != ids.end() );
03815           }
03816           if ( all ) {
03817             // store a face definition
03818             for ( iN = 0; iN < nbN; ++iN ) {
03819               theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
03820             }
03821             theQuantity.push_back( nbN );
03822             defsAdded = true;
03823           }
03824         }
03825       }
03826     }
03827   }
03828   if ( !defsAdded ) {
03829     theQuantity.push_back( faceDef.size() );
03830     theFaceDefs.splice( theFaceDefs.end(), faceDef );
03831   }
03832 
03833   return makePoly;
03834 }
03835 
03836 //=======================================================================
03837 //function : clearSubMesh
03838 //purpose  : 
03839 //=======================================================================
03840 
03841 static bool clearSubMesh( SMESH_Mesh*         theMesh,
03842                           const TopoDS_Shape& theShape)
03843 {
03844   bool removed = false;
03845   if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
03846   {
03847     removed = !aSubMesh->IsEmpty();
03848     if ( removed )
03849       aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
03850   }
03851   else {
03852     SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
03853     if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
03854     {
03855       SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
03856       removed = eIt->more();
03857       while ( eIt->more() )
03858         aMeshDS->RemoveElement( eIt->next() );
03859       SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
03860       removed = removed || nIt->more();
03861       while ( nIt->more() )
03862         aMeshDS->RemoveNode( smdsNode( nIt->next() ));
03863     }
03864   }
03865   return removed;
03866 }
03867 
03868 //=======================================================================
03869 //function : clearMesh
03870 //purpose  : clear mesh elements existing on myShape in theMesh
03871 //=======================================================================
03872 
03873 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
03874 {
03875 
03876   if ( !myShape.IsNull() )
03877   {
03878     if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
03879       TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
03880       for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
03881       {
03882         clearSubMesh( theMesh, it.Value() );
03883       }
03884     }
03885   }
03886 }
03887 
03888 //=======================================================================
03889 //function : MakeMesh
03890 //purpose  : Create nodes and elements in <theMesh> using nodes
03891 //           coordinates computed by either of Apply...() methods
03892 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
03893 //           it does not care of nodes and elements already existing on
03894 //           sub-shapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
03895 //=======================================================================
03896 
03897 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
03898                              const bool  toCreatePolygons,
03899                              const bool  toCreatePolyedrs)
03900 {
03901   MESSAGE(" ::MakeMesh() " );
03902   if ( !myIsComputed )
03903     return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
03904 
03905   mergePoints( toCreatePolygons );
03906 
03907   SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
03908 
03909   // clear elements and nodes existing on myShape
03910   clearMesh(theMesh);
03911 
03912   bool onMeshElements = ( !myElements.empty() );
03913 
03914   // Create missing nodes
03915 
03916   vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
03917   if ( onMeshElements )
03918   {
03919     nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
03920     map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
03921     for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
03922       nodesVector[ i_node->first ] = i_node->second;
03923     }
03924     for ( int i = 0; i < myXYZ.size(); ++i ) {
03925       if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
03926         nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
03927                                              myXYZ[ i ].Y(),
03928                                              myXYZ[ i ].Z());
03929     }
03930   }
03931   else
03932   {
03933     nodesVector.resize( myPoints.size(), 0 );
03934 
03935     // to find point index
03936     map< TPoint*, int > pointIndex;
03937     for ( int i = 0; i < myPoints.size(); i++ )
03938       pointIndex.insert( make_pair( & myPoints[ i ], i ));
03939 
03940     // loop on sub-shapes of myShape: create nodes
03941     map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
03942     for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
03943     {
03944       TopoDS_Shape S;
03945       //SMESHDS_SubMesh * subMeshDS = 0;
03946       if ( !myShapeIDMap.IsEmpty() ) {
03947         S = myShapeIDMap( idPointIt->first );
03948         //subMeshDS = aMeshDS->MeshElements( S );
03949       }
03950       list< TPoint* > & points = idPointIt->second;
03951       list< TPoint* >::iterator pIt = points.begin();
03952       for ( ; pIt != points.end(); pIt++ )
03953       {
03954         TPoint* point = *pIt;
03955         int pIndex = pointIndex[ point ];
03956         if ( nodesVector [ pIndex ] )
03957           continue;
03958         SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
03959                                                 point->myXYZ.Y(),
03960                                                 point->myXYZ.Z());
03961         nodesVector [ pIndex ] = node;
03962 
03963         if ( !S.IsNull() /*subMeshDS*/ ) {
03964           // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
03965           switch ( S.ShapeType() ) {
03966           case TopAbs_VERTEX: {
03967             aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
03968           }
03969           case TopAbs_EDGE: {
03970             aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
03971           }
03972           case TopAbs_FACE: {
03973             aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
03974                                     point->myUV.X(), point->myUV.Y() ); break;
03975           }
03976           default:
03977             aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
03978           }
03979         }
03980       }
03981     }
03982   }
03983 
03984   // create elements
03985 
03986   if ( onMeshElements )
03987   {
03988     // prepare data to create poly elements
03989     makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
03990 
03991     // refine elements
03992     createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
03993     // sew old and new elements
03994     createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
03995   }
03996   else
03997   {
03998     createElements( theMesh, nodesVector, myElemPointIDs, myElements );
03999   }
04000 
04001   aMeshDS->compactMesh();
04002 
04003 //   const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
04004 //   map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
04005 //   for ( ; i_sm != sm.end(); i_sm++ )
04006 //   {
04007 //     cout << " SM " << i_sm->first << " ";
04008 //     TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
04009 //     //SMDS_ElemIteratorPtr GetElements();
04010 //     SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
04011 //     while ( nit->more() )
04012 //       cout << nit->next()->GetID() << " ";
04013 //     cout << endl;
04014 //   }
04015   return setErrorCode( ERR_OK );
04016 }
04017 
04018 //=======================================================================
04019 //function : createElements
04020 //purpose  : add elements to the mesh
04021 //=======================================================================
04022 
04023 void SMESH_Pattern::createElements(SMESH_Mesh*                            theMesh,
04024                                    const vector<const SMDS_MeshNode* >&   theNodesVector,
04025                                    const list< TElemDef > &               theElemNodeIDs,
04026                                    const vector<const SMDS_MeshElement*>& theElements)
04027 {
04028   SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
04029   SMESH_MeshEditor editor( theMesh );
04030 
04031   bool onMeshElements = !theElements.empty();
04032 
04033   // shapes and groups theElements are on
04034   vector< int > shapeIDs;
04035   vector< list< SMESHDS_Group* > > groups;
04036   set< const SMDS_MeshNode* > shellNodes;
04037   if ( onMeshElements )
04038   {
04039     shapeIDs.resize( theElements.size() );
04040     groups.resize( theElements.size() );
04041     const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
04042     set<SMESHDS_GroupBase*>::const_iterator grIt;
04043     for ( int i = 0; i < theElements.size(); i++ )
04044     {
04045       shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
04046       for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
04047         SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
04048         if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
04049           groups[ i ].push_back( group );
04050       }
04051     }
04052     // get all nodes bound to shells because their SpacePosition is not set
04053     // by SMESHDS_Mesh::SetNodeInVolume()
04054     TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
04055     if ( !aMainShape.IsNull() ) {
04056       TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
04057       for ( ; shellExp.More(); shellExp.Next() )
04058       {
04059         SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
04060         if ( sm ) {
04061           SMDS_NodeIteratorPtr nIt = sm->GetNodes();
04062           while ( nIt->more() )
04063             shellNodes.insert( nIt->next() );
04064         }
04065       }
04066     }
04067   }
04068    // nb new elements per a refined element
04069   int nbNewElemsPerOld = 1;
04070   if ( onMeshElements )
04071     nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
04072 
04073   bool is2d = myIs2D;
04074 
04075   list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
04076   list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
04077   for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
04078   {
04079     const TElemDef & elemNodeInd = *enIt;
04080     // retrieve nodes
04081     vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
04082     TElemDef::const_iterator id = elemNodeInd.begin();
04083     int nbNodes;
04084     for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
04085       if ( *id < theNodesVector.size() )
04086         nodes[ nbNodes++ ] = theNodesVector[ *id ];
04087       else
04088         nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
04089     }
04090     // dim of refined elem
04091     int elemIndex = iElem / nbNewElemsPerOld; // refined element index
04092     if ( onMeshElements ) {
04093       is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
04094     }
04095     // add an element
04096     const SMDS_MeshElement* elem = 0;
04097     if ( is2d ) {
04098       switch ( nbNodes ) {
04099       case 3:
04100         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
04101       case 4:
04102         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
04103       case 6:
04104         if ( !onMeshElements ) {// create a quadratic face
04105           elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
04106                                    nodes[4], nodes[5] ); break;
04107         } // else do not break but create a polygon
04108       case 8:
04109         if ( !onMeshElements ) {// create a quadratic face
04110           elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
04111                                    nodes[4], nodes[5], nodes[6], nodes[7] ); break;
04112         } // else do not break but create a polygon
04113       default:
04114         elem = aMeshDS->AddPolygonalFace( nodes );
04115       }
04116     }
04117     else {
04118       switch ( nbNodes ) {
04119       case 4:
04120         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
04121       case 5:
04122         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
04123                                    nodes[4] ); break;
04124       case 6:
04125         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
04126                                    nodes[4], nodes[5] ); break;
04127       case 8:
04128         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
04129                                    nodes[4], nodes[5], nodes[6], nodes[7] ); break;
04130       default:
04131         elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
04132       }
04133     }
04134     // set element on a shape
04135     if ( elem && onMeshElements ) // applied to mesh elements
04136     {
04137       int shapeID = shapeIDs[ elemIndex ];
04138       if ( shapeID > 0 ) {
04139         aMeshDS->SetMeshElementOnShape( elem, shapeID );
04140         // set nodes on a shape
04141         TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
04142         if ( S.ShapeType() == TopAbs_SOLID ) {
04143           TopoDS_Iterator shellIt( S );
04144           if ( shellIt.More() )
04145             shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
04146         }
04147         SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
04148         while ( noIt->more() ) {
04149           SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
04150           if (!node->getshapeId() &&
04151               shellNodes.find( node ) == shellNodes.end() ) {
04152             if ( S.ShapeType() == TopAbs_FACE )
04153               aMeshDS->SetNodeOnFace( node, shapeID,
04154                                       Precision::Infinite(),// <- it's a sign that UV is not set
04155                                       Precision::Infinite());
04156             else {
04157               aMeshDS->SetNodeInVolume( node, shapeID );
04158               shellNodes.insert( node );
04159             }
04160           }
04161         }
04162       }
04163       // add elem in groups
04164       list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
04165       for ( ; g != groups[ elemIndex ].end(); ++g )
04166         (*g)->SMDSGroup().Add( elem );
04167     }
04168     if ( elem && !myShape.IsNull() ) // applied to shape
04169       aMeshDS->SetMeshElementOnShape( elem, myShape );
04170   }
04171 
04172   // make that SMESH_subMesh::_computeState == COMPUTE_OK
04173   // so that operations with hypotheses will erase the mesh being built
04174 
04175   SMESH_subMesh * subMesh;
04176   if ( !myShape.IsNull() ) {
04177     subMesh = theMesh->GetSubMesh( myShape );
04178     if ( subMesh )
04179       subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
04180   }
04181   if ( onMeshElements ) {
04182     list< int > elemIDs;
04183     for ( int i = 0; i < theElements.size(); i++ )
04184     {
04185       subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
04186       if ( subMesh )
04187         subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
04188 
04189       elemIDs.push_back( theElements[ i ]->GetID() );
04190     }
04191     // remove refined elements
04192     editor.Remove( elemIDs, false );
04193   }
04194 }
04195 
04196 //=======================================================================
04197 //function : isReversed
04198 //purpose  : check xyz ids order in theIdsList taking into account
04199 //           theFirstNode on a link
04200 //=======================================================================
04201 
04202 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
04203                                const list< int >&   theIdsList) const
04204 {
04205   if ( theIdsList.size() < 2 )
04206     return false;
04207 
04208   gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
04209   gp_Pnt P[2];
04210   list<int>::const_iterator id = theIdsList.begin();
04211   for ( int i = 0; i < 2; ++i, ++id ) {
04212     if ( *id < myXYZ.size() )
04213       P[ i ] = myXYZ[ *id ];
04214     else {
04215       map< int, const SMDS_MeshNode*>::const_iterator i_n;
04216       i_n = myXYZIdToNodeMap.find( *id );
04217       ASSERT( i_n != myXYZIdToNodeMap.end() );
04218       const SMDS_MeshNode* n = i_n->second;
04219       P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
04220     }
04221   }
04222   return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
04223 }
04224 
04225 
04226 //=======================================================================
04227 //function : arrangeBoundaries
04228 //purpose  : if there are several wires, arrange boundaryPoints so that
04229 //           the outer wire goes first and fix inner wires orientation
04230 //           update myKeyPointIDs to correspond to the order of key-points
04231 //           in boundaries; sort internal boundaries by the nb of key-points
04232 //=======================================================================
04233 
04234 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
04235 {
04236   typedef list< list< TPoint* > >::iterator TListOfListIt;
04237   TListOfListIt bndIt;
04238   list< TPoint* >::iterator pIt;
04239 
04240   int nbBoundaries = boundaryList.size();
04241   if ( nbBoundaries > 1 )
04242   {
04243     // sort boundaries by nb of key-points
04244     if ( nbBoundaries > 2 )
04245     {
04246       // move boundaries in tmp list
04247       list< list< TPoint* > > tmpList;
04248       tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
04249       // make a map nb-key-points to boundary-position-in-tmpList,
04250       // boundary-positions get ordered in it
04251       typedef map< int, TListOfListIt > TNbKpBndPosMap;
04252       TNbKpBndPosMap nbKpBndPosMap;
04253       bndIt = tmpList.begin();
04254       list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
04255       for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
04256         int nb = *nbKpIt * nbBoundaries;
04257         while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
04258           nb++;
04259         nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
04260       }
04261       // move boundaries back to boundaryList
04262       TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
04263       for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
04264         TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
04265         TListOfListIt bndPos1 = bndPos2++;
04266         boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
04267       }
04268     }
04269 
04270     // Look for the outer boundary: the one with the point with the least X
04271     double leastX = DBL_MAX;
04272     TListOfListIt outerBndPos;
04273     for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
04274     {
04275       list< TPoint* >& boundary = (*bndIt);
04276       for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
04277       {
04278         TPoint* point = *pIt;
04279         if ( point->myInitXYZ.X() < leastX ) {
04280           leastX = point->myInitXYZ.X();
04281           outerBndPos = bndIt;
04282         }
04283       }
04284     }
04285 
04286     if ( outerBndPos != boundaryList.begin() )
04287       boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
04288 
04289   } // if nbBoundaries > 1
04290 
04291   // Check boundaries orientation and re-fill myKeyPointIDs
04292 
04293   set< TPoint* > keyPointSet;
04294   list< int >::iterator kpIt = myKeyPointIDs.begin();
04295   for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
04296     keyPointSet.insert( & myPoints[ *kpIt ]);
04297   myKeyPointIDs.clear();
04298 
04299   // update myNbKeyPntInBoundary also
04300   list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
04301 
04302   for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
04303   {
04304     // find the point with the least X
04305     double leastX = DBL_MAX;
04306     list< TPoint* >::iterator xpIt;
04307     list< TPoint* >& boundary = (*bndIt);
04308     for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
04309     {
04310       TPoint* point = *pIt;
04311       if ( point->myInitXYZ.X() < leastX ) {
04312         leastX = point->myInitXYZ.X();
04313         xpIt = pIt;
04314       }
04315     }
04316     // find points next to the point with the least X
04317     TPoint* p = *xpIt, *pPrev, *pNext;
04318     if ( p == boundary.front() )
04319       pPrev = *(++boundary.rbegin());
04320     else {
04321       xpIt--;
04322       pPrev = *xpIt;
04323       xpIt++;
04324     }
04325     if ( p == boundary.back() )
04326       pNext = *(++boundary.begin());
04327     else {
04328       xpIt++;
04329       pNext = *xpIt;
04330     }
04331     // vectors of boundary direction near <p>
04332     gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
04333     double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
04334     if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
04335       double yPrev = v1.Y() / sqrt( sqMag1 );
04336       double yNext = v2.Y() / sqrt( sqMag2 );
04337       double sumY = yPrev + yNext;
04338       bool reverse;
04339       if ( bndIt == boundaryList.begin() ) // outer boundary
04340         reverse = sumY > 0;
04341       else
04342         reverse = sumY < 0;
04343       if ( reverse )
04344         boundary.reverse();
04345     }
04346 
04347     // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
04348     (*nbKpIt) = 0; // count nb of key-points again
04349     pIt = boundary.begin();
04350     for ( ; pIt != boundary.end(); pIt++)
04351     {
04352       TPoint* point = *pIt;
04353       if ( keyPointSet.find( point ) == keyPointSet.end() )
04354         continue;
04355       // find an index of a keypoint
04356       int index = 0;
04357       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
04358       for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
04359         if ( &(*pVecIt) == point )
04360           break;
04361       myKeyPointIDs.push_back( index );
04362       (*nbKpIt)++;
04363     }
04364     myKeyPointIDs.pop_back(); // remove the first key-point from the back
04365     (*nbKpIt)--;
04366 
04367   } // loop on a list of boundaries
04368 
04369   ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
04370 }
04371 
04372 //=======================================================================
04373 //function : findBoundaryPoints
04374 //purpose  : if loaded from file, find points to map on edges and faces and
04375 //           compute their parameters
04376 //=======================================================================
04377 
04378 bool SMESH_Pattern::findBoundaryPoints()
04379 {
04380   if ( myIsBoundaryPointsFound ) return true;
04381 
04382   MESSAGE(" findBoundaryPoints() ");
04383 
04384   myNbKeyPntInBoundary.clear();
04385 
04386   if ( myIs2D )
04387   {
04388     set< TPoint* > pointsInElems;
04389 
04390     // Find free links of elements:
04391     // put links of all elements in a set and remove links encountered twice
04392 
04393     typedef pair< TPoint*, TPoint*> TLink;
04394     set< TLink > linkSet;
04395     list<TElemDef >::iterator epIt = myElemPointIDs.begin();
04396     for ( ; epIt != myElemPointIDs.end(); epIt++ )
04397     {
04398       TElemDef & elemPoints = *epIt;
04399       TElemDef::iterator pIt = elemPoints.begin();
04400       int prevP = elemPoints.back();
04401       for ( ; pIt != elemPoints.end(); pIt++ ) {
04402         TPoint* p1 = & myPoints[ prevP ];
04403         TPoint* p2 = & myPoints[ *pIt ];
04404         TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
04405         ASSERT( link.first != link.second );
04406         pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
04407         if ( !itUniq.second )
04408           linkSet.erase( itUniq.first );
04409         prevP = *pIt;
04410 
04411         pointsInElems.insert( p1 );
04412       }
04413     }
04414     // Now linkSet contains only free links,
04415     // find the points order that they have in boundaries
04416 
04417     // 1. make a map of key-points
04418     set< TPoint* > keyPointSet;
04419     list< int >::iterator kpIt = myKeyPointIDs.begin();
04420     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
04421       keyPointSet.insert( & myPoints[ *kpIt ]);
04422 
04423     // 2. chain up boundary points
04424     list< list< TPoint* > > boundaryList;
04425     boundaryList.push_back( list< TPoint* >() );
04426     list< TPoint* > * boundary = & boundaryList.back();
04427 
04428     TPoint *point1, *point2, *keypoint1;
04429     kpIt = myKeyPointIDs.begin();
04430     point1 = keypoint1 = & myPoints[ *kpIt++ ];
04431     // loop on free links: look for the next point
04432     int iKeyPoint = 0;
04433     set< TLink >::iterator lIt = linkSet.begin();
04434     while ( lIt != linkSet.end() )
04435     {
04436       if ( (*lIt).first == point1 )
04437         point2 = (*lIt).second;
04438       else if ( (*lIt).second == point1 )
04439         point2 = (*lIt).first;
04440       else {
04441         lIt++;
04442         continue;
04443       }
04444       linkSet.erase( lIt );
04445       lIt = linkSet.begin();
04446 
04447       if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
04448       {
04449         boundary->push_back( point2 );
04450       }
04451       else // a key-point found
04452       {
04453         keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
04454         iKeyPoint++;
04455         if ( point2 != keypoint1 ) // its not the boundary end
04456         {
04457           boundary->push_back( point2 );
04458         }
04459         else  // the boundary end reached
04460         {
04461           boundary->push_front( keypoint1 );
04462           boundary->push_back( keypoint1 );
04463           myNbKeyPntInBoundary.push_back( iKeyPoint );
04464           if ( keyPointSet.empty() )
04465             break; // all boundaries containing key-points are found
04466 
04467           // prepare to search for the next boundary
04468           boundaryList.push_back( list< TPoint* >() );
04469           boundary = & boundaryList.back();
04470           point2 = keypoint1 = (*keyPointSet.begin());
04471         }
04472       }
04473       point1 = point2;
04474     } // loop on the free links set
04475 
04476     if ( boundary->empty() ) {
04477       MESSAGE(" a separate key-point");
04478       return setErrorCode( ERR_READ_BAD_KEY_POINT );
04479     }
04480 
04481     // if there are several wires, arrange boundaryPoints so that
04482     // the outer wire goes first and fix inner wires orientation;
04483     // sort myKeyPointIDs to correspond to the order of key-points
04484     // in boundaries
04485     arrangeBoundaries( boundaryList );
04486 
04487     // Find correspondence shape ID - points,
04488     // compute points parameter on edge
04489 
04490     keyPointSet.clear();
04491     for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
04492       keyPointSet.insert( & myPoints[ *kpIt ]);
04493 
04494     set< TPoint* > edgePointSet; // to find in-face points
04495     int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
04496     int edgeID = myKeyPointIDs.size() + 1;
04497 
04498     list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
04499     for ( ; bndIt != boundaryList.end(); bndIt++ )
04500     {
04501       boundary = & (*bndIt);
04502       double edgeLength = 0;
04503       list< TPoint* >::iterator pIt = boundary->begin();
04504       getShapePoints( edgeID ).push_back( *pIt );
04505       getShapePoints( vertexID++ ).push_back( *pIt );
04506       for ( pIt++; pIt != boundary->end(); pIt++)
04507       {
04508         list< TPoint* > & edgePoints = getShapePoints( edgeID );
04509         TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
04510         TPoint* point = *pIt;
04511         edgePointSet.insert( point );
04512         if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
04513         {
04514           edgePoints.push_back( point );
04515           edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
04516           point->myInitU = edgeLength;
04517         }
04518         else // a key-point
04519         {
04520           // treat points on the edge which ends up: compute U [0,1]
04521           edgePoints.push_back( point );
04522           if ( edgePoints.size() > 2 ) {
04523             edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
04524             list< TPoint* >::iterator epIt = edgePoints.begin();
04525             for ( ; epIt != edgePoints.end(); epIt++ )
04526               (*epIt)->myInitU /= edgeLength;
04527           }
04528           // begin the next edge treatment
04529           edgeLength = 0;
04530           edgeID++;
04531           if ( point != boundary->front() ) { // not the first key-point again
04532             getShapePoints( edgeID ).push_back( point );
04533             getShapePoints( vertexID++ ).push_back( point );
04534           }
04535         }
04536       }
04537     }
04538 
04539     // find in-face points
04540     list< TPoint* > & facePoints = getShapePoints( edgeID );
04541     vector< TPoint >::iterator pVecIt = myPoints.begin();
04542     for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
04543       TPoint* point = &(*pVecIt);
04544       if ( edgePointSet.find( point ) == edgePointSet.end() &&
04545           pointsInElems.find( point ) != pointsInElems.end())
04546         facePoints.push_back( point );
04547     }
04548 
04549   } // 2D case
04550 
04551   else // 3D case
04552   {
04553     // bind points to shapes according to point parameters
04554     vector< TPoint >::iterator pVecIt = myPoints.begin();
04555     for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
04556       TPoint* point = &(*pVecIt);
04557       int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
04558       getShapePoints( shapeID ).push_back( point );
04559       // detect key-points
04560       if ( SMESH_Block::IsVertexID( shapeID ))
04561         myKeyPointIDs.push_back( i );
04562     }
04563   }
04564 
04565   myIsBoundaryPointsFound = true;
04566   return myIsBoundaryPointsFound;
04567 }
04568 
04569 //=======================================================================
04570 //function : Clear
04571 //purpose  : clear fields
04572 //=======================================================================
04573 
04574 void SMESH_Pattern::Clear()
04575 {
04576   myIsComputed = myIsBoundaryPointsFound = false;
04577 
04578   myPoints.clear();
04579   myKeyPointIDs.clear();
04580   myElemPointIDs.clear();
04581   myShapeIDToPointsMap.clear();
04582   myShapeIDMap.Clear();
04583   myShape.Nullify();
04584   myNbKeyPntInBoundary.clear();
04585 
04586   myXYZ.clear();
04587   myElemXYZIDs.clear();
04588   myXYZIdToNodeMap.clear();
04589   myElements.clear();
04590   myOrderedNodes.clear();
04591   myPolyElems.clear();
04592   myPolyElemXYZIDs.clear();
04593   myPolyhedronQuantities.clear();
04594   myIdsOnBoundary.clear();
04595   myReverseConnectivity.clear();
04596 }
04597 
04598 //================================================================================
04602 //================================================================================
04603 
04604 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
04605 {
04606   myErrorCode = theErrorCode;
04607   return myErrorCode == ERR_OK;
04608 }
04609 
04610 //=======================================================================
04611 //function : setShapeToMesh
04612 //purpose  : set a shape to be meshed. Return True if meshing is possible
04613 //=======================================================================
04614 
04615 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
04616 {
04617   if ( !IsLoaded() ) {
04618     MESSAGE( "Pattern not loaded" );
04619     return setErrorCode( ERR_APPL_NOT_LOADED );
04620   }
04621 
04622   TopAbs_ShapeEnum aType = theShape.ShapeType();
04623   bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
04624   if ( !dimOk ) {
04625     MESSAGE( "Pattern dimention mismatch" );
04626     return setErrorCode( ERR_APPL_BAD_DIMENTION );
04627   }
04628 
04629   // check if a face is closed
04630   int nbNodeOnSeamEdge = 0;
04631   if ( myIs2D ) {
04632     TopTools_MapOfShape seamVertices;
04633     TopoDS_Face face = TopoDS::Face( theShape );
04634     TopExp_Explorer eExp( theShape, TopAbs_EDGE );
04635     for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
04636       const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
04637       if ( BRep_Tool::IsClosed(ee, face) ) {
04638         // seam edge and vertices encounter twice in theFace
04639         if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
04640         if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
04641       }
04642     }
04643   }
04644 
04645   // check nb of vertices
04646   TopTools_IndexedMapOfShape vMap;
04647   TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
04648   if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
04649     MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
04650     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
04651   }
04652 
04653   myElements.clear(); // not refine elements
04654   myElemXYZIDs.clear();
04655 
04656   myShapeIDMap.Clear();
04657   myShape = theShape;
04658   return true;
04659 }
04660 
04661 //=======================================================================
04662 //function : GetMappedPoints
04663 //purpose  : Return nodes coordinates computed by Apply() method
04664 //=======================================================================
04665 
04666 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
04667 {
04668   thePoints.clear();
04669   if ( !myIsComputed )
04670     return false;
04671 
04672   if ( myElements.empty() ) { // applied to shape
04673     vector< TPoint >::const_iterator pVecIt = myPoints.begin();
04674     for ( ; pVecIt != myPoints.end(); pVecIt++ )
04675       thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
04676   }
04677   else { // applied to mesh elements
04678     const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
04679     vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
04680     for ( ; xyz != myXYZ.end(); ++xyz )
04681       if ( !isDefined( *xyz ))
04682         thePoints.push_back( definedXYZ );
04683       else
04684         thePoints.push_back( & (*xyz) );
04685   }
04686   return !thePoints.empty();
04687 }
04688 
04689 
04690 //=======================================================================
04691 //function : GetPoints
04692 //purpose  : Return nodes coordinates of the pattern
04693 //=======================================================================
04694 
04695 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
04696 {
04697   thePoints.clear();
04698 
04699   if ( !IsLoaded() )
04700     return false;
04701 
04702   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
04703   for ( ; pVecIt != myPoints.end(); pVecIt++ )
04704     thePoints.push_back( & (*pVecIt).myInitXYZ );
04705 
04706   return ( thePoints.size() > 0 );
04707 }
04708 
04709 //=======================================================================
04710 //function : getShapePoints
04711 //purpose  : return list of points located on theShape
04712 //=======================================================================
04713 
04714 list< SMESH_Pattern::TPoint* > &
04715   SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
04716 {
04717   int aShapeID;
04718   if ( !myShapeIDMap.Contains( theShape ))
04719     aShapeID = myShapeIDMap.Add( theShape );
04720   else
04721     aShapeID = myShapeIDMap.FindIndex( theShape );
04722 
04723   return myShapeIDToPointsMap[ aShapeID ];
04724 }
04725 
04726 //=======================================================================
04727 //function : getShapePoints
04728 //purpose  : return list of points located on the shape
04729 //=======================================================================
04730 
04731 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
04732 {
04733   return myShapeIDToPointsMap[ theShapeID ];
04734 }
04735 
04736 //=======================================================================
04737 //function : DumpPoints
04738 //purpose  : Debug
04739 //=======================================================================
04740 
04741 void SMESH_Pattern::DumpPoints() const
04742 {
04743 #ifdef _DEBUG_
04744   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
04745   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
04746     MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
04747 #endif
04748 }
04749 
04750 //=======================================================================
04751 //function : TPoint()
04752 //purpose  : 
04753 //=======================================================================
04754 
04755 SMESH_Pattern::TPoint::TPoint()
04756 {
04757 #ifdef _DEBUG_
04758   myInitXYZ.SetCoord(0,0,0);
04759   myInitUV.SetCoord(0.,0.);
04760   myInitU = 0;
04761   myXYZ.SetCoord(0,0,0);
04762   myUV.SetCoord(0.,0.);
04763   myU = 0;
04764 #endif
04765 }
04766 
04767 //=======================================================================
04768 //function : operator <<
04769 //purpose  : 
04770 //=======================================================================
04771 
04772 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
04773 {
04774   gp_XYZ xyz = p.myInitXYZ;
04775   OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
04776   gp_XY xy = p.myInitUV;
04777   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
04778   double u = p.myInitU;
04779   OS << " u( " <<  u << " )) " << &p << endl;
04780   xyz = p.myXYZ.XYZ();
04781   OS << "\t    ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
04782   xy = p.myUV;
04783   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
04784   u = p.myU;
04785   OS << " u( " <<  u << " ))" << endl;
04786 
04787   return OS;
04788 }