1 // Copyright (C) 2007-2019 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, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_Pattern.hxx
24 // Created : Mon Aug 2 10:30:00 2004
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_Pattern.hxx"
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FacePosition.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshFace.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Group.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "SMESHDS_SubMesh.hxx"
38 #include "SMESH_Block.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MeshEditor.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_subMesh.hxx"
45 #include <BRepAdaptor_Curve.hxx>
46 #include <BRepTools.hxx>
47 #include <BRepTools_WireExplorer.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_Box.hxx>
50 #include <Bnd_Box2d.hxx>
52 #include <Extrema_ExtPC.hxx>
53 #include <Extrema_GenExtPS.hxx>
54 #include <Extrema_POnSurf.hxx>
55 #include <Geom2d_Curve.hxx>
56 #include <GeomAdaptor_Surface.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Surface.hxx>
59 #include <Precision.hxx>
60 #include <TopAbs_ShapeEnum.hxx>
62 #include <TopExp_Explorer.hxx>
63 #include <TopLoc_Location.hxx>
64 #include <TopTools_ListIteratorOfListOfShape.hxx>
66 #include <TopoDS_Edge.hxx>
67 #include <TopoDS_Face.hxx>
68 #include <TopoDS_Iterator.hxx>
69 #include <TopoDS_Shell.hxx>
70 #include <TopoDS_Vertex.hxx>
71 #include <TopoDS_Wire.hxx>
73 #include <gp_Lin2d.hxx>
74 #include <gp_Pnt2d.hxx>
75 #include <gp_Trsf.hxx>
79 #include <Basics_Utils.hxx>
80 #include "utilities.h"
84 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
86 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
91 //=======================================================================
94 //=======================================================================
96 inline int getInt( const char * theSring )
98 if ( *theSring < '0' || *theSring > '9' )
102 int val = strtol( theSring, &ptr, 10 );
103 if ( ptr == theSring ||
104 // there must not be neither '.' nor ',' nor 'E' ...
105 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0' && *ptr != '\r'))
111 //=======================================================================
112 //function : getDouble
114 //=======================================================================
116 inline double getDouble( const char * theSring )
119 return strtod( theSring, &ptr );
122 //=======================================================================
123 //function : readLine
124 //purpose : Put token starting positions in theFields until '\n' or '\0'
125 // Return the number of the found tokens
126 //=======================================================================
128 int readLine (list <const char*> & theFields,
129 const char* & theLineBeg,
130 const bool theClearFields )
132 if ( theClearFields )
137 /* switch ( symbol ) { */
138 /* case white-space: */
139 /* look for a non-space symbol; */
140 /* case string-end: */
143 /* case comment beginning: */
144 /* skip all till a line-end; */
146 /* put its position in theFields, skip till a white-space;*/
152 bool stopReading = false;
155 bool isNumber = false;
156 switch ( *theLineBeg )
158 case ' ': // white space
163 case '\n': // a line ends
164 stopReading = ( nbRead > 0 );
169 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
173 case '\0': // file ends
176 case '-': // real number
181 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
183 theFields.push_back( theLineBeg );
186 while (*theLineBeg != ' ' &&
187 *theLineBeg != '\n' &&
188 *theLineBeg != '\0');
192 return 0; // incorrect file format
198 } while ( !stopReading );
203 //=======================================================================
204 //function : isRealSeam
205 //purpose : return true if an EDGE encounters twice in a FACE
206 //=======================================================================
208 // bool isRealSeam( const TopoDS_Edge& e, const TopoDS_Face& f )
210 // if ( BRep_Tool::IsClosed( e, f ))
213 // for (TopExp_Explorer exp( f, TopAbs_EDGE ); exp.More(); exp.Next())
214 // if ( exp.Current().IsSame( e ))
221 //=======================================================================
223 //purpose : load VERTEXes and EDGEs in a map. Return nb loaded VERTEXes
224 //=======================================================================
226 int loadVE( const list< TopoDS_Edge > & eList,
227 TopTools_IndexedMapOfOrientedShape & map )
229 list< TopoDS_Edge >::const_iterator eIt = eList.begin();
232 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
235 map.Add( TopExp::FirstVertex( *eIt, true ));
236 bool added = ( nbV < map.Extent() );
237 if ( !added ) { // vertex encountered twice
238 // a seam vertex have two corresponding key points
239 map.Add( TopExp::FirstVertex( *eIt, true ).Reversed());
245 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
253 //=======================================================================
254 //function : SMESH_Pattern
256 //=======================================================================
258 SMESH_Pattern::SMESH_Pattern (): myToKeepNodes(false)
262 //=======================================================================
264 //purpose : Load a pattern from <theFile>
265 //=======================================================================
267 bool SMESH_Pattern::Load (const char* theFileContents)
269 Kernel_Utils::Localizer loc;
273 // ! This is a comment
274 // NB_POINTS ! 1 integer - the number of points in the pattern.
275 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
276 // X2 Y2 [Z2] ! the pattern dimension is defined by the number of coordinates
278 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
279 // ! elements description goes after all
280 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
285 const char* lineBeg = theFileContents;
286 list <const char*> fields;
287 const bool clearFields = true;
289 // NB_POINTS ! 1 integer - the number of points in the pattern.
291 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
292 MESSAGE("Error reading NB_POINTS");
293 return setErrorCode( ERR_READ_NB_POINTS );
295 int nbPoints = getInt( fields.front() );
297 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
299 // read the first point coordinates to define pattern dimension
300 int dim = readLine( fields, lineBeg, clearFields );
306 MESSAGE("Error reading points: wrong nb of coordinates");
307 return setErrorCode( ERR_READ_POINT_COORDS );
309 if ( nbPoints <= dim ) {
310 MESSAGE(" Too few points ");
311 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
314 // read the rest points
316 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
317 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
318 MESSAGE("Error reading points : wrong nb of coordinates ");
319 return setErrorCode( ERR_READ_POINT_COORDS );
321 // store point coordinates
322 myPoints.resize( nbPoints );
323 list <const char*>::iterator fIt = fields.begin();
324 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
326 TPoint & p = myPoints[ iPoint ];
327 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
329 double coord = getDouble( *fIt );
330 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
331 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
333 return setErrorCode( ERR_READ_3D_COORD );
335 p.myInitXYZ.SetCoord( iCoord, coord );
337 p.myInitUV.SetCoord( iCoord, coord );
341 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
344 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
345 MESSAGE("Error: missing key-points");
347 return setErrorCode( ERR_READ_NO_KEYPOINT );
350 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
352 int pointIndex = getInt( *fIt );
353 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
354 MESSAGE("Error: invalid point index " << pointIndex );
356 return setErrorCode( ERR_READ_BAD_INDEX );
358 if ( idSet.insert( pointIndex ).second ) // unique?
359 myKeyPointIDs.push_back( pointIndex );
363 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
365 while ( readLine( fields, lineBeg, clearFields ))
367 myElemPointIDs.push_back( TElemDef() );
368 TElemDef& elemPoints = myElemPointIDs.back();
369 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
371 int pointIndex = getInt( *fIt );
372 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
373 MESSAGE("Error: invalid point index " << pointIndex );
375 return setErrorCode( ERR_READ_BAD_INDEX );
377 elemPoints.push_back( pointIndex );
379 // check the nb of nodes in element
381 switch ( elemPoints.size() ) {
382 case 3: if ( !myIs2D ) Ok = false; break;
386 case 8: if ( myIs2D ) Ok = false; break;
390 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
392 return setErrorCode( ERR_READ_ELEM_POINTS );
395 if ( myElemPointIDs.empty() ) {
396 MESSAGE("Error: no elements");
398 return setErrorCode( ERR_READ_NO_ELEMS );
401 findBoundaryPoints(); // sort key-points
403 return setErrorCode( ERR_OK );
406 //=======================================================================
408 //purpose : Save the loaded pattern into the file <theFileName>
409 //=======================================================================
411 bool SMESH_Pattern::Save (ostream& theFile)
413 Kernel_Utils::Localizer loc;
416 MESSAGE(" Pattern not loaded ");
417 return setErrorCode( ERR_SAVE_NOT_LOADED );
420 theFile << "!!! SALOME Mesh Pattern file" << endl;
421 theFile << "!!!" << endl;
422 theFile << "!!! Nb of points:" << endl;
423 theFile << myPoints.size() << endl;
427 // theFile.width( 8 );
428 // theFile.setf(ios::fixed);// use 123.45 floating notation
429 // theFile.setf(ios::right);
430 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
431 // theFile.setf(ios::showpoint); // do not show trailing zeros
432 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
433 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
434 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
435 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
436 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
437 theFile << " !- " << i << endl; // point id to ease reading by a human being
441 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
442 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
443 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
444 theFile << " " << *kpIt;
445 if ( !myKeyPointIDs.empty() )
449 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
450 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
451 for ( ; epIt != myElemPointIDs.end(); epIt++ )
453 const TElemDef & elemPoints = *epIt;
454 TElemDef::const_iterator iIt = elemPoints.begin();
455 for ( ; iIt != elemPoints.end(); iIt++ )
456 theFile << " " << *iIt;
462 return setErrorCode( ERR_OK );
465 //=======================================================================
466 //function : sortBySize
467 //purpose : sort theListOfList by size
468 //=======================================================================
470 template<typename T> struct TSizeCmp {
471 bool operator ()( const list < T > & l1, const list < T > & l2 )
472 const { return l1.size() < l2.size(); }
475 template<typename T> void sortBySize( list< list < T > > & theListOfList )
477 if ( theListOfList.size() > 2 ) {
478 TSizeCmp< T > SizeCmp;
479 theListOfList.sort( SizeCmp );
483 //=======================================================================
486 //=======================================================================
488 static gp_XY project (const SMDS_MeshNode* theNode,
489 Extrema_GenExtPS & theProjectorPS)
491 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
492 theProjectorPS.Perform( P );
493 if ( !theProjectorPS.IsDone() ) {
494 MESSAGE( "SMESH_Pattern: point projection FAILED");
497 double u =0, v =0, minVal = DBL_MAX;
498 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
499 if ( theProjectorPS.SquareDistance( i ) < minVal ) {
500 minVal = theProjectorPS.SquareDistance( i );
501 theProjectorPS.Point( i ).Parameter( u, v );
503 return gp_XY( u, v );
506 //=======================================================================
507 //function : areNodesBound
508 //purpose : true if all nodes of faces are bound to shapes
509 //=======================================================================
511 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
513 while ( faceItr->more() )
515 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
516 while ( nIt->more() )
518 const SMDS_MeshNode* node = smdsNode( nIt->next() );
519 if (node->getshapeId() <1) {
527 //=======================================================================
528 //function : isMeshBoundToShape
529 //purpose : return true if all 2d elements are bound to shape
530 // if aFaceSubmesh != NULL, then check faces bound to it
531 // else check all faces in aMeshDS
532 //=======================================================================
534 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
535 SMESHDS_SubMesh * aFaceSubmesh,
536 const bool isMainShape)
538 if ( isMainShape && aFaceSubmesh ) {
539 // check that all faces are bound to aFaceSubmesh
540 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
544 // check face nodes binding
545 if ( aFaceSubmesh ) {
546 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
547 return areNodesBound( fIt );
549 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
550 return areNodesBound( fIt );
553 //=======================================================================
555 //purpose : Create a pattern from the mesh built on <theFace>.
556 // <theProject>==true makes override nodes positions
557 // on <theFace> computed by mesher
558 //=======================================================================
560 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
561 const TopoDS_Face& theFace,
563 TopoDS_Vertex the1stVertex,
568 myToKeepNodes = theKeepNodes;
570 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
571 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
572 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
573 SMESH_MesherHelper helper( *theMesh );
574 helper.SetSubShape( theFace );
576 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
577 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
578 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
580 MESSAGE( "No elements bound to the face");
581 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
584 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
586 // check if face is closed
587 bool isClosed = helper.HasSeam();
588 list<TopoDS_Edge> eList;
589 list<TopoDS_Edge>::iterator elIt;
590 SMESH_Block::GetOrderedEdges( face, eList, myNbKeyPntInBoundary, the1stVertex );
592 // check that requested or needed projection is possible
593 bool isMainShape = theMesh->IsMainShape( face );
594 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
595 bool canProject = ( nbElems ? true : isMainShape );
597 canProject = false; // so far
599 if ( ( theProject || needProject ) && !canProject )
600 return setErrorCode( ERR_LOADF_CANT_PROJECT );
602 Extrema_GenExtPS projector;
603 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
604 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
607 TNodePointIDMap nodePointIDMap;
608 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
612 // ---------------------------------------------------------------
613 // The case where the submesh is projected to theFace
614 // ---------------------------------------------------------------
617 SMDS_ElemIteratorPtr fIt;
619 fIt = fSubMesh->GetElements();
621 fIt = aMeshDS->elementsIterator( SMDSAbs_Face );
623 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
624 while ( fIt->more() )
626 const SMDS_MeshElement* face = fIt->next();
627 myElemPointIDs.push_back( TElemDef() );
628 TElemDef& elemPoints = myElemPointIDs.back();
629 int nbNodes = face->NbCornerNodes();
630 for ( int i = 0;i < nbNodes; ++i )
632 const SMDS_MeshElement* node = face->GetNode( i );
633 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
634 if ( nIdIt->second == -1 )
635 nIdIt->second = iPoint++;
636 elemPoints.push_back( (*nIdIt).second );
639 myPoints.resize( iPoint );
641 // project all nodes of 2d elements to theFace
642 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
643 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
645 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
646 TPoint * p = & myPoints[ (*nIdIt).second ];
647 p->myInitUV = project( node, projector );
648 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
650 // find key-points: the points most close to UV of vertices
651 TopExp_Explorer vExp( face, TopAbs_VERTEX );
652 set<int> foundIndices;
653 for ( ; vExp.More(); vExp.Next() ) {
654 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
655 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
656 double minDist = DBL_MAX;
658 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
659 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
660 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
661 if ( dist < minDist ) {
666 if ( foundIndices.insert( index ).second ) // unique?
667 myKeyPointIDs.push_back( index );
669 myIsBoundaryPointsFound = false;
674 // ---------------------------------------------------------------------
675 // The case where a pattern is being made from the mesh built by mesher
676 // ---------------------------------------------------------------------
678 // Load shapes in the consequent order and count nb of points
680 loadVE( eList, myShapeIDMap );
681 myShapeIDMap.Add( face );
683 nbNodes += myShapeIDMap.Extent() - 1;
685 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
686 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
687 nbNodes += eSubMesh->NbNodes() + 1;
689 myPoints.resize( nbNodes );
691 // care of INTERNAL VERTEXes
692 TopExp_Explorer vExp( face, TopAbs_VERTEX, TopAbs_EDGE );
693 for ( ; vExp.More(); vExp.Next() )
695 const SMDS_MeshNode* node =
696 SMESH_Algo::VertexNode( TopoDS::Vertex( vExp.Current()), aMeshDS );
697 if ( !node || node->NbInverseElements( SMDSAbs_Face ) == 0 )
699 myPoints.resize( ++nbNodes );
700 list< TPoint* > & fPoints = getShapePoints( face );
701 nodePointIDMap.insert( make_pair( node, iPoint ));
702 TPoint* p = &myPoints[ iPoint++ ];
703 fPoints.push_back( p );
704 gp_XY uv = helper.GetNodeUV( face, node );
705 p->myInitUV.SetCoord( uv.X(), uv.Y() );
706 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
709 // Load U of points on edges
711 Bnd_Box2d edgesUVBox;
713 list<int>::iterator nbEinW = myNbKeyPntInBoundary.begin();
715 vector< TopoDS_Edge > eVec;
716 for ( elIt = eList.begin(); elIt != eList.end(); elIt++, iE++ )
718 if ( isClosed && ( iE == 0 || iE == *nbEinW ))
720 // new wire begins; put wire EDGEs in eVec
721 list<TopoDS_Edge>::iterator eEnd = elIt;
724 std::advance( eEnd, *nbEinW );
725 eVec.assign( elIt, eEnd );
728 TopoDS_Edge & edge = *elIt;
729 list< TPoint* > & ePoints = getShapePoints( edge );
731 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
732 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
734 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
735 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
736 // to make adjacent edges share key-point, we make v2 FORWARD too
737 // (as we have different points for same shape with different orientation)
740 // on closed face we must have REVERSED some of seam vertices
742 if ( helper.IsSeamShape( edge ) ) {
743 if ( helper.IsRealSeam( edge ) && !isForward ) {
744 // reverse on reversed SEAM edge
749 else { // on CLOSED edge (i.e. having one vertex with different orientations)
750 for ( int is2 = 0; is2 < 2; ++is2 ) {
751 TopoDS_Shape & v = is2 ? v2 : v1;
752 if ( helper.IsRealSeam( v ) ) {
753 // reverse or not depending on orientation of adjacent seam
754 int iSeam = helper.WrapIndex( iE + ( is2 ? +1 : -1 ), eVec.size() );
755 if ( eVec[ iSeam ].Orientation() == TopAbs_REVERSED )
762 // the forward key-point
763 list< TPoint* > * vPoint = & getShapePoints( v1 );
764 if ( vPoint->empty() )
766 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
767 if ( vSubMesh && vSubMesh->NbNodes() ) {
768 myKeyPointIDs.push_back( iPoint );
769 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
770 const SMDS_MeshNode* node = nIt->next();
771 if ( v1.Orientation() == TopAbs_REVERSED )
772 closeNodePointIDMap.insert( make_pair( node, iPoint ));
774 nodePointIDMap.insert( make_pair( node, iPoint ));
776 TPoint* keyPoint = &myPoints[ iPoint++ ];
777 vPoint->push_back( keyPoint );
779 keyPoint->myInitUV = project( node, projector );
781 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
782 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
783 edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
786 if ( !vPoint->empty() )
787 ePoints.push_back( vPoint->front() );
790 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
791 if ( eSubMesh && eSubMesh->NbNodes() )
793 // loop on nodes of an edge: sort them by param on edge
794 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
795 TParamNodeMap paramNodeMap;
796 int nbMeduimNodes = 0;
797 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
798 while ( nIt->more() )
800 const SMDS_MeshNode* node = nIt->next();
801 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
805 SMDS_EdgePositionPtr epos = node->GetPosition();
806 double u = epos->GetUParameter();
807 paramNodeMap.insert( make_pair( u, node ));
809 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes ) {
810 // wrong U on edge, project
812 BRepAdaptor_Curve aCurve( edge );
813 proj.Initialize( aCurve, f, l );
814 paramNodeMap.clear();
815 nIt = eSubMesh->GetNodes();
816 for ( int iNode = 0; nIt->more(); ++iNode ) {
817 const SMDS_MeshNode* node = nIt->next();
818 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
820 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
822 if ( proj.IsDone() ) {
823 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
824 if ( proj.IsMin( i )) {
825 u = proj.Point( i ).Parameter();
829 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
831 paramNodeMap.insert( make_pair( u, node ));
834 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
835 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
836 return setErrorCode(ERR_UNEXPECTED);
839 // put U in [0,1] so that the first key-point has U==0
840 bool isSeam = helper.IsRealSeam( edge );
842 TParamNodeMap::iterator unIt = paramNodeMap.begin();
843 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
844 while ( unIt != paramNodeMap.end() )
846 TPoint* p = & myPoints[ iPoint ];
847 ePoints.push_back( p );
848 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
849 if ( isSeam && !isForward )
850 closeNodePointIDMap.insert( make_pair( node, iPoint ));
852 nodePointIDMap.insert ( make_pair( node, iPoint ));
855 p->myInitUV = project( node, projector );
857 double u = isForward ? (*unIt).first : (*unRIt).first;
858 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
859 p->myInitUV = C2d->Value( u ).XY();
861 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
862 edgesUVBox.Add( gp_Pnt2d( p->myInitUV ));
867 // the reverse key-point
868 vPoint = & getShapePoints( v2 );
869 if ( vPoint->empty() )
871 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
872 if ( vSubMesh && vSubMesh->NbNodes() ) {
873 myKeyPointIDs.push_back( iPoint );
874 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
875 const SMDS_MeshNode* node = nIt->next();
876 if ( v2.Orientation() == TopAbs_REVERSED )
877 closeNodePointIDMap.insert( make_pair( node, iPoint ));
879 nodePointIDMap.insert( make_pair( node, iPoint ));
881 TPoint* keyPoint = &myPoints[ iPoint++ ];
882 vPoint->push_back( keyPoint );
884 keyPoint->myInitUV = project( node, projector );
886 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
887 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
888 edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
891 if ( !vPoint->empty() )
892 ePoints.push_back( vPoint->front() );
894 // compute U of edge-points
897 double totalDist = 0;
898 list< TPoint* >::iterator pIt = ePoints.begin();
899 TPoint* prevP = *pIt;
900 prevP->myInitU = totalDist;
901 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
903 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
904 p->myInitU = totalDist;
907 if ( totalDist > DBL_MIN)
908 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
910 p->myInitU /= totalDist;
913 } // loop on edges of a wire
915 // Load in-face points and elements
917 if ( fSubMesh && fSubMesh->NbElements() )
919 list< TPoint* > & fPoints = getShapePoints( face );
920 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
921 while ( nIt->more() )
923 const SMDS_MeshNode* node = nIt->next();
924 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
926 nodePointIDMap.insert( make_pair( node, iPoint ));
927 TPoint* p = &myPoints[ iPoint++ ];
928 fPoints.push_back( p );
929 if ( theProject || edgesUVBox.IsOut( p->myInitUV ) )
930 p->myInitUV = project( node, projector );
932 SMDS_FacePositionPtr pos = node->GetPosition();
933 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
935 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
938 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
939 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
940 while ( elemIt->more() )
942 const SMDS_MeshElement* elem = elemIt->next();
943 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
944 myElemPointIDs.push_back( TElemDef() );
945 TElemDef& elemPoints = myElemPointIDs.back();
946 // find point indices corresponding to element nodes
947 while ( nIt->more() )
949 const SMDS_MeshNode* node = smdsNode( nIt->next() );
950 n_id = nodePointIDMap.find( node );
951 if ( n_id == nodePointIDMap.end() )
952 continue; // medium node
953 iPoint = n_id->second; // point index of interest
954 // for a node on a seam edge there are two points
955 if ( helper.IsRealSeam( node->getshapeId() ) &&
956 ( n_id = closeNodePointIDMap.find( node )) != not_found )
958 TPoint & p1 = myPoints[ iPoint ];
959 TPoint & p2 = myPoints[ n_id->second ];
960 // Select point closest to the rest nodes of element in UV space
961 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
962 const SMDS_MeshNode* notSeamNode = 0;
963 // find node not on a seam edge
964 while ( nIt2->more() && !notSeamNode ) {
965 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
966 if ( !helper.IsSeamShape( n->getshapeId() ))
969 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
970 double dist1 = uv.SquareDistance( p1.myInitUV );
971 double dist2 = uv.SquareDistance( p2.myInitUV );
973 iPoint = n_id->second;
975 elemPoints.push_back( iPoint );
979 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
981 myIsBoundaryPointsFound = true;
986 myInNodes.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
988 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
989 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
990 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
992 nIdIt = closeNodePointIDMap.begin();
993 for ( ; nIdIt != closeNodePointIDMap.end(); nIdIt++ )
994 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
997 // Assure that U range is proportional to V range
1000 vector< TPoint >::iterator pVecIt = myPoints.begin();
1001 for ( ; pVecIt != myPoints.end(); pVecIt++ )
1002 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
1003 double minU, minV, maxU, maxV;
1004 bndBox.Get( minU, minV, maxU, maxV );
1005 double dU = maxU - minU, dV = maxV - minV;
1006 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
1009 // define where is the problem, in the face or in the mesh
1010 TopExp_Explorer vExp( face, TopAbs_VERTEX );
1011 for ( ; vExp.More(); vExp.Next() ) {
1012 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
1015 bndBox.Get( minU, minV, maxU, maxV );
1016 dU = maxU - minU, dV = maxV - minV;
1017 if ( dU <= DBL_MIN || dV <= DBL_MIN )
1019 return setErrorCode( ERR_LOADF_NARROW_FACE );
1021 // mesh is projected onto a line, e.g.
1022 return setErrorCode( ERR_LOADF_CANT_PROJECT );
1024 double ratio = dU / dV, maxratio = 3, scale;
1026 if ( ratio > maxratio ) {
1027 scale = ratio / maxratio;
1030 else if ( ratio < 1./maxratio ) {
1031 scale = maxratio / ratio;
1036 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
1037 TPoint & p = *pVecIt;
1038 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
1039 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
1042 if ( myElemPointIDs.empty() ) {
1043 MESSAGE( "No elements bound to the face");
1044 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
1047 return setErrorCode( ERR_OK );
1050 //=======================================================================
1051 //function : computeUVOnEdge
1052 //purpose : compute coordinates of points on theEdge
1053 //=======================================================================
1055 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
1056 const list< TPoint* > & ePoints )
1058 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
1060 Handle(Geom2d_Curve) C2d =
1061 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
1063 ePoints.back()->myInitU = 1.0;
1064 //ePoints.front()->myInitU = 0.0; //myUV = C2d->Value( isForward ? f : l ).XY();
1065 list< TPoint* >::const_iterator pIt = ePoints.begin();
1066 for ( pIt++; pIt != ePoints.end(); pIt++ )
1068 TPoint* point = *pIt;
1070 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1071 point->myU = ( f * ( 1 - du ) + l * du );
1073 point->myUV = C2d->Value( point->myU ).XY();
1077 //=======================================================================
1078 //function : intersectIsolines
1080 //=======================================================================
1082 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1083 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1087 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1088 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1089 resUV = 0.5 * ( loc1 + loc2 );
1090 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1091 // SKL 26.07.2007 for NPAL16567
1092 double d1 = (uv11-uv12).Modulus();
1093 double d2 = (uv21-uv22).Modulus();
1094 // double delta = d1*d2*1e-6; PAL17233
1095 double delta = min( d1, d2 ) / 10.;
1096 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1098 // double len1 = ( uv11 - uv12 ).Modulus();
1099 // double len2 = ( uv21 - uv22 ).Modulus();
1100 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1104 // gp_Lin2d line1( uv11, uv12 - uv11 );
1105 // gp_Lin2d line2( uv21, uv22 - uv21 );
1106 // double angle = Abs( line1.Angle( line2 ) );
1108 // IntAna2d_AnaIntersection inter;
1109 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1110 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1112 // gp_Pnt2d interUV = inter.Point(1).Value();
1113 // resUV += interUV.XY();
1114 // inter.Perform( line1, line2 );
1115 // interUV = inter.Point(1).Value();
1116 // resUV += interUV.XY();
1120 // if ( isDeformed ) {
1121 // MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1122 // ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1127 //=======================================================================
1128 //function : compUVByIsoIntersection
1130 //=======================================================================
1132 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1133 const gp_XY& theInitUV,
1135 bool & theIsDeformed )
1137 // compute UV by intersection of 2 iso lines
1138 //gp_Lin2d isoLine[2];
1139 gp_XY uv1[2], uv2[2];
1141 const double zero = DBL_MIN;
1142 for ( int iIso = 0; iIso < 2; iIso++ )
1144 // to build an iso line:
1145 // find 2 pairs of consequent edge-points such that the range of their
1146 // initial parameters encloses the in-face point initial parameter
1147 gp_XY UV[2], initUV[2];
1148 int nbUV = 0, iCoord = iIso + 1;
1149 double initParam = theInitUV.Coord( iCoord );
1151 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1152 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1154 const list< TPoint* > & bndPoints = * bndIt;
1155 TPoint* prevP = bndPoints.back(); // this is the first point
1156 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1157 bool coincPrev = false;
1158 // loop on the edge-points
1159 for ( ; pIt != bndPoints.end(); pIt++ )
1161 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1162 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1163 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1164 if (!coincPrev && // ignore if initParam coincides with prev point param
1165 sumOfDiff > zero && // ignore if both points coincide with initParam
1166 prevParamDiff * paramDiff <= zero )
1168 // find UV in parametric space of theFace
1169 double r = Abs(prevParamDiff) / sumOfDiff;
1170 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1173 // throw away uv most distant from <theInitUV>
1174 gp_XY vec0 = initUV[0] - theInitUV;
1175 gp_XY vec1 = initUV[1] - theInitUV;
1176 gp_XY vec = uvInit - theInitUV;
1177 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1178 double dist0 = vec0.SquareModulus();
1179 double dist1 = vec1.SquareModulus();
1180 double dist = vec .SquareModulus();
1181 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1182 i = ( dist0 < dist1 ? 1 : 0 );
1183 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1184 i = 3; // theInitUV must remain between
1188 initUV[ i ] = uvInit;
1189 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1191 coincPrev = ( Abs(paramDiff) <= zero );
1198 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1199 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1200 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1201 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1203 // an iso line should be normal to UV[0] - UV[1] direction
1204 // and be located at the same relative distance as from initial ends
1205 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1207 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1208 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1209 //isoLine[ iIso ] = iso.Normal( isoLoc );
1210 uv1[ iIso ] = UV[0];
1211 uv2[ iIso ] = UV[1];
1214 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1215 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1216 MESSAGE(" Can't intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1217 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1224 // ==========================================================
1225 // structure representing a node of a grid of iso-poly-lines
1226 // ==========================================================
1233 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1234 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1235 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1236 TIsoNode(double initU, double initV):
1237 myIsMovable(true), myInitUV( initU, initV ), myUV( 1e100, 1e100 )
1238 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1239 bool IsUVComputed() const
1240 { return myUV.X() != 1e100; }
1241 bool IsMovable() const
1242 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1243 void SetNotMovable()
1244 { myIsMovable = false; }
1245 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1246 { myBndNodes[ iDir + i * 2 ] = node; }
1247 TIsoNode* GetBoundaryNode(int iDir, int i)
1248 { return myBndNodes[ iDir + i * 2 ]; }
1249 void SetNext(TIsoNode* node, int iDir, int isForward)
1250 { myNext[ iDir + isForward * 2 ] = node; }
1251 TIsoNode* GetNext(int iDir, int isForward)
1252 { return myNext[ iDir + isForward * 2 ]; }
1255 //=======================================================================
1256 //function : getNextNode
1258 //=======================================================================
1260 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1262 TIsoNode* n = node->myNext[ dir ];
1263 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1264 n = 0;//node->myBndNodes[ dir ];
1265 // MESSAGE("getNextNode: use bnd for node "<<
1266 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1270 //=======================================================================
1271 //function : checkQuads
1272 //purpose : check if newUV destortes quadrangles around node,
1273 // and if ( crit == FIX_OLD ) fix newUV in this case
1274 //=======================================================================
1276 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1278 static bool checkQuads (const TIsoNode* node,
1280 const bool reversed,
1281 const int crit = FIX_OLD,
1282 double fixSize = 0.)
1284 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1285 int nbOldFix = 0, nbOldImpr = 0;
1286 double newBadRate = 0, oldBadRate = 0;
1287 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1288 int i, dir1 = 0, dir2 = 3;
1289 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1291 if ( dir2 > 3 ) dir2 = 0;
1293 // walking counterclockwise around a quad,
1294 // nodes are in the order: node, n[0], n[1], n[2]
1295 n[0] = getNextNode( node, dir1 );
1296 n[2] = getNextNode( node, dir2 );
1297 if ( !n[0] || !n[2] ) continue;
1298 n[1] = getNextNode( n[0], dir2 );
1299 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1300 bool isTriangle = ( !n[1] );
1302 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1304 // if ( fixSize != 0 ) {
1305 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1306 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1307 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1308 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1310 // check if a quadrangle is degenerated
1312 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1313 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1316 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1319 // find min size of the diagonal node-n[1]
1320 double minDiag = fixSize;
1321 if ( minDiag == 0. ) {
1322 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1323 if ( !isTriangle ) {
1324 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1325 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1327 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1328 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1331 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1332 // ( behind means "to the right of")
1334 // 1. newUV is not behind 01 and 12 dirs
1335 // 2. or newUV is not behind 02 dir and n[2] is convex
1336 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1337 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1338 gp_Vec2d moveVec[3], outVec[3];
1339 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1341 bool isDiag = ( i == 2 );
1342 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1346 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1348 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1350 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1352 gp_Vec2d newDir( n[i]->myUV, newUV );
1353 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1355 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1356 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1357 if ( crit == FIX_OLD ) {
1358 wasIn[i] = ( outDir * oldDir < 0 );
1359 wasOk[i] = ( outDir * oldDir < -minDiag );
1361 newBadRate += outDir * newDir;
1363 oldBadRate += outDir * oldDir;
1366 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1367 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1368 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1369 moveVec[i] = ( oldDist - minDiag ) * outDir;
1374 // check if n[2] is convex
1377 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1379 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1380 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1381 newIsOk = ( newIsOk && isNewOk );
1382 newIsIn = ( newIsIn && isNewIn );
1384 if ( crit != FIX_OLD ) {
1385 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1386 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1390 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1391 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1392 oldIsIn = ( oldIsIn && isOldIn );
1393 oldIsOk = ( oldIsOk && isOldIn );
1396 if ( !isOldIn ) { // node is outside a quadrangle
1397 // move newUV inside a quadrangle
1398 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1399 // node and newUV are outside: push newUV inside
1401 if ( convex || isTriangle ) {
1402 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1405 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1406 double outSize = out.Magnitude();
1407 if ( outSize > DBL_MIN )
1410 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1411 uv = n[1]->myUV - minDiag * out.XY();
1413 oldUVFixed[ nbOldFix++ ] = uv;
1414 //node->myUV = newUV;
1416 else if ( !isOldOk ) {
1417 // try to fix old UV: move node inside as less as possible
1418 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1419 gp_XY uv1, uv2 = node->myUV;
1420 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1422 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1423 while ( !isOldOk ) {
1424 // find the least moveVec
1426 double minMove2 = 1e100;
1427 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1429 if ( moveVec[i].Coord(1) < 1e100 ) {
1430 double move2 = moveVec[i].SquareMagnitude();
1431 if ( move2 < minMove2 ) {
1440 // move node to newUV
1441 uv1 = node->myUV + moveVec[ iMin ].XY();
1442 uv2 += moveVec[ iMin ].XY();
1443 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1444 // check if uv1 is ok
1445 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1446 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1447 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1449 oldUVImpr[ nbOldImpr++ ] = uv1;
1451 // check if uv2 is ok
1452 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1453 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1454 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1456 oldUVImpr[ nbOldImpr++ ] = uv2;
1461 } // loop on 4 quadrangles around <node>
1463 if ( crit == CHECK_NEW_OK )
1465 if ( crit == CHECK_NEW_IN )
1474 if ( oldIsIn && nbOldImpr ) {
1475 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1476 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1477 gp_XY uv = oldUVImpr[ 0 ];
1478 for ( int i = 1; i < nbOldImpr; i++ )
1479 uv += oldUVImpr[ i ];
1481 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1486 //MESSAGE(" Can't improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1489 if ( !oldIsIn && nbOldFix ) {
1490 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1491 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1492 gp_XY uv = oldUVFixed[ 0 ];
1493 for ( int i = 1; i < nbOldFix; i++ )
1494 uv += oldUVFixed[ i ];
1496 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1501 //MESSAGE(" Can't fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1504 if ( newIsIn && oldIsIn )
1505 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1506 else if ( !newIsIn )
1513 //=======================================================================
1514 //function : compUVByElasticIsolines
1515 //purpose : compute UV as nodes of iso-poly-lines consisting of
1516 // segments keeping relative size as in the pattern
1517 //=======================================================================
1518 //#define DEB_COMPUVBYELASTICISOLINES
1519 bool SMESH_Pattern::
1520 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1521 const list< TPoint* >& thePntToCompute)
1523 return false; // PAL17233
1524 //cout << "============================== KEY POINTS =============================="<<endl;
1525 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1526 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1527 // TPoint& p = myPoints[ *kpIt ];
1528 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1529 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1531 //cout << "=============================="<<endl;
1533 // Define parameters of iso-grid nodes in U and V dir
1535 set< double > paramSet[ 2 ];
1536 list< list< TPoint* > >::const_iterator pListIt;
1537 list< TPoint* >::const_iterator pIt;
1538 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1539 const list< TPoint* > & pList = * pListIt;
1540 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1541 paramSet[0].insert( (*pIt)->myInitUV.X() );
1542 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1545 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1546 paramSet[0].insert( (*pIt)->myInitUV.X() );
1547 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1549 // unite close parameters and split too long segments
1552 for ( iDir = 0; iDir < 2; iDir++ )
1554 set< double > & params = paramSet[ iDir ];
1555 double range = ( *params.rbegin() - *params.begin() );
1556 double toler = range / 1e6;
1557 tol[ iDir ] = toler;
1558 // double maxSegment = range / params.size() / 2.;
1560 // set< double >::iterator parIt = params.begin();
1561 // double prevPar = *parIt;
1562 // for ( parIt++; parIt != params.end(); parIt++ )
1564 // double segLen = (*parIt) - prevPar;
1565 // if ( segLen < toler )
1566 // ;//params.erase( prevPar ); // unite
1567 // else if ( segLen > maxSegment )
1568 // params.insert( prevPar + 0.5 * segLen ); // split
1569 // prevPar = (*parIt);
1573 // Make nodes of a grid of iso-poly-lines
1575 list < TIsoNode > nodes;
1576 typedef list < TIsoNode *> TIsoLine;
1577 map < double, TIsoLine > isoMap[ 2 ];
1579 set< double > & params0 = paramSet[ 0 ];
1580 set< double >::iterator par0It = params0.begin();
1581 for ( ; par0It != params0.end(); par0It++ )
1583 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1584 set< double > & params1 = paramSet[ 1 ];
1585 set< double >::iterator par1It = params1.begin();
1586 for ( ; par1It != params1.end(); par1It++ )
1588 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1589 isoLine0.push_back( & nodes.back() );
1590 isoMap[1][ *par1It ].push_back( & nodes.back() );
1594 // Compute intersections of boundaries with iso-lines:
1595 // only boundary nodes will have computed UV so far
1598 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1599 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1600 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1602 const list< TPoint* > & bndPoints = * bndIt;
1603 TPoint* prevP = bndPoints.back(); // this is the first point
1604 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1605 // loop on the edge-points
1606 for ( ; pIt != bndPoints.end(); pIt++ )
1608 TPoint* point = *pIt;
1609 for ( iDir = 0; iDir < 2; iDir++ )
1611 const int iCoord = iDir + 1;
1612 const int iOtherCoord = 2 - iDir;
1613 double par1 = prevP->myInitUV.Coord( iCoord );
1614 double par2 = point->myInitUV.Coord( iCoord );
1615 double parDif = par2 - par1;
1616 if ( Abs( parDif ) <= DBL_MIN )
1618 // find iso-lines intersecting a bounadry
1619 double toler = tol[ 1 - iDir ];
1620 double minPar = Min ( par1, par2 );
1621 double maxPar = Max ( par1, par2 );
1622 map < double, TIsoLine >& isos = isoMap[ iDir ];
1623 map < double, TIsoLine >::iterator isoIt = isos.begin();
1624 for ( ; isoIt != isos.end(); isoIt++ )
1626 double isoParam = (*isoIt).first;
1627 if ( isoParam < minPar || isoParam > maxPar )
1629 double r = ( isoParam - par1 ) / parDif;
1630 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1631 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1632 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1633 // find existing node with otherPar or insert a new one
1634 TIsoLine & isoLine = (*isoIt).second;
1636 TIsoLine::iterator nIt = isoLine.begin();
1637 for ( ; nIt != isoLine.end(); nIt++ ) {
1638 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1639 if ( nodePar >= otherPar )
1643 if ( Abs( nodePar - otherPar ) <= toler )
1644 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1646 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1647 node = & nodes.back();
1648 isoLine.insert( nIt, node );
1650 node->SetNotMovable();
1652 uvBnd.Add( gp_Pnt2d( uv ));
1653 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1655 gp_XY tgt( point->myUV - prevP->myUV );
1656 if ( ::IsEqual( r, 1. ))
1657 node->myDir[ 0 ] = tgt;
1658 else if ( ::IsEqual( r, 0. ))
1659 node->myDir[ 1 ] = tgt;
1661 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1662 // keep boundary nodes corresponding to boundary points
1663 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1664 if ( bndNodes.empty() || bndNodes.back() != node )
1665 bndNodes.push_back( node );
1666 } // loop on isolines
1667 } // loop on 2 directions
1669 } // loop on boundary points
1670 } // loop on boundaries
1672 // Define orientation
1674 // find the point with the least X
1675 double leastX = DBL_MAX;
1676 TIsoNode * leftNode;
1677 list < TIsoNode >::iterator nodeIt = nodes.begin();
1678 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1679 TIsoNode & node = *nodeIt;
1680 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1681 leastX = node.myUV.X();
1684 // if ( node.IsUVComputed() ) {
1685 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1686 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1687 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1688 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1691 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1692 //SCRUTE( reversed );
1694 // Prepare internal nodes:
1696 // 2. compute ratios
1697 // 3. find boundary nodes for each node
1698 // 4. remove nodes out of the boundary
1699 for ( iDir = 0; iDir < 2; iDir++ )
1701 const int iCoord = 2 - iDir; // coord changing along an isoline
1702 map < double, TIsoLine >& isos = isoMap[ iDir ];
1703 map < double, TIsoLine >::iterator isoIt = isos.begin();
1704 for ( ; isoIt != isos.end(); isoIt++ )
1706 TIsoLine & isoLine = (*isoIt).second;
1707 bool firstCompNodeFound = false;
1708 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1709 nPrevIt = nIt = nNextIt = isoLine.begin();
1711 nNextIt++; nNextIt++;
1712 while ( nIt != isoLine.end() )
1714 // 1. connect prev - cur
1715 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1716 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1717 firstCompNodeFound = true;
1718 lastCompNodePos = nPrevIt;
1720 if ( firstCompNodeFound ) {
1721 node->SetNext( prevNode, iDir, 0 );
1722 prevNode->SetNext( node, iDir, 1 );
1725 if ( nNextIt != isoLine.end() ) {
1726 double par1 = prevNode->myInitUV.Coord( iCoord );
1727 double par2 = node->myInitUV.Coord( iCoord );
1728 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1729 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1731 // 3. find boundary nodes
1732 if ( node->IsUVComputed() )
1733 lastCompNodePos = nIt;
1734 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1735 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1736 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1737 if ( (*nIt2)->IsUVComputed() )
1739 if ( nIt2 != isoLine.end() ) {
1741 node->SetBoundaryNode( bndNode1, iDir, 0 );
1742 node->SetBoundaryNode( bndNode2, iDir, 1 );
1743 // cout << "--------------------------------------------------"<<endl;
1744 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1745 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1746 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1747 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1748 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1749 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1752 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1753 node->SetBoundaryNode( 0, iDir, 0 );
1754 node->SetBoundaryNode( 0, iDir, 1 );
1758 if ( nNextIt != isoLine.end() ) nNextIt++;
1759 // 4. remove nodes out of the boundary
1760 if ( !firstCompNodeFound )
1761 isoLine.pop_front();
1762 } // loop on isoLine nodes
1764 // remove nodes after the boundary
1765 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1766 // (*nIt)->SetNotMovable();
1767 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1768 } // loop on isolines
1769 } // loop on 2 directions
1771 // Compute local isoline direction for internal nodes
1774 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1775 map < double, TIsoLine >::iterator isoIt = isos.begin();
1776 for ( ; isoIt != isos.end(); isoIt++ )
1778 TIsoLine & isoLine = (*isoIt).second;
1779 TIsoLine::iterator nIt = isoLine.begin();
1780 for ( ; nIt != isoLine.end(); nIt++ )
1782 TIsoNode* node = *nIt;
1783 if ( node->IsUVComputed() || !node->IsMovable() )
1785 gp_Vec2d aTgt[2], aNorm[2];
1788 for ( iDir = 0; iDir < 2; iDir++ )
1790 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1791 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1792 if ( !bndNode1 || !bndNode2 ) {
1796 const int iCoord = 2 - iDir; // coord changing along an isoline
1797 double par1 = bndNode1->myInitUV.Coord( iCoord );
1798 double par2 = node->myInitUV.Coord( iCoord );
1799 double par3 = bndNode2->myInitUV.Coord( iCoord );
1800 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1802 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1803 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1804 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1805 else tgt1.Reverse();
1806 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1808 if ( ratio[ iDir ] < 0.5 )
1809 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1811 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1813 aNorm[ iDir ].Reverse(); // along iDir isoline
1815 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1816 // maybe angle is more than |PI|
1817 if ( Abs( angle ) > PI / 2. ) {
1818 // check direction of the last but one perpendicular isoline
1819 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1820 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1821 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1822 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1823 if ( isoDir * tgt2 < 0 )
1825 double angle2 = tgt1.Angle( isoDir );
1826 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1827 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1828 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1829 //MESSAGE("REVERSE ANGLE");
1832 if ( Abs( angle2 ) > Abs( angle ) ||
1833 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1834 //MESSAGE("Add PI");
1835 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1836 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1837 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1838 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1839 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1840 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1843 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1847 for ( iDir = 0; iDir < 2; iDir++ )
1849 aTgt[iDir].Normalize();
1850 aNorm[1-iDir].Normalize();
1851 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1854 node->myDir[iDir] = //aTgt[iDir];
1855 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1857 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1858 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1859 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1860 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1862 } // loop on iso nodes
1863 } // loop on isolines
1865 // Find nodes to start computing UV from
1867 list< TIsoNode* > startNodes;
1868 list< TIsoNode* >::iterator nIt = bndNodes.end();
1869 TIsoNode* node = *(--nIt);
1870 TIsoNode* prevNode = *(--nIt);
1871 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1873 TIsoNode* nextNode = *nIt;
1874 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1875 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1876 double initAngle = initTgt1.Angle( initTgt2 );
1877 double angle = node->myDir[0].Angle( node->myDir[1] );
1878 if ( reversed ) angle = -angle;
1879 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1880 // find a close internal node
1881 TIsoNode* nClose = 0;
1882 list< TIsoNode* > testNodes;
1883 testNodes.push_back( node );
1884 list< TIsoNode* >::iterator it = testNodes.begin();
1885 for ( ; !nClose && it != testNodes.end(); it++ )
1887 for (int i = 0; i < 4; i++ )
1889 nClose = (*it)->myNext[ i ];
1891 if ( !nClose->IsUVComputed() )
1894 testNodes.push_back( nClose );
1900 startNodes.push_back( nClose );
1901 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1902 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1903 // "initAngle: " << initAngle << " angle: " << angle << endl;
1904 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1905 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1906 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1907 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1913 // Compute starting UV of internal nodes
1915 list < TIsoNode* > internNodes;
1916 bool needIteration = true;
1917 if ( startNodes.empty() ) {
1918 //MESSAGE( " Starting UV by compUVByIsoIntersection()");
1919 needIteration = false;
1920 map < double, TIsoLine >& isos = isoMap[ 0 ];
1921 map < double, TIsoLine >::iterator isoIt = isos.begin();
1922 for ( ; isoIt != isos.end(); isoIt++ )
1924 TIsoLine & isoLine = (*isoIt).second;
1925 TIsoLine::iterator nIt = isoLine.begin();
1926 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1928 TIsoNode* node = *nIt;
1929 if ( !node->IsUVComputed() && node->IsMovable() ) {
1930 internNodes.push_back( node );
1932 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1933 node->myUV, needIteration ))
1934 node->myUV = node->myInitUV;
1938 if ( needIteration )
1939 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1941 TIsoNode* node = *nIt, *nClose = 0;
1942 list< TIsoNode* > testNodes;
1943 testNodes.push_back( node );
1944 list< TIsoNode* >::iterator it = testNodes.begin();
1945 for ( ; !nClose && it != testNodes.end(); it++ )
1947 for (int i = 0; i < 4; i++ )
1949 nClose = (*it)->myNext[ i ];
1951 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1954 testNodes.push_back( nClose );
1960 startNodes.push_back( nClose );
1964 double aMin[2], aMax[2], step[2];
1965 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1966 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1967 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1968 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1969 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1971 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1973 TIsoNode *node = *nIt;
1974 if ( node->IsUVComputed() || !node->IsMovable() )
1976 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1977 int nbComp = 0, nbPrev = 0;
1978 for ( iDir = 0; iDir < 2; iDir++ )
1980 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1981 TIsoNode* n = node->GetNext( iDir, 0 );
1982 if ( n->IsUVComputed() )
1985 startNodes.push_back( n );
1986 n = node->GetNext( iDir, 1 );
1987 if ( n->IsUVComputed() )
1990 startNodes.push_back( n );
1992 prevNode1 = prevNode2;
1995 if ( prevNode1 ) nbPrev++;
1996 if ( prevNode2 ) nbPrev++;
1999 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
2000 double par = node->myInitUV.Coord( 2 - iDir );
2001 bool isEnd = ( prevPar > par );
2002 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
2003 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2004 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
2006 MESSAGE("Why we are here?");
2009 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
2010 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
2011 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
2012 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
2013 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
2014 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
2015 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
2016 //" par: " << prevPar << endl;
2017 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
2018 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
2020 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2021 gp_XY & uv1 = prevNode1->myUV;
2022 gp_XY & uv2 = prevNode2->myUV;
2023 // dir = ( uv2 - uv1 );
2024 // double len = dir.Modulus();
2025 // if ( len > DBL_MIN )
2026 // dir /= len * 0.5;
2027 double r = node->myRatio[ iDir ];
2028 newUV += uv1 * ( 1 - r ) + uv2 * r;
2031 newUV += prevNode1->myUV + dir * step[ iDir ];
2037 if ( !nbComp ) continue;
2040 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2042 // check if a quadrangle is not distorted
2044 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
2045 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
2046 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
2047 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
2051 internNodes.push_back( node );
2056 static int maxNbIter = 100;
2057 #ifdef DEB_COMPUVBYELASTICISOLINES
2059 bool useNbMoveNode = 0;
2060 static int maxNbNodeMove = 100;
2063 if ( !useNbMoveNode )
2064 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2069 if ( !needIteration) break;
2070 #ifdef DEB_COMPUVBYELASTICISOLINES
2071 if ( nbIter >= maxNbIter ) break;
2074 list < TIsoNode* >::iterator nIt = internNodes.begin();
2075 for ( ; nIt != internNodes.end(); nIt++ ) {
2076 #ifdef DEB_COMPUVBYELASTICISOLINES
2078 cout << nbNodeMove <<" =================================================="<<endl;
2080 TIsoNode * node = *nIt;
2084 for ( iDir = 0; iDir < 2; iDir++ )
2086 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2087 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2088 double r = node->myRatio[ iDir ];
2089 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2090 // line[ iDir ].SetLocation( loc[ iDir ] );
2091 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2094 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2095 // double locR[2] = { 0, 0 };
2096 for ( iDir = 0; iDir < 2; iDir++ )
2098 const int iCoord = 2 - iDir; // coord changing along an isoline
2099 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2100 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2101 if ( !bndNode1 || !bndNode2 ) {
2104 double par1 = bndNode1->myInitUV.Coord( iCoord );
2105 double par2 = node->myInitUV.Coord( iCoord );
2106 double par3 = bndNode2->myInitUV.Coord( iCoord );
2107 double r = ( par2 - par1 ) / ( par3 - par1 );
2108 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2109 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2111 //locR[0] = locR[1] = 0.25;
2112 // intersect the 2 lines and move a node
2113 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2114 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2116 // double intR = 1 - locR[0] - locR[1];
2117 // gp_XY newUV = inter.Point(1).Value().XY();
2118 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2119 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2121 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2122 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2123 // avoid parallel isolines intersection
2124 checkQuads( node, newUV, reversed );
2126 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2128 } // intersection found
2129 #ifdef DEB_COMPUVBYELASTICISOLINES
2130 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2132 } // loop on internal nodes
2133 #ifdef DEB_COMPUVBYELASTICISOLINES
2134 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2136 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2138 //MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2140 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2141 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2142 #ifndef DEB_COMPUVBYELASTICISOLINES
2147 // Set computed UV to points
2149 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2150 TPoint* point = *pIt;
2151 //gp_XY oldUV = point->myUV;
2152 double minDist = DBL_MAX;
2153 list < TIsoNode >::iterator nIt = nodes.begin();
2154 for ( ; nIt != nodes.end(); nIt++ ) {
2155 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2156 if ( dist < minDist ) {
2158 point->myUV = (*nIt).myUV;
2167 //=======================================================================
2168 //function : setFirstEdge
2169 //purpose : choose the best first edge of theWire; return the summary distance
2170 // between point UV computed by isolines intersection and
2171 // eventual UV got from edge p-curves
2172 //=======================================================================
2174 //#define DBG_SETFIRSTEDGE
2175 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2177 int iE, nbEdges = theWire.size();
2181 // Transform UVs computed by iso to fit bnd box of a wire
2183 // max nb of points on an edge
2185 int eID = theFirstEdgeID;
2186 for ( iE = 0; iE < nbEdges; iE++ )
2187 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2189 // compute bnd boxes
2190 TopoDS_Face face = TopoDS::Face( myShape );
2191 Bnd_Box2d bndBox, eBndBox;
2192 eID = theFirstEdgeID;
2193 list< TopoDS_Edge >::iterator eIt;
2194 list< TPoint* >::iterator pIt;
2195 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2197 // UV by isos stored in TPoint.myXYZ
2198 list< TPoint* > & ePoints = getShapePoints( eID++ );
2199 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2201 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2203 // UV by an edge p-curve
2205 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2206 double dU = ( l - f ) / ( maxNbPnt - 1 );
2207 for ( int i = 0; i < maxNbPnt; i++ )
2208 eBndBox.Add( C2d->Value( f + i * dU ));
2211 // transform UVs by isos
2212 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2213 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2214 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2215 #ifdef DBG_SETFIRSTEDGE
2216 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2217 << eMinPar[1] << " - " << eMaxPar[1] );
2219 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2221 double dMin = eMinPar[i] - minPar[i];
2222 double dMax = eMaxPar[i] - maxPar[i];
2223 double dPar = maxPar[i] - minPar[i];
2224 eID = theFirstEdgeID;
2225 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2227 list< TPoint* > & ePoints = getShapePoints( eID++ );
2228 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2230 double par = (*pIt)->myXYZ.Coord( iC );
2231 double r = ( par - minPar[i] ) / dPar;
2232 par += ( 1 - r ) * dMin + r * dMax;
2233 (*pIt)->myXYZ.SetCoord( iC, par );
2239 double minDist = DBL_MAX;
2240 for ( iE = 0 ; iE < nbEdges; iE++ )
2242 #ifdef DBG_SETFIRSTEDGE
2243 MESSAGE ( " VARIANT " << iE );
2245 // evaluate the distance between UV computed by the 2 methods:
2246 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2248 int eID = theFirstEdgeID;
2249 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2251 list< TPoint* > & ePoints = getShapePoints( eID++ );
2252 computeUVOnEdge( *eIt, ePoints );
2253 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2255 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2256 #ifdef DBG_SETFIRSTEDGE
2257 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2258 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2262 #ifdef DBG_SETFIRSTEDGE
2263 MESSAGE ( "dist -- " << dist );
2265 if ( dist < minDist ) {
2267 eBest = theWire.front();
2269 // check variant with another first edge
2270 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2272 // put the best first edge to the theWire front
2273 if ( eBest != theWire.front() ) {
2274 eIt = find ( theWire.begin(), theWire.end(), eBest );
2275 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2281 //=======================================================================
2282 //function : sortSameSizeWires
2283 //purpose : sort wires in theWireList from theFromWire until theToWire,
2284 // the wires are set in the order to correspond to the order
2285 // of boundaries; after sorting, edges in the wires are put
2286 // in a good order, point UVs on edges are computed and points
2287 // are appended to theEdgesPointsList
2288 //=======================================================================
2290 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2291 const TListOfEdgesList::iterator& theFromWire,
2292 const TListOfEdgesList::iterator& theToWire,
2293 const int theFirstEdgeID,
2294 list< list< TPoint* > >& theEdgesPointsList )
2296 TopoDS_Face F = TopoDS::Face( myShape );
2297 int iW, nbWires = 0;
2298 TListOfEdgesList::iterator wlIt = theFromWire;
2299 while ( wlIt++ != theToWire )
2302 // Recompute key-point UVs by isolines intersection,
2303 // compute CG of key-points for each wire and bnd boxes of GCs
2306 gp_XY orig( gp::Origin2d().XY() );
2307 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2308 Bnd_Box2d bndBox, vBndBox;
2309 int eID = theFirstEdgeID;
2310 list< TopoDS_Edge >::iterator eIt;
2311 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2313 list< TopoDS_Edge > & wire = *wlIt;
2314 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2316 list< TPoint* > & ePoints = getShapePoints( eID++ );
2317 TPoint* p = ePoints.front();
2318 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2319 MESSAGE("can't sortSameSizeWires()");
2322 gcVec[iW] += p->myUV;
2323 bndBox.Add( gp_Pnt2d( p->myUV ));
2324 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2325 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2326 vGcVec[iW] += vXY.XY();
2328 // keep the computed UV to compare against by setFirstEdge()
2329 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2331 gcVec[iW] /= nbWires;
2332 vGcVec[iW] /= nbWires;
2333 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2334 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2337 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2339 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2340 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2341 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2342 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2344 double dMin = vMinPar[i] - minPar[i];
2345 double dMax = vMaxPar[i] - maxPar[i];
2346 double dPar = maxPar[i] - minPar[i];
2347 if ( Abs( dPar ) <= DBL_MIN )
2349 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2350 double par = gcVec[iW].Coord( iC );
2351 double r = ( par - minPar[i] ) / dPar;
2352 par += ( 1 - r ) * dMin + r * dMax;
2353 gcVec[iW].SetCoord( iC, par );
2357 // Define boundary - wire correspondence by GC closeness
2359 TListOfEdgesList tmpWList;
2360 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2361 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2362 TIntWirePosMap bndIndWirePosMap;
2363 vector< bool > bndFound( nbWires, false );
2364 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2366 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2367 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2368 double minDist = DBL_MAX;
2369 gp_XY & wGc = vGcVec[ iW ];
2371 for ( int iB = 0; iB < nbWires; iB++ ) {
2372 if ( bndFound[ iB ] ) continue;
2373 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2374 if ( dist < minDist ) {
2379 bndFound[ bIndex ] = true;
2380 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2385 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2386 eID = theFirstEdgeID;
2387 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2389 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2390 list < TopoDS_Edge > & wire = ( *wirePos );
2392 // choose the best first edge of a wire
2393 setFirstEdge( wire, eID );
2395 // compute eventual UV and fill theEdgesPointsList
2396 theEdgesPointsList.push_back( list< TPoint* >() );
2397 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2398 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2400 list< TPoint* > & ePoints = getShapePoints( eID++ );
2401 computeUVOnEdge( *eIt, ePoints );
2402 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2404 // put wire back to theWireList
2406 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2412 //=======================================================================
2414 //purpose : Compute nodes coordinates applying
2415 // the loaded pattern to <theFace>. The first key-point
2416 // will be mapped into <theVertexOnKeyPoint1>
2417 //=======================================================================
2419 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2420 const TopoDS_Vertex& theVertexOnKeyPoint1,
2421 const bool theReverse)
2423 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2424 if ( !setShapeToMesh( face ))
2427 // find points on edges, it fills myNbKeyPntInBoundary
2428 if ( !findBoundaryPoints() )
2431 // Define the edges order so that the first edge starts at
2432 // theVertexOnKeyPoint1
2434 list< TopoDS_Edge > eList;
2435 list< int > nbVertexInWires;
2436 int nbWires = SMESH_Block::GetOrderedEdges( face, eList, nbVertexInWires, theVertexOnKeyPoint1);
2437 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2439 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2440 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2442 // check nb wires and edges
2443 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2444 l1.sort(); l2.sort();
2447 MESSAGE( "Wrong nb vertices in wires" );
2448 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2451 // here shapes get IDs, for the outer wire IDs are OK
2452 int nbVertices = loadVE( eList, myShapeIDMap );
2453 myShapeIDMap.Add( face );
2455 if ((int) myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2456 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2457 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2460 // points on edges to be used for UV computation of in-face points
2461 list< list< TPoint* > > edgesPointsList;
2462 edgesPointsList.push_back( list< TPoint* >() );
2463 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2464 list< TPoint* >::iterator pIt, pEnd;
2466 // compute UV of points on the outer wire
2467 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2468 list< TopoDS_Edge >::iterator elIt;
2469 for (iE = 0, elIt = eList.begin();
2470 iE < nbEdgesInOuterWire && elIt != eList.end();
2473 list< TPoint* > & ePoints = getShapePoints( *elIt );
2475 computeUVOnEdge( *elIt, ePoints );
2476 // collect on-edge points (excluding the last one)
2477 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2480 // If there are several wires, define the order of edges of inner wires:
2481 // compute UV of inner edge-points using 2 methods: the one for in-face points
2482 // and the one for on-edge points and then choose the best edge order
2483 // by the best correspondence of the 2 results
2486 // compute UV of inner edge-points using the method for in-face points
2487 // and divide eList into a list of separate wires
2489 list< list< TopoDS_Edge > > wireList;
2490 list<TopoDS_Edge>::iterator eIt = elIt;
2491 list<int>::iterator nbEIt = nbVertexInWires.begin();
2492 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2494 int nbEdges = *nbEIt;
2495 wireList.push_back( list< TopoDS_Edge >() );
2496 list< TopoDS_Edge > & wire = wireList.back();
2497 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2499 list< TPoint* > & ePoints = getShapePoints( *eIt );
2500 pIt = ePoints.begin();
2501 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2503 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2504 MESSAGE("can't Apply(face)");
2507 // keep the computed UV to compare against by setFirstEdge()
2508 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2510 wire.push_back( *eIt );
2513 // remove inner edges from eList
2514 eList.erase( elIt, eList.end() );
2516 // sort wireList by nb edges in a wire
2517 sortBySize< TopoDS_Edge > ( wireList );
2519 // an ID of the first edge of a boundary
2520 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2521 // if ( nbSeamShapes > 0 )
2522 // id1 += 2; // 2 vertices more
2524 // find points - edge correspondence for wires of unique size,
2525 // edge order within a wire should be defined only
2527 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2528 while ( wlIt != wireList.end() )
2530 list< TopoDS_Edge >& wire = (*wlIt);
2531 size_t nbEdges = wire.size();
2533 if ( wlIt != wireList.end() && (*wlIt).size() != nbEdges ) // a unique size wire
2535 // choose the best first edge of a wire
2536 setFirstEdge( wire, id1 );
2538 // compute eventual UV and collect on-edge points
2539 edgesPointsList.push_back( list< TPoint* >() );
2540 edgesPoints = & edgesPointsList.back();
2542 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2544 list< TPoint* > & ePoints = getShapePoints( eID++ );
2545 computeUVOnEdge( *eIt, ePoints );
2546 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2552 // find boundary - wire correspondence for several wires of same size
2554 id1 = nbVertices + nbEdgesInOuterWire + 1;
2555 wlIt = wireList.begin();
2556 while ( wlIt != wireList.end() )
2558 size_t nbSameSize = 0, nbEdges = (*wlIt).size();
2559 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2561 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2565 if ( nbSameSize > 0 )
2566 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2569 id1 += nbEdges * ( nbSameSize + 1 );
2572 // add well-ordered edges to eList
2574 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2576 list< TopoDS_Edge >& wire = (*wlIt);
2577 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2580 // re-fill myShapeIDMap - all shapes get good IDs
2582 myShapeIDMap.Clear();
2583 nbVertices = loadVE( eList, myShapeIDMap );
2584 myShapeIDMap.Add( face );
2586 } // there are inner wires
2588 // Set XYZ of on-vertex points
2590 // for ( int iV = 1; iV <= nbVertices; ++iV )
2592 // const TopoDS_Vertex& V = TopoDS::Vertex( myShapeIDMap( iV ));
2593 // list< TPoint* > & vPoints = getShapePoints( iV );
2594 // if ( !vPoints.empty() )
2596 // //vPoints.front()->myUV = BRep_Tool::Parameters( V, theFace ).XY();
2597 // vPoints.front()->myXYZ = BRep_Tool::Pnt( V );
2601 // Compute XYZ of on-edge points
2603 TopLoc_Location loc;
2604 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2606 BRepAdaptor_Curve C3d( *elIt );
2607 list< TPoint* > & ePoints = getShapePoints( iE++ );
2608 for ( pIt = ++ePoints.begin(), pEnd = ePoints.end(); pIt != pEnd; pIt++ )
2610 TPoint* point = *pIt;
2611 point->myXYZ = C3d.Value( point->myU );
2615 // Compute UV and XYZ of in-face points
2617 // try to use a simple algo
2618 list< TPoint* > & fPoints = getShapePoints( face );
2619 bool isDeformed = false;
2620 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2621 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2622 (*pIt)->myUV, isDeformed )) {
2623 MESSAGE("can't Apply(face)");
2626 // try to use a complex algo if it is a difficult case
2627 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2629 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2630 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2631 (*pIt)->myUV, isDeformed )) {
2632 MESSAGE("can't Apply(face)");
2637 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2638 const gp_Trsf & aTrsf = loc.Transformation();
2639 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2641 TPoint * point = *pIt;
2642 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2643 if ( !loc.IsIdentity() )
2644 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2647 myIsComputed = true;
2649 return setErrorCode( ERR_OK );
2652 //=======================================================================
2654 //purpose : Compute nodes coordinates applying
2655 // the loaded pattern to <theFace>. The first key-point
2656 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2657 //=======================================================================
2659 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2660 const int theNodeIndexOnKeyPoint1,
2661 const bool theReverse)
2663 // MESSAGE(" ::Apply(MeshFace) " );
2665 if ( !IsLoaded() ) {
2666 MESSAGE( "Pattern not loaded" );
2667 return setErrorCode( ERR_APPL_NOT_LOADED );
2670 // check nb of nodes
2671 const int nbFaceNodes = theFace->NbCornerNodes();
2672 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2673 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2674 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2677 // find points on edges, it fills myNbKeyPntInBoundary
2678 if ( !findBoundaryPoints() )
2681 // check that there are no holes in a pattern
2682 if (myNbKeyPntInBoundary.size() > 1 ) {
2683 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2686 // Define the nodes order
2688 list< const SMDS_MeshNode* > nodes;
2689 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2690 SMDS_NodeIteratorPtr noIt = theFace->nodeIterator();
2692 while ( noIt->more() && iSub < nbFaceNodes ) {
2693 const SMDS_MeshNode* node = noIt->next();
2694 nodes.push_back( node );
2695 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2698 if ( n != nodes.end() ) {
2700 if ( n != --nodes.end() )
2701 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2704 else if ( n != nodes.begin() )
2705 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2707 list< gp_XYZ > xyzList;
2708 myOrderedNodes.resize( nbFaceNodes );
2709 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2710 xyzList.push_back( SMESH_TNodeXYZ( *n ));
2711 myOrderedNodes[ iSub++] = *n;
2714 // Define a face plane
2716 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2717 gp_Pnt P ( *xyzIt++ );
2718 gp_Vec Vx( P, *xyzIt++ ), N;
2720 N = Vx ^ gp_Vec( P, *xyzIt++ );
2721 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2722 if ( N.SquareMagnitude() <= DBL_MIN )
2723 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2724 gp_Ax2 pos( P, N, Vx );
2726 // Compute UV of key-points on a plane
2727 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2729 gp_Vec vec ( pos.Location(), *xyzIt );
2730 TPoint* p = getShapePoints( iSub ).front();
2731 p->myUV.SetX( vec * pos.XDirection() );
2732 p->myUV.SetY( vec * pos.YDirection() );
2736 // points on edges to be used for UV computation of in-face points
2737 list< list< TPoint* > > edgesPointsList;
2738 edgesPointsList.push_back( list< TPoint* >() );
2739 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2740 list< TPoint* >::iterator pIt;
2742 // compute UV and XYZ of points on edges
2744 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2746 gp_XYZ& xyz1 = *xyzIt++;
2747 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2749 list< TPoint* > & ePoints = getShapePoints( iSub );
2750 ePoints.back()->myInitU = 1.0;
2751 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2752 while ( *pIt != ePoints.back() )
2755 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2756 gp_Vec vec ( pos.Location(), p->myXYZ );
2757 p->myUV.SetX( vec * pos.XDirection() );
2758 p->myUV.SetY( vec * pos.YDirection() );
2760 // collect on-edge points (excluding the last one)
2761 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2764 // Compute UV and XYZ of in-face points
2766 // try to use a simple algo to compute UV
2767 list< TPoint* > & fPoints = getShapePoints( iSub );
2768 bool isDeformed = false;
2769 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2770 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2771 (*pIt)->myUV, isDeformed )) {
2772 MESSAGE("can't Apply(face)");
2775 // try to use a complex algo if it is a difficult case
2776 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2778 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2779 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2780 (*pIt)->myUV, isDeformed )) {
2781 MESSAGE("can't Apply(face)");
2786 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2788 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2791 myIsComputed = true;
2793 return setErrorCode( ERR_OK );
2796 //=======================================================================
2798 //purpose : Compute nodes coordinates applying
2799 // the loaded pattern to <theFace>. The first key-point
2800 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2801 //=======================================================================
2803 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2804 const SMDS_MeshFace* theFace,
2805 const TopoDS_Shape& theSurface,
2806 const int theNodeIndexOnKeyPoint1,
2807 const bool theReverse)
2809 // MESSAGE(" ::Apply(MeshFace) " );
2810 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2811 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2813 const TopoDS_Face& face = TopoDS::Face( theSurface );
2814 TopLoc_Location loc;
2815 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2816 const gp_Trsf & aTrsf = loc.Transformation();
2818 if ( !IsLoaded() ) {
2819 MESSAGE( "Pattern not loaded" );
2820 return setErrorCode( ERR_APPL_NOT_LOADED );
2823 // check nb of nodes
2824 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2825 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2826 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2829 // find points on edges, it fills myNbKeyPntInBoundary
2830 if ( !findBoundaryPoints() )
2833 // check that there are no holes in a pattern
2834 if (myNbKeyPntInBoundary.size() > 1 ) {
2835 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2838 // Define the nodes order
2840 list< const SMDS_MeshNode* > nodes;
2841 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2842 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2844 while ( noIt->more() ) {
2845 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2846 nodes.push_back( node );
2847 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2850 if ( n != nodes.end() ) {
2852 if ( n != --nodes.end() )
2853 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2856 else if ( n != nodes.begin() )
2857 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2860 // find a node not on a seam edge, if necessary
2861 SMESH_MesherHelper helper( *theMesh );
2862 helper.SetSubShape( theSurface );
2863 const SMDS_MeshNode* inFaceNode = 0;
2864 if ( helper.GetNodeUVneedInFaceNode() )
2866 SMESH_MeshEditor editor( theMesh );
2867 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2868 int shapeID = editor.FindShape( *n );
2870 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2871 if ( !helper.IsSeamShape( shapeID ))
2876 // Set UV of key-points (i.e. of nodes of theFace )
2877 vector< gp_XY > keyUV( theFace->NbNodes() );
2878 myOrderedNodes.resize( theFace->NbNodes() );
2879 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2881 TPoint* p = getShapePoints( iSub ).front();
2882 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2883 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2885 keyUV[ iSub-1 ] = p->myUV;
2886 myOrderedNodes[ iSub-1 ] = *n;
2889 // points on edges to be used for UV computation of in-face points
2890 list< list< TPoint* > > edgesPointsList;
2891 edgesPointsList.push_back( list< TPoint* >() );
2892 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2893 list< TPoint* >::iterator pIt;
2895 // compute UV and XYZ of points on edges
2897 for ( size_t i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2899 gp_XY& uv1 = keyUV[ i ];
2900 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2902 list< TPoint* > & ePoints = getShapePoints( iSub );
2903 ePoints.back()->myInitU = 1.0;
2904 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2905 while ( *pIt != ePoints.back() )
2908 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2909 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2910 if ( !loc.IsIdentity() )
2911 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2913 // collect on-edge points (excluding the last one)
2914 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2917 // Compute UV and XYZ of in-face points
2919 // try to use a simple algo to compute UV
2920 list< TPoint* > & fPoints = getShapePoints( iSub );
2921 bool isDeformed = false;
2922 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2923 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2924 (*pIt)->myUV, isDeformed )) {
2925 MESSAGE("can't Apply(face)");
2928 // try to use a complex algo if it is a difficult case
2929 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2931 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2932 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2933 (*pIt)->myUV, isDeformed )) {
2934 MESSAGE("can't Apply(face)");
2939 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2941 TPoint * point = *pIt;
2942 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2943 if ( !loc.IsIdentity() )
2944 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2947 myIsComputed = true;
2949 return setErrorCode( ERR_OK );
2952 //=======================================================================
2953 //function : undefinedXYZ
2955 //=======================================================================
2957 static const gp_XYZ& undefinedXYZ()
2959 static gp_XYZ xyz( 1.e100, 0., 0. );
2963 //=======================================================================
2964 //function : isDefined
2966 //=======================================================================
2968 inline static bool isDefined(const gp_XYZ& theXYZ)
2970 return theXYZ.X() < 1.e100;
2973 //=======================================================================
2975 //purpose : Compute nodes coordinates applying
2976 // the loaded pattern to <theFaces>. The first key-point
2977 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2978 //=======================================================================
2980 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2981 std::set<const SMDS_MeshFace*>& theFaces,
2982 const int theNodeIndexOnKeyPoint1,
2983 const bool theReverse)
2985 MESSAGE(" ::Apply(set<MeshFace>) " );
2987 if ( !IsLoaded() ) {
2988 MESSAGE( "Pattern not loaded" );
2989 return setErrorCode( ERR_APPL_NOT_LOADED );
2992 // find points on edges, it fills myNbKeyPntInBoundary
2993 if ( !findBoundaryPoints() )
2996 // check that there are no holes in a pattern
2997 if (myNbKeyPntInBoundary.size() > 1 ) {
2998 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3003 myElemXYZIDs.clear();
3004 myXYZIdToNodeMap.clear();
3006 myIdsOnBoundary.clear();
3007 myReverseConnectivity.clear();
3009 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
3010 myElements.reserve( theFaces.size() );
3012 int ind1 = 0; // lowest point index for a face
3017 // SMESH_MeshEditor editor( theMesh );
3019 // apply to each face in theFaces set
3020 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
3021 for ( ; face != theFaces.end(); ++face )
3023 // int curShapeId = editor.FindShape( *face );
3024 // if ( curShapeId != shapeID ) {
3025 // if ( curShapeId )
3026 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
3029 // shapeID = curShapeId;
3032 if ( shape.IsNull() )
3033 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
3035 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
3037 MESSAGE( "Failed on " << *face );
3040 myElements.push_back( *face );
3042 // store computed points belonging to elements
3043 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3044 for ( ; ll != myElemPointIDs.end(); ++ll )
3046 myElemXYZIDs.push_back(TElemDef());
3047 TElemDef& xyzIds = myElemXYZIDs.back();
3048 TElemDef& pIds = *ll;
3049 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3050 int pIndex = *id + ind1;
3051 xyzIds.push_back( pIndex );
3052 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3053 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3056 // put points on links to myIdsOnBoundary,
3057 // they will be used to sew new elements on adjacent refined elements
3058 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3059 for ( int i = 0; i < nbNodes; i++ )
3061 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3062 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3063 const SMDS_MeshNode* n2 = myOrderedNodes[( i+1 ) % nbNodes ];
3064 // make a link and a node set
3065 TNodeSet linkSet, node1Set;
3066 linkSet.insert( n1 );
3067 linkSet.insert( n2 );
3068 node1Set.insert( n1 );
3069 list< TPoint* >::iterator p = linkPoints.begin();
3071 // map the first link point to n1
3072 int nId = ( *p - &myPoints[0] ) + ind1;
3073 myXYZIdToNodeMap[ nId ] = n1;
3074 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3075 groups.push_back(list< int > ());
3076 groups.back().push_back( nId );
3078 // add the linkSet to the map
3079 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3080 groups.push_back(list< int > ());
3081 list< int >& indList = groups.back();
3082 // add points to the map excluding the end points
3083 for ( p++; *p != linkPoints.back(); p++ )
3084 indList.push_back( ( *p - &myPoints[0] ) + ind1 );
3086 ind1 += myPoints.size();
3089 return !myElemXYZIDs.empty();
3092 //=======================================================================
3094 //purpose : Compute nodes coordinates applying
3095 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3096 // will be mapped into <theNode000Index>-th node. The
3097 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3099 //=======================================================================
3101 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3102 const int theNode000Index,
3103 const int theNode001Index)
3105 if ( !IsLoaded() ) {
3106 MESSAGE( "Pattern not loaded" );
3107 return setErrorCode( ERR_APPL_NOT_LOADED );
3110 // bind ID to points
3111 if ( !findBoundaryPoints() )
3114 // check that there are no holes in a pattern
3115 if (myNbKeyPntInBoundary.size() > 1 ) {
3116 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3121 myElemXYZIDs.clear();
3122 myXYZIdToNodeMap.clear();
3124 myIdsOnBoundary.clear();
3125 myReverseConnectivity.clear();
3127 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3128 myElements.reserve( theVolumes.size() );
3130 // to find point index
3131 map< TPoint*, int > pointIndex;
3132 for ( size_t i = 0; i < myPoints.size(); i++ )
3133 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3135 int ind1 = 0; // lowest point index for an element
3137 // apply to each element in theVolumes set
3138 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3139 for ( ; vol != theVolumes.end(); ++vol )
3141 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3142 MESSAGE( "Failed on " << *vol );
3145 myElements.push_back( *vol );
3147 // store computed points belonging to elements
3148 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3149 for ( ; ll != myElemPointIDs.end(); ++ll )
3151 myElemXYZIDs.push_back(TElemDef());
3152 TElemDef& xyzIds = myElemXYZIDs.back();
3153 TElemDef& pIds = *ll;
3154 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3155 int pIndex = *id + ind1;
3156 xyzIds.push_back( pIndex );
3157 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3158 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3161 // put points on edges and faces to myIdsOnBoundary,
3162 // they will be used to sew new elements on adjacent refined elements
3163 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3165 // make a set of sub-points
3167 vector< int > subIDs;
3168 if ( SMESH_Block::IsVertexID( Id )) {
3169 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3171 else if ( SMESH_Block::IsEdgeID( Id )) {
3172 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3173 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3174 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3177 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3178 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3179 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3180 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3181 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3182 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3183 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3184 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3187 list< TPoint* > & points = getShapePoints( Id );
3188 list< TPoint* >::iterator p = points.begin();
3189 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3190 groups.push_back(list< int > ());
3191 list< int >& indList = groups.back();
3192 for ( ; p != points.end(); p++ )
3193 indList.push_back( pointIndex[ *p ] + ind1 );
3194 if ( subNodes.size() == 1 ) // vertex case
3195 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3197 ind1 += myPoints.size();
3200 return !myElemXYZIDs.empty();
3203 //=======================================================================
3205 //purpose : Create a pattern from the mesh built on <theBlock>
3206 //=======================================================================
3208 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3209 const TopoDS_Shell& theBlock,
3214 myToKeepNodes = theKeepNodes;
3215 SMESHDS_SubMesh * aSubMesh;
3217 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3219 // load shapes in myShapeIDMap
3221 TopoDS_Vertex v1, v2;
3222 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3223 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3226 int nbNodes = 0, shapeID;
3227 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3229 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3230 aSubMesh = getSubmeshWithElements( theMesh, S );
3232 nbNodes += aSubMesh->NbNodes();
3234 myPoints.resize( nbNodes );
3236 // load U of points on edges
3237 TNodePointIDMap nodePointIDMap;
3239 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3241 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3242 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3243 aSubMesh = getSubmeshWithElements( theMesh, S );
3244 if ( ! aSubMesh ) continue;
3245 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3246 if ( !nIt->more() ) continue;
3248 // store a node and a point
3249 while ( nIt->more() ) {
3250 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3251 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3253 nodePointIDMap.insert( make_pair( node, iPoint ));
3254 if ( block.IsVertexID( shapeID ))
3255 myKeyPointIDs.push_back( iPoint );
3256 TPoint* p = & myPoints[ iPoint++ ];
3257 shapePoints.push_back( p );
3258 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3259 p->myInitXYZ.SetCoord( 0,0,0 );
3261 list< TPoint* >::iterator pIt = shapePoints.begin();
3264 switch ( S.ShapeType() )
3269 for ( ; pIt != shapePoints.end(); pIt++ ) {
3270 double * coef = block.GetShapeCoef( shapeID );
3271 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3272 if ( coef[ iCoord - 1] > 0 )
3273 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3275 if ( S.ShapeType() == TopAbs_VERTEX )
3278 const TopoDS_Edge& edge = TopoDS::Edge( S );
3280 BRep_Tool::Range( edge, f, l );
3281 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3282 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3283 pIt = shapePoints.begin();
3284 nIt = aSubMesh->GetNodes();
3285 for ( ; nIt->more(); pIt++ )
3287 const SMDS_MeshNode* node = nIt->next();
3288 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3290 SMDS_EdgePositionPtr epos = node->GetPosition();
3291 double u = ( epos->GetUParameter() - f ) / ( l - f );
3292 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3297 for ( ; pIt != shapePoints.end(); pIt++ )
3299 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3300 MESSAGE( "!block.ComputeParameters()" );
3301 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3305 } // loop on block sub-shapes
3309 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3312 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3313 while ( elemIt->more() ) {
3314 const SMDS_MeshElement* elem = elemIt->next();
3315 myElemPointIDs.push_back( TElemDef() );
3316 TElemDef& elemPoints = myElemPointIDs.back();
3317 int nbNodes = elem->NbCornerNodes();
3318 for ( int i = 0;i < nbNodes; ++i )
3319 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3323 myIsBoundaryPointsFound = true;
3325 if ( myToKeepNodes )
3327 myInNodes.resize( nodePointIDMap.size() );
3328 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
3329 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
3330 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
3333 return setErrorCode( ERR_OK );
3336 //=======================================================================
3337 //function : getSubmeshWithElements
3338 //purpose : return submesh containing elements bound to theBlock in theMesh
3339 //=======================================================================
3341 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3342 const TopoDS_Shape& theShape)
3344 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3345 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3348 if ( theShape.ShapeType() == TopAbs_SHELL )
3350 // look for submesh of VOLUME
3351 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3352 for (; it.More(); it.Next()) {
3353 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3354 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3362 //=======================================================================
3364 //purpose : Compute nodes coordinates applying
3365 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3366 // will be mapped into <theVertex000>. The (0,0,1)
3367 // fifth key-point will be mapped into <theVertex001>.
3368 //=======================================================================
3370 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3371 const TopoDS_Vertex& theVertex000,
3372 const TopoDS_Vertex& theVertex001)
3374 if (!findBoundaryPoints() || // bind ID to points
3375 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3378 SMESH_Block block; // bind ID to shape
3379 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3380 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3382 // compute XYZ of points on shapes
3384 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3386 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3387 list< TPoint* >::iterator pIt = shapePoints.begin();
3388 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3389 switch ( S.ShapeType() )
3391 case TopAbs_VERTEX: {
3393 for ( ; pIt != shapePoints.end(); pIt++ )
3394 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3399 for ( ; pIt != shapePoints.end(); pIt++ )
3400 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3405 for ( ; pIt != shapePoints.end(); pIt++ )
3406 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3410 for ( ; pIt != shapePoints.end(); pIt++ )
3411 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3413 } // loop on block sub-shapes
3415 myIsComputed = true;
3417 return setErrorCode( ERR_OK );
3420 //=======================================================================
3422 //purpose : Compute nodes coordinates applying
3423 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3424 // will be mapped into <theNode000Index>-th node. The
3425 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3427 //=======================================================================
3429 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3430 const int theNode000Index,
3431 const int theNode001Index)
3433 if (!findBoundaryPoints()) // bind ID to points
3436 SMESH_Block block; // bind ID to shape
3437 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3438 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3439 // compute XYZ of points on shapes
3441 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3443 list< TPoint* > & shapePoints = getShapePoints( ID );
3444 list< TPoint* >::iterator pIt = shapePoints.begin();
3446 if ( block.IsVertexID( ID ))
3447 for ( ; pIt != shapePoints.end(); pIt++ ) {
3448 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3450 else if ( block.IsEdgeID( ID ))
3451 for ( ; pIt != shapePoints.end(); pIt++ ) {
3452 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3454 else if ( block.IsFaceID( ID ))
3455 for ( ; pIt != shapePoints.end(); pIt++ ) {
3456 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3459 for ( ; pIt != shapePoints.end(); pIt++ )
3460 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3461 } // loop on block sub-shapes
3463 myIsComputed = true;
3465 return setErrorCode( ERR_OK );
3468 //=======================================================================
3469 //function : mergePoints
3470 //purpose : Merge XYZ on edges and/or faces.
3471 //=======================================================================
3473 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3475 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3476 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3478 list<list< int > >& groups = idListIt->second;
3479 if ( groups.size() < 2 )
3483 const TNodeSet& nodes = idListIt->first;
3484 double tol2 = 1.e-10;
3485 if ( nodes.size() > 1 ) {
3487 TNodeSet::const_iterator n = nodes.begin();
3488 for ( ; n != nodes.end(); ++n )
3489 box.Add( gp_Pnt( SMESH_TNodeXYZ( *n )));
3490 double x, y, z, X, Y, Z;
3491 box.Get( x, y, z, X, Y, Z );
3492 gp_Pnt p( x, y, z ), P( X, Y, Z );
3493 tol2 = 1.e-4 * p.SquareDistance( P );
3496 // to unite groups on link
3497 bool unite = ( uniteGroups && nodes.size() == 2 );
3498 map< double, int > distIndMap;
3499 const SMDS_MeshNode* node = *nodes.begin();
3500 gp_Pnt P = SMESH_TNodeXYZ( node );
3502 // compare points, replace indices
3504 list< int >::iterator ind1, ind2;
3505 list< list< int > >::iterator grpIt1, grpIt2;
3506 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3508 list< int >& indices1 = *grpIt1;
3510 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3512 list< int >& indices2 = *grpIt2;
3513 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3515 gp_XYZ& p1 = myXYZ[ *ind1 ];
3516 ind2 = indices2.begin();
3517 while ( ind2 != indices2.end() )
3519 gp_XYZ& p2 = myXYZ[ *ind2 ];
3520 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3521 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3523 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3524 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3525 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3526 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3528 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3529 myXYZ[ *ind2 ] = undefinedXYZ();
3530 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3532 ind2 = indices2.erase( ind2 );
3539 if ( unite ) { // sort indices using distIndMap
3540 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3542 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3543 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3544 distIndMap.insert( make_pair( dist, *ind1 ));
3548 if ( unite ) { // put all sorted indices into the first group
3549 list< int >& g = groups.front();
3551 map< double, int >::iterator dist_ind = distIndMap.begin();
3552 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3553 g.push_back( dist_ind->second );
3555 } // loop on myIdsOnBoundary
3558 //=======================================================================
3559 //function : makePolyElements
3560 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3561 //=======================================================================
3563 void SMESH_Pattern::
3564 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3565 const bool toCreatePolygons,
3566 const bool toCreatePolyedrs)
3568 myPolyElemXYZIDs.clear();
3569 myPolyElems.clear();
3570 myPolyElems.reserve( myIdsOnBoundary.size() );
3572 // make a set of refined elements
3573 TIDSortedElemSet elemSet, avoidSet( myElements.begin(), myElements.end() );
3575 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3577 if ( toCreatePolygons )
3579 int lastFreeId = myXYZ.size();
3581 // loop on links of refined elements
3582 indListIt = myIdsOnBoundary.begin();
3583 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3585 const TNodeSet & linkNodes = indListIt->first;
3586 if ( linkNodes.size() != 2 )
3587 continue; // skip face
3588 const SMDS_MeshNode* n1 = * linkNodes.begin();
3589 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3591 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3592 if ( idGroups.empty() || idGroups.front().empty() )
3595 // find not refined face having n1-n2 link
3599 const SMDS_MeshElement* face =
3600 SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet );
3603 avoidSet.insert ( face );
3604 myPolyElems.push_back( face );
3606 // some links of <face> are split;
3607 // make list of xyz for <face>
3608 myPolyElemXYZIDs.push_back(TElemDef());
3609 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3610 // loop on links of a <face>
3611 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3612 int i = 0, nbNodes = face->NbNodes();
3613 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3614 while ( nIt->more() )
3615 nodes[ i++ ] = smdsNode( nIt->next() );
3616 nodes[ i ] = nodes[ 0 ];
3617 for ( i = 0; i < nbNodes; ++i )
3619 // look for point mapped on a link
3620 TNodeSet faceLinkNodes;
3621 faceLinkNodes.insert( nodes[ i ] );
3622 faceLinkNodes.insert( nodes[ i + 1 ] );
3623 if ( faceLinkNodes == linkNodes )
3624 nn_IdList = indListIt;
3626 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3627 // add face point ids
3628 faceNodeIds.push_back( ++lastFreeId );
3629 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3630 if ( nn_IdList != myIdsOnBoundary.end() )
3632 // there are points mapped on a link
3633 list< int >& mappedIds = nn_IdList->second.front();
3634 if ( isReversed( nodes[ i ], mappedIds ))
3635 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3637 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3639 } // loop on links of a <face>
3645 if ( myIs2D && idGroups.size() > 1 ) {
3647 // sew new elements on 2 refined elements sharing n1-n2 link
3649 list< int >& idsOnLink = idGroups.front();
3650 // temporarily add ids of link nodes to idsOnLink
3651 bool rev = isReversed( n1, idsOnLink );
3652 for ( int i = 0; i < 2; ++i )
3655 nodeSet.insert( i ? n2 : n1 );
3656 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3657 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3658 int nodeId = groups.front().front();
3660 if ( rev ) append = !append;
3662 idsOnLink.push_back( nodeId );
3664 idsOnLink.push_front( nodeId );
3666 list< int >::iterator id = idsOnLink.begin();
3667 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3669 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3670 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3671 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3673 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3674 // look for <id> in element definition
3675 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3676 ASSERT ( idDef != pIdList->end() );
3677 // look for 2 neighbour ids of <id> in element definition
3678 for ( int prev = 0; prev < 2; ++prev ) {
3679 TElemDef::iterator idDef2 = idDef;
3681 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3683 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3684 // look for idDef2 on a link starting from id
3685 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3686 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3687 // insert ids located on link between <id> and <id2>
3688 // into the element definition between idDef and idDef2
3690 for ( ; id2 != id; --id2 )
3691 pIdList->insert( idDef, *id2 );
3693 list< int >::iterator id1 = id;
3694 for ( ++id1, ++id2; id1 != id2; ++id1 )
3695 pIdList->insert( idDef2, *id1 );
3701 // remove ids of link nodes
3702 idsOnLink.pop_front();
3703 idsOnLink.pop_back();
3705 } // loop on myIdsOnBoundary
3706 } // if ( toCreatePolygons )
3708 if ( toCreatePolyedrs )
3710 // check volumes adjacent to the refined elements
3711 SMDS_VolumeTool volTool;
3712 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3713 for ( ; refinedElem != myElements.end(); ++refinedElem )
3715 // loop on nodes of refinedElem
3716 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3717 while ( nIt->more() ) {
3718 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3719 // loop on inverse elements of node
3720 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3721 while ( eIt->more() )
3723 const SMDS_MeshElement* elem = eIt->next();
3724 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3725 continue; // skip faces or refined elements
3726 // add polyhedron definition
3727 myPolyhedronQuantities.push_back(vector<int> ());
3728 myPolyElemXYZIDs.push_back(TElemDef());
3729 vector<int>& quantity = myPolyhedronQuantities.back();
3730 TElemDef & elemDef = myPolyElemXYZIDs.back();
3731 // get definitions of new elements on volume faces
3732 bool makePoly = false;
3733 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3735 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3736 volTool.NbFaceNodes( iF ),
3737 theNodes, elemDef, quantity))
3741 myPolyElems.push_back( elem );
3743 myPolyhedronQuantities.pop_back();
3744 myPolyElemXYZIDs.pop_back();
3752 //=======================================================================
3753 //function : getFacesDefinition
3754 //purpose : return faces definition for a volume face defined by theBndNodes
3755 //=======================================================================
3757 bool SMESH_Pattern::
3758 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3759 const int theNbBndNodes,
3760 const vector< const SMDS_MeshNode* >& theNodes,
3761 list< int >& theFaceDefs,
3762 vector<int>& theQuantity)
3764 bool makePoly = false;
3766 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3768 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3770 // make a set of all nodes on a face
3772 if ( !myIs2D ) { // for 2D, merge only edges
3773 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3774 if ( nn_IdList != myIdsOnBoundary.end() ) {
3775 list< int > & faceIds = nn_IdList->second.front();
3776 if ( !faceIds.empty() ) {
3778 ids.insert( faceIds.begin(), faceIds.end() );
3783 // add ids on links and bnd nodes
3784 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3785 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3786 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3788 // add id of iN-th bnd node
3790 nSet.insert( theBndNodes[ iN ] );
3791 nn_IdList = myIdsOnBoundary.find( nSet );
3792 int bndId = ++lastFreeId;
3793 if ( nn_IdList != myIdsOnBoundary.end() ) {
3794 bndId = nn_IdList->second.front().front();
3795 ids.insert( bndId );
3798 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3800 faceDef.push_back( bndId );
3801 // add ids on a link
3803 linkNodes.insert( theBndNodes[ iN ]);
3804 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3805 nn_IdList = myIdsOnBoundary.find( linkNodes );
3806 if ( nn_IdList != myIdsOnBoundary.end() ) {
3807 list< int > & linkIds = nn_IdList->second.front();
3808 if ( !linkIds.empty() )
3811 ids.insert( linkIds.begin(), linkIds.end() );
3812 if ( isReversed( theBndNodes[ iN ], linkIds ))
3813 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3815 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3820 // find faces definition of new volumes
3822 bool defsAdded = false;
3823 if ( !myIs2D ) { // for 2D, merge only edges
3824 SMDS_VolumeTool vol;
3825 set< TElemDef* > checkedVolDefs;
3826 set< int >::iterator id = ids.begin();
3827 for ( ; id != ids.end(); ++id )
3829 // definitions of volumes sharing id
3830 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3831 ASSERT( !defList.empty() );
3832 // loop on volume definitions
3833 list< TElemDef* >::iterator pIdList = defList.begin();
3834 for ( ; pIdList != defList.end(); ++pIdList)
3836 if ( !checkedVolDefs.insert( *pIdList ).second )
3837 continue; // skip already checked volume definition
3838 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3839 // loop on face defs of a volume
3840 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3841 if ( volType == SMDS_VolumeTool::UNKNOWN )
3843 int nbFaces = vol.NbFaces( volType );
3844 for ( int iF = 0; iF < nbFaces; ++iF )
3846 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3847 int iN, nbN = vol.NbFaceNodes( volType, iF );
3848 // check if all nodes of a faces are in <ids>
3850 for ( iN = 0; iN < nbN && all; ++iN ) {
3851 int nodeId = idVec[ nodeInds[ iN ]];
3852 all = ( ids.find( nodeId ) != ids.end() );
3855 // store a face definition
3856 for ( iN = 0; iN < nbN; ++iN ) {
3857 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3859 theQuantity.push_back( nbN );
3867 theQuantity.push_back( faceDef.size() );
3868 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3874 //=======================================================================
3875 //function : clearSubMesh
3877 //=======================================================================
3879 static bool clearSubMesh( SMESH_Mesh* theMesh,
3880 const TopoDS_Shape& theShape)
3882 bool removed = false;
3883 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3885 removed = !aSubMesh->IsEmpty();
3887 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3890 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3891 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3893 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3894 removed = eIt->more();
3895 while ( eIt->more() )
3896 aMeshDS->RemoveElement( eIt->next() );
3897 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3898 removed = removed || nIt->more();
3899 while ( nIt->more() )
3900 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3906 //=======================================================================
3907 //function : clearMesh
3908 //purpose : clear mesh elements existing on myShape in theMesh
3909 //=======================================================================
3911 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3914 if ( !myShape.IsNull() )
3916 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3917 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3918 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3920 clearSubMesh( theMesh, it.Value() );
3926 //=======================================================================
3927 //function : findExistingNodes
3928 //purpose : fills nodes vector with nodes existing on a given shape (IMP 22368)
3929 // Returns true if all nodes for all points on S are found
3930 //=======================================================================
3932 bool SMESH_Pattern::findExistingNodes( SMESH_Mesh* mesh,
3933 const TopoDS_Shape& S,
3934 const std::list< TPoint* > & points,
3935 vector< const SMDS_MeshNode* > & nodesVector)
3937 if ( S.IsNull() || points.empty() )
3940 SMESHDS_Mesh* aMeshDS = mesh->GetMeshDS();
3942 switch ( S.ShapeType() )
3946 int pIndex = points.back() - &myPoints[0];
3947 if ( !nodesVector[ pIndex ] )
3948 nodesVector[ pIndex ] = SMESH_Algo::VertexNode( TopoDS::Vertex( S ), aMeshDS );
3949 return nodesVector[ pIndex ];
3953 const TopoDS_Edge& edge = TopoDS::Edge( S );
3954 map< double, const SMDS_MeshNode* > paramsOfNodes;
3955 if ( !SMESH_Algo::GetSortedNodesOnEdge( aMeshDS, edge,
3956 /*ignoreMediumNodes=*/false,
3958 || paramsOfNodes.size() < 3 )
3960 // points on VERTEXes are included with wrong myU
3961 list< TPoint* >::const_reverse_iterator pItR = ++points.rbegin();
3962 list< TPoint* >::const_iterator pItF = ++points.begin();
3963 const bool isForward = ( (*pItF)->myU < (*pItR)->myU );
3964 map< double, const SMDS_MeshNode* >::iterator u2n = ++paramsOfNodes.begin();
3965 map< double, const SMDS_MeshNode* >::iterator u2nEnd = --paramsOfNodes.end();
3967 if ( paramsOfNodes.size() == points.size() )
3969 for ( ; u2n != u2nEnd; ++u2n )
3971 p = ( isForward ? *pItF : *pItR );
3972 int pIndex = p - &myPoints[0];
3973 if ( !nodesVector [ pIndex ] )
3974 nodesVector [ pIndex ] = u2n->second;
3982 const double tolFact = 0.05;
3983 while ( u2n != u2nEnd && pItF != points.end() )
3985 const double u = u2n->first;
3986 const SMDS_MeshNode* n = u2n->second;
3987 const double tol = ( (++u2n)->first - u ) * tolFact;
3990 p = ( isForward ? *pItF : *pItR );
3991 if ( Abs( u - p->myU ) < tol )
3993 int pIndex = p - &myPoints[0];
3994 if ( !nodesVector [ pIndex ] )
3995 nodesVector [ pIndex ] = n;
4001 while ( p->myU < u && ( ++pItF, ++pItR != points.rend() ));
4005 } // case TopAbs_EDGE:
4008 } // switch ( S.ShapeType() )
4013 //=======================================================================
4014 //function : MakeMesh
4015 //purpose : Create nodes and elements in <theMesh> using nodes
4016 // coordinates computed by either of Apply...() methods
4017 //=======================================================================
4019 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
4020 const bool toCreatePolygons,
4021 const bool toCreatePolyedrs)
4023 if ( !myIsComputed )
4024 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
4026 mergePoints( toCreatePolygons );
4028 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4030 // clear elements and nodes existing on myShape
4033 bool onMeshElements = ( !myElements.empty() );
4035 // Create missing nodes
4037 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
4038 if ( onMeshElements )
4040 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
4041 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
4042 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
4043 nodesVector[ i_node->first ] = i_node->second;
4045 for ( size_t i = 0; i < myXYZ.size(); ++i ) {
4046 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
4047 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
4051 if ( theMesh->HasShapeToMesh() )
4053 // set nodes on EDGEs (IMP 22368)
4054 SMESH_MesherHelper helper( *theMesh );
4055 helper.ToFixNodeParameters( true );
4056 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
4057 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
4059 list<list< int > >& groups = idListIt->second;
4060 const TNodeSet& nodes = idListIt->first;
4061 if ( nodes.size() != 2 )
4062 continue; // not a link
4063 const SMDS_MeshNode* n1 = *nodes.begin();
4064 const SMDS_MeshNode* n2 = *nodes.rbegin();
4065 TopoDS_Shape S1 = helper.GetSubShapeByNode( n1, aMeshDS );
4066 TopoDS_Shape S2 = helper.GetSubShapeByNode( n2, aMeshDS );
4067 if ( S1.IsNull() || S1.ShapeType() < TopAbs_EDGE ||
4068 S2.IsNull() || S2.ShapeType() < TopAbs_EDGE )
4071 if ( S1.ShapeType() == TopAbs_EDGE )
4073 if ( S1 == S2 || helper.IsSubShape( S2, S1 ))
4076 else if ( S2.ShapeType() == TopAbs_EDGE )
4078 if ( helper.IsSubShape( S1, S2 ))
4083 S = helper.GetCommonAncestor( S1, S2, *theMesh, TopAbs_EDGE );
4087 const TopoDS_Edge & E = TopoDS::Edge( S );
4088 helper.SetSubShape( E );
4089 list<list< int > >::iterator g = groups.begin();
4090 for ( ; g != groups.end(); ++g )
4092 list< int >& ids = *g;
4093 list< int >::iterator id = ids.begin();
4094 for ( ; id != ids.end(); ++id )
4095 if ( nodesVector[ *id ] && nodesVector[ *id ]->getshapeId() < 1 )
4098 aMeshDS->SetNodeOnEdge( nodesVector[ *id ], E, u );
4099 helper.CheckNodeU( E, nodesVector[ *id ], u, 1e-7, true );
4104 } // if ( onMeshElements )
4108 nodesVector.resize( myPoints.size(), 0 );
4110 // loop on sub-shapes of myShape: create nodes
4111 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
4112 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
4114 list< TPoint* > & points = idPointIt->second;
4116 if ( !myShapeIDMap.IsEmpty() )
4117 S = myShapeIDMap( idPointIt->first );
4119 // find existing nodes on EDGEs and VERTEXes
4120 if ( findExistingNodes( theMesh, S, points, nodesVector ))
4123 list< TPoint* >::iterator pIt = points.begin();
4124 for ( ; pIt != points.end(); pIt++ )
4126 TPoint* point = *pIt;
4127 int pIndex = point - &myPoints[0];
4128 if ( nodesVector [ pIndex ] )
4130 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
4133 nodesVector [ pIndex ] = node;
4135 if ( !S.IsNull() ) {
4137 switch ( S.ShapeType() ) {
4138 case TopAbs_VERTEX: {
4139 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
4142 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
4145 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
4146 point->myUV.X(), point->myUV.Y() ); break;
4149 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
4158 if ( onMeshElements )
4160 // prepare data to create poly elements
4161 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
4164 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
4165 // sew old and new elements
4166 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
4170 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4173 aMeshDS->Modified();
4174 aMeshDS->CompactMesh();
4176 if ( myToKeepNodes )
4177 myOutNodes.swap( nodesVector );
4179 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4180 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4181 // for ( ; i_sm != sm.end(); i_sm++ )
4183 // cout << " SM " << i_sm->first << " ";
4184 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4185 // //SMDS_ElemIteratorPtr GetElements();
4186 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4187 // while ( nit->more() )
4188 // cout << nit->next()->GetID() << " ";
4191 return setErrorCode( ERR_OK );
4194 //=======================================================================
4195 //function : createElements
4196 //purpose : add elements to the mesh
4197 //=======================================================================
4199 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4200 const vector<const SMDS_MeshNode* >& theNodesVector,
4201 const list< TElemDef > & theElemNodeIDs,
4202 const vector<const SMDS_MeshElement*>& theElements)
4204 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4205 SMESH_MeshEditor editor( theMesh );
4207 bool onMeshElements = !theElements.empty();
4209 // shapes and groups theElements are on
4210 vector< int > shapeIDs;
4211 vector< list< SMESHDS_Group* > > groups;
4212 set< const SMDS_MeshNode* > shellNodes;
4213 if ( onMeshElements )
4215 shapeIDs.resize( theElements.size() );
4216 groups.resize( theElements.size() );
4217 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4218 set<SMESHDS_GroupBase*>::const_iterator grIt;
4219 for ( size_t i = 0; i < theElements.size(); i++ )
4221 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4222 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4223 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4224 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4225 groups[ i ].push_back( group );
4228 // get all nodes bound to shells because their SpacePosition is not set
4229 // by SMESHDS_Mesh::SetNodeInVolume()
4230 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4231 if ( !aMainShape.IsNull() ) {
4232 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4233 for ( ; shellExp.More(); shellExp.Next() )
4235 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4237 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4238 while ( nIt->more() )
4239 shellNodes.insert( nIt->next() );
4244 // nb new elements per a refined element
4245 int nbNewElemsPerOld = 1;
4246 if ( onMeshElements )
4247 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4251 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4252 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4253 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4255 const TElemDef & elemNodeInd = *enIt;
4257 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4258 TElemDef::const_iterator id = elemNodeInd.begin();
4260 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4261 if ( *id < (int) theNodesVector.size() )
4262 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4264 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4266 // dim of refined elem
4267 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4268 if ( onMeshElements ) {
4269 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4272 const SMDS_MeshElement* elem = 0;
4274 switch ( nbNodes ) {
4276 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4278 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4280 if ( !onMeshElements ) {// create a quadratic face
4281 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4282 nodes[4], nodes[5] ); break;
4283 } // else do not break but create a polygon
4285 if ( !onMeshElements ) {// create a quadratic face
4286 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4287 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4288 } // else do not break but create a polygon
4290 elem = aMeshDS->AddPolygonalFace( nodes );
4294 switch ( nbNodes ) {
4296 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4298 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4301 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4302 nodes[4], nodes[5] ); break;
4304 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4305 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4307 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4310 // set element on a shape
4311 if ( elem && onMeshElements ) // applied to mesh elements
4313 int shapeID = shapeIDs[ elemIndex ];
4314 if ( shapeID > 0 ) {
4315 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4316 // set nodes on a shape
4317 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4318 if ( S.ShapeType() == TopAbs_SOLID ) {
4319 TopoDS_Iterator shellIt( S );
4320 if ( shellIt.More() )
4321 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4323 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4324 while ( noIt->more() ) {
4325 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4326 if ( node->getshapeId() < 1 &&
4327 shellNodes.find( node ) == shellNodes.end() )
4329 if ( S.ShapeType() == TopAbs_FACE )
4330 aMeshDS->SetNodeOnFace( node, shapeID,
4331 Precision::Infinite(),// <- it's a sign that UV is not set
4332 Precision::Infinite());
4334 aMeshDS->SetNodeInVolume( node, shapeID );
4335 shellNodes.insert( node );
4340 // add elem in groups
4341 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4342 for ( ; g != groups[ elemIndex ].end(); ++g )
4343 (*g)->SMDSGroup().Add( elem );
4345 if ( elem && !myShape.IsNull() ) // applied to shape
4346 aMeshDS->SetMeshElementOnShape( elem, myShape );
4349 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4350 // so that operations with hypotheses will erase the mesh being built
4352 SMESH_subMesh * subMesh;
4353 if ( !myShape.IsNull() ) {
4354 subMesh = theMesh->GetSubMesh( myShape );
4356 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4358 if ( onMeshElements ) {
4359 list< int > elemIDs;
4360 for ( size_t i = 0; i < theElements.size(); i++ )
4362 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4364 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4366 elemIDs.push_back( theElements[ i ]->GetID() );
4368 // remove refined elements
4369 editor.Remove( elemIDs, false );
4373 //=======================================================================
4374 //function : isReversed
4375 //purpose : check xyz ids order in theIdsList taking into account
4376 // theFirstNode on a link
4377 //=======================================================================
4379 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4380 const list< int >& theIdsList) const
4382 if ( theIdsList.size() < 2 )
4385 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4387 list<int>::const_iterator id = theIdsList.begin();
4388 for ( int i = 0; i < 2; ++i, ++id ) {
4389 if ( *id < (int) myXYZ.size() )
4390 P[ i ] = myXYZ[ *id ];
4392 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4393 i_n = myXYZIdToNodeMap.find( *id );
4394 ASSERT( i_n != myXYZIdToNodeMap.end() );
4395 const SMDS_MeshNode* n = i_n->second;
4396 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4399 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4403 //=======================================================================
4404 //function : arrangeBoundaries
4405 //purpose : if there are several wires, arrange boundaryPoints so that
4406 // the outer wire goes first and fix inner wires orientation
4407 // update myKeyPointIDs to correspond to the order of key-points
4408 // in boundaries; sort internal boundaries by the nb of key-points
4409 //=======================================================================
4411 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4413 typedef list< list< TPoint* > >::iterator TListOfListIt;
4414 TListOfListIt bndIt;
4415 list< TPoint* >::iterator pIt;
4417 int nbBoundaries = boundaryList.size();
4418 if ( nbBoundaries > 1 )
4420 // sort boundaries by nb of key-points
4421 if ( nbBoundaries > 2 )
4423 // move boundaries in tmp list
4424 list< list< TPoint* > > tmpList;
4425 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4426 // make a map nb-key-points to boundary-position-in-tmpList,
4427 // boundary-positions get ordered in it
4428 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4429 TNbKpBndPosMap nbKpBndPosMap;
4430 bndIt = tmpList.begin();
4431 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4432 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4433 int nb = *nbKpIt * nbBoundaries;
4434 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4436 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4438 // move boundaries back to boundaryList
4439 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4440 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4441 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4442 TListOfListIt bndPos1 = bndPos2++;
4443 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4447 // Look for the outer boundary: the one with the point with the least X
4448 double leastX = DBL_MAX;
4449 TListOfListIt outerBndPos;
4450 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4452 list< TPoint* >& boundary = (*bndIt);
4453 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4455 TPoint* point = *pIt;
4456 if ( point->myInitXYZ.X() < leastX ) {
4457 leastX = point->myInitXYZ.X();
4458 outerBndPos = bndIt;
4463 if ( outerBndPos != boundaryList.begin() )
4464 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos );
4466 } // if nbBoundaries > 1
4468 // Check boundaries orientation and re-fill myKeyPointIDs
4470 set< TPoint* > keyPointSet;
4471 list< int >::iterator kpIt = myKeyPointIDs.begin();
4472 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4473 keyPointSet.insert( & myPoints[ *kpIt ]);
4474 myKeyPointIDs.clear();
4476 // update myNbKeyPntInBoundary also
4477 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4479 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4481 // find the point with the least X
4482 double leastX = DBL_MAX;
4483 list< TPoint* >::iterator xpIt;
4484 list< TPoint* >& boundary = (*bndIt);
4485 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4487 TPoint* point = *pIt;
4488 if ( point->myInitXYZ.X() < leastX ) {
4489 leastX = point->myInitXYZ.X();
4493 // find points next to the point with the least X
4494 TPoint* p = *xpIt, *pPrev, *pNext;
4495 if ( p == boundary.front() )
4496 pPrev = *(++boundary.rbegin());
4502 if ( p == boundary.back() )
4503 pNext = *(++boundary.begin());
4508 // vectors of boundary direction near <p>
4509 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4510 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4511 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4512 double yPrev = v1.Y() / sqrt( sqMag1 );
4513 double yNext = v2.Y() / sqrt( sqMag2 );
4514 double sumY = yPrev + yNext;
4516 if ( bndIt == boundaryList.begin() ) // outer boundary
4524 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4525 (*nbKpIt) = 0; // count nb of key-points again
4526 pIt = boundary.begin();
4527 for ( ; pIt != boundary.end(); pIt++)
4529 TPoint* point = *pIt;
4530 if ( keyPointSet.find( point ) == keyPointSet.end() )
4532 // find an index of a keypoint
4534 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4535 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4536 if ( &(*pVecIt) == point )
4538 myKeyPointIDs.push_back( index );
4541 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4544 } // loop on a list of boundaries
4546 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4549 //=======================================================================
4550 //function : findBoundaryPoints
4551 //purpose : if loaded from file, find points to map on edges and faces and
4552 // compute their parameters
4553 //=======================================================================
4555 bool SMESH_Pattern::findBoundaryPoints()
4557 if ( myIsBoundaryPointsFound ) return true;
4559 myNbKeyPntInBoundary.clear();
4563 set< TPoint* > pointsInElems;
4565 // Find free links of elements:
4566 // put links of all elements in a set and remove links encountered twice
4568 typedef pair< TPoint*, TPoint*> TLink;
4569 set< TLink > linkSet;
4570 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4571 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4573 TElemDef & elemPoints = *epIt;
4574 TElemDef::iterator pIt = elemPoints.begin();
4575 int prevP = elemPoints.back();
4576 for ( ; pIt != elemPoints.end(); pIt++ ) {
4577 TPoint* p1 = & myPoints[ prevP ];
4578 TPoint* p2 = & myPoints[ *pIt ];
4579 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4580 ASSERT( link.first != link.second );
4581 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4582 if ( !itUniq.second )
4583 linkSet.erase( itUniq.first );
4586 pointsInElems.insert( p1 );
4589 // Now linkSet contains only free links,
4590 // find the points order that they have in boundaries
4592 // 1. make a map of key-points
4593 set< TPoint* > keyPointSet;
4594 list< int >::iterator kpIt = myKeyPointIDs.begin();
4595 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4596 keyPointSet.insert( & myPoints[ *kpIt ]);
4598 // 2. chain up boundary points
4599 list< list< TPoint* > > boundaryList;
4600 boundaryList.push_back( list< TPoint* >() );
4601 list< TPoint* > * boundary = & boundaryList.back();
4603 TPoint *point1, *point2, *keypoint1;
4604 kpIt = myKeyPointIDs.begin();
4605 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4606 // loop on free links: look for the next point
4608 set< TLink >::iterator lIt = linkSet.begin();
4609 while ( lIt != linkSet.end() )
4611 if ( (*lIt).first == point1 )
4612 point2 = (*lIt).second;
4613 else if ( (*lIt).second == point1 )
4614 point2 = (*lIt).first;
4619 linkSet.erase( lIt );
4620 lIt = linkSet.begin();
4622 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4624 boundary->push_back( point2 );
4626 else // a key-point found
4628 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4630 if ( point2 != keypoint1 ) // its not the boundary end
4632 boundary->push_back( point2 );
4634 else // the boundary end reached
4636 boundary->push_front( keypoint1 );
4637 boundary->push_back( keypoint1 );
4638 myNbKeyPntInBoundary.push_back( iKeyPoint );
4639 if ( keyPointSet.empty() )
4640 break; // all boundaries containing key-points are found
4642 // prepare to search for the next boundary
4643 boundaryList.push_back( list< TPoint* >() );
4644 boundary = & boundaryList.back();
4645 point2 = keypoint1 = (*keyPointSet.begin());
4649 } // loop on the free links set
4651 if ( boundary->empty() ) {
4652 MESSAGE(" a separate key-point");
4653 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4656 // if there are several wires, arrange boundaryPoints so that
4657 // the outer wire goes first and fix inner wires orientation;
4658 // sort myKeyPointIDs to correspond to the order of key-points
4660 arrangeBoundaries( boundaryList );
4662 // Find correspondence shape ID - points,
4663 // compute points parameter on edge
4665 keyPointSet.clear();
4666 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4667 keyPointSet.insert( & myPoints[ *kpIt ]);
4669 set< TPoint* > edgePointSet; // to find in-face points
4670 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4671 int edgeID = myKeyPointIDs.size() + 1;
4673 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4674 for ( ; bndIt != boundaryList.end(); bndIt++ )
4676 boundary = & (*bndIt);
4677 double edgeLength = 0;
4678 list< TPoint* >::iterator pIt = boundary->begin();
4679 getShapePoints( edgeID ).push_back( *pIt );
4680 getShapePoints( vertexID++ ).push_back( *pIt );
4681 for ( pIt++; pIt != boundary->end(); pIt++)
4683 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4684 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4685 TPoint* point = *pIt;
4686 edgePointSet.insert( point );
4687 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4689 edgePoints.push_back( point );
4690 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4691 point->myInitU = edgeLength;
4695 // treat points on the edge which ends up: compute U [0,1]
4696 edgePoints.push_back( point );
4697 if ( edgePoints.size() > 2 ) {
4698 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4699 list< TPoint* >::iterator epIt = edgePoints.begin();
4700 for ( ; epIt != edgePoints.end(); epIt++ )
4701 (*epIt)->myInitU /= edgeLength;
4703 // begin the next edge treatment
4706 if ( point != boundary->front() ) { // not the first key-point again
4707 getShapePoints( edgeID ).push_back( point );
4708 getShapePoints( vertexID++ ).push_back( point );
4714 // find in-face points
4715 list< TPoint* > & facePoints = getShapePoints( edgeID );
4716 vector< TPoint >::iterator pVecIt = myPoints.begin();
4717 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4718 TPoint* point = &(*pVecIt);
4719 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4720 pointsInElems.find( point ) != pointsInElems.end())
4721 facePoints.push_back( point );
4728 // bind points to shapes according to point parameters
4729 vector< TPoint >::iterator pVecIt = myPoints.begin();
4730 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4731 TPoint* point = &(*pVecIt);
4732 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4733 getShapePoints( shapeID ).push_back( point );
4734 // detect key-points
4735 if ( SMESH_Block::IsVertexID( shapeID ))
4736 myKeyPointIDs.push_back( i );
4740 myIsBoundaryPointsFound = true;
4741 return myIsBoundaryPointsFound;
4744 //=======================================================================
4746 //purpose : clear fields
4747 //=======================================================================
4749 void SMESH_Pattern::Clear()
4751 myIsComputed = myIsBoundaryPointsFound = false;
4754 myKeyPointIDs.clear();
4755 myElemPointIDs.clear();
4756 myShapeIDToPointsMap.clear();
4757 myShapeIDMap.Clear();
4759 myNbKeyPntInBoundary.clear();
4762 myElemXYZIDs.clear();
4763 myXYZIdToNodeMap.clear();
4765 myOrderedNodes.clear();
4766 myPolyElems.clear();
4767 myPolyElemXYZIDs.clear();
4768 myPolyhedronQuantities.clear();
4769 myIdsOnBoundary.clear();
4770 myReverseConnectivity.clear();
4773 //================================================================================
4775 * \brief set ErrorCode and return true if it is Ok
4777 //================================================================================
4779 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4781 myErrorCode = theErrorCode;
4782 return myErrorCode == ERR_OK;
4785 //=======================================================================
4786 //function : setShapeToMesh
4787 //purpose : set a shape to be meshed. Return True if meshing is possible
4788 //=======================================================================
4790 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4792 if ( !IsLoaded() ) {
4793 MESSAGE( "Pattern not loaded" );
4794 return setErrorCode( ERR_APPL_NOT_LOADED );
4797 TopAbs_ShapeEnum aType = theShape.ShapeType();
4798 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4800 MESSAGE( "Pattern dimension mismatch" );
4801 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4804 // check if a face is closed
4805 int nbNodeOnSeamEdge = 0;
4807 TopTools_MapOfShape seamVertices;
4808 TopoDS_Face face = TopoDS::Face( theShape );
4809 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4810 for ( ; eExp.More() /*&& nbNodeOnSeamEdge == 0*/; eExp.Next() ) {
4811 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4812 if ( BRep_Tool::IsClosed(ee, face) ) {
4813 // seam edge and vertices encounter twice in theFace
4814 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4815 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4820 // check nb of vertices
4821 TopTools_IndexedMapOfShape vMap;
4822 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4823 if ( vMap.Extent() + nbNodeOnSeamEdge != (int)myKeyPointIDs.size() ) {
4824 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4825 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4828 myElements.clear(); // not refine elements
4829 myElemXYZIDs.clear();
4831 myShapeIDMap.Clear();
4836 //=======================================================================
4837 //function : GetMappedPoints
4838 //purpose : Return nodes coordinates computed by Apply() method
4839 //=======================================================================
4841 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4844 if ( !myIsComputed )
4847 if ( myElements.empty() ) { // applied to shape
4848 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4849 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4850 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4852 else { // applied to mesh elements
4853 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4854 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4855 for ( ; xyz != myXYZ.end(); ++xyz )
4856 if ( !isDefined( *xyz ))
4857 thePoints.push_back( definedXYZ );
4859 thePoints.push_back( & (*xyz) );
4861 return !thePoints.empty();
4865 //=======================================================================
4866 //function : GetPoints
4867 //purpose : Return nodes coordinates of the pattern
4868 //=======================================================================
4870 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4877 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4878 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4879 thePoints.push_back( & (*pVecIt).myInitXYZ );
4881 return ( thePoints.size() > 0 );
4884 //=======================================================================
4885 //function : getShapePoints
4886 //purpose : return list of points located on theShape
4887 //=======================================================================
4889 list< SMESH_Pattern::TPoint* > &
4890 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4893 if ( !myShapeIDMap.Contains( theShape ))
4894 aShapeID = myShapeIDMap.Add( theShape );
4896 aShapeID = myShapeIDMap.FindIndex( theShape );
4898 return myShapeIDToPointsMap[ aShapeID ];
4901 //=======================================================================
4902 //function : getShapePoints
4903 //purpose : return list of points located on the shape
4904 //=======================================================================
4906 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4908 return myShapeIDToPointsMap[ theShapeID ];
4911 //=======================================================================
4912 //function : DumpPoints
4914 //=======================================================================
4916 void SMESH_Pattern::DumpPoints() const
4919 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4920 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4921 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4925 //=======================================================================
4926 //function : TPoint()
4928 //=======================================================================
4930 SMESH_Pattern::TPoint::TPoint()
4933 myInitXYZ.SetCoord(0,0,0);
4934 myInitUV.SetCoord(0.,0.);
4936 myXYZ.SetCoord(0,0,0);
4937 myUV.SetCoord(0.,0.);
4942 //=======================================================================
4943 //function : operator <<
4945 //=======================================================================
4947 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4949 gp_XYZ xyz = p.myInitXYZ;
4950 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4951 gp_XY xy = p.myInitUV;
4952 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4953 double u = p.myInitU;
4954 OS << " u( " << u << " )) " << &p << endl;
4955 xyz = p.myXYZ.XYZ();
4956 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4958 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4960 OS << " u( " << u << " ))" << endl;