1 // Copyright (C) 2007-2010 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 <BRepAdaptor_Curve.hxx>
30 #include <BRepTools.hxx>
31 #include <BRepTools_WireExplorer.hxx>
32 #include <BRep_Tool.hxx>
33 #include <Bnd_Box.hxx>
34 #include <Bnd_Box2d.hxx>
36 #include <Extrema_ExtPC.hxx>
37 #include <Extrema_GenExtPS.hxx>
38 #include <Extrema_POnSurf.hxx>
39 #include <Geom2d_Curve.hxx>
40 #include <GeomAdaptor_Surface.hxx>
41 #include <Geom_Curve.hxx>
42 #include <Geom_Surface.hxx>
43 #include <TopAbs_ShapeEnum.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopLoc_Location.hxx>
47 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TopoDS_Edge.hxx>
50 #include <TopoDS_Face.hxx>
51 #include <TopoDS_Iterator.hxx>
52 #include <TopoDS_Shell.hxx>
53 #include <TopoDS_Vertex.hxx>
54 #include <TopoDS_Wire.hxx>
56 #include <gp_Lin2d.hxx>
57 #include <gp_Pnt2d.hxx>
58 #include <gp_Trsf.hxx>
62 #include "SMDS_EdgePosition.hxx"
63 #include "SMDS_FacePosition.hxx"
64 #include "SMDS_MeshElement.hxx"
65 #include "SMDS_MeshFace.hxx"
66 #include "SMDS_MeshNode.hxx"
67 #include "SMDS_VolumeTool.hxx"
68 #include "SMESHDS_Group.hxx"
69 #include "SMESHDS_Mesh.hxx"
70 #include "SMESHDS_SubMesh.hxx"
71 #include "SMESH_Block.hxx"
72 #include "SMESH_Mesh.hxx"
73 #include "SMESH_MesherHelper.hxx"
74 #include "SMESH_subMesh.hxx"
76 #include "utilities.h"
80 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
82 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
84 //=======================================================================
85 //function : SMESH_Pattern
87 //=======================================================================
89 SMESH_Pattern::SMESH_Pattern ()
92 //=======================================================================
95 //=======================================================================
97 static inline int getInt( const char * theSring )
99 if ( *theSring < '0' || *theSring > '9' )
103 int val = strtol( theSring, &ptr, 10 );
104 if ( ptr == theSring ||
105 // there must not be neither '.' nor ',' nor 'E' ...
106 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
112 //=======================================================================
113 //function : getDouble
115 //=======================================================================
117 static inline double getDouble( const char * theSring )
120 return strtod( theSring, &ptr );
123 //=======================================================================
124 //function : readLine
125 //purpose : Put token starting positions in theFields until '\n' or '\0'
126 // Return the number of the found tokens
127 //=======================================================================
129 static int readLine (list <const char*> & theFields,
130 const char* & theLineBeg,
131 const bool theClearFields )
133 if ( theClearFields )
138 /* switch ( symbol ) { */
139 /* case white-space: */
140 /* look for a non-space symbol; */
141 /* case string-end: */
144 /* case comment beginning: */
145 /* skip all till a line-end; */
147 /* put its position in theFields, skip till a white-space;*/
153 bool stopReading = false;
156 bool isNumber = false;
157 switch ( *theLineBeg )
159 case ' ': // white space
164 case '\n': // a line ends
165 stopReading = ( nbRead > 0 );
170 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
174 case '\0': // file ends
177 case '-': // real number
182 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
184 theFields.push_back( theLineBeg );
187 while (*theLineBeg != ' ' &&
188 *theLineBeg != '\n' &&
189 *theLineBeg != '\0');
193 return 0; // incorrect file format
199 } while ( !stopReading );
204 //=======================================================================
206 //purpose : Load a pattern from <theFile>
207 //=======================================================================
209 bool SMESH_Pattern::Load (const char* theFileContents)
211 MESSAGE("Load( file ) ");
215 // ! This is a comment
216 // NB_POINTS ! 1 integer - the number of points in the pattern.
217 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
218 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
220 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
221 // ! elements description goes after all
222 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
227 const char* lineBeg = theFileContents;
228 list <const char*> fields;
229 const bool clearFields = true;
231 // NB_POINTS ! 1 integer - the number of points in the pattern.
233 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
234 MESSAGE("Error reading NB_POINTS");
235 return setErrorCode( ERR_READ_NB_POINTS );
237 int nbPoints = getInt( fields.front() );
239 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
241 // read the first point coordinates to define pattern dimention
242 int dim = readLine( fields, lineBeg, clearFields );
248 MESSAGE("Error reading points: wrong nb of coordinates");
249 return setErrorCode( ERR_READ_POINT_COORDS );
251 if ( nbPoints <= dim ) {
252 MESSAGE(" Too few points ");
253 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
256 // read the rest points
258 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
259 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
260 MESSAGE("Error reading points : wrong nb of coordinates ");
261 return setErrorCode( ERR_READ_POINT_COORDS );
263 // store point coordinates
264 myPoints.resize( nbPoints );
265 list <const char*>::iterator fIt = fields.begin();
266 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
268 TPoint & p = myPoints[ iPoint ];
269 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
271 double coord = getDouble( *fIt );
272 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
273 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
275 return setErrorCode( ERR_READ_3D_COORD );
277 p.myInitXYZ.SetCoord( iCoord, coord );
279 p.myInitUV.SetCoord( iCoord, coord );
283 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
286 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
287 MESSAGE("Error: missing key-points");
289 return setErrorCode( ERR_READ_NO_KEYPOINT );
292 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
294 int pointIndex = getInt( *fIt );
295 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
296 MESSAGE("Error: invalid point index " << pointIndex );
298 return setErrorCode( ERR_READ_BAD_INDEX );
300 if ( idSet.insert( pointIndex ).second ) // unique?
301 myKeyPointIDs.push_back( pointIndex );
305 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
307 while ( readLine( fields, lineBeg, clearFields ))
309 myElemPointIDs.push_back( TElemDef() );
310 TElemDef& elemPoints = myElemPointIDs.back();
311 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
313 int pointIndex = getInt( *fIt );
314 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
315 MESSAGE("Error: invalid point index " << pointIndex );
317 return setErrorCode( ERR_READ_BAD_INDEX );
319 elemPoints.push_back( pointIndex );
321 // check the nb of nodes in element
323 switch ( elemPoints.size() ) {
324 case 3: if ( !myIs2D ) Ok = false; break;
328 case 8: if ( myIs2D ) Ok = false; break;
332 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
334 return setErrorCode( ERR_READ_ELEM_POINTS );
337 if ( myElemPointIDs.empty() ) {
338 MESSAGE("Error: no elements");
340 return setErrorCode( ERR_READ_NO_ELEMS );
343 findBoundaryPoints(); // sort key-points
345 return setErrorCode( ERR_OK );
348 //=======================================================================
350 //purpose : Save the loaded pattern into the file <theFileName>
351 //=======================================================================
353 bool SMESH_Pattern::Save (ostream& theFile)
355 MESSAGE(" ::Save(file) " );
357 MESSAGE(" Pattern not loaded ");
358 return setErrorCode( ERR_SAVE_NOT_LOADED );
361 theFile << "!!! SALOME Mesh Pattern file" << endl;
362 theFile << "!!!" << endl;
363 theFile << "!!! Nb of points:" << endl;
364 theFile << myPoints.size() << endl;
368 // theFile.width( 8 );
369 // theFile.setf(ios::fixed);// use 123.45 floating notation
370 // theFile.setf(ios::right);
371 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
372 // theFile.setf(ios::showpoint); // do not show trailing zeros
373 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
374 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
375 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
376 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
377 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
378 theFile << " !- " << i << endl; // point id to ease reading by a human being
382 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
383 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
384 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
385 theFile << " " << *kpIt;
386 if ( !myKeyPointIDs.empty() )
390 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
391 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
392 for ( ; epIt != myElemPointIDs.end(); epIt++ )
394 const TElemDef & elemPoints = *epIt;
395 TElemDef::const_iterator iIt = elemPoints.begin();
396 for ( ; iIt != elemPoints.end(); iIt++ )
397 theFile << " " << *iIt;
403 return setErrorCode( ERR_OK );
406 //=======================================================================
407 //function : sortBySize
408 //purpose : sort theListOfList by size
409 //=======================================================================
411 template<typename T> struct TSizeCmp {
412 bool operator ()( const list < T > & l1, const list < T > & l2 )
413 const { return l1.size() < l2.size(); }
416 template<typename T> void sortBySize( list< list < T > > & theListOfList )
418 if ( theListOfList.size() > 2 ) {
419 TSizeCmp< T > SizeCmp;
420 theListOfList.sort( SizeCmp );
424 //=======================================================================
427 //=======================================================================
429 static gp_XY project (const SMDS_MeshNode* theNode,
430 Extrema_GenExtPS & theProjectorPS)
432 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
433 theProjectorPS.Perform( P );
434 if ( !theProjectorPS.IsDone() ) {
435 MESSAGE( "SMESH_Pattern: point projection FAILED");
438 double u, v, minVal = DBL_MAX;
439 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
440 if ( theProjectorPS.Value( i ) < minVal ) {
441 minVal = theProjectorPS.Value( i );
442 theProjectorPS.Point( i ).Parameter( u, v );
444 return gp_XY( u, v );
447 //=======================================================================
448 //function : areNodesBound
449 //purpose : true if all nodes of faces are bound to shapes
450 //=======================================================================
452 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
454 while ( faceItr->more() )
456 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
457 while ( nIt->more() )
459 const SMDS_MeshNode* node = smdsNode( nIt->next() );
460 SMDS_PositionPtr pos = node->GetPosition();
461 if ( !pos || !pos->GetShapeId() ) {
469 //=======================================================================
470 //function : isMeshBoundToShape
471 //purpose : return true if all 2d elements are bound to shape
472 // if aFaceSubmesh != NULL, then check faces bound to it
473 // else check all faces in aMeshDS
474 //=======================================================================
476 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
477 SMESHDS_SubMesh * aFaceSubmesh,
478 const bool isMainShape)
481 // check that all faces are bound to aFaceSubmesh
482 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
486 // check face nodes binding
487 if ( aFaceSubmesh ) {
488 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
489 return areNodesBound( fIt );
491 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
492 return areNodesBound( fIt );
495 //=======================================================================
497 //purpose : Create a pattern from the mesh built on <theFace>.
498 // <theProject>==true makes override nodes positions
499 // on <theFace> computed by mesher
500 //=======================================================================
502 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
503 const TopoDS_Face& theFace,
506 MESSAGE(" ::Load(face) " );
510 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
511 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
512 SMESH_MesherHelper helper( *theMesh );
513 helper.SetSubShape( theFace );
515 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
516 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
517 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
519 MESSAGE( "No elements bound to the face");
520 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
523 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
525 // check if face is closed
526 bool isClosed = helper.HasSeam();
528 list<TopoDS_Edge> eList;
529 list<TopoDS_Edge>::iterator elIt;
530 SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
532 // check that requested or needed projection is possible
533 bool isMainShape = theMesh->IsMainShape( face );
534 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
535 bool canProject = ( nbElems ? true : isMainShape );
537 canProject = false; // so far
539 if ( ( theProject || needProject ) && !canProject )
540 return setErrorCode( ERR_LOADF_CANT_PROJECT );
542 Extrema_GenExtPS projector;
543 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
544 if ( theProject || needProject )
545 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
548 TNodePointIDMap nodePointIDMap;
549 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
553 MESSAGE("Project the submesh");
554 // ---------------------------------------------------------------
555 // The case where the submesh is projected to theFace
556 // ---------------------------------------------------------------
559 list< const SMDS_MeshElement* > faces;
561 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
562 while ( fIt->more() ) {
563 const SMDS_MeshElement* f = fIt->next();
564 if ( f && f->GetType() == SMDSAbs_Face )
565 faces.push_back( f );
569 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
570 while ( fIt->more() )
571 faces.push_back( fIt->next() );
574 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
575 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
576 for ( ; fIt != faces.end(); ++fIt )
578 myElemPointIDs.push_back( TElemDef() );
579 TElemDef& elemPoints = myElemPointIDs.back();
580 SMDS_ElemIteratorPtr nIt = (*fIt)->nodesIterator();
581 while ( nIt->more() )
583 const SMDS_MeshElement* node = nIt->next();
584 TNodePointIDMap::iterator nIdIt = nodePointIDMap.find( node );
585 if ( nIdIt == nodePointIDMap.end() )
587 elemPoints.push_back( iPoint );
588 nodePointIDMap.insert( make_pair( node, iPoint++ ));
591 elemPoints.push_back( (*nIdIt).second );
594 myPoints.resize( iPoint );
596 // project all nodes of 2d elements to theFace
597 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
598 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
600 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
601 TPoint * p = & myPoints[ (*nIdIt).second ];
602 p->myInitUV = project( node, projector );
603 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
605 // find key-points: the points most close to UV of vertices
606 TopExp_Explorer vExp( face, TopAbs_VERTEX );
607 set<int> foundIndices;
608 for ( ; vExp.More(); vExp.Next() ) {
609 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
610 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
611 double minDist = DBL_MAX;
613 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
614 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
615 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
616 if ( dist < minDist ) {
621 if ( foundIndices.insert( index ).second ) // unique?
622 myKeyPointIDs.push_back( index );
624 myIsBoundaryPointsFound = false;
629 // ---------------------------------------------------------------------
630 // The case where a pattern is being made from the mesh built by mesher
631 // ---------------------------------------------------------------------
633 // Load shapes in the consequent order and count nb of points
636 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
637 int nbV = myShapeIDMap.Extent();
638 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
639 bool added = ( nbV < myShapeIDMap.Extent() );
640 if ( !added ) { // vertex encountered twice
641 // a seam vertex have two corresponding key points
642 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ).Reversed());
645 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
646 nbNodes += eSubMesh->NbNodes() + 1;
649 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
650 myShapeIDMap.Add( *elIt );
652 myShapeIDMap.Add( face );
654 myPoints.resize( nbNodes );
656 // Load U of points on edges
658 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
660 TopoDS_Edge & edge = *elIt;
661 list< TPoint* > & ePoints = getShapePoints( edge );
663 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
664 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
666 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
667 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
668 // to make adjacent edges share key-point, we make v2 FORWARD too
669 // (as we have different points for same shape with different orienation)
672 // on closed face we must have REVERSED some of seam vertices
674 if ( helper.IsSeamShape( edge ) ) {
675 if ( helper.IsRealSeam( edge ) && !isForward ) {
676 // reverse on reversed SEAM edge
681 else { // on CLOSED edge (i.e. having one vertex with different orienations)
682 for ( int is2 = 0; is2 < 2; ++is2 ) {
683 TopoDS_Shape & v = is2 ? v2 : v1;
684 if ( helper.IsRealSeam( v ) ) {
685 // reverse or not depending on orientation of adjacent seam
687 list<TopoDS_Edge>::iterator eIt2 = elIt;
689 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
691 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
692 if ( seam.Orientation() == TopAbs_REVERSED )
699 // the forward key-point
700 list< TPoint* > * vPoint = & getShapePoints( v1 );
701 if ( vPoint->empty() )
703 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
704 if ( vSubMesh && vSubMesh->NbNodes() ) {
705 myKeyPointIDs.push_back( iPoint );
706 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
707 const SMDS_MeshNode* node = nIt->next();
708 if ( v1.Orientation() == TopAbs_REVERSED )
709 closeNodePointIDMap.insert( make_pair( node, iPoint ));
711 nodePointIDMap.insert( make_pair( node, iPoint ));
713 TPoint* keyPoint = &myPoints[ iPoint++ ];
714 vPoint->push_back( keyPoint );
716 keyPoint->myInitUV = project( node, projector );
718 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
719 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
722 if ( !vPoint->empty() )
723 ePoints.push_back( vPoint->front() );
726 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
727 if ( eSubMesh && eSubMesh->NbNodes() )
729 // loop on nodes of an edge: sort them by param on edge
730 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
731 TParamNodeMap paramNodeMap;
732 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
733 while ( nIt->more() )
735 const SMDS_MeshNode* node = smdsNode( nIt->next() );
736 const SMDS_EdgePosition* epos =
737 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
738 double u = epos->GetUParameter();
739 paramNodeMap.insert( make_pair( u, node ));
741 if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
742 // wrong U on edge, project
744 BRepAdaptor_Curve aCurve( edge );
745 proj.Initialize( aCurve, f, l );
746 paramNodeMap.clear();
747 nIt = eSubMesh->GetNodes();
748 for ( int iNode = 0; nIt->more(); ++iNode ) {
749 const SMDS_MeshNode* node = smdsNode( nIt->next() );
750 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
752 if ( proj.IsDone() ) {
753 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
754 if ( proj.IsMin( i )) {
755 u = proj.Point( i ).Parameter();
759 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
761 paramNodeMap.insert( make_pair( u, node ));
764 // put U in [0,1] so that the first key-point has U==0
765 bool isSeam = helper.IsRealSeam( edge );
767 TParamNodeMap::iterator unIt = paramNodeMap.begin();
768 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
769 while ( unIt != paramNodeMap.end() )
771 TPoint* p = & myPoints[ iPoint ];
772 ePoints.push_back( p );
773 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
774 if ( isSeam && !isForward )
775 closeNodePointIDMap.insert( make_pair( node, iPoint ));
777 nodePointIDMap.insert ( make_pair( node, iPoint ));
780 p->myInitUV = project( node, projector );
782 double u = isForward ? (*unIt).first : (*unRIt).first;
783 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
784 p->myInitUV = C2d->Value( u ).XY();
786 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
791 // the reverse key-point
792 vPoint = & getShapePoints( v2 );
793 if ( vPoint->empty() )
795 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
796 if ( vSubMesh && vSubMesh->NbNodes() ) {
797 myKeyPointIDs.push_back( iPoint );
798 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
799 const SMDS_MeshNode* node = nIt->next();
800 if ( v2.Orientation() == TopAbs_REVERSED )
801 closeNodePointIDMap.insert( make_pair( node, iPoint ));
803 nodePointIDMap.insert( make_pair( node, iPoint ));
805 TPoint* keyPoint = &myPoints[ iPoint++ ];
806 vPoint->push_back( keyPoint );
808 keyPoint->myInitUV = project( node, projector );
810 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
811 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
814 if ( !vPoint->empty() )
815 ePoints.push_back( vPoint->front() );
817 // compute U of edge-points
820 double totalDist = 0;
821 list< TPoint* >::iterator pIt = ePoints.begin();
822 TPoint* prevP = *pIt;
823 prevP->myInitU = totalDist;
824 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
826 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
827 p->myInitU = totalDist;
830 if ( totalDist > DBL_MIN)
831 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
833 p->myInitU /= totalDist;
836 } // loop on edges of a wire
838 // Load in-face points and elements
840 if ( fSubMesh && fSubMesh->NbElements() )
842 list< TPoint* > & fPoints = getShapePoints( face );
843 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
844 while ( nIt->more() )
846 const SMDS_MeshNode* node = smdsNode( nIt->next() );
847 nodePointIDMap.insert( make_pair( node, iPoint ));
848 TPoint* p = &myPoints[ iPoint++ ];
849 fPoints.push_back( p );
851 p->myInitUV = project( node, projector );
853 const SMDS_FacePosition* pos =
854 static_cast<const SMDS_FacePosition*>(node->GetPosition().get());
855 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
857 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
860 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
861 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
862 while ( elemIt->more() )
864 const SMDS_MeshElement* elem = elemIt->next();
865 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
866 myElemPointIDs.push_back( TElemDef() );
867 TElemDef& elemPoints = myElemPointIDs.back();
868 // find point indices corresponding to element nodes
869 while ( nIt->more() )
871 const SMDS_MeshNode* node = smdsNode( nIt->next() );
872 iPoint = nodePointIDMap[ node ]; // point index of interest
873 // for a node on a seam edge there are two points
874 if ( helper.IsRealSeam( node->GetPosition()->GetShapeId() ) &&
875 ( n_id = closeNodePointIDMap.find( node )) != not_found )
877 TPoint & p1 = myPoints[ iPoint ];
878 TPoint & p2 = myPoints[ n_id->second ];
879 // Select point closest to the rest nodes of element in UV space
880 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
881 const SMDS_MeshNode* notSeamNode = 0;
882 // find node not on a seam edge
883 while ( nIt2->more() && !notSeamNode ) {
884 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
885 if ( !helper.IsSeamShape( n->GetPosition()->GetShapeId() ))
888 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
889 double dist1 = uv.SquareDistance( p1.myInitUV );
890 double dist2 = uv.SquareDistance( p2.myInitUV );
892 iPoint = n_id->second;
894 elemPoints.push_back( iPoint );
899 myIsBoundaryPointsFound = true;
902 // Assure that U range is proportional to V range
905 vector< TPoint >::iterator pVecIt = myPoints.begin();
906 for ( ; pVecIt != myPoints.end(); pVecIt++ )
907 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
908 double minU, minV, maxU, maxV;
909 bndBox.Get( minU, minV, maxU, maxV );
910 double dU = maxU - minU, dV = maxV - minV;
911 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
914 // define where is the problem, in the face or in the mesh
915 TopExp_Explorer vExp( face, TopAbs_VERTEX );
916 for ( ; vExp.More(); vExp.Next() ) {
917 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
920 bndBox.Get( minU, minV, maxU, maxV );
921 dU = maxU - minU, dV = maxV - minV;
922 if ( dU <= DBL_MIN || dV <= DBL_MIN )
924 return setErrorCode( ERR_LOADF_NARROW_FACE );
926 // mesh is projected onto a line, e.g.
927 return setErrorCode( ERR_LOADF_CANT_PROJECT );
929 double ratio = dU / dV, maxratio = 3, scale;
931 if ( ratio > maxratio ) {
932 scale = ratio / maxratio;
935 else if ( ratio < 1./maxratio ) {
936 scale = maxratio / ratio;
941 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
942 TPoint & p = *pVecIt;
943 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
944 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
947 if ( myElemPointIDs.empty() ) {
948 MESSAGE( "No elements bound to the face");
949 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
952 return setErrorCode( ERR_OK );
955 //=======================================================================
956 //function : computeUVOnEdge
957 //purpose : compute coordinates of points on theEdge
958 //=======================================================================
960 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
961 const list< TPoint* > & ePoints )
963 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
965 Handle(Geom2d_Curve) C2d =
966 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
968 ePoints.back()->myInitU = 1.0;
969 list< TPoint* >::const_iterator pIt = ePoints.begin();
970 for ( pIt++; pIt != ePoints.end(); pIt++ )
972 TPoint* point = *pIt;
974 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
975 point->myU = ( f * ( 1 - du ) + l * du );
977 point->myUV = C2d->Value( point->myU ).XY();
981 //=======================================================================
982 //function : intersectIsolines
984 //=======================================================================
986 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
987 const gp_XY& uv21, const gp_XY& uv22, const double r2,
991 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
992 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
993 resUV = 0.5 * ( loc1 + loc2 );
994 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
995 // SKL 26.07.2007 for NPAL16567
996 double d1 = (uv11-uv12).Modulus();
997 double d2 = (uv21-uv22).Modulus();
998 // double delta = d1*d2*1e-6; PAL17233
999 double delta = min( d1, d2 ) / 10.;
1000 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1002 // double len1 = ( uv11 - uv12 ).Modulus();
1003 // double len2 = ( uv21 - uv22 ).Modulus();
1004 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1008 // gp_Lin2d line1( uv11, uv12 - uv11 );
1009 // gp_Lin2d line2( uv21, uv22 - uv21 );
1010 // double angle = Abs( line1.Angle( line2 ) );
1012 // IntAna2d_AnaIntersection inter;
1013 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1014 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1016 // gp_Pnt2d interUV = inter.Point(1).Value();
1017 // resUV += interUV.XY();
1018 // inter.Perform( line1, line2 );
1019 // interUV = inter.Point(1).Value();
1020 // resUV += interUV.XY();
1025 MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1026 ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1031 //=======================================================================
1032 //function : compUVByIsoIntersection
1034 //=======================================================================
1036 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1037 const gp_XY& theInitUV,
1039 bool & theIsDeformed )
1041 // compute UV by intersection of 2 iso lines
1042 //gp_Lin2d isoLine[2];
1043 gp_XY uv1[2], uv2[2];
1045 const double zero = DBL_MIN;
1046 for ( int iIso = 0; iIso < 2; iIso++ )
1048 // to build an iso line:
1049 // find 2 pairs of consequent edge-points such that the range of their
1050 // initial parameters encloses the in-face point initial parameter
1051 gp_XY UV[2], initUV[2];
1052 int nbUV = 0, iCoord = iIso + 1;
1053 double initParam = theInitUV.Coord( iCoord );
1055 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1056 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1058 const list< TPoint* > & bndPoints = * bndIt;
1059 TPoint* prevP = bndPoints.back(); // this is the first point
1060 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1061 bool coincPrev = false;
1062 // loop on the edge-points
1063 for ( ; pIt != bndPoints.end(); pIt++ )
1065 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1066 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1067 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1068 if (!coincPrev && // ignore if initParam coincides with prev point param
1069 sumOfDiff > zero && // ignore if both points coincide with initParam
1070 prevParamDiff * paramDiff <= zero )
1072 // find UV in parametric space of theFace
1073 double r = Abs(prevParamDiff) / sumOfDiff;
1074 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1077 // throw away uv most distant from <theInitUV>
1078 gp_XY vec0 = initUV[0] - theInitUV;
1079 gp_XY vec1 = initUV[1] - theInitUV;
1080 gp_XY vec = uvInit - theInitUV;
1081 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1082 double dist0 = vec0.SquareModulus();
1083 double dist1 = vec1.SquareModulus();
1084 double dist = vec .SquareModulus();
1085 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1086 i = ( dist0 < dist1 ? 1 : 0 );
1087 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1088 i = 3; // theInitUV must remain between
1092 initUV[ i ] = uvInit;
1093 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1095 coincPrev = ( Abs(paramDiff) <= zero );
1102 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1103 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1104 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1105 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1107 // an iso line should be normal to UV[0] - UV[1] direction
1108 // and be located at the same relative distance as from initial ends
1109 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1111 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1112 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1113 //isoLine[ iIso ] = iso.Normal( isoLoc );
1114 uv1[ iIso ] = UV[0];
1115 uv2[ iIso ] = UV[1];
1118 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1119 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1120 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1121 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1128 // ==========================================================
1129 // structure representing a node of a grid of iso-poly-lines
1130 // ==========================================================
1137 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1138 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1139 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1140 TIsoNode(double initU, double initV):
1141 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1142 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1143 bool IsUVComputed() const
1144 { return myUV.X() != 1e100; }
1145 bool IsMovable() const
1146 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1147 void SetNotMovable()
1148 { myIsMovable = false; }
1149 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1150 { myBndNodes[ iDir + i * 2 ] = node; }
1151 TIsoNode* GetBoundaryNode(int iDir, int i)
1152 { return myBndNodes[ iDir + i * 2 ]; }
1153 void SetNext(TIsoNode* node, int iDir, int isForward)
1154 { myNext[ iDir + isForward * 2 ] = node; }
1155 TIsoNode* GetNext(int iDir, int isForward)
1156 { return myNext[ iDir + isForward * 2 ]; }
1159 //=======================================================================
1160 //function : getNextNode
1162 //=======================================================================
1164 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1166 TIsoNode* n = node->myNext[ dir ];
1167 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1168 n = 0;//node->myBndNodes[ dir ];
1169 // MESSAGE("getNextNode: use bnd for node "<<
1170 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1174 //=======================================================================
1175 //function : checkQuads
1176 //purpose : check if newUV destortes quadrangles around node,
1177 // and if ( crit == FIX_OLD ) fix newUV in this case
1178 //=======================================================================
1180 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1182 static bool checkQuads (const TIsoNode* node,
1184 const bool reversed,
1185 const int crit = FIX_OLD,
1186 double fixSize = 0.)
1188 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1189 int nbOldFix = 0, nbOldImpr = 0;
1190 double newBadRate = 0, oldBadRate = 0;
1191 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1192 int i, dir1 = 0, dir2 = 3;
1193 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1195 if ( dir2 > 3 ) dir2 = 0;
1197 // walking counterclockwise around a quad,
1198 // nodes are in the order: node, n[0], n[1], n[2]
1199 n[0] = getNextNode( node, dir1 );
1200 n[2] = getNextNode( node, dir2 );
1201 if ( !n[0] || !n[2] ) continue;
1202 n[1] = getNextNode( n[0], dir2 );
1203 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1204 bool isTriangle = ( !n[1] );
1206 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1208 // if ( fixSize != 0 ) {
1209 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1210 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1211 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1212 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1214 // check if a quadrangle is degenerated
1216 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1217 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1220 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1223 // find min size of the diagonal node-n[1]
1224 double minDiag = fixSize;
1225 if ( minDiag == 0. ) {
1226 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1227 if ( !isTriangle ) {
1228 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1229 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1231 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1232 minDiag = sqrt( maxLen2 ) * PI / 60.; // ~ maxLen * Sin( 3 deg )
1235 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1236 // ( behind means "to the right of")
1238 // 1. newUV is not behind 01 and 12 dirs
1239 // 2. or newUV is not behind 02 dir and n[2] is convex
1240 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1241 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1242 gp_Vec2d moveVec[3], outVec[3];
1243 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1245 bool isDiag = ( i == 2 );
1246 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1250 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1252 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1254 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1256 gp_Vec2d newDir( n[i]->myUV, newUV );
1257 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1259 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1260 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1261 if ( crit == FIX_OLD ) {
1262 wasIn[i] = ( outDir * oldDir < 0 );
1263 wasOk[i] = ( outDir * oldDir < -minDiag );
1265 newBadRate += outDir * newDir;
1267 oldBadRate += outDir * oldDir;
1270 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1271 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1272 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1273 moveVec[i] = ( oldDist - minDiag ) * outDir;
1278 // check if n[2] is convex
1281 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1283 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1284 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1285 newIsOk = ( newIsOk && isNewOk );
1286 newIsIn = ( newIsIn && isNewIn );
1288 if ( crit != FIX_OLD ) {
1289 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1290 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1294 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1295 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1296 oldIsIn = ( oldIsIn && isOldIn );
1297 oldIsOk = ( oldIsOk && isOldIn );
1300 if ( !isOldIn ) { // node is outside a quadrangle
1301 // move newUV inside a quadrangle
1302 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1303 // node and newUV are outside: push newUV inside
1305 if ( convex || isTriangle ) {
1306 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1309 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1310 double outSize = out.Magnitude();
1311 if ( outSize > DBL_MIN )
1314 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1315 uv = n[1]->myUV - minDiag * out.XY();
1317 oldUVFixed[ nbOldFix++ ] = uv;
1318 //node->myUV = newUV;
1320 else if ( !isOldOk ) {
1321 // try to fix old UV: move node inside as less as possible
1322 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1323 gp_XY uv1, uv2 = node->myUV;
1324 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1326 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1327 while ( !isOldOk ) {
1328 // find the least moveVec
1330 double minMove2 = 1e100;
1331 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1333 if ( moveVec[i].Coord(1) < 1e100 ) {
1334 double move2 = moveVec[i].SquareMagnitude();
1335 if ( move2 < minMove2 ) {
1344 // move node to newUV
1345 uv1 = node->myUV + moveVec[ iMin ].XY();
1346 uv2 += moveVec[ iMin ].XY();
1347 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1348 // check if uv1 is ok
1349 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1350 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1351 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1353 oldUVImpr[ nbOldImpr++ ] = uv1;
1355 // check if uv2 is ok
1356 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1357 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1358 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1360 oldUVImpr[ nbOldImpr++ ] = uv2;
1365 } // loop on 4 quadrangles around <node>
1367 if ( crit == CHECK_NEW_OK )
1369 if ( crit == CHECK_NEW_IN )
1378 if ( oldIsIn && nbOldImpr ) {
1379 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1380 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1381 gp_XY uv = oldUVImpr[ 0 ];
1382 for ( int i = 1; i < nbOldImpr; i++ )
1383 uv += oldUVImpr[ i ];
1385 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1390 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1393 if ( !oldIsIn && nbOldFix ) {
1394 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1395 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1396 gp_XY uv = oldUVFixed[ 0 ];
1397 for ( int i = 1; i < nbOldFix; i++ )
1398 uv += oldUVFixed[ i ];
1400 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1405 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1408 if ( newIsIn && oldIsIn )
1409 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1410 else if ( !newIsIn )
1417 //=======================================================================
1418 //function : compUVByElasticIsolines
1419 //purpose : compute UV as nodes of iso-poly-lines consisting of
1420 // segments keeping relative size as in the pattern
1421 //=======================================================================
1422 //#define DEB_COMPUVBYELASTICISOLINES
1423 bool SMESH_Pattern::
1424 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1425 const list< TPoint* >& thePntToCompute)
1427 return false; // PAL17233
1428 //cout << "============================== KEY POINTS =============================="<<endl;
1429 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1430 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1431 // TPoint& p = myPoints[ *kpIt ];
1432 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1433 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1435 //cout << "=============================="<<endl;
1437 // Define parameters of iso-grid nodes in U and V dir
1439 set< double > paramSet[ 2 ];
1440 list< list< TPoint* > >::const_iterator pListIt;
1441 list< TPoint* >::const_iterator pIt;
1442 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1443 const list< TPoint* > & pList = * pListIt;
1444 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1445 paramSet[0].insert( (*pIt)->myInitUV.X() );
1446 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1449 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1450 paramSet[0].insert( (*pIt)->myInitUV.X() );
1451 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1453 // unite close parameters and split too long segments
1456 for ( iDir = 0; iDir < 2; iDir++ )
1458 set< double > & params = paramSet[ iDir ];
1459 double range = ( *params.rbegin() - *params.begin() );
1460 double toler = range / 1e6;
1461 tol[ iDir ] = toler;
1462 // double maxSegment = range / params.size() / 2.;
1464 // set< double >::iterator parIt = params.begin();
1465 // double prevPar = *parIt;
1466 // for ( parIt++; parIt != params.end(); parIt++ )
1468 // double segLen = (*parIt) - prevPar;
1469 // if ( segLen < toler )
1470 // ;//params.erase( prevPar ); // unite
1471 // else if ( segLen > maxSegment )
1472 // params.insert( prevPar + 0.5 * segLen ); // split
1473 // prevPar = (*parIt);
1477 // Make nodes of a grid of iso-poly-lines
1479 list < TIsoNode > nodes;
1480 typedef list < TIsoNode *> TIsoLine;
1481 map < double, TIsoLine > isoMap[ 2 ];
1483 set< double > & params0 = paramSet[ 0 ];
1484 set< double >::iterator par0It = params0.begin();
1485 for ( ; par0It != params0.end(); par0It++ )
1487 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1488 set< double > & params1 = paramSet[ 1 ];
1489 set< double >::iterator par1It = params1.begin();
1490 for ( ; par1It != params1.end(); par1It++ )
1492 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1493 isoLine0.push_back( & nodes.back() );
1494 isoMap[1][ *par1It ].push_back( & nodes.back() );
1498 // Compute intersections of boundaries with iso-lines:
1499 // only boundary nodes will have computed UV so far
1502 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1503 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1504 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1506 const list< TPoint* > & bndPoints = * bndIt;
1507 TPoint* prevP = bndPoints.back(); // this is the first point
1508 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1509 // loop on the edge-points
1510 for ( ; pIt != bndPoints.end(); pIt++ )
1512 TPoint* point = *pIt;
1513 for ( iDir = 0; iDir < 2; iDir++ )
1515 const int iCoord = iDir + 1;
1516 const int iOtherCoord = 2 - iDir;
1517 double par1 = prevP->myInitUV.Coord( iCoord );
1518 double par2 = point->myInitUV.Coord( iCoord );
1519 double parDif = par2 - par1;
1520 if ( Abs( parDif ) <= DBL_MIN )
1522 // find iso-lines intersecting a bounadry
1523 double toler = tol[ 1 - iDir ];
1524 double minPar = Min ( par1, par2 );
1525 double maxPar = Max ( par1, par2 );
1526 map < double, TIsoLine >& isos = isoMap[ iDir ];
1527 map < double, TIsoLine >::iterator isoIt = isos.begin();
1528 for ( ; isoIt != isos.end(); isoIt++ )
1530 double isoParam = (*isoIt).first;
1531 if ( isoParam < minPar || isoParam > maxPar )
1533 double r = ( isoParam - par1 ) / parDif;
1534 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1535 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1536 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1537 // find existing node with otherPar or insert a new one
1538 TIsoLine & isoLine = (*isoIt).second;
1540 TIsoLine::iterator nIt = isoLine.begin();
1541 for ( ; nIt != isoLine.end(); nIt++ ) {
1542 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1543 if ( nodePar >= otherPar )
1547 if ( Abs( nodePar - otherPar ) <= toler )
1548 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1550 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1551 node = & nodes.back();
1552 isoLine.insert( nIt, node );
1554 node->SetNotMovable();
1556 uvBnd.Add( gp_Pnt2d( uv ));
1557 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1559 gp_XY tgt( point->myUV - prevP->myUV );
1560 if ( ::IsEqual( r, 1. ))
1561 node->myDir[ 0 ] = tgt;
1562 else if ( ::IsEqual( r, 0. ))
1563 node->myDir[ 1 ] = tgt;
1565 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1566 // keep boundary nodes corresponding to boundary points
1567 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1568 if ( bndNodes.empty() || bndNodes.back() != node )
1569 bndNodes.push_back( node );
1570 } // loop on isolines
1571 } // loop on 2 directions
1573 } // loop on boundary points
1574 } // loop on boundaries
1576 // Define orientation
1578 // find the point with the least X
1579 double leastX = DBL_MAX;
1580 TIsoNode * leftNode;
1581 list < TIsoNode >::iterator nodeIt = nodes.begin();
1582 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1583 TIsoNode & node = *nodeIt;
1584 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1585 leastX = node.myUV.X();
1588 // if ( node.IsUVComputed() ) {
1589 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1590 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1591 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1592 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1595 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1596 //SCRUTE( reversed );
1598 // Prepare internal nodes:
1600 // 2. compute ratios
1601 // 3. find boundary nodes for each node
1602 // 4. remove nodes out of the boundary
1603 for ( iDir = 0; iDir < 2; iDir++ )
1605 const int iCoord = 2 - iDir; // coord changing along an isoline
1606 map < double, TIsoLine >& isos = isoMap[ iDir ];
1607 map < double, TIsoLine >::iterator isoIt = isos.begin();
1608 for ( ; isoIt != isos.end(); isoIt++ )
1610 TIsoLine & isoLine = (*isoIt).second;
1611 bool firstCompNodeFound = false;
1612 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1613 nPrevIt = nIt = nNextIt = isoLine.begin();
1615 nNextIt++; nNextIt++;
1616 while ( nIt != isoLine.end() )
1618 // 1. connect prev - cur
1619 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1620 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1621 firstCompNodeFound = true;
1622 lastCompNodePos = nPrevIt;
1624 if ( firstCompNodeFound ) {
1625 node->SetNext( prevNode, iDir, 0 );
1626 prevNode->SetNext( node, iDir, 1 );
1629 if ( nNextIt != isoLine.end() ) {
1630 double par1 = prevNode->myInitUV.Coord( iCoord );
1631 double par2 = node->myInitUV.Coord( iCoord );
1632 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1633 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1635 // 3. find boundary nodes
1636 if ( node->IsUVComputed() )
1637 lastCompNodePos = nIt;
1638 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1639 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1640 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1641 if ( (*nIt2)->IsUVComputed() )
1643 if ( nIt2 != isoLine.end() ) {
1645 node->SetBoundaryNode( bndNode1, iDir, 0 );
1646 node->SetBoundaryNode( bndNode2, iDir, 1 );
1647 // cout << "--------------------------------------------------"<<endl;
1648 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1649 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1650 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1651 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1652 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1653 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1656 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1657 node->SetBoundaryNode( 0, iDir, 0 );
1658 node->SetBoundaryNode( 0, iDir, 1 );
1662 if ( nNextIt != isoLine.end() ) nNextIt++;
1663 // 4. remove nodes out of the boundary
1664 if ( !firstCompNodeFound )
1665 isoLine.pop_front();
1666 } // loop on isoLine nodes
1668 // remove nodes after the boundary
1669 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1670 // (*nIt)->SetNotMovable();
1671 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1672 } // loop on isolines
1673 } // loop on 2 directions
1675 // Compute local isoline direction for internal nodes
1678 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1679 map < double, TIsoLine >::iterator isoIt = isos.begin();
1680 for ( ; isoIt != isos.end(); isoIt++ )
1682 TIsoLine & isoLine = (*isoIt).second;
1683 TIsoLine::iterator nIt = isoLine.begin();
1684 for ( ; nIt != isoLine.end(); nIt++ )
1686 TIsoNode* node = *nIt;
1687 if ( node->IsUVComputed() || !node->IsMovable() )
1689 gp_Vec2d aTgt[2], aNorm[2];
1692 for ( iDir = 0; iDir < 2; iDir++ )
1694 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1695 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1696 if ( !bndNode1 || !bndNode2 ) {
1700 const int iCoord = 2 - iDir; // coord changing along an isoline
1701 double par1 = bndNode1->myInitUV.Coord( iCoord );
1702 double par2 = node->myInitUV.Coord( iCoord );
1703 double par3 = bndNode2->myInitUV.Coord( iCoord );
1704 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1706 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1707 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1708 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1709 else tgt1.Reverse();
1710 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1712 if ( ratio[ iDir ] < 0.5 )
1713 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1715 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1717 aNorm[ iDir ].Reverse(); // along iDir isoline
1719 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1720 // maybe angle is more than |PI|
1721 if ( Abs( angle ) > PI / 2. ) {
1722 // check direction of the last but one perpendicular isoline
1723 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1724 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1725 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1726 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1727 if ( isoDir * tgt2 < 0 )
1729 double angle2 = tgt1.Angle( isoDir );
1730 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1731 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1732 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1733 //MESSAGE("REVERSE ANGLE");
1736 if ( Abs( angle2 ) > Abs( angle ) ||
1737 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1738 //MESSAGE("Add PI");
1739 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1740 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1741 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1742 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1743 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1744 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1747 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1751 for ( iDir = 0; iDir < 2; iDir++ )
1753 aTgt[iDir].Normalize();
1754 aNorm[1-iDir].Normalize();
1755 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1758 node->myDir[iDir] = //aTgt[iDir];
1759 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1761 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1762 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1763 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1764 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1766 } // loop on iso nodes
1767 } // loop on isolines
1769 // Find nodes to start computing UV from
1771 list< TIsoNode* > startNodes;
1772 list< TIsoNode* >::iterator nIt = bndNodes.end();
1773 TIsoNode* node = *(--nIt);
1774 TIsoNode* prevNode = *(--nIt);
1775 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1777 TIsoNode* nextNode = *nIt;
1778 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1779 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1780 double initAngle = initTgt1.Angle( initTgt2 );
1781 double angle = node->myDir[0].Angle( node->myDir[1] );
1782 if ( reversed ) angle = -angle;
1783 if ( initAngle > angle && initAngle - angle > PI / 2.1 ) {
1784 // find a close internal node
1785 TIsoNode* nClose = 0;
1786 list< TIsoNode* > testNodes;
1787 testNodes.push_back( node );
1788 list< TIsoNode* >::iterator it = testNodes.begin();
1789 for ( ; !nClose && it != testNodes.end(); it++ )
1791 for (int i = 0; i < 4; i++ )
1793 nClose = (*it)->myNext[ i ];
1795 if ( !nClose->IsUVComputed() )
1798 testNodes.push_back( nClose );
1804 startNodes.push_back( nClose );
1805 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1806 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1807 // "initAngle: " << initAngle << " angle: " << angle << endl;
1808 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1809 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1810 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1811 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1817 // Compute starting UV of internal nodes
1819 list < TIsoNode* > internNodes;
1820 bool needIteration = true;
1821 if ( startNodes.empty() ) {
1822 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1823 needIteration = false;
1824 map < double, TIsoLine >& isos = isoMap[ 0 ];
1825 map < double, TIsoLine >::iterator isoIt = isos.begin();
1826 for ( ; isoIt != isos.end(); isoIt++ )
1828 TIsoLine & isoLine = (*isoIt).second;
1829 TIsoLine::iterator nIt = isoLine.begin();
1830 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1832 TIsoNode* node = *nIt;
1833 if ( !node->IsUVComputed() && node->IsMovable() ) {
1834 internNodes.push_back( node );
1836 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1837 node->myUV, needIteration ))
1838 node->myUV = node->myInitUV;
1842 if ( needIteration )
1843 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1845 TIsoNode* node = *nIt, *nClose = 0;
1846 list< TIsoNode* > testNodes;
1847 testNodes.push_back( node );
1848 list< TIsoNode* >::iterator it = testNodes.begin();
1849 for ( ; !nClose && it != testNodes.end(); it++ )
1851 for (int i = 0; i < 4; i++ )
1853 nClose = (*it)->myNext[ i ];
1855 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1858 testNodes.push_back( nClose );
1864 startNodes.push_back( nClose );
1868 double aMin[2], aMax[2], step[2];
1869 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1870 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1871 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1872 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1873 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1875 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1877 TIsoNode* prevN[2], *node = *nIt;
1878 if ( node->IsUVComputed() || !node->IsMovable() )
1880 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1881 int nbComp = 0, nbPrev = 0;
1882 for ( iDir = 0; iDir < 2; iDir++ )
1884 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1885 TIsoNode* n = node->GetNext( iDir, 0 );
1886 if ( n->IsUVComputed() )
1889 startNodes.push_back( n );
1890 n = node->GetNext( iDir, 1 );
1891 if ( n->IsUVComputed() )
1894 startNodes.push_back( n );
1896 prevNode1 = prevNode2;
1899 if ( prevNode1 ) nbPrev++;
1900 if ( prevNode2 ) nbPrev++;
1903 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1904 double par = node->myInitUV.Coord( 2 - iDir );
1905 bool isEnd = ( prevPar > par );
1906 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1907 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1908 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1910 MESSAGE("Why we are here?");
1913 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1914 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1915 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1916 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1917 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1918 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1919 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1920 //" par: " << prevPar << endl;
1921 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1922 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1924 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1925 gp_XY & uv1 = prevNode1->myUV;
1926 gp_XY & uv2 = prevNode2->myUV;
1927 // dir = ( uv2 - uv1 );
1928 // double len = dir.Modulus();
1929 // if ( len > DBL_MIN )
1930 // dir /= len * 0.5;
1931 double r = node->myRatio[ iDir ];
1932 newUV += uv1 * ( 1 - r ) + uv2 * r;
1935 newUV += prevNode1->myUV + dir * step[ iDir ];
1938 prevN[ iDir ] = prevNode1;
1942 if ( !nbComp ) continue;
1945 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1947 // check if a quadrangle is not distorted
1949 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1950 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1951 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1952 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1956 internNodes.push_back( node );
1961 static int maxNbIter = 100;
1962 #ifdef DEB_COMPUVBYELASTICISOLINES
1964 bool useNbMoveNode = 0;
1965 static int maxNbNodeMove = 100;
1968 if ( !useNbMoveNode )
1969 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1974 if ( !needIteration) break;
1975 #ifdef DEB_COMPUVBYELASTICISOLINES
1976 if ( nbIter >= maxNbIter ) break;
1979 list < TIsoNode* >::iterator nIt = internNodes.begin();
1980 for ( ; nIt != internNodes.end(); nIt++ ) {
1981 #ifdef DEB_COMPUVBYELASTICISOLINES
1983 cout << nbNodeMove <<" =================================================="<<endl;
1985 TIsoNode * node = *nIt;
1989 for ( iDir = 0; iDir < 2; iDir++ )
1991 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
1992 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
1993 double r = node->myRatio[ iDir ];
1994 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
1995 // line[ iDir ].SetLocation( loc[ iDir ] );
1996 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
1999 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2000 double locR[2] = { 0, 0 };
2001 for ( iDir = 0; iDir < 2; iDir++ )
2003 const int iCoord = 2 - iDir; // coord changing along an isoline
2004 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2005 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2006 if ( !bndNode1 || !bndNode2 ) {
2009 double par1 = bndNode1->myInitUV.Coord( iCoord );
2010 double par2 = node->myInitUV.Coord( iCoord );
2011 double par3 = bndNode2->myInitUV.Coord( iCoord );
2012 double r = ( par2 - par1 ) / ( par3 - par1 );
2013 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2014 locR[ iDir ] = ( 1 - r * r ) * 0.25;
2016 //locR[0] = locR[1] = 0.25;
2017 // intersect the 2 lines and move a node
2018 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2019 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2021 // double intR = 1 - locR[0] - locR[1];
2022 // gp_XY newUV = inter.Point(1).Value().XY();
2023 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2024 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2026 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2027 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2028 // avoid parallel isolines intersection
2029 checkQuads( node, newUV, reversed );
2031 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2033 } // intersection found
2034 #ifdef DEB_COMPUVBYELASTICISOLINES
2035 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2037 } // loop on internal nodes
2038 #ifdef DEB_COMPUVBYELASTICISOLINES
2039 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2041 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2043 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2045 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2046 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2047 #ifndef DEB_COMPUVBYELASTICISOLINES
2052 // Set computed UV to points
2054 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2055 TPoint* point = *pIt;
2056 //gp_XY oldUV = point->myUV;
2057 double minDist = DBL_MAX;
2058 list < TIsoNode >::iterator nIt = nodes.begin();
2059 for ( ; nIt != nodes.end(); nIt++ ) {
2060 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2061 if ( dist < minDist ) {
2063 point->myUV = (*nIt).myUV;
2072 //=======================================================================
2073 //function : setFirstEdge
2074 //purpose : choose the best first edge of theWire; return the summary distance
2075 // between point UV computed by isolines intersection and
2076 // eventual UV got from edge p-curves
2077 //=======================================================================
2079 //#define DBG_SETFIRSTEDGE
2080 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2082 int iE, nbEdges = theWire.size();
2086 // Transform UVs computed by iso to fit bnd box of a wire
2088 // max nb of points on an edge
2090 int eID = theFirstEdgeID;
2091 for ( iE = 0; iE < nbEdges; iE++ )
2092 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2094 // compute bnd boxes
2095 TopoDS_Face face = TopoDS::Face( myShape );
2096 Bnd_Box2d bndBox, eBndBox;
2097 eID = theFirstEdgeID;
2098 list< TopoDS_Edge >::iterator eIt;
2099 list< TPoint* >::iterator pIt;
2100 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2102 // UV by isos stored in TPoint.myXYZ
2103 list< TPoint* > & ePoints = getShapePoints( eID++ );
2104 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2106 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2108 // UV by an edge p-curve
2110 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2111 double dU = ( l - f ) / ( maxNbPnt - 1 );
2112 for ( int i = 0; i < maxNbPnt; i++ )
2113 eBndBox.Add( C2d->Value( f + i * dU ));
2116 // transform UVs by isos
2117 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2118 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2119 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2120 #ifdef DBG_SETFIRSTEDGE
2121 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2122 << eMinPar[1] << " - " << eMaxPar[1] );
2124 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2126 double dMin = eMinPar[i] - minPar[i];
2127 double dMax = eMaxPar[i] - maxPar[i];
2128 double dPar = maxPar[i] - minPar[i];
2129 eID = theFirstEdgeID;
2130 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2132 list< TPoint* > & ePoints = getShapePoints( eID++ );
2133 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2135 double par = (*pIt)->myXYZ.Coord( iC );
2136 double r = ( par - minPar[i] ) / dPar;
2137 par += ( 1 - r ) * dMin + r * dMax;
2138 (*pIt)->myXYZ.SetCoord( iC, par );
2144 double minDist = DBL_MAX;
2145 for ( iE = 0 ; iE < nbEdges; iE++ )
2147 #ifdef DBG_SETFIRSTEDGE
2148 MESSAGE ( " VARIANT " << iE );
2150 // evaluate the distance between UV computed by the 2 methods:
2151 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2153 int eID = theFirstEdgeID;
2154 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2156 list< TPoint* > & ePoints = getShapePoints( eID++ );
2157 computeUVOnEdge( *eIt, ePoints );
2158 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2160 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2161 #ifdef DBG_SETFIRSTEDGE
2162 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2163 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2167 #ifdef DBG_SETFIRSTEDGE
2168 MESSAGE ( "dist -- " << dist );
2170 if ( dist < minDist ) {
2172 eBest = theWire.front();
2174 // check variant with another first edge
2175 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2177 // put the best first edge to the theWire front
2178 if ( eBest != theWire.front() ) {
2179 eIt = find ( theWire.begin(), theWire.end(), eBest );
2180 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2186 //=======================================================================
2187 //function : sortSameSizeWires
2188 //purpose : sort wires in theWireList from theFromWire until theToWire,
2189 // the wires are set in the order to correspond to the order
2190 // of boundaries; after sorting, edges in the wires are put
2191 // in a good order, point UVs on edges are computed and points
2192 // are appended to theEdgesPointsList
2193 //=======================================================================
2195 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2196 const TListOfEdgesList::iterator& theFromWire,
2197 const TListOfEdgesList::iterator& theToWire,
2198 const int theFirstEdgeID,
2199 list< list< TPoint* > >& theEdgesPointsList )
2201 TopoDS_Face F = TopoDS::Face( myShape );
2202 int iW, nbWires = 0;
2203 TListOfEdgesList::iterator wlIt = theFromWire;
2204 while ( wlIt++ != theToWire )
2207 // Recompute key-point UVs by isolines intersection,
2208 // compute CG of key-points for each wire and bnd boxes of GCs
2211 gp_XY orig( gp::Origin2d().XY() );
2212 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2213 Bnd_Box2d bndBox, vBndBox;
2214 int eID = theFirstEdgeID;
2215 list< TopoDS_Edge >::iterator eIt;
2216 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2218 list< TopoDS_Edge > & wire = *wlIt;
2219 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2221 list< TPoint* > & ePoints = getShapePoints( eID++ );
2222 TPoint* p = ePoints.front();
2223 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2224 MESSAGE("cant sortSameSizeWires()");
2227 gcVec[iW] += p->myUV;
2228 bndBox.Add( gp_Pnt2d( p->myUV ));
2229 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2230 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2231 vGcVec[iW] += vXY.XY();
2233 // keep the computed UV to compare against by setFirstEdge()
2234 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2236 gcVec[iW] /= nbWires;
2237 vGcVec[iW] /= nbWires;
2238 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2239 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2242 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2244 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2245 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2246 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2247 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2249 double dMin = vMinPar[i] - minPar[i];
2250 double dMax = vMaxPar[i] - maxPar[i];
2251 double dPar = maxPar[i] - minPar[i];
2252 if ( Abs( dPar ) <= DBL_MIN )
2254 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2255 double par = gcVec[iW].Coord( iC );
2256 double r = ( par - minPar[i] ) / dPar;
2257 par += ( 1 - r ) * dMin + r * dMax;
2258 gcVec[iW].SetCoord( iC, par );
2262 // Define boundary - wire correspondence by GC closeness
2264 TListOfEdgesList tmpWList;
2265 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2266 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2267 TIntWirePosMap bndIndWirePosMap;
2268 vector< bool > bndFound( nbWires, false );
2269 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2271 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2272 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2273 double minDist = DBL_MAX;
2274 gp_XY & wGc = vGcVec[ iW ];
2276 for ( int iB = 0; iB < nbWires; iB++ ) {
2277 if ( bndFound[ iB ] ) continue;
2278 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2279 if ( dist < minDist ) {
2284 bndFound[ bIndex ] = true;
2285 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2290 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2291 eID = theFirstEdgeID;
2292 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2294 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2295 list < TopoDS_Edge > & wire = ( *wirePos );
2297 // choose the best first edge of a wire
2298 setFirstEdge( wire, eID );
2300 // compute eventual UV and fill theEdgesPointsList
2301 theEdgesPointsList.push_back( list< TPoint* >() );
2302 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2303 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2305 list< TPoint* > & ePoints = getShapePoints( eID++ );
2306 computeUVOnEdge( *eIt, ePoints );
2307 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2309 // put wire back to theWireList
2311 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2317 //=======================================================================
2319 //purpose : Compute nodes coordinates applying
2320 // the loaded pattern to <theFace>. The first key-point
2321 // will be mapped into <theVertexOnKeyPoint1>
2322 //=======================================================================
2324 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2325 const TopoDS_Vertex& theVertexOnKeyPoint1,
2326 const bool theReverse)
2328 MESSAGE(" ::Apply(face) " );
2329 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2330 if ( !setShapeToMesh( face ))
2333 // find points on edges, it fills myNbKeyPntInBoundary
2334 if ( !findBoundaryPoints() )
2337 // Define the edges order so that the first edge starts at
2338 // theVertexOnKeyPoint1
2340 list< TopoDS_Edge > eList;
2341 list< int > nbVertexInWires;
2342 int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2343 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2345 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2346 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2348 // check nb wires and edges
2349 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2350 l1.sort(); l2.sort();
2353 MESSAGE( "Wrong nb vertices in wires" );
2354 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2357 // here shapes get IDs, for the outer wire IDs are OK
2358 list<TopoDS_Edge>::iterator elIt = eList.begin();
2359 for ( ; elIt != eList.end(); elIt++ ) {
2360 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2361 bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
2362 // BEGIN: jfa for bug 0019943
2365 for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
2366 const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
2368 for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
2369 if (we.Current().IsSame(*elIt)) {
2371 if (nbe == 2) isClosed1 = true;
2376 // END: jfa for bug 0019943
2378 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
2380 int nbVertices = myShapeIDMap.Extent();
2382 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2383 myShapeIDMap.Add( *elIt );
2385 myShapeIDMap.Add( face );
2387 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2388 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2389 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2392 // points on edges to be used for UV computation of in-face points
2393 list< list< TPoint* > > edgesPointsList;
2394 edgesPointsList.push_back( list< TPoint* >() );
2395 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2396 list< TPoint* >::iterator pIt;
2398 // compute UV of points on the outer wire
2399 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2400 for (iE = 0, elIt = eList.begin();
2401 iE < nbEdgesInOuterWire && elIt != eList.end();
2404 list< TPoint* > & ePoints = getShapePoints( *elIt );
2406 computeUVOnEdge( *elIt, ePoints );
2407 // collect on-edge points (excluding the last one)
2408 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2411 // If there are several wires, define the order of edges of inner wires:
2412 // compute UV of inner edge-points using 2 methods: the one for in-face points
2413 // and the one for on-edge points and then choose the best edge order
2414 // by the best correspondance of the 2 results
2417 // compute UV of inner edge-points using the method for in-face points
2418 // and devide eList into a list of separate wires
2420 list< list< TopoDS_Edge > > wireList;
2421 list<TopoDS_Edge>::iterator eIt = elIt;
2422 list<int>::iterator nbEIt = nbVertexInWires.begin();
2423 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2425 int nbEdges = *nbEIt;
2426 wireList.push_back( list< TopoDS_Edge >() );
2427 list< TopoDS_Edge > & wire = wireList.back();
2428 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2430 list< TPoint* > & ePoints = getShapePoints( *eIt );
2431 pIt = ePoints.begin();
2432 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2434 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2435 MESSAGE("cant Apply(face)");
2438 // keep the computed UV to compare against by setFirstEdge()
2439 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2441 wire.push_back( *eIt );
2444 // remove inner edges from eList
2445 eList.erase( elIt, eList.end() );
2447 // sort wireList by nb edges in a wire
2448 sortBySize< TopoDS_Edge > ( wireList );
2450 // an ID of the first edge of a boundary
2451 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2452 // if ( nbSeamShapes > 0 )
2453 // id1 += 2; // 2 vertices more
2455 // find points - edge correspondence for wires of unique size,
2456 // edge order within a wire should be defined only
2458 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2459 while ( wlIt != wireList.end() )
2461 list< TopoDS_Edge >& wire = (*wlIt);
2462 int nbEdges = wire.size();
2464 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2466 // choose the best first edge of a wire
2467 setFirstEdge( wire, id1 );
2469 // compute eventual UV and collect on-edge points
2470 edgesPointsList.push_back( list< TPoint* >() );
2471 edgesPoints = & edgesPointsList.back();
2473 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2475 list< TPoint* > & ePoints = getShapePoints( eID++ );
2476 computeUVOnEdge( *eIt, ePoints );
2477 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2483 // find boundary - wire correspondence for several wires of same size
2485 id1 = nbVertices + nbEdgesInOuterWire + 1;
2486 wlIt = wireList.begin();
2487 while ( wlIt != wireList.end() )
2489 int nbSameSize = 0, nbEdges = (*wlIt).size();
2490 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2492 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2496 if ( nbSameSize > 0 )
2497 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2500 id1 += nbEdges * ( nbSameSize + 1 );
2503 // add well-ordered edges to eList
2505 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2507 list< TopoDS_Edge >& wire = (*wlIt);
2508 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2511 // re-fill myShapeIDMap - all shapes get good IDs
2513 myShapeIDMap.Clear();
2514 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2515 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2516 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2517 myShapeIDMap.Add( *elIt );
2518 myShapeIDMap.Add( face );
2520 } // there are inner wires
2522 // Compute XYZ of on-edge points
2524 TopLoc_Location loc;
2525 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2527 BRepAdaptor_Curve C3d( *elIt );
2528 list< TPoint* > & ePoints = getShapePoints( iE++ );
2529 pIt = ePoints.begin();
2530 for ( pIt++; pIt != ePoints.end(); pIt++ )
2532 TPoint* point = *pIt;
2533 point->myXYZ = C3d.Value( point->myU );
2537 // Compute UV and XYZ of in-face points
2539 // try to use a simple algo
2540 list< TPoint* > & fPoints = getShapePoints( face );
2541 bool isDeformed = false;
2542 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2543 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2544 (*pIt)->myUV, isDeformed )) {
2545 MESSAGE("cant Apply(face)");
2548 // try to use a complex algo if it is a difficult case
2549 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2551 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2552 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2553 (*pIt)->myUV, isDeformed )) {
2554 MESSAGE("cant Apply(face)");
2559 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2560 const gp_Trsf & aTrsf = loc.Transformation();
2561 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2563 TPoint * point = *pIt;
2564 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2565 if ( !loc.IsIdentity() )
2566 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2569 myIsComputed = true;
2571 return setErrorCode( ERR_OK );
2574 //=======================================================================
2576 //purpose : Compute nodes coordinates applying
2577 // the loaded pattern to <theFace>. The first key-point
2578 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2579 //=======================================================================
2581 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2582 const int theNodeIndexOnKeyPoint1,
2583 const bool theReverse)
2585 // MESSAGE(" ::Apply(MeshFace) " );
2587 if ( !IsLoaded() ) {
2588 MESSAGE( "Pattern not loaded" );
2589 return setErrorCode( ERR_APPL_NOT_LOADED );
2592 // check nb of nodes
2593 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2594 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2595 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2598 // find points on edges, it fills myNbKeyPntInBoundary
2599 if ( !findBoundaryPoints() )
2602 // check that there are no holes in a pattern
2603 if (myNbKeyPntInBoundary.size() > 1 ) {
2604 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2607 // Define the nodes order
2609 list< const SMDS_MeshNode* > nodes;
2610 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2611 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2613 while ( noIt->more() ) {
2614 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2615 nodes.push_back( node );
2616 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2619 if ( n != nodes.end() ) {
2621 if ( n != --nodes.end() )
2622 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2625 else if ( n != nodes.begin() )
2626 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2628 list< gp_XYZ > xyzList;
2629 myOrderedNodes.resize( theFace->NbNodes() );
2630 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2631 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2632 myOrderedNodes[ iSub++] = *n;
2635 // Define a face plane
2637 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2638 gp_Pnt P ( *xyzIt++ );
2639 gp_Vec Vx( P, *xyzIt++ ), N;
2641 N = Vx ^ gp_Vec( P, *xyzIt++ );
2642 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2643 if ( N.SquareMagnitude() <= DBL_MIN )
2644 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2645 gp_Ax2 pos( P, N, Vx );
2647 // Compute UV of key-points on a plane
2648 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2650 gp_Vec vec ( pos.Location(), *xyzIt );
2651 TPoint* p = getShapePoints( iSub ).front();
2652 p->myUV.SetX( vec * pos.XDirection() );
2653 p->myUV.SetY( vec * pos.YDirection() );
2657 // points on edges to be used for UV computation of in-face points
2658 list< list< TPoint* > > edgesPointsList;
2659 edgesPointsList.push_back( list< TPoint* >() );
2660 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2661 list< TPoint* >::iterator pIt;
2663 // compute UV and XYZ of points on edges
2665 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2667 gp_XYZ& xyz1 = *xyzIt++;
2668 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2670 list< TPoint* > & ePoints = getShapePoints( iSub );
2671 ePoints.back()->myInitU = 1.0;
2672 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2673 while ( *pIt != ePoints.back() )
2676 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2677 gp_Vec vec ( pos.Location(), p->myXYZ );
2678 p->myUV.SetX( vec * pos.XDirection() );
2679 p->myUV.SetY( vec * pos.YDirection() );
2681 // collect on-edge points (excluding the last one)
2682 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2685 // Compute UV and XYZ of in-face points
2687 // try to use a simple algo to compute UV
2688 list< TPoint* > & fPoints = getShapePoints( iSub );
2689 bool isDeformed = false;
2690 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2691 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2692 (*pIt)->myUV, isDeformed )) {
2693 MESSAGE("cant Apply(face)");
2696 // try to use a complex algo if it is a difficult case
2697 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2699 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2700 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2701 (*pIt)->myUV, isDeformed )) {
2702 MESSAGE("cant Apply(face)");
2707 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2709 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2712 myIsComputed = true;
2714 return setErrorCode( ERR_OK );
2717 //=======================================================================
2719 //purpose : Compute nodes coordinates applying
2720 // the loaded pattern to <theFace>. The first key-point
2721 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2722 //=======================================================================
2724 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2725 const SMDS_MeshFace* theFace,
2726 const TopoDS_Shape& theSurface,
2727 const int theNodeIndexOnKeyPoint1,
2728 const bool theReverse)
2730 // MESSAGE(" ::Apply(MeshFace) " );
2731 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2732 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2734 const TopoDS_Face& face = TopoDS::Face( theSurface );
2735 TopLoc_Location loc;
2736 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2737 const gp_Trsf & aTrsf = loc.Transformation();
2739 if ( !IsLoaded() ) {
2740 MESSAGE( "Pattern not loaded" );
2741 return setErrorCode( ERR_APPL_NOT_LOADED );
2744 // check nb of nodes
2745 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2746 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2747 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2750 // find points on edges, it fills myNbKeyPntInBoundary
2751 if ( !findBoundaryPoints() )
2754 // check that there are no holes in a pattern
2755 if (myNbKeyPntInBoundary.size() > 1 ) {
2756 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2759 // Define the nodes order
2761 list< const SMDS_MeshNode* > nodes;
2762 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2763 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2765 while ( noIt->more() ) {
2766 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2767 nodes.push_back( node );
2768 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2771 if ( n != nodes.end() ) {
2773 if ( n != --nodes.end() )
2774 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2777 else if ( n != nodes.begin() )
2778 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2781 // find a node not on a seam edge, if necessary
2782 SMESH_MesherHelper helper( *theMesh );
2783 helper.SetSubShape( theSurface );
2784 const SMDS_MeshNode* inFaceNode = 0;
2785 if ( helper.GetNodeUVneedInFaceNode() )
2787 SMESH_MeshEditor editor( theMesh );
2788 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2789 int shapeID = editor.FindShape( *n );
2791 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2792 if ( !helper.IsSeamShape( shapeID ))
2797 // Set UV of key-points (i.e. of nodes of theFace )
2798 vector< gp_XY > keyUV( theFace->NbNodes() );
2799 myOrderedNodes.resize( theFace->NbNodes() );
2800 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2802 TPoint* p = getShapePoints( iSub ).front();
2803 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2804 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2806 keyUV[ iSub-1 ] = p->myUV;
2807 myOrderedNodes[ iSub-1 ] = *n;
2810 // points on edges to be used for UV computation of in-face points
2811 list< list< TPoint* > > edgesPointsList;
2812 edgesPointsList.push_back( list< TPoint* >() );
2813 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2814 list< TPoint* >::iterator pIt;
2816 // compute UV and XYZ of points on edges
2818 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2820 gp_XY& uv1 = keyUV[ i ];
2821 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2823 list< TPoint* > & ePoints = getShapePoints( iSub );
2824 ePoints.back()->myInitU = 1.0;
2825 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2826 while ( *pIt != ePoints.back() )
2829 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2830 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2831 if ( !loc.IsIdentity() )
2832 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2834 // collect on-edge points (excluding the last one)
2835 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2838 // Compute UV and XYZ of in-face points
2840 // try to use a simple algo to compute UV
2841 list< TPoint* > & fPoints = getShapePoints( iSub );
2842 bool isDeformed = false;
2843 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2844 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2845 (*pIt)->myUV, isDeformed )) {
2846 MESSAGE("cant Apply(face)");
2849 // try to use a complex algo if it is a difficult case
2850 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2852 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2853 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2854 (*pIt)->myUV, isDeformed )) {
2855 MESSAGE("cant Apply(face)");
2860 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2862 TPoint * point = *pIt;
2863 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2864 if ( !loc.IsIdentity() )
2865 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2868 myIsComputed = true;
2870 return setErrorCode( ERR_OK );
2873 //=======================================================================
2874 //function : undefinedXYZ
2876 //=======================================================================
2878 static const gp_XYZ& undefinedXYZ()
2880 static gp_XYZ xyz( 1.e100, 0., 0. );
2884 //=======================================================================
2885 //function : isDefined
2887 //=======================================================================
2889 inline static bool isDefined(const gp_XYZ& theXYZ)
2891 return theXYZ.X() < 1.e100;
2894 //=======================================================================
2896 //purpose : Compute nodes coordinates applying
2897 // the loaded pattern to <theFaces>. The first key-point
2898 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2899 //=======================================================================
2901 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2902 std::set<const SMDS_MeshFace*>& theFaces,
2903 const int theNodeIndexOnKeyPoint1,
2904 const bool theReverse)
2906 MESSAGE(" ::Apply(set<MeshFace>) " );
2908 if ( !IsLoaded() ) {
2909 MESSAGE( "Pattern not loaded" );
2910 return setErrorCode( ERR_APPL_NOT_LOADED );
2913 // find points on edges, it fills myNbKeyPntInBoundary
2914 if ( !findBoundaryPoints() )
2917 // check that there are no holes in a pattern
2918 if (myNbKeyPntInBoundary.size() > 1 ) {
2919 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2924 myElemXYZIDs.clear();
2925 myXYZIdToNodeMap.clear();
2927 myIdsOnBoundary.clear();
2928 myReverseConnectivity.clear();
2930 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2931 myElements.reserve( theFaces.size() );
2933 // to find point index
2934 map< TPoint*, int > pointIndex;
2935 for ( int i = 0; i < myPoints.size(); i++ )
2936 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2938 int ind1 = 0; // lowest point index for a face
2943 // SMESH_MeshEditor editor( theMesh );
2945 // apply to each face in theFaces set
2946 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2947 for ( ; face != theFaces.end(); ++face )
2949 // int curShapeId = editor.FindShape( *face );
2950 // if ( curShapeId != shapeID ) {
2951 // if ( curShapeId )
2952 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2955 // shapeID = curShapeId;
2958 if ( shape.IsNull() )
2959 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2961 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2963 MESSAGE( "Failed on " << *face );
2966 myElements.push_back( *face );
2968 // store computed points belonging to elements
2969 list< TElemDef >::iterator ll = myElemPointIDs.begin();
2970 for ( ; ll != myElemPointIDs.end(); ++ll )
2972 myElemXYZIDs.push_back(TElemDef());
2973 TElemDef& xyzIds = myElemXYZIDs.back();
2974 TElemDef& pIds = *ll;
2975 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
2976 int pIndex = *id + ind1;
2977 xyzIds.push_back( pIndex );
2978 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
2979 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
2982 // put points on links to myIdsOnBoundary,
2983 // they will be used to sew new elements on adjacent refined elements
2984 int nbNodes = (*face)->NbNodes(), eID = nbNodes + 1;
2985 for ( int i = 0; i < nbNodes; i++ )
2987 list< TPoint* > & linkPoints = getShapePoints( eID++ );
2988 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
2989 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
2990 // make a link and a node set
2991 TNodeSet linkSet, node1Set;
2992 linkSet.insert( n1 );
2993 linkSet.insert( n2 );
2994 node1Set.insert( n1 );
2995 list< TPoint* >::iterator p = linkPoints.begin();
2997 // map the first link point to n1
2998 int nId = pointIndex[ *p ] + ind1;
2999 myXYZIdToNodeMap[ nId ] = n1;
3000 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3001 groups.push_back(list< int > ());
3002 groups.back().push_back( nId );
3004 // add the linkSet to the map
3005 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3006 groups.push_back(list< int > ());
3007 list< int >& indList = groups.back();
3008 // add points to the map excluding the end points
3009 for ( p++; *p != linkPoints.back(); p++ )
3010 indList.push_back( pointIndex[ *p ] + ind1 );
3012 ind1 += myPoints.size();
3015 return !myElemXYZIDs.empty();
3018 //=======================================================================
3020 //purpose : Compute nodes coordinates applying
3021 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3022 // will be mapped into <theNode000Index>-th node. The
3023 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3025 //=======================================================================
3027 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3028 const int theNode000Index,
3029 const int theNode001Index)
3031 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3033 if ( !IsLoaded() ) {
3034 MESSAGE( "Pattern not loaded" );
3035 return setErrorCode( ERR_APPL_NOT_LOADED );
3038 // bind ID to points
3039 if ( !findBoundaryPoints() )
3042 // check that there are no holes in a pattern
3043 if (myNbKeyPntInBoundary.size() > 1 ) {
3044 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3049 myElemXYZIDs.clear();
3050 myXYZIdToNodeMap.clear();
3052 myIdsOnBoundary.clear();
3053 myReverseConnectivity.clear();
3055 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3056 myElements.reserve( theVolumes.size() );
3058 // to find point index
3059 map< TPoint*, int > pointIndex;
3060 for ( int i = 0; i < myPoints.size(); i++ )
3061 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3063 int ind1 = 0; // lowest point index for an element
3065 // apply to each element in theVolumes set
3066 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3067 for ( ; vol != theVolumes.end(); ++vol )
3069 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3070 MESSAGE( "Failed on " << *vol );
3073 myElements.push_back( *vol );
3075 // store computed points belonging to elements
3076 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3077 for ( ; ll != myElemPointIDs.end(); ++ll )
3079 myElemXYZIDs.push_back(TElemDef());
3080 TElemDef& xyzIds = myElemXYZIDs.back();
3081 TElemDef& pIds = *ll;
3082 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3083 int pIndex = *id + ind1;
3084 xyzIds.push_back( pIndex );
3085 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3086 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3089 // put points on edges and faces to myIdsOnBoundary,
3090 // they will be used to sew new elements on adjacent refined elements
3091 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3093 // make a set of sub-points
3095 vector< int > subIDs;
3096 if ( SMESH_Block::IsVertexID( Id )) {
3097 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3099 else if ( SMESH_Block::IsEdgeID( Id )) {
3100 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3101 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3102 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3105 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3106 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3107 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3108 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3109 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3110 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3111 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3112 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3115 list< TPoint* > & points = getShapePoints( Id );
3116 list< TPoint* >::iterator p = points.begin();
3117 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3118 groups.push_back(list< int > ());
3119 list< int >& indList = groups.back();
3120 for ( ; p != points.end(); p++ )
3121 indList.push_back( pointIndex[ *p ] + ind1 );
3122 if ( subNodes.size() == 1 ) // vertex case
3123 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3125 ind1 += myPoints.size();
3128 return !myElemXYZIDs.empty();
3131 //=======================================================================
3133 //purpose : Create a pattern from the mesh built on <theBlock>
3134 //=======================================================================
3136 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3137 const TopoDS_Shell& theBlock)
3139 MESSAGE(" ::Load(volume) " );
3142 SMESHDS_SubMesh * aSubMesh;
3144 // load shapes in myShapeIDMap
3146 TopoDS_Vertex v1, v2;
3147 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3148 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3151 int nbNodes = 0, shapeID;
3152 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3154 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3155 aSubMesh = getSubmeshWithElements( theMesh, S );
3157 nbNodes += aSubMesh->NbNodes();
3159 myPoints.resize( nbNodes );
3161 // load U of points on edges
3162 TNodePointIDMap nodePointIDMap;
3164 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3166 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3167 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3168 aSubMesh = getSubmeshWithElements( theMesh, S );
3169 if ( ! aSubMesh ) continue;
3170 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3171 if ( !nIt->more() ) continue;
3173 // store a node and a point
3174 while ( nIt->more() ) {
3175 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3176 nodePointIDMap.insert( make_pair( node, iPoint ));
3177 if ( block.IsVertexID( shapeID ))
3178 myKeyPointIDs.push_back( iPoint );
3179 TPoint* p = & myPoints[ iPoint++ ];
3180 shapePoints.push_back( p );
3181 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3182 p->myInitXYZ.SetCoord( 0,0,0 );
3184 list< TPoint* >::iterator pIt = shapePoints.begin();
3187 switch ( S.ShapeType() )
3192 for ( ; pIt != shapePoints.end(); pIt++ ) {
3193 double * coef = block.GetShapeCoef( shapeID );
3194 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3195 if ( coef[ iCoord - 1] > 0 )
3196 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3198 if ( S.ShapeType() == TopAbs_VERTEX )
3201 const TopoDS_Edge& edge = TopoDS::Edge( S );
3203 BRep_Tool::Range( edge, f, l );
3204 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3205 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3206 pIt = shapePoints.begin();
3207 nIt = aSubMesh->GetNodes();
3208 for ( ; nIt->more(); pIt++ )
3210 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3211 const SMDS_EdgePosition* epos =
3212 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
3213 double u = ( epos->GetUParameter() - f ) / ( l - f );
3214 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3219 for ( ; pIt != shapePoints.end(); pIt++ )
3221 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3222 MESSAGE( "!block.ComputeParameters()" );
3223 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3227 } // loop on block sub-shapes
3231 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3234 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3235 while ( elemIt->more() ) {
3236 SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
3237 myElemPointIDs.push_back( TElemDef() );
3238 TElemDef& elemPoints = myElemPointIDs.back();
3239 while ( nIt->more() )
3240 elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
3244 myIsBoundaryPointsFound = true;
3246 return setErrorCode( ERR_OK );
3249 //=======================================================================
3250 //function : getSubmeshWithElements
3251 //purpose : return submesh containing elements bound to theBlock in theMesh
3252 //=======================================================================
3254 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3255 const TopoDS_Shape& theShape)
3257 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3258 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3261 if ( theShape.ShapeType() == TopAbs_SHELL )
3263 // look for submesh of VOLUME
3264 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3265 for (; it.More(); it.Next()) {
3266 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3267 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3275 //=======================================================================
3277 //purpose : Compute nodes coordinates applying
3278 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3279 // will be mapped into <theVertex000>. The (0,0,1)
3280 // fifth key-point will be mapped into <theVertex001>.
3281 //=======================================================================
3283 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3284 const TopoDS_Vertex& theVertex000,
3285 const TopoDS_Vertex& theVertex001)
3287 MESSAGE(" ::Apply(volume) " );
3289 if (!findBoundaryPoints() || // bind ID to points
3290 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3293 SMESH_Block block; // bind ID to shape
3294 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3295 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3297 // compute XYZ of points on shapes
3299 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3301 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3302 list< TPoint* >::iterator pIt = shapePoints.begin();
3303 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3304 switch ( S.ShapeType() )
3306 case TopAbs_VERTEX: {
3308 for ( ; pIt != shapePoints.end(); pIt++ )
3309 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3314 for ( ; pIt != shapePoints.end(); pIt++ )
3315 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3320 for ( ; pIt != shapePoints.end(); pIt++ )
3321 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3325 for ( ; pIt != shapePoints.end(); pIt++ )
3326 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3328 } // loop on block sub-shapes
3330 myIsComputed = true;
3332 return setErrorCode( ERR_OK );
3335 //=======================================================================
3337 //purpose : Compute nodes coordinates applying
3338 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3339 // will be mapped into <theNode000Index>-th node. The
3340 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3342 //=======================================================================
3344 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3345 const int theNode000Index,
3346 const int theNode001Index)
3348 //MESSAGE(" ::Apply(MeshVolume) " );
3350 if (!findBoundaryPoints()) // bind ID to points
3353 SMESH_Block block; // bind ID to shape
3354 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3355 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3356 // compute XYZ of points on shapes
3358 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3360 list< TPoint* > & shapePoints = getShapePoints( ID );
3361 list< TPoint* >::iterator pIt = shapePoints.begin();
3363 if ( block.IsVertexID( ID ))
3364 for ( ; pIt != shapePoints.end(); pIt++ ) {
3365 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3367 else if ( block.IsEdgeID( ID ))
3368 for ( ; pIt != shapePoints.end(); pIt++ ) {
3369 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3371 else if ( block.IsFaceID( ID ))
3372 for ( ; pIt != shapePoints.end(); pIt++ ) {
3373 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3376 for ( ; pIt != shapePoints.end(); pIt++ )
3377 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3378 } // loop on block sub-shapes
3380 myIsComputed = true;
3382 return setErrorCode( ERR_OK );
3385 //=======================================================================
3386 //function : mergePoints
3387 //purpose : Merge XYZ on edges and/or faces.
3388 //=======================================================================
3390 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3392 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3393 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3395 list<list< int > >& groups = idListIt->second;
3396 if ( groups.size() < 2 )
3400 const TNodeSet& nodes = idListIt->first;
3401 double tol2 = 1.e-10;
3402 if ( nodes.size() > 1 ) {
3404 TNodeSet::const_iterator n = nodes.begin();
3405 for ( ; n != nodes.end(); ++n )
3406 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3407 double x, y, z, X, Y, Z;
3408 box.Get( x, y, z, X, Y, Z );
3409 gp_Pnt p( x, y, z ), P( X, Y, Z );
3410 tol2 = 1.e-4 * p.SquareDistance( P );
3413 // to unite groups on link
3414 bool unite = ( uniteGroups && nodes.size() == 2 );
3415 map< double, int > distIndMap;
3416 const SMDS_MeshNode* node = *nodes.begin();
3417 gp_Pnt P( node->X(), node->Y(), node->Z() );
3419 // compare points, replace indices
3421 list< int >::iterator ind1, ind2;
3422 list< list< int > >::iterator grpIt1, grpIt2;
3423 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3425 list< int >& indices1 = *grpIt1;
3427 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3429 list< int >& indices2 = *grpIt2;
3430 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3432 gp_XYZ& p1 = myXYZ[ *ind1 ];
3433 ind2 = indices2.begin();
3434 while ( ind2 != indices2.end() )
3436 gp_XYZ& p2 = myXYZ[ *ind2 ];
3437 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3438 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3440 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3441 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3442 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3443 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3445 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3446 myXYZ[ *ind2 ] = undefinedXYZ();
3447 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3449 ind2 = indices2.erase( ind2 );
3456 if ( unite ) { // sort indices using distIndMap
3457 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3459 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3460 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3461 distIndMap.insert( make_pair( dist, *ind1 ));
3465 if ( unite ) { // put all sorted indices into the first group
3466 list< int >& g = groups.front();
3468 map< double, int >::iterator dist_ind = distIndMap.begin();
3469 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3470 g.push_back( dist_ind->second );
3472 } // loop on myIdsOnBoundary
3475 //=======================================================================
3476 //function : makePolyElements
3477 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3478 //=======================================================================
3480 void SMESH_Pattern::
3481 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3482 const bool toCreatePolygons,
3483 const bool toCreatePolyedrs)
3485 myPolyElemXYZIDs.clear();
3486 myPolyElems.clear();
3487 myPolyElems.reserve( myIdsOnBoundary.size() );
3489 // make a set of refined elements
3490 TIDSortedElemSet avoidSet, elemSet;
3491 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3492 for(; itv!=myElements.end(); itv++) {
3493 const SMDS_MeshElement* el = (*itv);
3494 avoidSet.insert( el );
3496 //avoidSet.insert( myElements.begin(), myElements.end() );
3498 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3500 if ( toCreatePolygons )
3502 int lastFreeId = myXYZ.size();
3504 // loop on links of refined elements
3505 indListIt = myIdsOnBoundary.begin();
3506 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3508 const TNodeSet & linkNodes = indListIt->first;
3509 if ( linkNodes.size() != 2 )
3510 continue; // skip face
3511 const SMDS_MeshNode* n1 = * linkNodes.begin();
3512 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3514 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3515 if ( idGroups.empty() || idGroups.front().empty() )
3518 // find not refined face having n1-n2 link
3522 const SMDS_MeshElement* face =
3523 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3526 avoidSet.insert ( face );
3527 myPolyElems.push_back( face );
3529 // some links of <face> are split;
3530 // make list of xyz for <face>
3531 myPolyElemXYZIDs.push_back(TElemDef());
3532 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3533 // loop on links of a <face>
3534 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3535 int i = 0, nbNodes = face->NbNodes();
3536 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3537 while ( nIt->more() )
3538 nodes[ i++ ] = smdsNode( nIt->next() );
3539 nodes[ i ] = nodes[ 0 ];
3540 for ( i = 0; i < nbNodes; ++i )
3542 // look for point mapped on a link
3543 TNodeSet faceLinkNodes;
3544 faceLinkNodes.insert( nodes[ i ] );
3545 faceLinkNodes.insert( nodes[ i + 1 ] );
3546 if ( faceLinkNodes == linkNodes )
3547 nn_IdList = indListIt;
3549 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3550 // add face point ids
3551 faceNodeIds.push_back( ++lastFreeId );
3552 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3553 if ( nn_IdList != myIdsOnBoundary.end() )
3555 // there are points mapped on a link
3556 list< int >& mappedIds = nn_IdList->second.front();
3557 if ( isReversed( nodes[ i ], mappedIds ))
3558 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3560 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3562 } // loop on links of a <face>
3568 if ( myIs2D && idGroups.size() > 1 ) {
3570 // sew new elements on 2 refined elements sharing n1-n2 link
3572 list< int >& idsOnLink = idGroups.front();
3573 // temporarily add ids of link nodes to idsOnLink
3574 bool rev = isReversed( n1, idsOnLink );
3575 for ( int i = 0; i < 2; ++i )
3578 nodeSet.insert( i ? n2 : n1 );
3579 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3580 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3581 int nodeId = groups.front().front();
3583 if ( rev ) append = !append;
3585 idsOnLink.push_back( nodeId );
3587 idsOnLink.push_front( nodeId );
3589 list< int >::iterator id = idsOnLink.begin();
3590 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3592 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3593 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3594 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3596 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3597 // look for <id> in element definition
3598 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3599 ASSERT ( idDef != pIdList->end() );
3600 // look for 2 neighbour ids of <id> in element definition
3601 for ( int prev = 0; prev < 2; ++prev ) {
3602 TElemDef::iterator idDef2 = idDef;
3604 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3606 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3607 // look for idDef2 on a link starting from id
3608 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3609 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3610 // insert ids located on link between <id> and <id2>
3611 // into the element definition between idDef and idDef2
3613 for ( ; id2 != id; --id2 )
3614 pIdList->insert( idDef, *id2 );
3616 list< int >::iterator id1 = id;
3617 for ( ++id1, ++id2; id1 != id2; ++id1 )
3618 pIdList->insert( idDef2, *id1 );
3624 // remove ids of link nodes
3625 idsOnLink.pop_front();
3626 idsOnLink.pop_back();
3628 } // loop on myIdsOnBoundary
3629 } // if ( toCreatePolygons )
3631 if ( toCreatePolyedrs )
3633 // check volumes adjacent to the refined elements
3634 SMDS_VolumeTool volTool;
3635 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3636 for ( ; refinedElem != myElements.end(); ++refinedElem )
3638 // loop on nodes of refinedElem
3639 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3640 while ( nIt->more() ) {
3641 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3642 // loop on inverse elements of node
3643 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3644 while ( eIt->more() )
3646 const SMDS_MeshElement* elem = eIt->next();
3647 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3648 continue; // skip faces or refined elements
3649 // add polyhedron definition
3650 myPolyhedronQuantities.push_back(vector<int> ());
3651 myPolyElemXYZIDs.push_back(TElemDef());
3652 vector<int>& quantity = myPolyhedronQuantities.back();
3653 TElemDef & elemDef = myPolyElemXYZIDs.back();
3654 // get definitions of new elements on volume faces
3655 bool makePoly = false;
3656 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3658 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3659 volTool.NbFaceNodes( iF ),
3660 theNodes, elemDef, quantity))
3664 myPolyElems.push_back( elem );
3666 myPolyhedronQuantities.pop_back();
3667 myPolyElemXYZIDs.pop_back();
3675 //=======================================================================
3676 //function : getFacesDefinition
3677 //purpose : return faces definition for a volume face defined by theBndNodes
3678 //=======================================================================
3680 bool SMESH_Pattern::
3681 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3682 const int theNbBndNodes,
3683 const vector< const SMDS_MeshNode* >& theNodes,
3684 list< int >& theFaceDefs,
3685 vector<int>& theQuantity)
3687 bool makePoly = false;
3688 // cout << "FROM FACE NODES: " <<endl;
3689 // for ( int i = 0; i < theNbBndNodes; ++i )
3690 // cout << theBndNodes[ i ];
3692 set< const SMDS_MeshNode* > bndNodeSet;
3693 for ( int i = 0; i < theNbBndNodes; ++i )
3694 bndNodeSet.insert( theBndNodes[ i ]);
3696 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3698 // make a set of all nodes on a face
3700 if ( !myIs2D ) { // for 2D, merge only edges
3701 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3702 if ( nn_IdList != myIdsOnBoundary.end() ) {
3704 list< int > & faceIds = nn_IdList->second.front();
3705 ids.insert( faceIds.begin(), faceIds.end() );
3708 //bool hasIdsInFace = !ids.empty();
3710 // add ids on links and bnd nodes
3711 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3712 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3713 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3715 // add id of iN-th bnd node
3717 nSet.insert( theBndNodes[ iN ] );
3718 nn_IdList = myIdsOnBoundary.find( nSet );
3719 int bndId = ++lastFreeId;
3720 if ( nn_IdList != myIdsOnBoundary.end() ) {
3721 bndId = nn_IdList->second.front().front();
3722 ids.insert( bndId );
3725 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3726 faceDef.push_back( bndId );
3727 // add ids on a link
3729 linkNodes.insert( theBndNodes[ iN ]);
3730 linkNodes.insert( theBndNodes[ iN + 1 == theNbBndNodes ? 0 : iN + 1 ]);
3731 nn_IdList = myIdsOnBoundary.find( linkNodes );
3732 if ( nn_IdList != myIdsOnBoundary.end() ) {
3734 list< int > & linkIds = nn_IdList->second.front();
3735 ids.insert( linkIds.begin(), linkIds.end() );
3736 if ( isReversed( theBndNodes[ iN ], linkIds ))
3737 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3739 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3743 // find faces definition of new volumes
3745 bool defsAdded = false;
3746 if ( !myIs2D ) { // for 2D, merge only edges
3747 SMDS_VolumeTool vol;
3748 set< TElemDef* > checkedVolDefs;
3749 set< int >::iterator id = ids.begin();
3750 for ( ; id != ids.end(); ++id )
3752 // definitions of volumes sharing id
3753 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3754 ASSERT( !defList.empty() );
3755 // loop on volume definitions
3756 list< TElemDef* >::iterator pIdList = defList.begin();
3757 for ( ; pIdList != defList.end(); ++pIdList)
3759 if ( !checkedVolDefs.insert( *pIdList ).second )
3760 continue; // skip already checked volume definition
3761 vector< int > idVec;
3762 idVec.reserve( (*pIdList)->size() );
3763 idVec.insert( idVec.begin(), (*pIdList)->begin(), (*pIdList)->end() );
3764 // loop on face defs of a volume
3765 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3766 if ( volType == SMDS_VolumeTool::UNKNOWN )
3768 int nbFaces = vol.NbFaces( volType );
3769 for ( int iF = 0; iF < nbFaces; ++iF )
3771 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3772 int iN, nbN = vol.NbFaceNodes( volType, iF );
3773 // check if all nodes of a faces are in <ids>
3775 for ( iN = 0; iN < nbN && all; ++iN ) {
3776 int nodeId = idVec[ nodeInds[ iN ]];
3777 all = ( ids.find( nodeId ) != ids.end() );
3780 // store a face definition
3781 for ( iN = 0; iN < nbN; ++iN ) {
3782 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3784 theQuantity.push_back( nbN );
3792 theQuantity.push_back( faceDef.size() );
3793 theFaceDefs.splice( theFaceDefs.end(), faceDef, faceDef.begin(), faceDef.end() );
3799 //=======================================================================
3800 //function : clearSubMesh
3802 //=======================================================================
3804 static bool clearSubMesh( SMESH_Mesh* theMesh,
3805 const TopoDS_Shape& theShape)
3807 bool removed = false;
3808 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3810 removed = !aSubMesh->IsEmpty();
3812 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3815 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3816 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3818 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3819 removed = eIt->more();
3820 while ( eIt->more() )
3821 aMeshDS->RemoveElement( eIt->next() );
3822 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3823 removed = removed || nIt->more();
3824 while ( nIt->more() )
3825 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3831 //=======================================================================
3832 //function : clearMesh
3833 //purpose : clear mesh elements existing on myShape in theMesh
3834 //=======================================================================
3836 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3839 if ( !myShape.IsNull() )
3841 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3842 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3843 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3845 clearSubMesh( theMesh, it.Value() );
3851 //=======================================================================
3852 //function : MakeMesh
3853 //purpose : Create nodes and elements in <theMesh> using nodes
3854 // coordinates computed by either of Apply...() methods
3855 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3856 // it does not care of nodes and elements already existing on
3857 // subshapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3858 //=======================================================================
3860 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3861 const bool toCreatePolygons,
3862 const bool toCreatePolyedrs)
3864 MESSAGE(" ::MakeMesh() " );
3865 if ( !myIsComputed )
3866 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3868 mergePoints( toCreatePolygons );
3870 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3872 // clear elements and nodes existing on myShape
3875 bool onMeshElements = ( !myElements.empty() );
3877 // Create missing nodes
3879 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3880 if ( onMeshElements )
3882 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3883 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3884 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3885 nodesVector[ i_node->first ] = i_node->second;
3887 for ( int i = 0; i < myXYZ.size(); ++i ) {
3888 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3889 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3896 nodesVector.resize( myPoints.size(), 0 );
3898 // to find point index
3899 map< TPoint*, int > pointIndex;
3900 for ( int i = 0; i < myPoints.size(); i++ )
3901 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3903 // loop on sub-shapes of myShape: create nodes
3904 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3905 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3908 //SMESHDS_SubMesh * subMeshDS = 0;
3909 if ( !myShapeIDMap.IsEmpty() ) {
3910 S = myShapeIDMap( idPointIt->first );
3911 //subMeshDS = aMeshDS->MeshElements( S );
3913 list< TPoint* > & points = idPointIt->second;
3914 list< TPoint* >::iterator pIt = points.begin();
3915 for ( ; pIt != points.end(); pIt++ )
3917 TPoint* point = *pIt;
3918 int pIndex = pointIndex[ point ];
3919 if ( nodesVector [ pIndex ] )
3921 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3924 nodesVector [ pIndex ] = node;
3926 if ( !S.IsNull() /*subMeshDS*/ ) {
3927 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3928 switch ( S.ShapeType() ) {
3929 case TopAbs_VERTEX: {
3930 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3933 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3936 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3937 point->myUV.X(), point->myUV.Y() ); break;
3940 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3949 if ( onMeshElements )
3951 // prepare data to create poly elements
3952 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3955 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3956 // sew old and new elements
3957 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3961 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
3964 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
3965 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
3966 // for ( ; i_sm != sm.end(); i_sm++ )
3968 // cout << " SM " << i_sm->first << " ";
3969 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
3970 // //SMDS_ElemIteratorPtr GetElements();
3971 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
3972 // while ( nit->more() )
3973 // cout << nit->next()->GetID() << " ";
3976 return setErrorCode( ERR_OK );
3979 //=======================================================================
3980 //function : createElements
3981 //purpose : add elements to the mesh
3982 //=======================================================================
3984 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
3985 const vector<const SMDS_MeshNode* >& theNodesVector,
3986 const list< TElemDef > & theElemNodeIDs,
3987 const vector<const SMDS_MeshElement*>& theElements)
3989 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3990 SMESH_MeshEditor editor( theMesh );
3992 bool onMeshElements = !theElements.empty();
3994 // shapes and groups theElements are on
3995 vector< int > shapeIDs;
3996 vector< list< SMESHDS_Group* > > groups;
3997 set< const SMDS_MeshNode* > shellNodes;
3998 if ( onMeshElements )
4000 shapeIDs.resize( theElements.size() );
4001 groups.resize( theElements.size() );
4002 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4003 set<SMESHDS_GroupBase*>::const_iterator grIt;
4004 for ( int i = 0; i < theElements.size(); i++ )
4006 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4007 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4008 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4009 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4010 groups[ i ].push_back( group );
4013 // get all nodes bound to shells because their SpacePosition is not set
4014 // by SMESHDS_Mesh::SetNodeInVolume()
4015 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4016 if ( !aMainShape.IsNull() ) {
4017 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4018 for ( ; shellExp.More(); shellExp.Next() )
4020 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4022 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4023 while ( nIt->more() )
4024 shellNodes.insert( nIt->next() );
4029 // nb new elements per a refined element
4030 int nbNewElemsPerOld = 1;
4031 if ( onMeshElements )
4032 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4036 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4037 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4038 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4040 const TElemDef & elemNodeInd = *enIt;
4042 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4043 TElemDef::const_iterator id = elemNodeInd.begin();
4045 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4046 if ( *id < theNodesVector.size() )
4047 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4049 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4051 // dim of refined elem
4052 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4053 if ( onMeshElements ) {
4054 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4057 const SMDS_MeshElement* elem = 0;
4059 switch ( nbNodes ) {
4061 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4063 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4065 if ( !onMeshElements ) {// create a quadratic face
4066 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4067 nodes[4], nodes[5] ); break;
4068 } // else do not break but create a polygon
4070 if ( !onMeshElements ) {// create a quadratic face
4071 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4072 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4073 } // else do not break but create a polygon
4075 elem = aMeshDS->AddPolygonalFace( nodes );
4079 switch ( nbNodes ) {
4081 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4083 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4086 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4087 nodes[4], nodes[5] ); break;
4089 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4090 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4092 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4095 // set element on a shape
4096 if ( elem && onMeshElements ) // applied to mesh elements
4098 int shapeID = shapeIDs[ elemIndex ];
4099 if ( shapeID > 0 ) {
4100 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4101 // set nodes on a shape
4102 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4103 if ( S.ShapeType() == TopAbs_SOLID ) {
4104 TopoDS_Iterator shellIt( S );
4105 if ( shellIt.More() )
4106 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4108 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4109 while ( noIt->more() ) {
4110 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4111 if (!node->GetPosition()->GetShapeId() &&
4112 shellNodes.find( node ) == shellNodes.end() ) {
4113 if ( S.ShapeType() == TopAbs_FACE )
4114 aMeshDS->SetNodeOnFace( node, shapeID );
4116 aMeshDS->SetNodeInVolume( node, shapeID );
4117 shellNodes.insert( node );
4122 // add elem in groups
4123 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4124 for ( ; g != groups[ elemIndex ].end(); ++g )
4125 (*g)->SMDSGroup().Add( elem );
4127 if ( elem && !myShape.IsNull() ) // applied to shape
4128 aMeshDS->SetMeshElementOnShape( elem, myShape );
4131 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4132 // so that operations with hypotheses will erase the mesh being built
4134 SMESH_subMesh * subMesh;
4135 if ( !myShape.IsNull() ) {
4136 subMesh = theMesh->GetSubMesh( myShape );
4138 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4140 if ( onMeshElements ) {
4141 list< int > elemIDs;
4142 for ( int i = 0; i < theElements.size(); i++ )
4144 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4146 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4148 elemIDs.push_back( theElements[ i ]->GetID() );
4150 // remove refined elements
4151 editor.Remove( elemIDs, false );
4155 //=======================================================================
4156 //function : isReversed
4157 //purpose : check xyz ids order in theIdsList taking into account
4158 // theFirstNode on a link
4159 //=======================================================================
4161 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4162 const list< int >& theIdsList) const
4164 if ( theIdsList.size() < 2 )
4167 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4169 list<int>::const_iterator id = theIdsList.begin();
4170 for ( int i = 0; i < 2; ++i, ++id ) {
4171 if ( *id < myXYZ.size() )
4172 P[ i ] = myXYZ[ *id ];
4174 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4175 i_n = myXYZIdToNodeMap.find( *id );
4176 ASSERT( i_n != myXYZIdToNodeMap.end() );
4177 const SMDS_MeshNode* n = i_n->second;
4178 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4181 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4185 //=======================================================================
4186 //function : arrangeBoundaries
4187 //purpose : if there are several wires, arrange boundaryPoints so that
4188 // the outer wire goes first and fix inner wires orientation
4189 // update myKeyPointIDs to correspond to the order of key-points
4190 // in boundaries; sort internal boundaries by the nb of key-points
4191 //=======================================================================
4193 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4195 typedef list< list< TPoint* > >::iterator TListOfListIt;
4196 TListOfListIt bndIt;
4197 list< TPoint* >::iterator pIt;
4199 int nbBoundaries = boundaryList.size();
4200 if ( nbBoundaries > 1 )
4202 // sort boundaries by nb of key-points
4203 if ( nbBoundaries > 2 )
4205 // move boundaries in tmp list
4206 list< list< TPoint* > > tmpList;
4207 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4208 // make a map nb-key-points to boundary-position-in-tmpList,
4209 // boundary-positions get ordered in it
4210 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4211 TNbKpBndPosMap nbKpBndPosMap;
4212 bndIt = tmpList.begin();
4213 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4214 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4215 int nb = *nbKpIt * nbBoundaries;
4216 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4218 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4220 // move boundaries back to boundaryList
4221 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4222 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4223 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4224 TListOfListIt bndPos1 = bndPos2++;
4225 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4229 // Look for the outer boundary: the one with the point with the least X
4230 double leastX = DBL_MAX;
4231 TListOfListIt outerBndPos;
4232 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4234 list< TPoint* >& boundary = (*bndIt);
4235 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4237 TPoint* point = *pIt;
4238 if ( point->myInitXYZ.X() < leastX ) {
4239 leastX = point->myInitXYZ.X();
4240 outerBndPos = bndIt;
4245 if ( outerBndPos != boundaryList.begin() )
4246 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4248 } // if nbBoundaries > 1
4250 // Check boundaries orientation and re-fill myKeyPointIDs
4252 set< TPoint* > keyPointSet;
4253 list< int >::iterator kpIt = myKeyPointIDs.begin();
4254 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4255 keyPointSet.insert( & myPoints[ *kpIt ]);
4256 myKeyPointIDs.clear();
4258 // update myNbKeyPntInBoundary also
4259 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4261 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4263 // find the point with the least X
4264 double leastX = DBL_MAX;
4265 list< TPoint* >::iterator xpIt;
4266 list< TPoint* >& boundary = (*bndIt);
4267 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4269 TPoint* point = *pIt;
4270 if ( point->myInitXYZ.X() < leastX ) {
4271 leastX = point->myInitXYZ.X();
4275 // find points next to the point with the least X
4276 TPoint* p = *xpIt, *pPrev, *pNext;
4277 if ( p == boundary.front() )
4278 pPrev = *(++boundary.rbegin());
4284 if ( p == boundary.back() )
4285 pNext = *(++boundary.begin());
4290 // vectors of boundary direction near <p>
4291 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4292 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4293 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4294 double yPrev = v1.Y() / sqrt( sqMag1 );
4295 double yNext = v2.Y() / sqrt( sqMag2 );
4296 double sumY = yPrev + yNext;
4298 if ( bndIt == boundaryList.begin() ) // outer boundary
4306 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4307 (*nbKpIt) = 0; // count nb of key-points again
4308 pIt = boundary.begin();
4309 for ( ; pIt != boundary.end(); pIt++)
4311 TPoint* point = *pIt;
4312 if ( keyPointSet.find( point ) == keyPointSet.end() )
4314 // find an index of a keypoint
4316 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4317 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4318 if ( &(*pVecIt) == point )
4320 myKeyPointIDs.push_back( index );
4323 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4326 } // loop on a list of boundaries
4328 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4331 //=======================================================================
4332 //function : findBoundaryPoints
4333 //purpose : if loaded from file, find points to map on edges and faces and
4334 // compute their parameters
4335 //=======================================================================
4337 bool SMESH_Pattern::findBoundaryPoints()
4339 if ( myIsBoundaryPointsFound ) return true;
4341 MESSAGE(" findBoundaryPoints() ");
4343 myNbKeyPntInBoundary.clear();
4347 set< TPoint* > pointsInElems;
4349 // Find free links of elements:
4350 // put links of all elements in a set and remove links encountered twice
4352 typedef pair< TPoint*, TPoint*> TLink;
4353 set< TLink > linkSet;
4354 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4355 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4357 TElemDef & elemPoints = *epIt;
4358 TElemDef::iterator pIt = elemPoints.begin();
4359 int prevP = elemPoints.back();
4360 for ( ; pIt != elemPoints.end(); pIt++ ) {
4361 TPoint* p1 = & myPoints[ prevP ];
4362 TPoint* p2 = & myPoints[ *pIt ];
4363 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4364 ASSERT( link.first != link.second );
4365 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4366 if ( !itUniq.second )
4367 linkSet.erase( itUniq.first );
4370 pointsInElems.insert( p1 );
4373 // Now linkSet contains only free links,
4374 // find the points order that they have in boundaries
4376 // 1. make a map of key-points
4377 set< TPoint* > keyPointSet;
4378 list< int >::iterator kpIt = myKeyPointIDs.begin();
4379 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4380 keyPointSet.insert( & myPoints[ *kpIt ]);
4382 // 2. chain up boundary points
4383 list< list< TPoint* > > boundaryList;
4384 boundaryList.push_back( list< TPoint* >() );
4385 list< TPoint* > * boundary = & boundaryList.back();
4387 TPoint *point1, *point2, *keypoint1;
4388 kpIt = myKeyPointIDs.begin();
4389 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4390 // loop on free links: look for the next point
4392 set< TLink >::iterator lIt = linkSet.begin();
4393 while ( lIt != linkSet.end() )
4395 if ( (*lIt).first == point1 )
4396 point2 = (*lIt).second;
4397 else if ( (*lIt).second == point1 )
4398 point2 = (*lIt).first;
4403 linkSet.erase( lIt );
4404 lIt = linkSet.begin();
4406 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4408 boundary->push_back( point2 );
4410 else // a key-point found
4412 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4414 if ( point2 != keypoint1 ) // its not the boundary end
4416 boundary->push_back( point2 );
4418 else // the boundary end reached
4420 boundary->push_front( keypoint1 );
4421 boundary->push_back( keypoint1 );
4422 myNbKeyPntInBoundary.push_back( iKeyPoint );
4423 if ( keyPointSet.empty() )
4424 break; // all boundaries containing key-points are found
4426 // prepare to search for the next boundary
4427 boundaryList.push_back( list< TPoint* >() );
4428 boundary = & boundaryList.back();
4429 point2 = keypoint1 = (*keyPointSet.begin());
4433 } // loop on the free links set
4435 if ( boundary->empty() ) {
4436 MESSAGE(" a separate key-point");
4437 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4440 // if there are several wires, arrange boundaryPoints so that
4441 // the outer wire goes first and fix inner wires orientation;
4442 // sort myKeyPointIDs to correspond to the order of key-points
4444 arrangeBoundaries( boundaryList );
4446 // Find correspondence shape ID - points,
4447 // compute points parameter on edge
4449 keyPointSet.clear();
4450 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4451 keyPointSet.insert( & myPoints[ *kpIt ]);
4453 set< TPoint* > edgePointSet; // to find in-face points
4454 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4455 int edgeID = myKeyPointIDs.size() + 1;
4457 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4458 for ( ; bndIt != boundaryList.end(); bndIt++ )
4460 boundary = & (*bndIt);
4461 double edgeLength = 0;
4462 list< TPoint* >::iterator pIt = boundary->begin();
4463 getShapePoints( edgeID ).push_back( *pIt );
4464 getShapePoints( vertexID++ ).push_back( *pIt );
4465 for ( pIt++; pIt != boundary->end(); pIt++)
4467 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4468 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4469 TPoint* point = *pIt;
4470 edgePointSet.insert( point );
4471 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4473 edgePoints.push_back( point );
4474 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4475 point->myInitU = edgeLength;
4479 // treat points on the edge which ends up: compute U [0,1]
4480 edgePoints.push_back( point );
4481 if ( edgePoints.size() > 2 ) {
4482 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4483 list< TPoint* >::iterator epIt = edgePoints.begin();
4484 for ( ; epIt != edgePoints.end(); epIt++ )
4485 (*epIt)->myInitU /= edgeLength;
4487 // begin the next edge treatment
4490 if ( point != boundary->front() ) { // not the first key-point again
4491 getShapePoints( edgeID ).push_back( point );
4492 getShapePoints( vertexID++ ).push_back( point );
4498 // find in-face points
4499 list< TPoint* > & facePoints = getShapePoints( edgeID );
4500 vector< TPoint >::iterator pVecIt = myPoints.begin();
4501 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4502 TPoint* point = &(*pVecIt);
4503 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4504 pointsInElems.find( point ) != pointsInElems.end())
4505 facePoints.push_back( point );
4512 // bind points to shapes according to point parameters
4513 vector< TPoint >::iterator pVecIt = myPoints.begin();
4514 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4515 TPoint* point = &(*pVecIt);
4516 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4517 getShapePoints( shapeID ).push_back( point );
4518 // detect key-points
4519 if ( SMESH_Block::IsVertexID( shapeID ))
4520 myKeyPointIDs.push_back( i );
4524 myIsBoundaryPointsFound = true;
4525 return myIsBoundaryPointsFound;
4528 //=======================================================================
4530 //purpose : clear fields
4531 //=======================================================================
4533 void SMESH_Pattern::Clear()
4535 myIsComputed = myIsBoundaryPointsFound = false;
4538 myKeyPointIDs.clear();
4539 myElemPointIDs.clear();
4540 myShapeIDToPointsMap.clear();
4541 myShapeIDMap.Clear();
4543 myNbKeyPntInBoundary.clear();
4546 //=======================================================================
4547 //function : setShapeToMesh
4548 //purpose : set a shape to be meshed. Return True if meshing is possible
4549 //=======================================================================
4551 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4553 if ( !IsLoaded() ) {
4554 MESSAGE( "Pattern not loaded" );
4555 return setErrorCode( ERR_APPL_NOT_LOADED );
4558 TopAbs_ShapeEnum aType = theShape.ShapeType();
4559 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4561 MESSAGE( "Pattern dimention mismatch" );
4562 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4565 // check if a face is closed
4566 int nbNodeOnSeamEdge = 0;
4568 TopTools_MapOfShape seamVertices;
4569 TopoDS_Face face = TopoDS::Face( theShape );
4570 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4571 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
4572 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4573 if ( BRep_Tool::IsClosed(ee, face) ) {
4574 // seam edge and vertices encounter twice in theFace
4575 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4576 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4581 // check nb of vertices
4582 TopTools_IndexedMapOfShape vMap;
4583 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4584 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4585 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4586 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4589 myElements.clear(); // not refine elements
4590 myElemXYZIDs.clear();
4592 myShapeIDMap.Clear();
4597 //=======================================================================
4598 //function : GetMappedPoints
4599 //purpose : Return nodes coordinates computed by Apply() method
4600 //=======================================================================
4602 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4605 if ( !myIsComputed )
4608 if ( myElements.empty() ) { // applied to shape
4609 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4610 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4611 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4613 else { // applied to mesh elements
4614 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4615 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4616 for ( ; xyz != myXYZ.end(); ++xyz )
4617 if ( !isDefined( *xyz ))
4618 thePoints.push_back( definedXYZ );
4620 thePoints.push_back( & (*xyz) );
4622 return !thePoints.empty();
4626 //=======================================================================
4627 //function : GetPoints
4628 //purpose : Return nodes coordinates of the pattern
4629 //=======================================================================
4631 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4638 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4639 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4640 thePoints.push_back( & (*pVecIt).myInitXYZ );
4642 return ( thePoints.size() > 0 );
4645 //=======================================================================
4646 //function : getShapePoints
4647 //purpose : return list of points located on theShape
4648 //=======================================================================
4650 list< SMESH_Pattern::TPoint* > &
4651 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4654 if ( !myShapeIDMap.Contains( theShape ))
4655 aShapeID = myShapeIDMap.Add( theShape );
4657 aShapeID = myShapeIDMap.FindIndex( theShape );
4659 return myShapeIDToPointsMap[ aShapeID ];
4662 //=======================================================================
4663 //function : getShapePoints
4664 //purpose : return list of points located on the shape
4665 //=======================================================================
4667 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4669 return myShapeIDToPointsMap[ theShapeID ];
4672 //=======================================================================
4673 //function : DumpPoints
4675 //=======================================================================
4677 void SMESH_Pattern::DumpPoints() const
4680 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4681 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4682 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4686 //=======================================================================
4687 //function : TPoint()
4689 //=======================================================================
4691 SMESH_Pattern::TPoint::TPoint()
4694 myInitXYZ.SetCoord(0,0,0);
4695 myInitUV.SetCoord(0.,0.);
4697 myXYZ.SetCoord(0,0,0);
4698 myUV.SetCoord(0.,0.);
4703 //=======================================================================
4704 //function : operator <<
4706 //=======================================================================
4708 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4710 gp_XYZ xyz = p.myInitXYZ;
4711 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4712 gp_XY xy = p.myInitUV;
4713 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4714 double u = p.myInitU;
4715 OS << " u( " << u << " )) " << &p << endl;
4716 xyz = p.myXYZ.XYZ();
4717 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4719 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4721 OS << " u( " << u << " ))" << endl;