1 // Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_Pattern.hxx
24 // Created : Mon Aug 2 10:30:00 2004
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_Pattern.hxx"
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FacePosition.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshFace.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Group.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "SMESHDS_SubMesh.hxx"
38 #include "SMESH_Block.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_subMesh.hxx"
44 #include <BRepAdaptor_Curve.hxx>
45 #include <BRepTools.hxx>
46 #include <BRepTools_WireExplorer.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_Box.hxx>
49 #include <Bnd_Box2d.hxx>
51 #include <Extrema_ExtPC.hxx>
52 #include <Extrema_GenExtPS.hxx>
53 #include <Extrema_POnSurf.hxx>
54 #include <Geom2d_Curve.hxx>
55 #include <GeomAdaptor_Surface.hxx>
56 #include <Geom_Curve.hxx>
57 #include <Geom_Surface.hxx>
58 #include <Precision.hxx>
59 #include <TopAbs_ShapeEnum.hxx>
61 #include <TopExp_Explorer.hxx>
62 #include <TopLoc_Location.hxx>
63 #include <TopTools_ListIteratorOfListOfShape.hxx>
65 #include <TopoDS_Edge.hxx>
66 #include <TopoDS_Face.hxx>
67 #include <TopoDS_Iterator.hxx>
68 #include <TopoDS_Shell.hxx>
69 #include <TopoDS_Vertex.hxx>
70 #include <TopoDS_Wire.hxx>
72 #include <gp_Lin2d.hxx>
73 #include <gp_Pnt2d.hxx>
74 #include <gp_Trsf.hxx>
78 #include <Basics_OCCTVersion.hxx>
80 #include <Basics_Utils.hxx>
81 #include "utilities.h"
85 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
87 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
89 //=======================================================================
90 //function : SMESH_Pattern
92 //=======================================================================
94 SMESH_Pattern::SMESH_Pattern ()
97 //=======================================================================
100 //=======================================================================
102 static inline int getInt( const char * theSring )
104 if ( *theSring < '0' || *theSring > '9' )
108 int val = strtol( theSring, &ptr, 10 );
109 if ( ptr == theSring ||
110 // there must not be neither '.' nor ',' nor 'E' ...
111 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
117 //=======================================================================
118 //function : getDouble
120 //=======================================================================
122 static inline double getDouble( const char * theSring )
125 return strtod( theSring, &ptr );
128 //=======================================================================
129 //function : readLine
130 //purpose : Put token starting positions in theFields until '\n' or '\0'
131 // Return the number of the found tokens
132 //=======================================================================
134 static int readLine (list <const char*> & theFields,
135 const char* & theLineBeg,
136 const bool theClearFields )
138 if ( theClearFields )
143 /* switch ( symbol ) { */
144 /* case white-space: */
145 /* look for a non-space symbol; */
146 /* case string-end: */
149 /* case comment beginning: */
150 /* skip all till a line-end; */
152 /* put its position in theFields, skip till a white-space;*/
158 bool stopReading = false;
161 bool isNumber = false;
162 switch ( *theLineBeg )
164 case ' ': // white space
169 case '\n': // a line ends
170 stopReading = ( nbRead > 0 );
175 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
179 case '\0': // file ends
182 case '-': // real number
187 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
189 theFields.push_back( theLineBeg );
192 while (*theLineBeg != ' ' &&
193 *theLineBeg != '\n' &&
194 *theLineBeg != '\0');
198 return 0; // incorrect file format
204 } while ( !stopReading );
209 //=======================================================================
211 //purpose : Load a pattern from <theFile>
212 //=======================================================================
214 bool SMESH_Pattern::Load (const char* theFileContents)
216 MESSAGE("Load( file ) ");
218 Kernel_Utils::Localizer loc;
222 // ! This is a comment
223 // NB_POINTS ! 1 integer - the number of points in the pattern.
224 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
225 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
227 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
228 // ! elements description goes after all
229 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
234 const char* lineBeg = theFileContents;
235 list <const char*> fields;
236 const bool clearFields = true;
238 // NB_POINTS ! 1 integer - the number of points in the pattern.
240 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
241 MESSAGE("Error reading NB_POINTS");
242 return setErrorCode( ERR_READ_NB_POINTS );
244 int nbPoints = getInt( fields.front() );
246 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
248 // read the first point coordinates to define pattern dimention
249 int dim = readLine( fields, lineBeg, clearFields );
255 MESSAGE("Error reading points: wrong nb of coordinates");
256 return setErrorCode( ERR_READ_POINT_COORDS );
258 if ( nbPoints <= dim ) {
259 MESSAGE(" Too few points ");
260 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
263 // read the rest points
265 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
266 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
267 MESSAGE("Error reading points : wrong nb of coordinates ");
268 return setErrorCode( ERR_READ_POINT_COORDS );
270 // store point coordinates
271 myPoints.resize( nbPoints );
272 list <const char*>::iterator fIt = fields.begin();
273 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
275 TPoint & p = myPoints[ iPoint ];
276 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
278 double coord = getDouble( *fIt );
279 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
280 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
282 return setErrorCode( ERR_READ_3D_COORD );
284 p.myInitXYZ.SetCoord( iCoord, coord );
286 p.myInitUV.SetCoord( iCoord, coord );
290 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
293 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
294 MESSAGE("Error: missing key-points");
296 return setErrorCode( ERR_READ_NO_KEYPOINT );
299 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
301 int pointIndex = getInt( *fIt );
302 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
303 MESSAGE("Error: invalid point index " << pointIndex );
305 return setErrorCode( ERR_READ_BAD_INDEX );
307 if ( idSet.insert( pointIndex ).second ) // unique?
308 myKeyPointIDs.push_back( pointIndex );
312 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
314 while ( readLine( fields, lineBeg, clearFields ))
316 myElemPointIDs.push_back( TElemDef() );
317 TElemDef& elemPoints = myElemPointIDs.back();
318 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
320 int pointIndex = getInt( *fIt );
321 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
322 MESSAGE("Error: invalid point index " << pointIndex );
324 return setErrorCode( ERR_READ_BAD_INDEX );
326 elemPoints.push_back( pointIndex );
328 // check the nb of nodes in element
330 switch ( elemPoints.size() ) {
331 case 3: if ( !myIs2D ) Ok = false; break;
335 case 8: if ( myIs2D ) Ok = false; break;
339 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
341 return setErrorCode( ERR_READ_ELEM_POINTS );
344 if ( myElemPointIDs.empty() ) {
345 MESSAGE("Error: no elements");
347 return setErrorCode( ERR_READ_NO_ELEMS );
350 findBoundaryPoints(); // sort key-points
352 return setErrorCode( ERR_OK );
355 //=======================================================================
357 //purpose : Save the loaded pattern into the file <theFileName>
358 //=======================================================================
360 bool SMESH_Pattern::Save (ostream& theFile)
362 MESSAGE(" ::Save(file) " );
364 Kernel_Utils::Localizer loc;
367 MESSAGE(" Pattern not loaded ");
368 return setErrorCode( ERR_SAVE_NOT_LOADED );
371 theFile << "!!! SALOME Mesh Pattern file" << endl;
372 theFile << "!!!" << endl;
373 theFile << "!!! Nb of points:" << endl;
374 theFile << myPoints.size() << endl;
378 // theFile.width( 8 );
379 // theFile.setf(ios::fixed);// use 123.45 floating notation
380 // theFile.setf(ios::right);
381 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
382 // theFile.setf(ios::showpoint); // do not show trailing zeros
383 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
384 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
385 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
386 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
387 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
388 theFile << " !- " << i << endl; // point id to ease reading by a human being
392 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
393 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
394 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
395 theFile << " " << *kpIt;
396 if ( !myKeyPointIDs.empty() )
400 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
401 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
402 for ( ; epIt != myElemPointIDs.end(); epIt++ )
404 const TElemDef & elemPoints = *epIt;
405 TElemDef::const_iterator iIt = elemPoints.begin();
406 for ( ; iIt != elemPoints.end(); iIt++ )
407 theFile << " " << *iIt;
413 return setErrorCode( ERR_OK );
416 //=======================================================================
417 //function : sortBySize
418 //purpose : sort theListOfList by size
419 //=======================================================================
421 template<typename T> struct TSizeCmp {
422 bool operator ()( const list < T > & l1, const list < T > & l2 )
423 const { return l1.size() < l2.size(); }
426 template<typename T> void sortBySize( list< list < T > > & theListOfList )
428 if ( theListOfList.size() > 2 ) {
429 TSizeCmp< T > SizeCmp;
430 theListOfList.sort( SizeCmp );
434 //=======================================================================
437 //=======================================================================
439 static gp_XY project (const SMDS_MeshNode* theNode,
440 Extrema_GenExtPS & theProjectorPS)
442 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
443 theProjectorPS.Perform( P );
444 if ( !theProjectorPS.IsDone() ) {
445 MESSAGE( "SMESH_Pattern: point projection FAILED");
448 double u, v, minVal = DBL_MAX;
449 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
450 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
451 if ( theProjectorPS.SquareDistance( i ) < minVal ) {
452 minVal = theProjectorPS.SquareDistance( i );
454 if ( theProjectorPS.Value( i ) < minVal ) {
455 minVal = theProjectorPS.Value( i );
457 theProjectorPS.Point( i ).Parameter( u, v );
459 return gp_XY( u, v );
462 //=======================================================================
463 //function : areNodesBound
464 //purpose : true if all nodes of faces are bound to shapes
465 //=======================================================================
467 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
469 while ( faceItr->more() )
471 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
472 while ( nIt->more() )
474 const SMDS_MeshNode* node = smdsNode( nIt->next() );
475 if (node->getshapeId() <1) {
483 //=======================================================================
484 //function : isMeshBoundToShape
485 //purpose : return true if all 2d elements are bound to shape
486 // if aFaceSubmesh != NULL, then check faces bound to it
487 // else check all faces in aMeshDS
488 //=======================================================================
490 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
491 SMESHDS_SubMesh * aFaceSubmesh,
492 const bool isMainShape)
495 // check that all faces are bound to aFaceSubmesh
496 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
500 // check face nodes binding
501 if ( aFaceSubmesh ) {
502 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
503 return areNodesBound( fIt );
505 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
506 return areNodesBound( fIt );
509 //=======================================================================
511 //purpose : Create a pattern from the mesh built on <theFace>.
512 // <theProject>==true makes override nodes positions
513 // on <theFace> computed by mesher
514 //=======================================================================
516 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
517 const TopoDS_Face& theFace,
519 TopoDS_Vertex the1stVertex)
521 MESSAGE(" ::Load(face) " );
525 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
526 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
527 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
528 SMESH_MesherHelper helper( *theMesh );
529 helper.SetSubShape( theFace );
531 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
532 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
533 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
535 MESSAGE( "No elements bound to the face");
536 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
539 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
541 // check if face is closed
542 bool isClosed = helper.HasSeam();
543 list<TopoDS_Edge> eList;
544 list<TopoDS_Edge>::iterator elIt;
545 SMESH_Block::GetOrderedEdges( face, eList, myNbKeyPntInBoundary, the1stVertex );
547 // check that requested or needed projection is possible
548 bool isMainShape = theMesh->IsMainShape( face );
549 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
550 bool canProject = ( nbElems ? true : isMainShape );
552 canProject = false; // so far
554 if ( ( theProject || needProject ) && !canProject )
555 return setErrorCode( ERR_LOADF_CANT_PROJECT );
557 Extrema_GenExtPS projector;
558 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
559 if ( theProject || needProject )
560 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
563 TNodePointIDMap nodePointIDMap;
564 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
568 MESSAGE("Project the submesh");
569 // ---------------------------------------------------------------
570 // The case where the submesh is projected to theFace
571 // ---------------------------------------------------------------
574 list< const SMDS_MeshElement* > faces;
576 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
577 while ( fIt->more() ) {
578 const SMDS_MeshElement* f = fIt->next();
579 if ( f && f->GetType() == SMDSAbs_Face )
580 faces.push_back( f );
584 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
585 while ( fIt->more() )
586 faces.push_back( fIt->next() );
589 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
590 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
591 for ( ; fIt != faces.end(); ++fIt )
593 myElemPointIDs.push_back( TElemDef() );
594 TElemDef& elemPoints = myElemPointIDs.back();
595 int nbNodes = (*fIt)->NbCornerNodes();
596 for ( int i = 0;i < nbNodes; ++i )
598 const SMDS_MeshElement* node = (*fIt)->GetNode( i );
599 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
600 if ( nIdIt->second == -1 )
602 elemPoints.push_back( iPoint );
603 nIdIt->second = iPoint++;
606 elemPoints.push_back( (*nIdIt).second );
609 myPoints.resize( iPoint );
611 // project all nodes of 2d elements to theFace
612 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
613 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
615 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
616 TPoint * p = & myPoints[ (*nIdIt).second ];
617 p->myInitUV = project( node, projector );
618 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
620 // find key-points: the points most close to UV of vertices
621 TopExp_Explorer vExp( face, TopAbs_VERTEX );
622 set<int> foundIndices;
623 for ( ; vExp.More(); vExp.Next() ) {
624 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
625 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
626 double minDist = DBL_MAX;
628 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
629 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
630 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
631 if ( dist < minDist ) {
636 if ( foundIndices.insert( index ).second ) // unique?
637 myKeyPointIDs.push_back( index );
639 myIsBoundaryPointsFound = false;
644 // ---------------------------------------------------------------------
645 // The case where a pattern is being made from the mesh built by mesher
646 // ---------------------------------------------------------------------
648 // Load shapes in the consequent order and count nb of points
651 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
652 int nbV = myShapeIDMap.Extent();
653 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
654 bool added = ( nbV < myShapeIDMap.Extent() );
655 if ( !added ) { // vertex encountered twice
656 // a seam vertex have two corresponding key points
657 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ).Reversed());
660 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
661 nbNodes += eSubMesh->NbNodes() + 1;
664 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
665 myShapeIDMap.Add( *elIt );
667 myShapeIDMap.Add( face );
669 myPoints.resize( nbNodes );
671 // Load U of points on edges
673 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
675 TopoDS_Edge & edge = *elIt;
676 list< TPoint* > & ePoints = getShapePoints( edge );
678 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
679 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
681 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
682 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
683 // to make adjacent edges share key-point, we make v2 FORWARD too
684 // (as we have different points for same shape with different orienation)
687 // on closed face we must have REVERSED some of seam vertices
689 if ( helper.IsSeamShape( edge ) ) {
690 if ( helper.IsRealSeam( edge ) && !isForward ) {
691 // reverse on reversed SEAM edge
696 else { // on CLOSED edge (i.e. having one vertex with different orienations)
697 for ( int is2 = 0; is2 < 2; ++is2 ) {
698 TopoDS_Shape & v = is2 ? v2 : v1;
699 if ( helper.IsRealSeam( v ) ) {
700 // reverse or not depending on orientation of adjacent seam
702 list<TopoDS_Edge>::iterator eIt2 = elIt;
704 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
706 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
707 if ( seam.Orientation() == TopAbs_REVERSED )
714 // the forward key-point
715 list< TPoint* > * vPoint = & getShapePoints( v1 );
716 if ( vPoint->empty() )
718 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
719 if ( vSubMesh && vSubMesh->NbNodes() ) {
720 myKeyPointIDs.push_back( iPoint );
721 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
722 const SMDS_MeshNode* node = nIt->next();
723 if ( v1.Orientation() == TopAbs_REVERSED )
724 closeNodePointIDMap.insert( make_pair( node, iPoint ));
726 nodePointIDMap.insert( make_pair( node, iPoint ));
728 TPoint* keyPoint = &myPoints[ iPoint++ ];
729 vPoint->push_back( keyPoint );
731 keyPoint->myInitUV = project( node, projector );
733 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
734 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
737 if ( !vPoint->empty() )
738 ePoints.push_back( vPoint->front() );
741 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
742 if ( eSubMesh && eSubMesh->NbNodes() )
744 // loop on nodes of an edge: sort them by param on edge
745 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
746 TParamNodeMap paramNodeMap;
747 int nbMeduimNodes = 0;
748 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
749 while ( nIt->more() )
751 const SMDS_MeshNode* node = nIt->next();
752 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
756 const SMDS_EdgePosition* epos =
757 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
758 double u = epos->GetUParameter();
759 paramNodeMap.insert( make_pair( u, node ));
761 if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
762 // wrong U on edge, project
764 BRepAdaptor_Curve aCurve( edge );
765 proj.Initialize( aCurve, f, l );
766 paramNodeMap.clear();
767 nIt = eSubMesh->GetNodes();
768 for ( int iNode = 0; nIt->more(); ++iNode ) {
769 const SMDS_MeshNode* node = nIt->next();
770 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
772 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
774 if ( proj.IsDone() ) {
775 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
776 if ( proj.IsMin( i )) {
777 u = proj.Point( i ).Parameter();
781 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
783 paramNodeMap.insert( make_pair( u, node ));
786 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
787 if ( paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
788 return setErrorCode(ERR_UNEXPECTED);
791 // put U in [0,1] so that the first key-point has U==0
792 bool isSeam = helper.IsRealSeam( edge );
794 TParamNodeMap::iterator unIt = paramNodeMap.begin();
795 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
796 while ( unIt != paramNodeMap.end() )
798 TPoint* p = & myPoints[ iPoint ];
799 ePoints.push_back( p );
800 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
801 if ( isSeam && !isForward )
802 closeNodePointIDMap.insert( make_pair( node, iPoint ));
804 nodePointIDMap.insert ( make_pair( node, iPoint ));
807 p->myInitUV = project( node, projector );
809 double u = isForward ? (*unIt).first : (*unRIt).first;
810 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
811 p->myInitUV = C2d->Value( u ).XY();
813 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
818 // the reverse key-point
819 vPoint = & getShapePoints( v2 );
820 if ( vPoint->empty() )
822 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
823 if ( vSubMesh && vSubMesh->NbNodes() ) {
824 myKeyPointIDs.push_back( iPoint );
825 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
826 const SMDS_MeshNode* node = nIt->next();
827 if ( v2.Orientation() == TopAbs_REVERSED )
828 closeNodePointIDMap.insert( make_pair( node, iPoint ));
830 nodePointIDMap.insert( make_pair( node, iPoint ));
832 TPoint* keyPoint = &myPoints[ iPoint++ ];
833 vPoint->push_back( keyPoint );
835 keyPoint->myInitUV = project( node, projector );
837 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
838 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
841 if ( !vPoint->empty() )
842 ePoints.push_back( vPoint->front() );
844 // compute U of edge-points
847 double totalDist = 0;
848 list< TPoint* >::iterator pIt = ePoints.begin();
849 TPoint* prevP = *pIt;
850 prevP->myInitU = totalDist;
851 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
853 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
854 p->myInitU = totalDist;
857 if ( totalDist > DBL_MIN)
858 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
860 p->myInitU /= totalDist;
863 } // loop on edges of a wire
865 // Load in-face points and elements
867 if ( fSubMesh && fSubMesh->NbElements() )
869 list< TPoint* > & fPoints = getShapePoints( face );
870 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
871 while ( nIt->more() )
873 const SMDS_MeshNode* node = nIt->next();
874 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
876 nodePointIDMap.insert( make_pair( node, iPoint ));
877 TPoint* p = &myPoints[ iPoint++ ];
878 fPoints.push_back( p );
880 p->myInitUV = project( node, projector );
882 const SMDS_FacePosition* pos =
883 static_cast<const SMDS_FacePosition*>(node->GetPosition());
884 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
886 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
889 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
890 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
891 while ( elemIt->more() )
893 const SMDS_MeshElement* elem = elemIt->next();
894 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
895 myElemPointIDs.push_back( TElemDef() );
896 TElemDef& elemPoints = myElemPointIDs.back();
897 // find point indices corresponding to element nodes
898 while ( nIt->more() )
900 const SMDS_MeshNode* node = smdsNode( nIt->next() );
901 n_id = nodePointIDMap.find( node );
902 if ( n_id == nodePointIDMap.end() )
903 continue; // medium node
904 iPoint = n_id->second; // point index of interest
905 // for a node on a seam edge there are two points
906 if ( helper.IsRealSeam( node->getshapeId() ) &&
907 ( n_id = closeNodePointIDMap.find( node )) != not_found )
909 TPoint & p1 = myPoints[ iPoint ];
910 TPoint & p2 = myPoints[ n_id->second ];
911 // Select point closest to the rest nodes of element in UV space
912 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
913 const SMDS_MeshNode* notSeamNode = 0;
914 // find node not on a seam edge
915 while ( nIt2->more() && !notSeamNode ) {
916 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
917 if ( !helper.IsSeamShape( n->getshapeId() ))
920 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
921 double dist1 = uv.SquareDistance( p1.myInitUV );
922 double dist2 = uv.SquareDistance( p2.myInitUV );
924 iPoint = n_id->second;
926 elemPoints.push_back( iPoint );
930 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
932 myIsBoundaryPointsFound = true;
935 // Assure that U range is proportional to V range
938 vector< TPoint >::iterator pVecIt = myPoints.begin();
939 for ( ; pVecIt != myPoints.end(); pVecIt++ )
940 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
941 double minU, minV, maxU, maxV;
942 bndBox.Get( minU, minV, maxU, maxV );
943 double dU = maxU - minU, dV = maxV - minV;
944 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
947 // define where is the problem, in the face or in the mesh
948 TopExp_Explorer vExp( face, TopAbs_VERTEX );
949 for ( ; vExp.More(); vExp.Next() ) {
950 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
953 bndBox.Get( minU, minV, maxU, maxV );
954 dU = maxU - minU, dV = maxV - minV;
955 if ( dU <= DBL_MIN || dV <= DBL_MIN )
957 return setErrorCode( ERR_LOADF_NARROW_FACE );
959 // mesh is projected onto a line, e.g.
960 return setErrorCode( ERR_LOADF_CANT_PROJECT );
962 double ratio = dU / dV, maxratio = 3, scale;
964 if ( ratio > maxratio ) {
965 scale = ratio / maxratio;
968 else if ( ratio < 1./maxratio ) {
969 scale = maxratio / ratio;
974 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
975 TPoint & p = *pVecIt;
976 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
977 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
980 if ( myElemPointIDs.empty() ) {
981 MESSAGE( "No elements bound to the face");
982 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
985 return setErrorCode( ERR_OK );
988 //=======================================================================
989 //function : computeUVOnEdge
990 //purpose : compute coordinates of points on theEdge
991 //=======================================================================
993 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
994 const list< TPoint* > & ePoints )
996 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
998 Handle(Geom2d_Curve) C2d =
999 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
1001 ePoints.back()->myInitU = 1.0;
1002 list< TPoint* >::const_iterator pIt = ePoints.begin();
1003 for ( pIt++; pIt != ePoints.end(); pIt++ )
1005 TPoint* point = *pIt;
1007 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1008 point->myU = ( f * ( 1 - du ) + l * du );
1010 point->myUV = C2d->Value( point->myU ).XY();
1014 //=======================================================================
1015 //function : intersectIsolines
1017 //=======================================================================
1019 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1020 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1024 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1025 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1026 resUV = 0.5 * ( loc1 + loc2 );
1027 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1028 // SKL 26.07.2007 for NPAL16567
1029 double d1 = (uv11-uv12).Modulus();
1030 double d2 = (uv21-uv22).Modulus();
1031 // double delta = d1*d2*1e-6; PAL17233
1032 double delta = min( d1, d2 ) / 10.;
1033 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1035 // double len1 = ( uv11 - uv12 ).Modulus();
1036 // double len2 = ( uv21 - uv22 ).Modulus();
1037 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1041 // gp_Lin2d line1( uv11, uv12 - uv11 );
1042 // gp_Lin2d line2( uv21, uv22 - uv21 );
1043 // double angle = Abs( line1.Angle( line2 ) );
1045 // IntAna2d_AnaIntersection inter;
1046 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1047 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1049 // gp_Pnt2d interUV = inter.Point(1).Value();
1050 // resUV += interUV.XY();
1051 // inter.Perform( line1, line2 );
1052 // interUV = inter.Point(1).Value();
1053 // resUV += interUV.XY();
1058 MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1059 ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1064 //=======================================================================
1065 //function : compUVByIsoIntersection
1067 //=======================================================================
1069 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1070 const gp_XY& theInitUV,
1072 bool & theIsDeformed )
1074 // compute UV by intersection of 2 iso lines
1075 //gp_Lin2d isoLine[2];
1076 gp_XY uv1[2], uv2[2];
1078 const double zero = DBL_MIN;
1079 for ( int iIso = 0; iIso < 2; iIso++ )
1081 // to build an iso line:
1082 // find 2 pairs of consequent edge-points such that the range of their
1083 // initial parameters encloses the in-face point initial parameter
1084 gp_XY UV[2], initUV[2];
1085 int nbUV = 0, iCoord = iIso + 1;
1086 double initParam = theInitUV.Coord( iCoord );
1088 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1089 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1091 const list< TPoint* > & bndPoints = * bndIt;
1092 TPoint* prevP = bndPoints.back(); // this is the first point
1093 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1094 bool coincPrev = false;
1095 // loop on the edge-points
1096 for ( ; pIt != bndPoints.end(); pIt++ )
1098 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1099 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1100 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1101 if (!coincPrev && // ignore if initParam coincides with prev point param
1102 sumOfDiff > zero && // ignore if both points coincide with initParam
1103 prevParamDiff * paramDiff <= zero )
1105 // find UV in parametric space of theFace
1106 double r = Abs(prevParamDiff) / sumOfDiff;
1107 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1110 // throw away uv most distant from <theInitUV>
1111 gp_XY vec0 = initUV[0] - theInitUV;
1112 gp_XY vec1 = initUV[1] - theInitUV;
1113 gp_XY vec = uvInit - theInitUV;
1114 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1115 double dist0 = vec0.SquareModulus();
1116 double dist1 = vec1.SquareModulus();
1117 double dist = vec .SquareModulus();
1118 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1119 i = ( dist0 < dist1 ? 1 : 0 );
1120 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1121 i = 3; // theInitUV must remain between
1125 initUV[ i ] = uvInit;
1126 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1128 coincPrev = ( Abs(paramDiff) <= zero );
1135 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1136 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1137 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1138 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1140 // an iso line should be normal to UV[0] - UV[1] direction
1141 // and be located at the same relative distance as from initial ends
1142 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1144 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1145 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1146 //isoLine[ iIso ] = iso.Normal( isoLoc );
1147 uv1[ iIso ] = UV[0];
1148 uv2[ iIso ] = UV[1];
1151 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1152 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1153 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1154 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1161 // ==========================================================
1162 // structure representing a node of a grid of iso-poly-lines
1163 // ==========================================================
1170 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1171 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1172 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1173 TIsoNode(double initU, double initV):
1174 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1175 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1176 bool IsUVComputed() const
1177 { return myUV.X() != 1e100; }
1178 bool IsMovable() const
1179 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1180 void SetNotMovable()
1181 { myIsMovable = false; }
1182 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1183 { myBndNodes[ iDir + i * 2 ] = node; }
1184 TIsoNode* GetBoundaryNode(int iDir, int i)
1185 { return myBndNodes[ iDir + i * 2 ]; }
1186 void SetNext(TIsoNode* node, int iDir, int isForward)
1187 { myNext[ iDir + isForward * 2 ] = node; }
1188 TIsoNode* GetNext(int iDir, int isForward)
1189 { return myNext[ iDir + isForward * 2 ]; }
1192 //=======================================================================
1193 //function : getNextNode
1195 //=======================================================================
1197 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1199 TIsoNode* n = node->myNext[ dir ];
1200 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1201 n = 0;//node->myBndNodes[ dir ];
1202 // MESSAGE("getNextNode: use bnd for node "<<
1203 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1207 //=======================================================================
1208 //function : checkQuads
1209 //purpose : check if newUV destortes quadrangles around node,
1210 // and if ( crit == FIX_OLD ) fix newUV in this case
1211 //=======================================================================
1213 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1215 static bool checkQuads (const TIsoNode* node,
1217 const bool reversed,
1218 const int crit = FIX_OLD,
1219 double fixSize = 0.)
1221 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1222 int nbOldFix = 0, nbOldImpr = 0;
1223 double newBadRate = 0, oldBadRate = 0;
1224 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1225 int i, dir1 = 0, dir2 = 3;
1226 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1228 if ( dir2 > 3 ) dir2 = 0;
1230 // walking counterclockwise around a quad,
1231 // nodes are in the order: node, n[0], n[1], n[2]
1232 n[0] = getNextNode( node, dir1 );
1233 n[2] = getNextNode( node, dir2 );
1234 if ( !n[0] || !n[2] ) continue;
1235 n[1] = getNextNode( n[0], dir2 );
1236 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1237 bool isTriangle = ( !n[1] );
1239 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1241 // if ( fixSize != 0 ) {
1242 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1243 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1244 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1245 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1247 // check if a quadrangle is degenerated
1249 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1250 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1253 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1256 // find min size of the diagonal node-n[1]
1257 double minDiag = fixSize;
1258 if ( minDiag == 0. ) {
1259 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1260 if ( !isTriangle ) {
1261 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1262 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1264 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1265 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1268 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1269 // ( behind means "to the right of")
1271 // 1. newUV is not behind 01 and 12 dirs
1272 // 2. or newUV is not behind 02 dir and n[2] is convex
1273 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1274 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1275 gp_Vec2d moveVec[3], outVec[3];
1276 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1278 bool isDiag = ( i == 2 );
1279 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1283 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1285 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1287 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1289 gp_Vec2d newDir( n[i]->myUV, newUV );
1290 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1292 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1293 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1294 if ( crit == FIX_OLD ) {
1295 wasIn[i] = ( outDir * oldDir < 0 );
1296 wasOk[i] = ( outDir * oldDir < -minDiag );
1298 newBadRate += outDir * newDir;
1300 oldBadRate += outDir * oldDir;
1303 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1304 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1305 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1306 moveVec[i] = ( oldDist - minDiag ) * outDir;
1311 // check if n[2] is convex
1314 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1316 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1317 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1318 newIsOk = ( newIsOk && isNewOk );
1319 newIsIn = ( newIsIn && isNewIn );
1321 if ( crit != FIX_OLD ) {
1322 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1323 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1327 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1328 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1329 oldIsIn = ( oldIsIn && isOldIn );
1330 oldIsOk = ( oldIsOk && isOldIn );
1333 if ( !isOldIn ) { // node is outside a quadrangle
1334 // move newUV inside a quadrangle
1335 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1336 // node and newUV are outside: push newUV inside
1338 if ( convex || isTriangle ) {
1339 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1342 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1343 double outSize = out.Magnitude();
1344 if ( outSize > DBL_MIN )
1347 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1348 uv = n[1]->myUV - minDiag * out.XY();
1350 oldUVFixed[ nbOldFix++ ] = uv;
1351 //node->myUV = newUV;
1353 else if ( !isOldOk ) {
1354 // try to fix old UV: move node inside as less as possible
1355 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1356 gp_XY uv1, uv2 = node->myUV;
1357 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1359 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1360 while ( !isOldOk ) {
1361 // find the least moveVec
1363 double minMove2 = 1e100;
1364 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1366 if ( moveVec[i].Coord(1) < 1e100 ) {
1367 double move2 = moveVec[i].SquareMagnitude();
1368 if ( move2 < minMove2 ) {
1377 // move node to newUV
1378 uv1 = node->myUV + moveVec[ iMin ].XY();
1379 uv2 += moveVec[ iMin ].XY();
1380 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1381 // check if uv1 is ok
1382 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1383 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1384 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1386 oldUVImpr[ nbOldImpr++ ] = uv1;
1388 // check if uv2 is ok
1389 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1390 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1391 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1393 oldUVImpr[ nbOldImpr++ ] = uv2;
1398 } // loop on 4 quadrangles around <node>
1400 if ( crit == CHECK_NEW_OK )
1402 if ( crit == CHECK_NEW_IN )
1411 if ( oldIsIn && nbOldImpr ) {
1412 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1413 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1414 gp_XY uv = oldUVImpr[ 0 ];
1415 for ( int i = 1; i < nbOldImpr; i++ )
1416 uv += oldUVImpr[ i ];
1418 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1423 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1426 if ( !oldIsIn && nbOldFix ) {
1427 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1428 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1429 gp_XY uv = oldUVFixed[ 0 ];
1430 for ( int i = 1; i < nbOldFix; i++ )
1431 uv += oldUVFixed[ i ];
1433 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1438 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1441 if ( newIsIn && oldIsIn )
1442 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1443 else if ( !newIsIn )
1450 //=======================================================================
1451 //function : compUVByElasticIsolines
1452 //purpose : compute UV as nodes of iso-poly-lines consisting of
1453 // segments keeping relative size as in the pattern
1454 //=======================================================================
1455 //#define DEB_COMPUVBYELASTICISOLINES
1456 bool SMESH_Pattern::
1457 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1458 const list< TPoint* >& thePntToCompute)
1460 return false; // PAL17233
1461 //cout << "============================== KEY POINTS =============================="<<endl;
1462 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1463 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1464 // TPoint& p = myPoints[ *kpIt ];
1465 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1466 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1468 //cout << "=============================="<<endl;
1470 // Define parameters of iso-grid nodes in U and V dir
1472 set< double > paramSet[ 2 ];
1473 list< list< TPoint* > >::const_iterator pListIt;
1474 list< TPoint* >::const_iterator pIt;
1475 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1476 const list< TPoint* > & pList = * pListIt;
1477 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1478 paramSet[0].insert( (*pIt)->myInitUV.X() );
1479 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1482 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1483 paramSet[0].insert( (*pIt)->myInitUV.X() );
1484 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1486 // unite close parameters and split too long segments
1489 for ( iDir = 0; iDir < 2; iDir++ )
1491 set< double > & params = paramSet[ iDir ];
1492 double range = ( *params.rbegin() - *params.begin() );
1493 double toler = range / 1e6;
1494 tol[ iDir ] = toler;
1495 // double maxSegment = range / params.size() / 2.;
1497 // set< double >::iterator parIt = params.begin();
1498 // double prevPar = *parIt;
1499 // for ( parIt++; parIt != params.end(); parIt++ )
1501 // double segLen = (*parIt) - prevPar;
1502 // if ( segLen < toler )
1503 // ;//params.erase( prevPar ); // unite
1504 // else if ( segLen > maxSegment )
1505 // params.insert( prevPar + 0.5 * segLen ); // split
1506 // prevPar = (*parIt);
1510 // Make nodes of a grid of iso-poly-lines
1512 list < TIsoNode > nodes;
1513 typedef list < TIsoNode *> TIsoLine;
1514 map < double, TIsoLine > isoMap[ 2 ];
1516 set< double > & params0 = paramSet[ 0 ];
1517 set< double >::iterator par0It = params0.begin();
1518 for ( ; par0It != params0.end(); par0It++ )
1520 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1521 set< double > & params1 = paramSet[ 1 ];
1522 set< double >::iterator par1It = params1.begin();
1523 for ( ; par1It != params1.end(); par1It++ )
1525 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1526 isoLine0.push_back( & nodes.back() );
1527 isoMap[1][ *par1It ].push_back( & nodes.back() );
1531 // Compute intersections of boundaries with iso-lines:
1532 // only boundary nodes will have computed UV so far
1535 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1536 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1537 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1539 const list< TPoint* > & bndPoints = * bndIt;
1540 TPoint* prevP = bndPoints.back(); // this is the first point
1541 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1542 // loop on the edge-points
1543 for ( ; pIt != bndPoints.end(); pIt++ )
1545 TPoint* point = *pIt;
1546 for ( iDir = 0; iDir < 2; iDir++ )
1548 const int iCoord = iDir + 1;
1549 const int iOtherCoord = 2 - iDir;
1550 double par1 = prevP->myInitUV.Coord( iCoord );
1551 double par2 = point->myInitUV.Coord( iCoord );
1552 double parDif = par2 - par1;
1553 if ( Abs( parDif ) <= DBL_MIN )
1555 // find iso-lines intersecting a bounadry
1556 double toler = tol[ 1 - iDir ];
1557 double minPar = Min ( par1, par2 );
1558 double maxPar = Max ( par1, par2 );
1559 map < double, TIsoLine >& isos = isoMap[ iDir ];
1560 map < double, TIsoLine >::iterator isoIt = isos.begin();
1561 for ( ; isoIt != isos.end(); isoIt++ )
1563 double isoParam = (*isoIt).first;
1564 if ( isoParam < minPar || isoParam > maxPar )
1566 double r = ( isoParam - par1 ) / parDif;
1567 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1568 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1569 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1570 // find existing node with otherPar or insert a new one
1571 TIsoLine & isoLine = (*isoIt).second;
1573 TIsoLine::iterator nIt = isoLine.begin();
1574 for ( ; nIt != isoLine.end(); nIt++ ) {
1575 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1576 if ( nodePar >= otherPar )
1580 if ( Abs( nodePar - otherPar ) <= toler )
1581 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1583 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1584 node = & nodes.back();
1585 isoLine.insert( nIt, node );
1587 node->SetNotMovable();
1589 uvBnd.Add( gp_Pnt2d( uv ));
1590 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1592 gp_XY tgt( point->myUV - prevP->myUV );
1593 if ( ::IsEqual( r, 1. ))
1594 node->myDir[ 0 ] = tgt;
1595 else if ( ::IsEqual( r, 0. ))
1596 node->myDir[ 1 ] = tgt;
1598 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1599 // keep boundary nodes corresponding to boundary points
1600 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1601 if ( bndNodes.empty() || bndNodes.back() != node )
1602 bndNodes.push_back( node );
1603 } // loop on isolines
1604 } // loop on 2 directions
1606 } // loop on boundary points
1607 } // loop on boundaries
1609 // Define orientation
1611 // find the point with the least X
1612 double leastX = DBL_MAX;
1613 TIsoNode * leftNode;
1614 list < TIsoNode >::iterator nodeIt = nodes.begin();
1615 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1616 TIsoNode & node = *nodeIt;
1617 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1618 leastX = node.myUV.X();
1621 // if ( node.IsUVComputed() ) {
1622 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1623 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1624 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1625 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1628 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1629 //SCRUTE( reversed );
1631 // Prepare internal nodes:
1633 // 2. compute ratios
1634 // 3. find boundary nodes for each node
1635 // 4. remove nodes out of the boundary
1636 for ( iDir = 0; iDir < 2; iDir++ )
1638 const int iCoord = 2 - iDir; // coord changing along an isoline
1639 map < double, TIsoLine >& isos = isoMap[ iDir ];
1640 map < double, TIsoLine >::iterator isoIt = isos.begin();
1641 for ( ; isoIt != isos.end(); isoIt++ )
1643 TIsoLine & isoLine = (*isoIt).second;
1644 bool firstCompNodeFound = false;
1645 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1646 nPrevIt = nIt = nNextIt = isoLine.begin();
1648 nNextIt++; nNextIt++;
1649 while ( nIt != isoLine.end() )
1651 // 1. connect prev - cur
1652 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1653 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1654 firstCompNodeFound = true;
1655 lastCompNodePos = nPrevIt;
1657 if ( firstCompNodeFound ) {
1658 node->SetNext( prevNode, iDir, 0 );
1659 prevNode->SetNext( node, iDir, 1 );
1662 if ( nNextIt != isoLine.end() ) {
1663 double par1 = prevNode->myInitUV.Coord( iCoord );
1664 double par2 = node->myInitUV.Coord( iCoord );
1665 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1666 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1668 // 3. find boundary nodes
1669 if ( node->IsUVComputed() )
1670 lastCompNodePos = nIt;
1671 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1672 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1673 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1674 if ( (*nIt2)->IsUVComputed() )
1676 if ( nIt2 != isoLine.end() ) {
1678 node->SetBoundaryNode( bndNode1, iDir, 0 );
1679 node->SetBoundaryNode( bndNode2, iDir, 1 );
1680 // cout << "--------------------------------------------------"<<endl;
1681 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1682 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1683 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1684 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1685 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1686 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1689 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1690 node->SetBoundaryNode( 0, iDir, 0 );
1691 node->SetBoundaryNode( 0, iDir, 1 );
1695 if ( nNextIt != isoLine.end() ) nNextIt++;
1696 // 4. remove nodes out of the boundary
1697 if ( !firstCompNodeFound )
1698 isoLine.pop_front();
1699 } // loop on isoLine nodes
1701 // remove nodes after the boundary
1702 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1703 // (*nIt)->SetNotMovable();
1704 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1705 } // loop on isolines
1706 } // loop on 2 directions
1708 // Compute local isoline direction for internal nodes
1711 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1712 map < double, TIsoLine >::iterator isoIt = isos.begin();
1713 for ( ; isoIt != isos.end(); isoIt++ )
1715 TIsoLine & isoLine = (*isoIt).second;
1716 TIsoLine::iterator nIt = isoLine.begin();
1717 for ( ; nIt != isoLine.end(); nIt++ )
1719 TIsoNode* node = *nIt;
1720 if ( node->IsUVComputed() || !node->IsMovable() )
1722 gp_Vec2d aTgt[2], aNorm[2];
1725 for ( iDir = 0; iDir < 2; iDir++ )
1727 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1728 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1729 if ( !bndNode1 || !bndNode2 ) {
1733 const int iCoord = 2 - iDir; // coord changing along an isoline
1734 double par1 = bndNode1->myInitUV.Coord( iCoord );
1735 double par2 = node->myInitUV.Coord( iCoord );
1736 double par3 = bndNode2->myInitUV.Coord( iCoord );
1737 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1739 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1740 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1741 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1742 else tgt1.Reverse();
1743 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1745 if ( ratio[ iDir ] < 0.5 )
1746 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1748 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1750 aNorm[ iDir ].Reverse(); // along iDir isoline
1752 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1753 // maybe angle is more than |PI|
1754 if ( Abs( angle ) > PI / 2. ) {
1755 // check direction of the last but one perpendicular isoline
1756 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1757 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1758 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1759 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1760 if ( isoDir * tgt2 < 0 )
1762 double angle2 = tgt1.Angle( isoDir );
1763 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1764 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1765 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1766 //MESSAGE("REVERSE ANGLE");
1769 if ( Abs( angle2 ) > Abs( angle ) ||
1770 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1771 //MESSAGE("Add PI");
1772 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1773 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1774 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1775 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1776 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1777 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1780 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1784 for ( iDir = 0; iDir < 2; iDir++ )
1786 aTgt[iDir].Normalize();
1787 aNorm[1-iDir].Normalize();
1788 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1791 node->myDir[iDir] = //aTgt[iDir];
1792 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1794 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1795 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1796 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1797 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1799 } // loop on iso nodes
1800 } // loop on isolines
1802 // Find nodes to start computing UV from
1804 list< TIsoNode* > startNodes;
1805 list< TIsoNode* >::iterator nIt = bndNodes.end();
1806 TIsoNode* node = *(--nIt);
1807 TIsoNode* prevNode = *(--nIt);
1808 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1810 TIsoNode* nextNode = *nIt;
1811 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1812 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1813 double initAngle = initTgt1.Angle( initTgt2 );
1814 double angle = node->myDir[0].Angle( node->myDir[1] );
1815 if ( reversed ) angle = -angle;
1816 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1817 // find a close internal node
1818 TIsoNode* nClose = 0;
1819 list< TIsoNode* > testNodes;
1820 testNodes.push_back( node );
1821 list< TIsoNode* >::iterator it = testNodes.begin();
1822 for ( ; !nClose && it != testNodes.end(); it++ )
1824 for (int i = 0; i < 4; i++ )
1826 nClose = (*it)->myNext[ i ];
1828 if ( !nClose->IsUVComputed() )
1831 testNodes.push_back( nClose );
1837 startNodes.push_back( nClose );
1838 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1839 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1840 // "initAngle: " << initAngle << " angle: " << angle << endl;
1841 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1842 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1843 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1844 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1850 // Compute starting UV of internal nodes
1852 list < TIsoNode* > internNodes;
1853 bool needIteration = true;
1854 if ( startNodes.empty() ) {
1855 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1856 needIteration = false;
1857 map < double, TIsoLine >& isos = isoMap[ 0 ];
1858 map < double, TIsoLine >::iterator isoIt = isos.begin();
1859 for ( ; isoIt != isos.end(); isoIt++ )
1861 TIsoLine & isoLine = (*isoIt).second;
1862 TIsoLine::iterator nIt = isoLine.begin();
1863 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1865 TIsoNode* node = *nIt;
1866 if ( !node->IsUVComputed() && node->IsMovable() ) {
1867 internNodes.push_back( node );
1869 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1870 node->myUV, needIteration ))
1871 node->myUV = node->myInitUV;
1875 if ( needIteration )
1876 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1878 TIsoNode* node = *nIt, *nClose = 0;
1879 list< TIsoNode* > testNodes;
1880 testNodes.push_back( node );
1881 list< TIsoNode* >::iterator it = testNodes.begin();
1882 for ( ; !nClose && it != testNodes.end(); it++ )
1884 for (int i = 0; i < 4; i++ )
1886 nClose = (*it)->myNext[ i ];
1888 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1891 testNodes.push_back( nClose );
1897 startNodes.push_back( nClose );
1901 double aMin[2], aMax[2], step[2];
1902 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1903 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1904 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1905 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1906 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1908 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1910 TIsoNode *node = *nIt;
1911 if ( node->IsUVComputed() || !node->IsMovable() )
1913 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1914 int nbComp = 0, nbPrev = 0;
1915 for ( iDir = 0; iDir < 2; iDir++ )
1917 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1918 TIsoNode* n = node->GetNext( iDir, 0 );
1919 if ( n->IsUVComputed() )
1922 startNodes.push_back( n );
1923 n = node->GetNext( iDir, 1 );
1924 if ( n->IsUVComputed() )
1927 startNodes.push_back( n );
1929 prevNode1 = prevNode2;
1932 if ( prevNode1 ) nbPrev++;
1933 if ( prevNode2 ) nbPrev++;
1936 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1937 double par = node->myInitUV.Coord( 2 - iDir );
1938 bool isEnd = ( prevPar > par );
1939 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1940 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1941 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1943 MESSAGE("Why we are here?");
1946 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1947 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1948 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1949 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1950 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1951 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1952 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1953 //" par: " << prevPar << endl;
1954 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1955 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1957 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1958 gp_XY & uv1 = prevNode1->myUV;
1959 gp_XY & uv2 = prevNode2->myUV;
1960 // dir = ( uv2 - uv1 );
1961 // double len = dir.Modulus();
1962 // if ( len > DBL_MIN )
1963 // dir /= len * 0.5;
1964 double r = node->myRatio[ iDir ];
1965 newUV += uv1 * ( 1 - r ) + uv2 * r;
1968 newUV += prevNode1->myUV + dir * step[ iDir ];
1974 if ( !nbComp ) continue;
1977 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1979 // check if a quadrangle is not distorted
1981 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1982 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1983 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1984 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1988 internNodes.push_back( node );
1993 static int maxNbIter = 100;
1994 #ifdef DEB_COMPUVBYELASTICISOLINES
1996 bool useNbMoveNode = 0;
1997 static int maxNbNodeMove = 100;
2000 if ( !useNbMoveNode )
2001 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2006 if ( !needIteration) break;
2007 #ifdef DEB_COMPUVBYELASTICISOLINES
2008 if ( nbIter >= maxNbIter ) break;
2011 list < TIsoNode* >::iterator nIt = internNodes.begin();
2012 for ( ; nIt != internNodes.end(); nIt++ ) {
2013 #ifdef DEB_COMPUVBYELASTICISOLINES
2015 cout << nbNodeMove <<" =================================================="<<endl;
2017 TIsoNode * node = *nIt;
2021 for ( iDir = 0; iDir < 2; iDir++ )
2023 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2024 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2025 double r = node->myRatio[ iDir ];
2026 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2027 // line[ iDir ].SetLocation( loc[ iDir ] );
2028 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2031 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2032 // double locR[2] = { 0, 0 };
2033 for ( iDir = 0; iDir < 2; iDir++ )
2035 const int iCoord = 2 - iDir; // coord changing along an isoline
2036 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2037 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2038 if ( !bndNode1 || !bndNode2 ) {
2041 double par1 = bndNode1->myInitUV.Coord( iCoord );
2042 double par2 = node->myInitUV.Coord( iCoord );
2043 double par3 = bndNode2->myInitUV.Coord( iCoord );
2044 double r = ( par2 - par1 ) / ( par3 - par1 );
2045 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2046 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2048 //locR[0] = locR[1] = 0.25;
2049 // intersect the 2 lines and move a node
2050 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2051 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2053 // double intR = 1 - locR[0] - locR[1];
2054 // gp_XY newUV = inter.Point(1).Value().XY();
2055 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2056 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2058 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2059 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2060 // avoid parallel isolines intersection
2061 checkQuads( node, newUV, reversed );
2063 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2065 } // intersection found
2066 #ifdef DEB_COMPUVBYELASTICISOLINES
2067 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2069 } // loop on internal nodes
2070 #ifdef DEB_COMPUVBYELASTICISOLINES
2071 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2073 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2075 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2077 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2078 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2079 #ifndef DEB_COMPUVBYELASTICISOLINES
2084 // Set computed UV to points
2086 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2087 TPoint* point = *pIt;
2088 //gp_XY oldUV = point->myUV;
2089 double minDist = DBL_MAX;
2090 list < TIsoNode >::iterator nIt = nodes.begin();
2091 for ( ; nIt != nodes.end(); nIt++ ) {
2092 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2093 if ( dist < minDist ) {
2095 point->myUV = (*nIt).myUV;
2104 //=======================================================================
2105 //function : setFirstEdge
2106 //purpose : choose the best first edge of theWire; return the summary distance
2107 // between point UV computed by isolines intersection and
2108 // eventual UV got from edge p-curves
2109 //=======================================================================
2111 //#define DBG_SETFIRSTEDGE
2112 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2114 int iE, nbEdges = theWire.size();
2118 // Transform UVs computed by iso to fit bnd box of a wire
2120 // max nb of points on an edge
2122 int eID = theFirstEdgeID;
2123 for ( iE = 0; iE < nbEdges; iE++ )
2124 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2126 // compute bnd boxes
2127 TopoDS_Face face = TopoDS::Face( myShape );
2128 Bnd_Box2d bndBox, eBndBox;
2129 eID = theFirstEdgeID;
2130 list< TopoDS_Edge >::iterator eIt;
2131 list< TPoint* >::iterator pIt;
2132 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2134 // UV by isos stored in TPoint.myXYZ
2135 list< TPoint* > & ePoints = getShapePoints( eID++ );
2136 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2138 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2140 // UV by an edge p-curve
2142 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2143 double dU = ( l - f ) / ( maxNbPnt - 1 );
2144 for ( int i = 0; i < maxNbPnt; i++ )
2145 eBndBox.Add( C2d->Value( f + i * dU ));
2148 // transform UVs by isos
2149 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2150 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2151 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2152 #ifdef DBG_SETFIRSTEDGE
2153 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2154 << eMinPar[1] << " - " << eMaxPar[1] );
2156 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2158 double dMin = eMinPar[i] - minPar[i];
2159 double dMax = eMaxPar[i] - maxPar[i];
2160 double dPar = maxPar[i] - minPar[i];
2161 eID = theFirstEdgeID;
2162 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2164 list< TPoint* > & ePoints = getShapePoints( eID++ );
2165 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2167 double par = (*pIt)->myXYZ.Coord( iC );
2168 double r = ( par - minPar[i] ) / dPar;
2169 par += ( 1 - r ) * dMin + r * dMax;
2170 (*pIt)->myXYZ.SetCoord( iC, par );
2176 double minDist = DBL_MAX;
2177 for ( iE = 0 ; iE < nbEdges; iE++ )
2179 #ifdef DBG_SETFIRSTEDGE
2180 MESSAGE ( " VARIANT " << iE );
2182 // evaluate the distance between UV computed by the 2 methods:
2183 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2185 int eID = theFirstEdgeID;
2186 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2188 list< TPoint* > & ePoints = getShapePoints( eID++ );
2189 computeUVOnEdge( *eIt, ePoints );
2190 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2192 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2193 #ifdef DBG_SETFIRSTEDGE
2194 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2195 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2199 #ifdef DBG_SETFIRSTEDGE
2200 MESSAGE ( "dist -- " << dist );
2202 if ( dist < minDist ) {
2204 eBest = theWire.front();
2206 // check variant with another first edge
2207 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2209 // put the best first edge to the theWire front
2210 if ( eBest != theWire.front() ) {
2211 eIt = find ( theWire.begin(), theWire.end(), eBest );
2212 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2218 //=======================================================================
2219 //function : sortSameSizeWires
2220 //purpose : sort wires in theWireList from theFromWire until theToWire,
2221 // the wires are set in the order to correspond to the order
2222 // of boundaries; after sorting, edges in the wires are put
2223 // in a good order, point UVs on edges are computed and points
2224 // are appended to theEdgesPointsList
2225 //=======================================================================
2227 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2228 const TListOfEdgesList::iterator& theFromWire,
2229 const TListOfEdgesList::iterator& theToWire,
2230 const int theFirstEdgeID,
2231 list< list< TPoint* > >& theEdgesPointsList )
2233 TopoDS_Face F = TopoDS::Face( myShape );
2234 int iW, nbWires = 0;
2235 TListOfEdgesList::iterator wlIt = theFromWire;
2236 while ( wlIt++ != theToWire )
2239 // Recompute key-point UVs by isolines intersection,
2240 // compute CG of key-points for each wire and bnd boxes of GCs
2243 gp_XY orig( gp::Origin2d().XY() );
2244 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2245 Bnd_Box2d bndBox, vBndBox;
2246 int eID = theFirstEdgeID;
2247 list< TopoDS_Edge >::iterator eIt;
2248 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2250 list< TopoDS_Edge > & wire = *wlIt;
2251 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2253 list< TPoint* > & ePoints = getShapePoints( eID++ );
2254 TPoint* p = ePoints.front();
2255 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2256 MESSAGE("cant sortSameSizeWires()");
2259 gcVec[iW] += p->myUV;
2260 bndBox.Add( gp_Pnt2d( p->myUV ));
2261 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2262 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2263 vGcVec[iW] += vXY.XY();
2265 // keep the computed UV to compare against by setFirstEdge()
2266 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2268 gcVec[iW] /= nbWires;
2269 vGcVec[iW] /= nbWires;
2270 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2271 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2274 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2276 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2277 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2278 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2279 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2281 double dMin = vMinPar[i] - minPar[i];
2282 double dMax = vMaxPar[i] - maxPar[i];
2283 double dPar = maxPar[i] - minPar[i];
2284 if ( Abs( dPar ) <= DBL_MIN )
2286 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2287 double par = gcVec[iW].Coord( iC );
2288 double r = ( par - minPar[i] ) / dPar;
2289 par += ( 1 - r ) * dMin + r * dMax;
2290 gcVec[iW].SetCoord( iC, par );
2294 // Define boundary - wire correspondence by GC closeness
2296 TListOfEdgesList tmpWList;
2297 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2298 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2299 TIntWirePosMap bndIndWirePosMap;
2300 vector< bool > bndFound( nbWires, false );
2301 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2303 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2304 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2305 double minDist = DBL_MAX;
2306 gp_XY & wGc = vGcVec[ iW ];
2308 for ( int iB = 0; iB < nbWires; iB++ ) {
2309 if ( bndFound[ iB ] ) continue;
2310 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2311 if ( dist < minDist ) {
2316 bndFound[ bIndex ] = true;
2317 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2322 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2323 eID = theFirstEdgeID;
2324 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2326 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2327 list < TopoDS_Edge > & wire = ( *wirePos );
2329 // choose the best first edge of a wire
2330 setFirstEdge( wire, eID );
2332 // compute eventual UV and fill theEdgesPointsList
2333 theEdgesPointsList.push_back( list< TPoint* >() );
2334 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2335 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2337 list< TPoint* > & ePoints = getShapePoints( eID++ );
2338 computeUVOnEdge( *eIt, ePoints );
2339 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2341 // put wire back to theWireList
2343 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2349 //=======================================================================
2351 //purpose : Compute nodes coordinates applying
2352 // the loaded pattern to <theFace>. The first key-point
2353 // will be mapped into <theVertexOnKeyPoint1>
2354 //=======================================================================
2356 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2357 const TopoDS_Vertex& theVertexOnKeyPoint1,
2358 const bool theReverse)
2360 MESSAGE(" ::Apply(face) " );
2361 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2362 if ( !setShapeToMesh( face ))
2365 // find points on edges, it fills myNbKeyPntInBoundary
2366 if ( !findBoundaryPoints() )
2369 // Define the edges order so that the first edge starts at
2370 // theVertexOnKeyPoint1
2372 list< TopoDS_Edge > eList;
2373 list< int > nbVertexInWires;
2374 int nbWires = SMESH_Block::GetOrderedEdges( face, eList, nbVertexInWires, theVertexOnKeyPoint1);
2375 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2377 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2378 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2380 // check nb wires and edges
2381 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2382 l1.sort(); l2.sort();
2385 MESSAGE( "Wrong nb vertices in wires" );
2386 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2389 // here shapes get IDs, for the outer wire IDs are OK
2390 list<TopoDS_Edge>::iterator elIt = eList.begin();
2391 for ( ; elIt != eList.end(); elIt++ ) {
2392 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2393 bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
2394 // BEGIN: jfa for bug 0019943
2397 for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
2398 const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
2400 for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
2401 if (we.Current().IsSame(*elIt)) {
2403 if (nbe == 2) isClosed1 = true;
2408 // END: jfa for bug 0019943
2410 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
2412 int nbVertices = myShapeIDMap.Extent();
2414 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2415 myShapeIDMap.Add( *elIt );
2417 myShapeIDMap.Add( face );
2419 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2420 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2421 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2424 // points on edges to be used for UV computation of in-face points
2425 list< list< TPoint* > > edgesPointsList;
2426 edgesPointsList.push_back( list< TPoint* >() );
2427 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2428 list< TPoint* >::iterator pIt;
2430 // compute UV of points on the outer wire
2431 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2432 for (iE = 0, elIt = eList.begin();
2433 iE < nbEdgesInOuterWire && elIt != eList.end();
2436 list< TPoint* > & ePoints = getShapePoints( *elIt );
2438 computeUVOnEdge( *elIt, ePoints );
2439 // collect on-edge points (excluding the last one)
2440 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2443 // If there are several wires, define the order of edges of inner wires:
2444 // compute UV of inner edge-points using 2 methods: the one for in-face points
2445 // and the one for on-edge points and then choose the best edge order
2446 // by the best correspondance of the 2 results
2449 // compute UV of inner edge-points using the method for in-face points
2450 // and devide eList into a list of separate wires
2452 list< list< TopoDS_Edge > > wireList;
2453 list<TopoDS_Edge>::iterator eIt = elIt;
2454 list<int>::iterator nbEIt = nbVertexInWires.begin();
2455 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2457 int nbEdges = *nbEIt;
2458 wireList.push_back( list< TopoDS_Edge >() );
2459 list< TopoDS_Edge > & wire = wireList.back();
2460 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2462 list< TPoint* > & ePoints = getShapePoints( *eIt );
2463 pIt = ePoints.begin();
2464 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2466 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2467 MESSAGE("cant Apply(face)");
2470 // keep the computed UV to compare against by setFirstEdge()
2471 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2473 wire.push_back( *eIt );
2476 // remove inner edges from eList
2477 eList.erase( elIt, eList.end() );
2479 // sort wireList by nb edges in a wire
2480 sortBySize< TopoDS_Edge > ( wireList );
2482 // an ID of the first edge of a boundary
2483 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2484 // if ( nbSeamShapes > 0 )
2485 // id1 += 2; // 2 vertices more
2487 // find points - edge correspondence for wires of unique size,
2488 // edge order within a wire should be defined only
2490 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2491 while ( wlIt != wireList.end() )
2493 list< TopoDS_Edge >& wire = (*wlIt);
2494 int nbEdges = wire.size();
2496 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2498 // choose the best first edge of a wire
2499 setFirstEdge( wire, id1 );
2501 // compute eventual UV and collect on-edge points
2502 edgesPointsList.push_back( list< TPoint* >() );
2503 edgesPoints = & edgesPointsList.back();
2505 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2507 list< TPoint* > & ePoints = getShapePoints( eID++ );
2508 computeUVOnEdge( *eIt, ePoints );
2509 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2515 // find boundary - wire correspondence for several wires of same size
2517 id1 = nbVertices + nbEdgesInOuterWire + 1;
2518 wlIt = wireList.begin();
2519 while ( wlIt != wireList.end() )
2521 int nbSameSize = 0, nbEdges = (*wlIt).size();
2522 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2524 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2528 if ( nbSameSize > 0 )
2529 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2532 id1 += nbEdges * ( nbSameSize + 1 );
2535 // add well-ordered edges to eList
2537 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2539 list< TopoDS_Edge >& wire = (*wlIt);
2540 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2543 // re-fill myShapeIDMap - all shapes get good IDs
2545 myShapeIDMap.Clear();
2546 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2547 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2548 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2549 myShapeIDMap.Add( *elIt );
2550 myShapeIDMap.Add( face );
2552 } // there are inner wires
2554 // Compute XYZ of on-edge points
2556 TopLoc_Location loc;
2557 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2559 BRepAdaptor_Curve C3d( *elIt );
2560 list< TPoint* > & ePoints = getShapePoints( iE++ );
2561 pIt = ePoints.begin();
2562 for ( pIt++; pIt != ePoints.end(); pIt++ )
2564 TPoint* point = *pIt;
2565 point->myXYZ = C3d.Value( point->myU );
2569 // Compute UV and XYZ of in-face points
2571 // try to use a simple algo
2572 list< TPoint* > & fPoints = getShapePoints( face );
2573 bool isDeformed = false;
2574 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2575 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2576 (*pIt)->myUV, isDeformed )) {
2577 MESSAGE("cant Apply(face)");
2580 // try to use a complex algo if it is a difficult case
2581 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2583 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2584 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2585 (*pIt)->myUV, isDeformed )) {
2586 MESSAGE("cant Apply(face)");
2591 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2592 const gp_Trsf & aTrsf = loc.Transformation();
2593 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2595 TPoint * point = *pIt;
2596 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2597 if ( !loc.IsIdentity() )
2598 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2601 myIsComputed = true;
2603 return setErrorCode( ERR_OK );
2606 //=======================================================================
2608 //purpose : Compute nodes coordinates applying
2609 // the loaded pattern to <theFace>. The first key-point
2610 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2611 //=======================================================================
2613 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2614 const int theNodeIndexOnKeyPoint1,
2615 const bool theReverse)
2617 // MESSAGE(" ::Apply(MeshFace) " );
2619 if ( !IsLoaded() ) {
2620 MESSAGE( "Pattern not loaded" );
2621 return setErrorCode( ERR_APPL_NOT_LOADED );
2624 // check nb of nodes
2625 const int nbFaceNodes = theFace->NbCornerNodes();
2626 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2627 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2628 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2631 // find points on edges, it fills myNbKeyPntInBoundary
2632 if ( !findBoundaryPoints() )
2635 // check that there are no holes in a pattern
2636 if (myNbKeyPntInBoundary.size() > 1 ) {
2637 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2640 // Define the nodes order
2642 list< const SMDS_MeshNode* > nodes;
2643 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2644 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2646 while ( noIt->more() && iSub < nbFaceNodes ) {
2647 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2648 nodes.push_back( node );
2649 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2652 if ( n != nodes.end() ) {
2654 if ( n != --nodes.end() )
2655 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2658 else if ( n != nodes.begin() )
2659 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2661 list< gp_XYZ > xyzList;
2662 myOrderedNodes.resize( nbFaceNodes );
2663 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2664 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2665 myOrderedNodes[ iSub++] = *n;
2668 // Define a face plane
2670 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2671 gp_Pnt P ( *xyzIt++ );
2672 gp_Vec Vx( P, *xyzIt++ ), N;
2674 N = Vx ^ gp_Vec( P, *xyzIt++ );
2675 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2676 if ( N.SquareMagnitude() <= DBL_MIN )
2677 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2678 gp_Ax2 pos( P, N, Vx );
2680 // Compute UV of key-points on a plane
2681 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2683 gp_Vec vec ( pos.Location(), *xyzIt );
2684 TPoint* p = getShapePoints( iSub ).front();
2685 p->myUV.SetX( vec * pos.XDirection() );
2686 p->myUV.SetY( vec * pos.YDirection() );
2690 // points on edges to be used for UV computation of in-face points
2691 list< list< TPoint* > > edgesPointsList;
2692 edgesPointsList.push_back( list< TPoint* >() );
2693 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2694 list< TPoint* >::iterator pIt;
2696 // compute UV and XYZ of points on edges
2698 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2700 gp_XYZ& xyz1 = *xyzIt++;
2701 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2703 list< TPoint* > & ePoints = getShapePoints( iSub );
2704 ePoints.back()->myInitU = 1.0;
2705 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2706 while ( *pIt != ePoints.back() )
2709 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2710 gp_Vec vec ( pos.Location(), p->myXYZ );
2711 p->myUV.SetX( vec * pos.XDirection() );
2712 p->myUV.SetY( vec * pos.YDirection() );
2714 // collect on-edge points (excluding the last one)
2715 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2718 // Compute UV and XYZ of in-face points
2720 // try to use a simple algo to compute UV
2721 list< TPoint* > & fPoints = getShapePoints( iSub );
2722 bool isDeformed = false;
2723 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2724 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2725 (*pIt)->myUV, isDeformed )) {
2726 MESSAGE("cant Apply(face)");
2729 // try to use a complex algo if it is a difficult case
2730 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2732 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2733 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2734 (*pIt)->myUV, isDeformed )) {
2735 MESSAGE("cant Apply(face)");
2740 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2742 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2745 myIsComputed = true;
2747 return setErrorCode( ERR_OK );
2750 //=======================================================================
2752 //purpose : Compute nodes coordinates applying
2753 // the loaded pattern to <theFace>. The first key-point
2754 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2755 //=======================================================================
2757 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2758 const SMDS_MeshFace* theFace,
2759 const TopoDS_Shape& theSurface,
2760 const int theNodeIndexOnKeyPoint1,
2761 const bool theReverse)
2763 // MESSAGE(" ::Apply(MeshFace) " );
2764 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2765 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2767 const TopoDS_Face& face = TopoDS::Face( theSurface );
2768 TopLoc_Location loc;
2769 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2770 const gp_Trsf & aTrsf = loc.Transformation();
2772 if ( !IsLoaded() ) {
2773 MESSAGE( "Pattern not loaded" );
2774 return setErrorCode( ERR_APPL_NOT_LOADED );
2777 // check nb of nodes
2778 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2779 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2780 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2783 // find points on edges, it fills myNbKeyPntInBoundary
2784 if ( !findBoundaryPoints() )
2787 // check that there are no holes in a pattern
2788 if (myNbKeyPntInBoundary.size() > 1 ) {
2789 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2792 // Define the nodes order
2794 list< const SMDS_MeshNode* > nodes;
2795 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2796 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2798 while ( noIt->more() ) {
2799 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2800 nodes.push_back( node );
2801 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2804 if ( n != nodes.end() ) {
2806 if ( n != --nodes.end() )
2807 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2810 else if ( n != nodes.begin() )
2811 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2814 // find a node not on a seam edge, if necessary
2815 SMESH_MesherHelper helper( *theMesh );
2816 helper.SetSubShape( theSurface );
2817 const SMDS_MeshNode* inFaceNode = 0;
2818 if ( helper.GetNodeUVneedInFaceNode() )
2820 SMESH_MeshEditor editor( theMesh );
2821 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2822 int shapeID = editor.FindShape( *n );
2824 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2825 if ( !helper.IsSeamShape( shapeID ))
2830 // Set UV of key-points (i.e. of nodes of theFace )
2831 vector< gp_XY > keyUV( theFace->NbNodes() );
2832 myOrderedNodes.resize( theFace->NbNodes() );
2833 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2835 TPoint* p = getShapePoints( iSub ).front();
2836 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2837 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2839 keyUV[ iSub-1 ] = p->myUV;
2840 myOrderedNodes[ iSub-1 ] = *n;
2843 // points on edges to be used for UV computation of in-face points
2844 list< list< TPoint* > > edgesPointsList;
2845 edgesPointsList.push_back( list< TPoint* >() );
2846 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2847 list< TPoint* >::iterator pIt;
2849 // compute UV and XYZ of points on edges
2851 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2853 gp_XY& uv1 = keyUV[ i ];
2854 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2856 list< TPoint* > & ePoints = getShapePoints( iSub );
2857 ePoints.back()->myInitU = 1.0;
2858 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2859 while ( *pIt != ePoints.back() )
2862 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2863 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2864 if ( !loc.IsIdentity() )
2865 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2867 // collect on-edge points (excluding the last one)
2868 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2871 // Compute UV and XYZ of in-face points
2873 // try to use a simple algo to compute UV
2874 list< TPoint* > & fPoints = getShapePoints( iSub );
2875 bool isDeformed = false;
2876 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2877 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2878 (*pIt)->myUV, isDeformed )) {
2879 MESSAGE("cant Apply(face)");
2882 // try to use a complex algo if it is a difficult case
2883 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2885 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2886 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2887 (*pIt)->myUV, isDeformed )) {
2888 MESSAGE("cant Apply(face)");
2893 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2895 TPoint * point = *pIt;
2896 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2897 if ( !loc.IsIdentity() )
2898 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2901 myIsComputed = true;
2903 return setErrorCode( ERR_OK );
2906 //=======================================================================
2907 //function : undefinedXYZ
2909 //=======================================================================
2911 static const gp_XYZ& undefinedXYZ()
2913 static gp_XYZ xyz( 1.e100, 0., 0. );
2917 //=======================================================================
2918 //function : isDefined
2920 //=======================================================================
2922 inline static bool isDefined(const gp_XYZ& theXYZ)
2924 return theXYZ.X() < 1.e100;
2927 //=======================================================================
2929 //purpose : Compute nodes coordinates applying
2930 // the loaded pattern to <theFaces>. The first key-point
2931 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2932 //=======================================================================
2934 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2935 std::set<const SMDS_MeshFace*>& theFaces,
2936 const int theNodeIndexOnKeyPoint1,
2937 const bool theReverse)
2939 MESSAGE(" ::Apply(set<MeshFace>) " );
2941 if ( !IsLoaded() ) {
2942 MESSAGE( "Pattern not loaded" );
2943 return setErrorCode( ERR_APPL_NOT_LOADED );
2946 // find points on edges, it fills myNbKeyPntInBoundary
2947 if ( !findBoundaryPoints() )
2950 // check that there are no holes in a pattern
2951 if (myNbKeyPntInBoundary.size() > 1 ) {
2952 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2957 myElemXYZIDs.clear();
2958 myXYZIdToNodeMap.clear();
2960 myIdsOnBoundary.clear();
2961 myReverseConnectivity.clear();
2963 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2964 myElements.reserve( theFaces.size() );
2966 // to find point index
2967 map< TPoint*, int > pointIndex;
2968 for ( int i = 0; i < myPoints.size(); i++ )
2969 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2971 int ind1 = 0; // lowest point index for a face
2976 // SMESH_MeshEditor editor( theMesh );
2978 // apply to each face in theFaces set
2979 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2980 for ( ; face != theFaces.end(); ++face )
2982 // int curShapeId = editor.FindShape( *face );
2983 // if ( curShapeId != shapeID ) {
2984 // if ( curShapeId )
2985 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2988 // shapeID = curShapeId;
2991 if ( shape.IsNull() )
2992 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2994 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2996 MESSAGE( "Failed on " << *face );
2999 myElements.push_back( *face );
3001 // store computed points belonging to elements
3002 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3003 for ( ; ll != myElemPointIDs.end(); ++ll )
3005 myElemXYZIDs.push_back(TElemDef());
3006 TElemDef& xyzIds = myElemXYZIDs.back();
3007 TElemDef& pIds = *ll;
3008 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3009 int pIndex = *id + ind1;
3010 xyzIds.push_back( pIndex );
3011 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3012 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3015 // put points on links to myIdsOnBoundary,
3016 // they will be used to sew new elements on adjacent refined elements
3017 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3018 for ( int i = 0; i < nbNodes; i++ )
3020 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3021 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3022 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
3023 // make a link and a node set
3024 TNodeSet linkSet, node1Set;
3025 linkSet.insert( n1 );
3026 linkSet.insert( n2 );
3027 node1Set.insert( n1 );
3028 list< TPoint* >::iterator p = linkPoints.begin();
3030 // map the first link point to n1
3031 int nId = pointIndex[ *p ] + ind1;
3032 myXYZIdToNodeMap[ nId ] = n1;
3033 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3034 groups.push_back(list< int > ());
3035 groups.back().push_back( nId );
3037 // add the linkSet to the map
3038 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3039 groups.push_back(list< int > ());
3040 list< int >& indList = groups.back();
3041 // add points to the map excluding the end points
3042 for ( p++; *p != linkPoints.back(); p++ )
3043 indList.push_back( pointIndex[ *p ] + ind1 );
3045 ind1 += myPoints.size();
3048 return !myElemXYZIDs.empty();
3051 //=======================================================================
3053 //purpose : Compute nodes coordinates applying
3054 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3055 // will be mapped into <theNode000Index>-th node. The
3056 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3058 //=======================================================================
3060 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3061 const int theNode000Index,
3062 const int theNode001Index)
3064 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3066 if ( !IsLoaded() ) {
3067 MESSAGE( "Pattern not loaded" );
3068 return setErrorCode( ERR_APPL_NOT_LOADED );
3071 // bind ID to points
3072 if ( !findBoundaryPoints() )
3075 // check that there are no holes in a pattern
3076 if (myNbKeyPntInBoundary.size() > 1 ) {
3077 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3082 myElemXYZIDs.clear();
3083 myXYZIdToNodeMap.clear();
3085 myIdsOnBoundary.clear();
3086 myReverseConnectivity.clear();
3088 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3089 myElements.reserve( theVolumes.size() );
3091 // to find point index
3092 map< TPoint*, int > pointIndex;
3093 for ( int i = 0; i < myPoints.size(); i++ )
3094 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3096 int ind1 = 0; // lowest point index for an element
3098 // apply to each element in theVolumes set
3099 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3100 for ( ; vol != theVolumes.end(); ++vol )
3102 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3103 MESSAGE( "Failed on " << *vol );
3106 myElements.push_back( *vol );
3108 // store computed points belonging to elements
3109 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3110 for ( ; ll != myElemPointIDs.end(); ++ll )
3112 myElemXYZIDs.push_back(TElemDef());
3113 TElemDef& xyzIds = myElemXYZIDs.back();
3114 TElemDef& pIds = *ll;
3115 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3116 int pIndex = *id + ind1;
3117 xyzIds.push_back( pIndex );
3118 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3119 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3122 // put points on edges and faces to myIdsOnBoundary,
3123 // they will be used to sew new elements on adjacent refined elements
3124 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3126 // make a set of sub-points
3128 vector< int > subIDs;
3129 if ( SMESH_Block::IsVertexID( Id )) {
3130 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3132 else if ( SMESH_Block::IsEdgeID( Id )) {
3133 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3134 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3135 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3138 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3139 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3140 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3141 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3142 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3143 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3144 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3145 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3148 list< TPoint* > & points = getShapePoints( Id );
3149 list< TPoint* >::iterator p = points.begin();
3150 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3151 groups.push_back(list< int > ());
3152 list< int >& indList = groups.back();
3153 for ( ; p != points.end(); p++ )
3154 indList.push_back( pointIndex[ *p ] + ind1 );
3155 if ( subNodes.size() == 1 ) // vertex case
3156 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3158 ind1 += myPoints.size();
3161 return !myElemXYZIDs.empty();
3164 //=======================================================================
3166 //purpose : Create a pattern from the mesh built on <theBlock>
3167 //=======================================================================
3169 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3170 const TopoDS_Shell& theBlock)
3172 MESSAGE(" ::Load(volume) " );
3175 SMESHDS_SubMesh * aSubMesh;
3177 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3179 // load shapes in myShapeIDMap
3181 TopoDS_Vertex v1, v2;
3182 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3183 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3186 int nbNodes = 0, shapeID;
3187 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3189 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3190 aSubMesh = getSubmeshWithElements( theMesh, S );
3192 nbNodes += aSubMesh->NbNodes();
3194 myPoints.resize( nbNodes );
3196 // load U of points on edges
3197 TNodePointIDMap nodePointIDMap;
3199 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3201 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3202 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3203 aSubMesh = getSubmeshWithElements( theMesh, S );
3204 if ( ! aSubMesh ) continue;
3205 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3206 if ( !nIt->more() ) continue;
3208 // store a node and a point
3209 while ( nIt->more() ) {
3210 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3211 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3213 nodePointIDMap.insert( make_pair( node, iPoint ));
3214 if ( block.IsVertexID( shapeID ))
3215 myKeyPointIDs.push_back( iPoint );
3216 TPoint* p = & myPoints[ iPoint++ ];
3217 shapePoints.push_back( p );
3218 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3219 p->myInitXYZ.SetCoord( 0,0,0 );
3221 list< TPoint* >::iterator pIt = shapePoints.begin();
3224 switch ( S.ShapeType() )
3229 for ( ; pIt != shapePoints.end(); pIt++ ) {
3230 double * coef = block.GetShapeCoef( shapeID );
3231 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3232 if ( coef[ iCoord - 1] > 0 )
3233 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3235 if ( S.ShapeType() == TopAbs_VERTEX )
3238 const TopoDS_Edge& edge = TopoDS::Edge( S );
3240 BRep_Tool::Range( edge, f, l );
3241 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3242 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3243 pIt = shapePoints.begin();
3244 nIt = aSubMesh->GetNodes();
3245 for ( ; nIt->more(); pIt++ )
3247 const SMDS_MeshNode* node = nIt->next();
3248 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3250 const SMDS_EdgePosition* epos =
3251 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3252 double u = ( epos->GetUParameter() - f ) / ( l - f );
3253 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3258 for ( ; pIt != shapePoints.end(); pIt++ )
3260 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3261 MESSAGE( "!block.ComputeParameters()" );
3262 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3266 } // loop on block sub-shapes
3270 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3273 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3274 while ( elemIt->more() ) {
3275 const SMDS_MeshElement* elem = elemIt->next();
3276 myElemPointIDs.push_back( TElemDef() );
3277 TElemDef& elemPoints = myElemPointIDs.back();
3278 int nbNodes = elem->NbCornerNodes();
3279 for ( int i = 0;i < nbNodes; ++i )
3280 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3284 myIsBoundaryPointsFound = true;
3286 return setErrorCode( ERR_OK );
3289 //=======================================================================
3290 //function : getSubmeshWithElements
3291 //purpose : return submesh containing elements bound to theBlock in theMesh
3292 //=======================================================================
3294 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3295 const TopoDS_Shape& theShape)
3297 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3298 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3301 if ( theShape.ShapeType() == TopAbs_SHELL )
3303 // look for submesh of VOLUME
3304 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3305 for (; it.More(); it.Next()) {
3306 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3307 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3315 //=======================================================================
3317 //purpose : Compute nodes coordinates applying
3318 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3319 // will be mapped into <theVertex000>. The (0,0,1)
3320 // fifth key-point will be mapped into <theVertex001>.
3321 //=======================================================================
3323 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3324 const TopoDS_Vertex& theVertex000,
3325 const TopoDS_Vertex& theVertex001)
3327 MESSAGE(" ::Apply(volume) " );
3329 if (!findBoundaryPoints() || // bind ID to points
3330 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3333 SMESH_Block block; // bind ID to shape
3334 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3335 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3337 // compute XYZ of points on shapes
3339 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3341 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3342 list< TPoint* >::iterator pIt = shapePoints.begin();
3343 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3344 switch ( S.ShapeType() )
3346 case TopAbs_VERTEX: {
3348 for ( ; pIt != shapePoints.end(); pIt++ )
3349 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3354 for ( ; pIt != shapePoints.end(); pIt++ )
3355 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3360 for ( ; pIt != shapePoints.end(); pIt++ )
3361 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3365 for ( ; pIt != shapePoints.end(); pIt++ )
3366 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3368 } // loop on block sub-shapes
3370 myIsComputed = true;
3372 return setErrorCode( ERR_OK );
3375 //=======================================================================
3377 //purpose : Compute nodes coordinates applying
3378 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3379 // will be mapped into <theNode000Index>-th node. The
3380 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3382 //=======================================================================
3384 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3385 const int theNode000Index,
3386 const int theNode001Index)
3388 //MESSAGE(" ::Apply(MeshVolume) " );
3390 if (!findBoundaryPoints()) // bind ID to points
3393 SMESH_Block block; // bind ID to shape
3394 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3395 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3396 // compute XYZ of points on shapes
3398 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3400 list< TPoint* > & shapePoints = getShapePoints( ID );
3401 list< TPoint* >::iterator pIt = shapePoints.begin();
3403 if ( block.IsVertexID( ID ))
3404 for ( ; pIt != shapePoints.end(); pIt++ ) {
3405 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3407 else if ( block.IsEdgeID( ID ))
3408 for ( ; pIt != shapePoints.end(); pIt++ ) {
3409 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3411 else if ( block.IsFaceID( ID ))
3412 for ( ; pIt != shapePoints.end(); pIt++ ) {
3413 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3416 for ( ; pIt != shapePoints.end(); pIt++ )
3417 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3418 } // loop on block sub-shapes
3420 myIsComputed = true;
3422 return setErrorCode( ERR_OK );
3425 //=======================================================================
3426 //function : mergePoints
3427 //purpose : Merge XYZ on edges and/or faces.
3428 //=======================================================================
3430 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3432 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3433 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3435 list<list< int > >& groups = idListIt->second;
3436 if ( groups.size() < 2 )
3440 const TNodeSet& nodes = idListIt->first;
3441 double tol2 = 1.e-10;
3442 if ( nodes.size() > 1 ) {
3444 TNodeSet::const_iterator n = nodes.begin();
3445 for ( ; n != nodes.end(); ++n )
3446 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3447 double x, y, z, X, Y, Z;
3448 box.Get( x, y, z, X, Y, Z );
3449 gp_Pnt p( x, y, z ), P( X, Y, Z );
3450 tol2 = 1.e-4 * p.SquareDistance( P );
3453 // to unite groups on link
3454 bool unite = ( uniteGroups && nodes.size() == 2 );
3455 map< double, int > distIndMap;
3456 const SMDS_MeshNode* node = *nodes.begin();
3457 gp_Pnt P( node->X(), node->Y(), node->Z() );
3459 // compare points, replace indices
3461 list< int >::iterator ind1, ind2;
3462 list< list< int > >::iterator grpIt1, grpIt2;
3463 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3465 list< int >& indices1 = *grpIt1;
3467 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3469 list< int >& indices2 = *grpIt2;
3470 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3472 gp_XYZ& p1 = myXYZ[ *ind1 ];
3473 ind2 = indices2.begin();
3474 while ( ind2 != indices2.end() )
3476 gp_XYZ& p2 = myXYZ[ *ind2 ];
3477 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3478 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3480 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3481 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3482 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3483 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3485 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3486 myXYZ[ *ind2 ] = undefinedXYZ();
3487 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3489 ind2 = indices2.erase( ind2 );
3496 if ( unite ) { // sort indices using distIndMap
3497 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3499 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3500 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3501 distIndMap.insert( make_pair( dist, *ind1 ));
3505 if ( unite ) { // put all sorted indices into the first group
3506 list< int >& g = groups.front();
3508 map< double, int >::iterator dist_ind = distIndMap.begin();
3509 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3510 g.push_back( dist_ind->second );
3512 } // loop on myIdsOnBoundary
3515 //=======================================================================
3516 //function : makePolyElements
3517 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3518 //=======================================================================
3520 void SMESH_Pattern::
3521 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3522 const bool toCreatePolygons,
3523 const bool toCreatePolyedrs)
3525 myPolyElemXYZIDs.clear();
3526 myPolyElems.clear();
3527 myPolyElems.reserve( myIdsOnBoundary.size() );
3529 // make a set of refined elements
3530 TIDSortedElemSet avoidSet, elemSet;
3531 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3532 for(; itv!=myElements.end(); itv++) {
3533 const SMDS_MeshElement* el = (*itv);
3534 avoidSet.insert( el );
3536 //avoidSet.insert( myElements.begin(), myElements.end() );
3538 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3540 if ( toCreatePolygons )
3542 int lastFreeId = myXYZ.size();
3544 // loop on links of refined elements
3545 indListIt = myIdsOnBoundary.begin();
3546 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3548 const TNodeSet & linkNodes = indListIt->first;
3549 if ( linkNodes.size() != 2 )
3550 continue; // skip face
3551 const SMDS_MeshNode* n1 = * linkNodes.begin();
3552 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3554 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3555 if ( idGroups.empty() || idGroups.front().empty() )
3558 // find not refined face having n1-n2 link
3562 const SMDS_MeshElement* face =
3563 SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet );
3566 avoidSet.insert ( face );
3567 myPolyElems.push_back( face );
3569 // some links of <face> are split;
3570 // make list of xyz for <face>
3571 myPolyElemXYZIDs.push_back(TElemDef());
3572 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3573 // loop on links of a <face>
3574 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3575 int i = 0, nbNodes = face->NbNodes();
3576 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3577 while ( nIt->more() )
3578 nodes[ i++ ] = smdsNode( nIt->next() );
3579 nodes[ i ] = nodes[ 0 ];
3580 for ( i = 0; i < nbNodes; ++i )
3582 // look for point mapped on a link
3583 TNodeSet faceLinkNodes;
3584 faceLinkNodes.insert( nodes[ i ] );
3585 faceLinkNodes.insert( nodes[ i + 1 ] );
3586 if ( faceLinkNodes == linkNodes )
3587 nn_IdList = indListIt;
3589 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3590 // add face point ids
3591 faceNodeIds.push_back( ++lastFreeId );
3592 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3593 if ( nn_IdList != myIdsOnBoundary.end() )
3595 // there are points mapped on a link
3596 list< int >& mappedIds = nn_IdList->second.front();
3597 if ( isReversed( nodes[ i ], mappedIds ))
3598 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3600 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3602 } // loop on links of a <face>
3608 if ( myIs2D && idGroups.size() > 1 ) {
3610 // sew new elements on 2 refined elements sharing n1-n2 link
3612 list< int >& idsOnLink = idGroups.front();
3613 // temporarily add ids of link nodes to idsOnLink
3614 bool rev = isReversed( n1, idsOnLink );
3615 for ( int i = 0; i < 2; ++i )
3618 nodeSet.insert( i ? n2 : n1 );
3619 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3620 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3621 int nodeId = groups.front().front();
3623 if ( rev ) append = !append;
3625 idsOnLink.push_back( nodeId );
3627 idsOnLink.push_front( nodeId );
3629 list< int >::iterator id = idsOnLink.begin();
3630 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3632 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3633 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3634 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3636 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3637 // look for <id> in element definition
3638 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3639 ASSERT ( idDef != pIdList->end() );
3640 // look for 2 neighbour ids of <id> in element definition
3641 for ( int prev = 0; prev < 2; ++prev ) {
3642 TElemDef::iterator idDef2 = idDef;
3644 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3646 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3647 // look for idDef2 on a link starting from id
3648 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3649 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3650 // insert ids located on link between <id> and <id2>
3651 // into the element definition between idDef and idDef2
3653 for ( ; id2 != id; --id2 )
3654 pIdList->insert( idDef, *id2 );
3656 list< int >::iterator id1 = id;
3657 for ( ++id1, ++id2; id1 != id2; ++id1 )
3658 pIdList->insert( idDef2, *id1 );
3664 // remove ids of link nodes
3665 idsOnLink.pop_front();
3666 idsOnLink.pop_back();
3668 } // loop on myIdsOnBoundary
3669 } // if ( toCreatePolygons )
3671 if ( toCreatePolyedrs )
3673 // check volumes adjacent to the refined elements
3674 SMDS_VolumeTool volTool;
3675 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3676 for ( ; refinedElem != myElements.end(); ++refinedElem )
3678 // loop on nodes of refinedElem
3679 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3680 while ( nIt->more() ) {
3681 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3682 // loop on inverse elements of node
3683 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3684 while ( eIt->more() )
3686 const SMDS_MeshElement* elem = eIt->next();
3687 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3688 continue; // skip faces or refined elements
3689 // add polyhedron definition
3690 myPolyhedronQuantities.push_back(vector<int> ());
3691 myPolyElemXYZIDs.push_back(TElemDef());
3692 vector<int>& quantity = myPolyhedronQuantities.back();
3693 TElemDef & elemDef = myPolyElemXYZIDs.back();
3694 // get definitions of new elements on volume faces
3695 bool makePoly = false;
3696 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3698 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3699 volTool.NbFaceNodes( iF ),
3700 theNodes, elemDef, quantity))
3704 myPolyElems.push_back( elem );
3706 myPolyhedronQuantities.pop_back();
3707 myPolyElemXYZIDs.pop_back();
3715 //=======================================================================
3716 //function : getFacesDefinition
3717 //purpose : return faces definition for a volume face defined by theBndNodes
3718 //=======================================================================
3720 bool SMESH_Pattern::
3721 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3722 const int theNbBndNodes,
3723 const vector< const SMDS_MeshNode* >& theNodes,
3724 list< int >& theFaceDefs,
3725 vector<int>& theQuantity)
3727 bool makePoly = false;
3729 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3731 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3733 // make a set of all nodes on a face
3735 if ( !myIs2D ) { // for 2D, merge only edges
3736 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3737 if ( nn_IdList != myIdsOnBoundary.end() ) {
3738 list< int > & faceIds = nn_IdList->second.front();
3739 if ( !faceIds.empty() ) {
3741 ids.insert( faceIds.begin(), faceIds.end() );
3746 // add ids on links and bnd nodes
3747 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3748 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3749 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3751 // add id of iN-th bnd node
3753 nSet.insert( theBndNodes[ iN ] );
3754 nn_IdList = myIdsOnBoundary.find( nSet );
3755 int bndId = ++lastFreeId;
3756 if ( nn_IdList != myIdsOnBoundary.end() ) {
3757 bndId = nn_IdList->second.front().front();
3758 ids.insert( bndId );
3761 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3763 faceDef.push_back( bndId );
3764 // add ids on a link
3766 linkNodes.insert( theBndNodes[ iN ]);
3767 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3768 nn_IdList = myIdsOnBoundary.find( linkNodes );
3769 if ( nn_IdList != myIdsOnBoundary.end() ) {
3770 list< int > & linkIds = nn_IdList->second.front();
3771 if ( !linkIds.empty() )
3774 ids.insert( linkIds.begin(), linkIds.end() );
3775 if ( isReversed( theBndNodes[ iN ], linkIds ))
3776 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3778 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3783 // find faces definition of new volumes
3785 bool defsAdded = false;
3786 if ( !myIs2D ) { // for 2D, merge only edges
3787 SMDS_VolumeTool vol;
3788 set< TElemDef* > checkedVolDefs;
3789 set< int >::iterator id = ids.begin();
3790 for ( ; id != ids.end(); ++id )
3792 // definitions of volumes sharing id
3793 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3794 ASSERT( !defList.empty() );
3795 // loop on volume definitions
3796 list< TElemDef* >::iterator pIdList = defList.begin();
3797 for ( ; pIdList != defList.end(); ++pIdList)
3799 if ( !checkedVolDefs.insert( *pIdList ).second )
3800 continue; // skip already checked volume definition
3801 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3802 // loop on face defs of a volume
3803 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3804 if ( volType == SMDS_VolumeTool::UNKNOWN )
3806 int nbFaces = vol.NbFaces( volType );
3807 for ( int iF = 0; iF < nbFaces; ++iF )
3809 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3810 int iN, nbN = vol.NbFaceNodes( volType, iF );
3811 // check if all nodes of a faces are in <ids>
3813 for ( iN = 0; iN < nbN && all; ++iN ) {
3814 int nodeId = idVec[ nodeInds[ iN ]];
3815 all = ( ids.find( nodeId ) != ids.end() );
3818 // store a face definition
3819 for ( iN = 0; iN < nbN; ++iN ) {
3820 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3822 theQuantity.push_back( nbN );
3830 theQuantity.push_back( faceDef.size() );
3831 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3837 //=======================================================================
3838 //function : clearSubMesh
3840 //=======================================================================
3842 static bool clearSubMesh( SMESH_Mesh* theMesh,
3843 const TopoDS_Shape& theShape)
3845 bool removed = false;
3846 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3848 removed = !aSubMesh->IsEmpty();
3850 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3853 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3854 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3856 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3857 removed = eIt->more();
3858 while ( eIt->more() )
3859 aMeshDS->RemoveElement( eIt->next() );
3860 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3861 removed = removed || nIt->more();
3862 while ( nIt->more() )
3863 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3869 //=======================================================================
3870 //function : clearMesh
3871 //purpose : clear mesh elements existing on myShape in theMesh
3872 //=======================================================================
3874 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3877 if ( !myShape.IsNull() )
3879 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3880 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3881 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3883 clearSubMesh( theMesh, it.Value() );
3889 //=======================================================================
3890 //function : MakeMesh
3891 //purpose : Create nodes and elements in <theMesh> using nodes
3892 // coordinates computed by either of Apply...() methods
3893 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3894 // it does not care of nodes and elements already existing on
3895 // sub-shapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3896 //=======================================================================
3898 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3899 const bool toCreatePolygons,
3900 const bool toCreatePolyedrs)
3902 MESSAGE(" ::MakeMesh() " );
3903 if ( !myIsComputed )
3904 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3906 mergePoints( toCreatePolygons );
3908 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3910 // clear elements and nodes existing on myShape
3913 bool onMeshElements = ( !myElements.empty() );
3915 // Create missing nodes
3917 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3918 if ( onMeshElements )
3920 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3921 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3922 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3923 nodesVector[ i_node->first ] = i_node->second;
3925 for ( int i = 0; i < myXYZ.size(); ++i ) {
3926 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3927 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3934 nodesVector.resize( myPoints.size(), 0 );
3936 // to find point index
3937 map< TPoint*, int > pointIndex;
3938 for ( int i = 0; i < myPoints.size(); i++ )
3939 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3941 // loop on sub-shapes of myShape: create nodes
3942 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3943 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3946 //SMESHDS_SubMesh * subMeshDS = 0;
3947 if ( !myShapeIDMap.IsEmpty() ) {
3948 S = myShapeIDMap( idPointIt->first );
3949 //subMeshDS = aMeshDS->MeshElements( S );
3951 list< TPoint* > & points = idPointIt->second;
3952 list< TPoint* >::iterator pIt = points.begin();
3953 for ( ; pIt != points.end(); pIt++ )
3955 TPoint* point = *pIt;
3956 int pIndex = pointIndex[ point ];
3957 if ( nodesVector [ pIndex ] )
3959 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3962 nodesVector [ pIndex ] = node;
3964 if ( !S.IsNull() /*subMeshDS*/ ) {
3965 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3966 switch ( S.ShapeType() ) {
3967 case TopAbs_VERTEX: {
3968 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3971 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3974 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3975 point->myUV.X(), point->myUV.Y() ); break;
3978 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3987 if ( onMeshElements )
3989 // prepare data to create poly elements
3990 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3993 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3994 // sew old and new elements
3995 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3999 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4002 aMeshDS->compactMesh();
4004 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4005 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4006 // for ( ; i_sm != sm.end(); i_sm++ )
4008 // cout << " SM " << i_sm->first << " ";
4009 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4010 // //SMDS_ElemIteratorPtr GetElements();
4011 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4012 // while ( nit->more() )
4013 // cout << nit->next()->GetID() << " ";
4016 return setErrorCode( ERR_OK );
4019 //=======================================================================
4020 //function : createElements
4021 //purpose : add elements to the mesh
4022 //=======================================================================
4024 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4025 const vector<const SMDS_MeshNode* >& theNodesVector,
4026 const list< TElemDef > & theElemNodeIDs,
4027 const vector<const SMDS_MeshElement*>& theElements)
4029 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4030 SMESH_MeshEditor editor( theMesh );
4032 bool onMeshElements = !theElements.empty();
4034 // shapes and groups theElements are on
4035 vector< int > shapeIDs;
4036 vector< list< SMESHDS_Group* > > groups;
4037 set< const SMDS_MeshNode* > shellNodes;
4038 if ( onMeshElements )
4040 shapeIDs.resize( theElements.size() );
4041 groups.resize( theElements.size() );
4042 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4043 set<SMESHDS_GroupBase*>::const_iterator grIt;
4044 for ( int i = 0; i < theElements.size(); i++ )
4046 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4047 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4048 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4049 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4050 groups[ i ].push_back( group );
4053 // get all nodes bound to shells because their SpacePosition is not set
4054 // by SMESHDS_Mesh::SetNodeInVolume()
4055 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4056 if ( !aMainShape.IsNull() ) {
4057 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4058 for ( ; shellExp.More(); shellExp.Next() )
4060 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4062 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4063 while ( nIt->more() )
4064 shellNodes.insert( nIt->next() );
4069 // nb new elements per a refined element
4070 int nbNewElemsPerOld = 1;
4071 if ( onMeshElements )
4072 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4076 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4077 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4078 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4080 const TElemDef & elemNodeInd = *enIt;
4082 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4083 TElemDef::const_iterator id = elemNodeInd.begin();
4085 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4086 if ( *id < theNodesVector.size() )
4087 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4089 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4091 // dim of refined elem
4092 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4093 if ( onMeshElements ) {
4094 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4097 const SMDS_MeshElement* elem = 0;
4099 switch ( nbNodes ) {
4101 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4103 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4105 if ( !onMeshElements ) {// create a quadratic face
4106 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4107 nodes[4], nodes[5] ); break;
4108 } // else do not break but create a polygon
4110 if ( !onMeshElements ) {// create a quadratic face
4111 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4112 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4113 } // else do not break but create a polygon
4115 elem = aMeshDS->AddPolygonalFace( nodes );
4119 switch ( nbNodes ) {
4121 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4123 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4126 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4127 nodes[4], nodes[5] ); break;
4129 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4130 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4132 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4135 // set element on a shape
4136 if ( elem && onMeshElements ) // applied to mesh elements
4138 int shapeID = shapeIDs[ elemIndex ];
4139 if ( shapeID > 0 ) {
4140 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4141 // set nodes on a shape
4142 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4143 if ( S.ShapeType() == TopAbs_SOLID ) {
4144 TopoDS_Iterator shellIt( S );
4145 if ( shellIt.More() )
4146 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4148 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4149 while ( noIt->more() ) {
4150 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4151 if (!node->getshapeId() &&
4152 shellNodes.find( node ) == shellNodes.end() ) {
4153 if ( S.ShapeType() == TopAbs_FACE )
4154 aMeshDS->SetNodeOnFace( node, shapeID,
4155 Precision::Infinite(),// <- it's a sign that UV is not set
4156 Precision::Infinite());
4158 aMeshDS->SetNodeInVolume( node, shapeID );
4159 shellNodes.insert( node );
4164 // add elem in groups
4165 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4166 for ( ; g != groups[ elemIndex ].end(); ++g )
4167 (*g)->SMDSGroup().Add( elem );
4169 if ( elem && !myShape.IsNull() ) // applied to shape
4170 aMeshDS->SetMeshElementOnShape( elem, myShape );
4173 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4174 // so that operations with hypotheses will erase the mesh being built
4176 SMESH_subMesh * subMesh;
4177 if ( !myShape.IsNull() ) {
4178 subMesh = theMesh->GetSubMesh( myShape );
4180 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4182 if ( onMeshElements ) {
4183 list< int > elemIDs;
4184 for ( int i = 0; i < theElements.size(); i++ )
4186 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4188 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4190 elemIDs.push_back( theElements[ i ]->GetID() );
4192 // remove refined elements
4193 editor.Remove( elemIDs, false );
4197 //=======================================================================
4198 //function : isReversed
4199 //purpose : check xyz ids order in theIdsList taking into account
4200 // theFirstNode on a link
4201 //=======================================================================
4203 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4204 const list< int >& theIdsList) const
4206 if ( theIdsList.size() < 2 )
4209 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4211 list<int>::const_iterator id = theIdsList.begin();
4212 for ( int i = 0; i < 2; ++i, ++id ) {
4213 if ( *id < myXYZ.size() )
4214 P[ i ] = myXYZ[ *id ];
4216 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4217 i_n = myXYZIdToNodeMap.find( *id );
4218 ASSERT( i_n != myXYZIdToNodeMap.end() );
4219 const SMDS_MeshNode* n = i_n->second;
4220 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4223 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4227 //=======================================================================
4228 //function : arrangeBoundaries
4229 //purpose : if there are several wires, arrange boundaryPoints so that
4230 // the outer wire goes first and fix inner wires orientation
4231 // update myKeyPointIDs to correspond to the order of key-points
4232 // in boundaries; sort internal boundaries by the nb of key-points
4233 //=======================================================================
4235 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4237 typedef list< list< TPoint* > >::iterator TListOfListIt;
4238 TListOfListIt bndIt;
4239 list< TPoint* >::iterator pIt;
4241 int nbBoundaries = boundaryList.size();
4242 if ( nbBoundaries > 1 )
4244 // sort boundaries by nb of key-points
4245 if ( nbBoundaries > 2 )
4247 // move boundaries in tmp list
4248 list< list< TPoint* > > tmpList;
4249 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4250 // make a map nb-key-points to boundary-position-in-tmpList,
4251 // boundary-positions get ordered in it
4252 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4253 TNbKpBndPosMap nbKpBndPosMap;
4254 bndIt = tmpList.begin();
4255 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4256 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4257 int nb = *nbKpIt * nbBoundaries;
4258 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4260 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4262 // move boundaries back to boundaryList
4263 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4264 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4265 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4266 TListOfListIt bndPos1 = bndPos2++;
4267 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4271 // Look for the outer boundary: the one with the point with the least X
4272 double leastX = DBL_MAX;
4273 TListOfListIt outerBndPos;
4274 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4276 list< TPoint* >& boundary = (*bndIt);
4277 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4279 TPoint* point = *pIt;
4280 if ( point->myInitXYZ.X() < leastX ) {
4281 leastX = point->myInitXYZ.X();
4282 outerBndPos = bndIt;
4287 if ( outerBndPos != boundaryList.begin() )
4288 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4290 } // if nbBoundaries > 1
4292 // Check boundaries orientation and re-fill myKeyPointIDs
4294 set< TPoint* > keyPointSet;
4295 list< int >::iterator kpIt = myKeyPointIDs.begin();
4296 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4297 keyPointSet.insert( & myPoints[ *kpIt ]);
4298 myKeyPointIDs.clear();
4300 // update myNbKeyPntInBoundary also
4301 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4303 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4305 // find the point with the least X
4306 double leastX = DBL_MAX;
4307 list< TPoint* >::iterator xpIt;
4308 list< TPoint* >& boundary = (*bndIt);
4309 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4311 TPoint* point = *pIt;
4312 if ( point->myInitXYZ.X() < leastX ) {
4313 leastX = point->myInitXYZ.X();
4317 // find points next to the point with the least X
4318 TPoint* p = *xpIt, *pPrev, *pNext;
4319 if ( p == boundary.front() )
4320 pPrev = *(++boundary.rbegin());
4326 if ( p == boundary.back() )
4327 pNext = *(++boundary.begin());
4332 // vectors of boundary direction near <p>
4333 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4334 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4335 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4336 double yPrev = v1.Y() / sqrt( sqMag1 );
4337 double yNext = v2.Y() / sqrt( sqMag2 );
4338 double sumY = yPrev + yNext;
4340 if ( bndIt == boundaryList.begin() ) // outer boundary
4348 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4349 (*nbKpIt) = 0; // count nb of key-points again
4350 pIt = boundary.begin();
4351 for ( ; pIt != boundary.end(); pIt++)
4353 TPoint* point = *pIt;
4354 if ( keyPointSet.find( point ) == keyPointSet.end() )
4356 // find an index of a keypoint
4358 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4359 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4360 if ( &(*pVecIt) == point )
4362 myKeyPointIDs.push_back( index );
4365 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4368 } // loop on a list of boundaries
4370 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4373 //=======================================================================
4374 //function : findBoundaryPoints
4375 //purpose : if loaded from file, find points to map on edges and faces and
4376 // compute their parameters
4377 //=======================================================================
4379 bool SMESH_Pattern::findBoundaryPoints()
4381 if ( myIsBoundaryPointsFound ) return true;
4383 MESSAGE(" findBoundaryPoints() ");
4385 myNbKeyPntInBoundary.clear();
4389 set< TPoint* > pointsInElems;
4391 // Find free links of elements:
4392 // put links of all elements in a set and remove links encountered twice
4394 typedef pair< TPoint*, TPoint*> TLink;
4395 set< TLink > linkSet;
4396 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4397 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4399 TElemDef & elemPoints = *epIt;
4400 TElemDef::iterator pIt = elemPoints.begin();
4401 int prevP = elemPoints.back();
4402 for ( ; pIt != elemPoints.end(); pIt++ ) {
4403 TPoint* p1 = & myPoints[ prevP ];
4404 TPoint* p2 = & myPoints[ *pIt ];
4405 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4406 ASSERT( link.first != link.second );
4407 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4408 if ( !itUniq.second )
4409 linkSet.erase( itUniq.first );
4412 pointsInElems.insert( p1 );
4415 // Now linkSet contains only free links,
4416 // find the points order that they have in boundaries
4418 // 1. make a map of key-points
4419 set< TPoint* > keyPointSet;
4420 list< int >::iterator kpIt = myKeyPointIDs.begin();
4421 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4422 keyPointSet.insert( & myPoints[ *kpIt ]);
4424 // 2. chain up boundary points
4425 list< list< TPoint* > > boundaryList;
4426 boundaryList.push_back( list< TPoint* >() );
4427 list< TPoint* > * boundary = & boundaryList.back();
4429 TPoint *point1, *point2, *keypoint1;
4430 kpIt = myKeyPointIDs.begin();
4431 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4432 // loop on free links: look for the next point
4434 set< TLink >::iterator lIt = linkSet.begin();
4435 while ( lIt != linkSet.end() )
4437 if ( (*lIt).first == point1 )
4438 point2 = (*lIt).second;
4439 else if ( (*lIt).second == point1 )
4440 point2 = (*lIt).first;
4445 linkSet.erase( lIt );
4446 lIt = linkSet.begin();
4448 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4450 boundary->push_back( point2 );
4452 else // a key-point found
4454 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4456 if ( point2 != keypoint1 ) // its not the boundary end
4458 boundary->push_back( point2 );
4460 else // the boundary end reached
4462 boundary->push_front( keypoint1 );
4463 boundary->push_back( keypoint1 );
4464 myNbKeyPntInBoundary.push_back( iKeyPoint );
4465 if ( keyPointSet.empty() )
4466 break; // all boundaries containing key-points are found
4468 // prepare to search for the next boundary
4469 boundaryList.push_back( list< TPoint* >() );
4470 boundary = & boundaryList.back();
4471 point2 = keypoint1 = (*keyPointSet.begin());
4475 } // loop on the free links set
4477 if ( boundary->empty() ) {
4478 MESSAGE(" a separate key-point");
4479 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4482 // if there are several wires, arrange boundaryPoints so that
4483 // the outer wire goes first and fix inner wires orientation;
4484 // sort myKeyPointIDs to correspond to the order of key-points
4486 arrangeBoundaries( boundaryList );
4488 // Find correspondence shape ID - points,
4489 // compute points parameter on edge
4491 keyPointSet.clear();
4492 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4493 keyPointSet.insert( & myPoints[ *kpIt ]);
4495 set< TPoint* > edgePointSet; // to find in-face points
4496 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4497 int edgeID = myKeyPointIDs.size() + 1;
4499 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4500 for ( ; bndIt != boundaryList.end(); bndIt++ )
4502 boundary = & (*bndIt);
4503 double edgeLength = 0;
4504 list< TPoint* >::iterator pIt = boundary->begin();
4505 getShapePoints( edgeID ).push_back( *pIt );
4506 getShapePoints( vertexID++ ).push_back( *pIt );
4507 for ( pIt++; pIt != boundary->end(); pIt++)
4509 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4510 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4511 TPoint* point = *pIt;
4512 edgePointSet.insert( point );
4513 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4515 edgePoints.push_back( point );
4516 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4517 point->myInitU = edgeLength;
4521 // treat points on the edge which ends up: compute U [0,1]
4522 edgePoints.push_back( point );
4523 if ( edgePoints.size() > 2 ) {
4524 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4525 list< TPoint* >::iterator epIt = edgePoints.begin();
4526 for ( ; epIt != edgePoints.end(); epIt++ )
4527 (*epIt)->myInitU /= edgeLength;
4529 // begin the next edge treatment
4532 if ( point != boundary->front() ) { // not the first key-point again
4533 getShapePoints( edgeID ).push_back( point );
4534 getShapePoints( vertexID++ ).push_back( point );
4540 // find in-face points
4541 list< TPoint* > & facePoints = getShapePoints( edgeID );
4542 vector< TPoint >::iterator pVecIt = myPoints.begin();
4543 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4544 TPoint* point = &(*pVecIt);
4545 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4546 pointsInElems.find( point ) != pointsInElems.end())
4547 facePoints.push_back( point );
4554 // bind points to shapes according to point parameters
4555 vector< TPoint >::iterator pVecIt = myPoints.begin();
4556 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4557 TPoint* point = &(*pVecIt);
4558 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4559 getShapePoints( shapeID ).push_back( point );
4560 // detect key-points
4561 if ( SMESH_Block::IsVertexID( shapeID ))
4562 myKeyPointIDs.push_back( i );
4566 myIsBoundaryPointsFound = true;
4567 return myIsBoundaryPointsFound;
4570 //=======================================================================
4572 //purpose : clear fields
4573 //=======================================================================
4575 void SMESH_Pattern::Clear()
4577 myIsComputed = myIsBoundaryPointsFound = false;
4580 myKeyPointIDs.clear();
4581 myElemPointIDs.clear();
4582 myShapeIDToPointsMap.clear();
4583 myShapeIDMap.Clear();
4585 myNbKeyPntInBoundary.clear();
4588 myElemXYZIDs.clear();
4589 myXYZIdToNodeMap.clear();
4591 myOrderedNodes.clear();
4592 myPolyElems.clear();
4593 myPolyElemXYZIDs.clear();
4594 myPolyhedronQuantities.clear();
4595 myIdsOnBoundary.clear();
4596 myReverseConnectivity.clear();
4599 //================================================================================
4601 * \brief set ErrorCode and return true if it is Ok
4603 //================================================================================
4605 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4607 myErrorCode = theErrorCode;
4608 return myErrorCode == ERR_OK;
4611 //=======================================================================
4612 //function : setShapeToMesh
4613 //purpose : set a shape to be meshed. Return True if meshing is possible
4614 //=======================================================================
4616 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4618 if ( !IsLoaded() ) {
4619 MESSAGE( "Pattern not loaded" );
4620 return setErrorCode( ERR_APPL_NOT_LOADED );
4623 TopAbs_ShapeEnum aType = theShape.ShapeType();
4624 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4626 MESSAGE( "Pattern dimention mismatch" );
4627 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4630 // check if a face is closed
4631 int nbNodeOnSeamEdge = 0;
4633 TopTools_MapOfShape seamVertices;
4634 TopoDS_Face face = TopoDS::Face( theShape );
4635 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4636 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
4637 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4638 if ( BRep_Tool::IsClosed(ee, face) ) {
4639 // seam edge and vertices encounter twice in theFace
4640 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4641 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4646 // check nb of vertices
4647 TopTools_IndexedMapOfShape vMap;
4648 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4649 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4650 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4651 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4654 myElements.clear(); // not refine elements
4655 myElemXYZIDs.clear();
4657 myShapeIDMap.Clear();
4662 //=======================================================================
4663 //function : GetMappedPoints
4664 //purpose : Return nodes coordinates computed by Apply() method
4665 //=======================================================================
4667 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4670 if ( !myIsComputed )
4673 if ( myElements.empty() ) { // applied to shape
4674 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4675 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4676 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4678 else { // applied to mesh elements
4679 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4680 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4681 for ( ; xyz != myXYZ.end(); ++xyz )
4682 if ( !isDefined( *xyz ))
4683 thePoints.push_back( definedXYZ );
4685 thePoints.push_back( & (*xyz) );
4687 return !thePoints.empty();
4691 //=======================================================================
4692 //function : GetPoints
4693 //purpose : Return nodes coordinates of the pattern
4694 //=======================================================================
4696 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4703 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4704 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4705 thePoints.push_back( & (*pVecIt).myInitXYZ );
4707 return ( thePoints.size() > 0 );
4710 //=======================================================================
4711 //function : getShapePoints
4712 //purpose : return list of points located on theShape
4713 //=======================================================================
4715 list< SMESH_Pattern::TPoint* > &
4716 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4719 if ( !myShapeIDMap.Contains( theShape ))
4720 aShapeID = myShapeIDMap.Add( theShape );
4722 aShapeID = myShapeIDMap.FindIndex( theShape );
4724 return myShapeIDToPointsMap[ aShapeID ];
4727 //=======================================================================
4728 //function : getShapePoints
4729 //purpose : return list of points located on the shape
4730 //=======================================================================
4732 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4734 return myShapeIDToPointsMap[ theShapeID ];
4737 //=======================================================================
4738 //function : DumpPoints
4740 //=======================================================================
4742 void SMESH_Pattern::DumpPoints() const
4745 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4746 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4747 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4751 //=======================================================================
4752 //function : TPoint()
4754 //=======================================================================
4756 SMESH_Pattern::TPoint::TPoint()
4759 myInitXYZ.SetCoord(0,0,0);
4760 myInitUV.SetCoord(0.,0.);
4762 myXYZ.SetCoord(0,0,0);
4763 myUV.SetCoord(0.,0.);
4768 //=======================================================================
4769 //function : operator <<
4771 //=======================================================================
4773 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4775 gp_XYZ xyz = p.myInitXYZ;
4776 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4777 gp_XY xy = p.myInitUV;
4778 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4779 double u = p.myInitU;
4780 OS << " u( " << u << " )) " << &p << endl;
4781 xyz = p.myXYZ.XYZ();
4782 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4784 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4786 OS << " u( " << u << " ))" << endl;