1 // Copyright (C) 2007-2011 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Pattern.hxx
23 // Created : Mon Aug 2 10:30:00 2004
24 // Author : Edward AGAPOV (eap)
26 #include "SMESH_Pattern.hxx"
28 #include <BRepAdaptor_Curve.hxx>
29 #include <BRepTools.hxx>
30 #include <BRepTools_WireExplorer.hxx>
31 #include <BRep_Tool.hxx>
32 #include <Bnd_Box.hxx>
33 #include <Bnd_Box2d.hxx>
35 #include <Extrema_ExtPC.hxx>
36 #include <Extrema_GenExtPS.hxx>
37 #include <Extrema_POnSurf.hxx>
38 #include <Geom2d_Curve.hxx>
39 #include <GeomAdaptor_Surface.hxx>
40 #include <Geom_Curve.hxx>
41 #include <Geom_Surface.hxx>
42 #include <Precision.hxx>
43 #include <TopAbs_ShapeEnum.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopLoc_Location.hxx>
47 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TopoDS_Edge.hxx>
50 #include <TopoDS_Face.hxx>
51 #include <TopoDS_Iterator.hxx>
52 #include <TopoDS_Shell.hxx>
53 #include <TopoDS_Vertex.hxx>
54 #include <TopoDS_Wire.hxx>
56 #include <gp_Lin2d.hxx>
57 #include <gp_Pnt2d.hxx>
58 #include <gp_Trsf.hxx>
62 #include "SMDS_EdgePosition.hxx"
63 #include "SMDS_FacePosition.hxx"
64 #include "SMDS_MeshElement.hxx"
65 #include "SMDS_MeshFace.hxx"
66 #include "SMDS_MeshNode.hxx"
67 #include "SMDS_VolumeTool.hxx"
68 #include "SMESHDS_Group.hxx"
69 #include "SMESHDS_Mesh.hxx"
70 #include "SMESHDS_SubMesh.hxx"
71 #include "SMESH_Block.hxx"
72 #include "SMESH_Mesh.hxx"
73 #include "SMESH_MesherHelper.hxx"
74 #include "SMESH_subMesh.hxx"
76 #include <Basics_OCCTVersion.hxx>
78 #include <Basics_Utils.hxx>
79 #include "utilities.h"
83 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
85 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
87 //=======================================================================
88 //function : SMESH_Pattern
90 //=======================================================================
92 SMESH_Pattern::SMESH_Pattern ()
95 //=======================================================================
98 //=======================================================================
100 static inline int getInt( const char * theSring )
102 if ( *theSring < '0' || *theSring > '9' )
106 int val = strtol( theSring, &ptr, 10 );
107 if ( ptr == theSring ||
108 // there must not be neither '.' nor ',' nor 'E' ...
109 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
115 //=======================================================================
116 //function : getDouble
118 //=======================================================================
120 static inline double getDouble( const char * theSring )
123 return strtod( theSring, &ptr );
126 //=======================================================================
127 //function : readLine
128 //purpose : Put token starting positions in theFields until '\n' or '\0'
129 // Return the number of the found tokens
130 //=======================================================================
132 static int readLine (list <const char*> & theFields,
133 const char* & theLineBeg,
134 const bool theClearFields )
136 if ( theClearFields )
141 /* switch ( symbol ) { */
142 /* case white-space: */
143 /* look for a non-space symbol; */
144 /* case string-end: */
147 /* case comment beginning: */
148 /* skip all till a line-end; */
150 /* put its position in theFields, skip till a white-space;*/
156 bool stopReading = false;
159 bool isNumber = false;
160 switch ( *theLineBeg )
162 case ' ': // white space
167 case '\n': // a line ends
168 stopReading = ( nbRead > 0 );
173 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
177 case '\0': // file ends
180 case '-': // real number
185 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
187 theFields.push_back( theLineBeg );
190 while (*theLineBeg != ' ' &&
191 *theLineBeg != '\n' &&
192 *theLineBeg != '\0');
196 return 0; // incorrect file format
202 } while ( !stopReading );
207 //=======================================================================
209 //purpose : Load a pattern from <theFile>
210 //=======================================================================
212 bool SMESH_Pattern::Load (const char* theFileContents)
214 MESSAGE("Load( file ) ");
216 Kernel_Utils::Localizer loc;
220 // ! This is a comment
221 // NB_POINTS ! 1 integer - the number of points in the pattern.
222 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
223 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
225 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
226 // ! elements description goes after all
227 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
232 const char* lineBeg = theFileContents;
233 list <const char*> fields;
234 const bool clearFields = true;
236 // NB_POINTS ! 1 integer - the number of points in the pattern.
238 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
239 MESSAGE("Error reading NB_POINTS");
240 return setErrorCode( ERR_READ_NB_POINTS );
242 int nbPoints = getInt( fields.front() );
244 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
246 // read the first point coordinates to define pattern dimention
247 int dim = readLine( fields, lineBeg, clearFields );
253 MESSAGE("Error reading points: wrong nb of coordinates");
254 return setErrorCode( ERR_READ_POINT_COORDS );
256 if ( nbPoints <= dim ) {
257 MESSAGE(" Too few points ");
258 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
261 // read the rest points
263 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
264 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
265 MESSAGE("Error reading points : wrong nb of coordinates ");
266 return setErrorCode( ERR_READ_POINT_COORDS );
268 // store point coordinates
269 myPoints.resize( nbPoints );
270 list <const char*>::iterator fIt = fields.begin();
271 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
273 TPoint & p = myPoints[ iPoint ];
274 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
276 double coord = getDouble( *fIt );
277 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
278 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
280 return setErrorCode( ERR_READ_3D_COORD );
282 p.myInitXYZ.SetCoord( iCoord, coord );
284 p.myInitUV.SetCoord( iCoord, coord );
288 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
291 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
292 MESSAGE("Error: missing key-points");
294 return setErrorCode( ERR_READ_NO_KEYPOINT );
297 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
299 int pointIndex = getInt( *fIt );
300 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
301 MESSAGE("Error: invalid point index " << pointIndex );
303 return setErrorCode( ERR_READ_BAD_INDEX );
305 if ( idSet.insert( pointIndex ).second ) // unique?
306 myKeyPointIDs.push_back( pointIndex );
310 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
312 while ( readLine( fields, lineBeg, clearFields ))
314 myElemPointIDs.push_back( TElemDef() );
315 TElemDef& elemPoints = myElemPointIDs.back();
316 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
318 int pointIndex = getInt( *fIt );
319 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
320 MESSAGE("Error: invalid point index " << pointIndex );
322 return setErrorCode( ERR_READ_BAD_INDEX );
324 elemPoints.push_back( pointIndex );
326 // check the nb of nodes in element
328 switch ( elemPoints.size() ) {
329 case 3: if ( !myIs2D ) Ok = false; break;
333 case 8: if ( myIs2D ) Ok = false; break;
337 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
339 return setErrorCode( ERR_READ_ELEM_POINTS );
342 if ( myElemPointIDs.empty() ) {
343 MESSAGE("Error: no elements");
345 return setErrorCode( ERR_READ_NO_ELEMS );
348 findBoundaryPoints(); // sort key-points
350 return setErrorCode( ERR_OK );
353 //=======================================================================
355 //purpose : Save the loaded pattern into the file <theFileName>
356 //=======================================================================
358 bool SMESH_Pattern::Save (ostream& theFile)
360 MESSAGE(" ::Save(file) " );
362 Kernel_Utils::Localizer loc;
365 MESSAGE(" Pattern not loaded ");
366 return setErrorCode( ERR_SAVE_NOT_LOADED );
369 theFile << "!!! SALOME Mesh Pattern file" << endl;
370 theFile << "!!!" << endl;
371 theFile << "!!! Nb of points:" << endl;
372 theFile << myPoints.size() << endl;
376 // theFile.width( 8 );
377 // theFile.setf(ios::fixed);// use 123.45 floating notation
378 // theFile.setf(ios::right);
379 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
380 // theFile.setf(ios::showpoint); // do not show trailing zeros
381 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
382 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
383 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
384 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
385 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
386 theFile << " !- " << i << endl; // point id to ease reading by a human being
390 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
391 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
392 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
393 theFile << " " << *kpIt;
394 if ( !myKeyPointIDs.empty() )
398 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
399 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
400 for ( ; epIt != myElemPointIDs.end(); epIt++ )
402 const TElemDef & elemPoints = *epIt;
403 TElemDef::const_iterator iIt = elemPoints.begin();
404 for ( ; iIt != elemPoints.end(); iIt++ )
405 theFile << " " << *iIt;
411 return setErrorCode( ERR_OK );
414 //=======================================================================
415 //function : sortBySize
416 //purpose : sort theListOfList by size
417 //=======================================================================
419 template<typename T> struct TSizeCmp {
420 bool operator ()( const list < T > & l1, const list < T > & l2 )
421 const { return l1.size() < l2.size(); }
424 template<typename T> void sortBySize( list< list < T > > & theListOfList )
426 if ( theListOfList.size() > 2 ) {
427 TSizeCmp< T > SizeCmp;
428 theListOfList.sort( SizeCmp );
432 //=======================================================================
435 //=======================================================================
437 static gp_XY project (const SMDS_MeshNode* theNode,
438 Extrema_GenExtPS & theProjectorPS)
440 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
441 theProjectorPS.Perform( P );
442 if ( !theProjectorPS.IsDone() ) {
443 MESSAGE( "SMESH_Pattern: point projection FAILED");
446 double u, v, minVal = DBL_MAX;
447 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
448 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
449 if ( theProjectorPS.SquareDistance( i ) < minVal ) {
450 minVal = theProjectorPS.SquareDistance( i );
452 if ( theProjectorPS.Value( i ) < minVal ) {
453 minVal = theProjectorPS.Value( i );
455 theProjectorPS.Point( i ).Parameter( u, v );
457 return gp_XY( u, v );
460 //=======================================================================
461 //function : areNodesBound
462 //purpose : true if all nodes of faces are bound to shapes
463 //=======================================================================
465 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
467 while ( faceItr->more() )
469 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
470 while ( nIt->more() )
472 const SMDS_MeshNode* node = smdsNode( nIt->next() );
473 if (node->getshapeId() <1) {
481 //=======================================================================
482 //function : isMeshBoundToShape
483 //purpose : return true if all 2d elements are bound to shape
484 // if aFaceSubmesh != NULL, then check faces bound to it
485 // else check all faces in aMeshDS
486 //=======================================================================
488 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
489 SMESHDS_SubMesh * aFaceSubmesh,
490 const bool isMainShape)
493 // check that all faces are bound to aFaceSubmesh
494 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
498 // check face nodes binding
499 if ( aFaceSubmesh ) {
500 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
501 return areNodesBound( fIt );
503 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
504 return areNodesBound( fIt );
507 //=======================================================================
509 //purpose : Create a pattern from the mesh built on <theFace>.
510 // <theProject>==true makes override nodes positions
511 // on <theFace> computed by mesher
512 //=======================================================================
514 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
515 const TopoDS_Face& theFace,
518 MESSAGE(" ::Load(face) " );
522 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
523 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
524 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
525 SMESH_MesherHelper helper( *theMesh );
526 helper.SetSubShape( theFace );
528 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
529 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
530 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
532 MESSAGE( "No elements bound to the face");
533 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
536 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
538 // check if face is closed
539 bool isClosed = helper.HasSeam();
541 list<TopoDS_Edge> eList;
542 list<TopoDS_Edge>::iterator elIt;
543 SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
545 // check that requested or needed projection is possible
546 bool isMainShape = theMesh->IsMainShape( face );
547 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
548 bool canProject = ( nbElems ? true : isMainShape );
550 canProject = false; // so far
552 if ( ( theProject || needProject ) && !canProject )
553 return setErrorCode( ERR_LOADF_CANT_PROJECT );
555 Extrema_GenExtPS projector;
556 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
557 if ( theProject || needProject )
558 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
561 TNodePointIDMap nodePointIDMap;
562 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
566 MESSAGE("Project the submesh");
567 // ---------------------------------------------------------------
568 // The case where the submesh is projected to theFace
569 // ---------------------------------------------------------------
572 list< const SMDS_MeshElement* > faces;
574 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
575 while ( fIt->more() ) {
576 const SMDS_MeshElement* f = fIt->next();
577 if ( f && f->GetType() == SMDSAbs_Face )
578 faces.push_back( f );
582 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
583 while ( fIt->more() )
584 faces.push_back( fIt->next() );
587 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
588 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
589 for ( ; fIt != faces.end(); ++fIt )
591 myElemPointIDs.push_back( TElemDef() );
592 TElemDef& elemPoints = myElemPointIDs.back();
593 int nbNodes = (*fIt)->NbCornerNodes();
594 for ( int i = 0;i < nbNodes; ++i )
596 const SMDS_MeshElement* node = (*fIt)->GetNode( i );
597 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
598 if ( nIdIt->second == -1 )
600 elemPoints.push_back( iPoint );
601 nIdIt->second = iPoint++;
604 elemPoints.push_back( (*nIdIt).second );
607 myPoints.resize( iPoint );
609 // project all nodes of 2d elements to theFace
610 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
611 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
613 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
614 TPoint * p = & myPoints[ (*nIdIt).second ];
615 p->myInitUV = project( node, projector );
616 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
618 // find key-points: the points most close to UV of vertices
619 TopExp_Explorer vExp( face, TopAbs_VERTEX );
620 set<int> foundIndices;
621 for ( ; vExp.More(); vExp.Next() ) {
622 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
623 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
624 double minDist = DBL_MAX;
626 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
627 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
628 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
629 if ( dist < minDist ) {
634 if ( foundIndices.insert( index ).second ) // unique?
635 myKeyPointIDs.push_back( index );
637 myIsBoundaryPointsFound = false;
642 // ---------------------------------------------------------------------
643 // The case where a pattern is being made from the mesh built by mesher
644 // ---------------------------------------------------------------------
646 // Load shapes in the consequent order and count nb of points
649 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
650 int nbV = myShapeIDMap.Extent();
651 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
652 bool added = ( nbV < myShapeIDMap.Extent() );
653 if ( !added ) { // vertex encountered twice
654 // a seam vertex have two corresponding key points
655 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ).Reversed());
658 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
659 nbNodes += eSubMesh->NbNodes() + 1;
662 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
663 myShapeIDMap.Add( *elIt );
665 myShapeIDMap.Add( face );
667 myPoints.resize( nbNodes );
669 // Load U of points on edges
671 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
673 TopoDS_Edge & edge = *elIt;
674 list< TPoint* > & ePoints = getShapePoints( edge );
676 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
677 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
679 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
680 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
681 // to make adjacent edges share key-point, we make v2 FORWARD too
682 // (as we have different points for same shape with different orienation)
685 // on closed face we must have REVERSED some of seam vertices
687 if ( helper.IsSeamShape( edge ) ) {
688 if ( helper.IsRealSeam( edge ) && !isForward ) {
689 // reverse on reversed SEAM edge
694 else { // on CLOSED edge (i.e. having one vertex with different orienations)
695 for ( int is2 = 0; is2 < 2; ++is2 ) {
696 TopoDS_Shape & v = is2 ? v2 : v1;
697 if ( helper.IsRealSeam( v ) ) {
698 // reverse or not depending on orientation of adjacent seam
700 list<TopoDS_Edge>::iterator eIt2 = elIt;
702 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
704 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
705 if ( seam.Orientation() == TopAbs_REVERSED )
712 // the forward key-point
713 list< TPoint* > * vPoint = & getShapePoints( v1 );
714 if ( vPoint->empty() )
716 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
717 if ( vSubMesh && vSubMesh->NbNodes() ) {
718 myKeyPointIDs.push_back( iPoint );
719 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
720 const SMDS_MeshNode* node = nIt->next();
721 if ( v1.Orientation() == TopAbs_REVERSED )
722 closeNodePointIDMap.insert( make_pair( node, iPoint ));
724 nodePointIDMap.insert( make_pair( node, iPoint ));
726 TPoint* keyPoint = &myPoints[ iPoint++ ];
727 vPoint->push_back( keyPoint );
729 keyPoint->myInitUV = project( node, projector );
731 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
732 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
735 if ( !vPoint->empty() )
736 ePoints.push_back( vPoint->front() );
739 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
740 if ( eSubMesh && eSubMesh->NbNodes() )
742 // loop on nodes of an edge: sort them by param on edge
743 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
744 TParamNodeMap paramNodeMap;
745 int nbMeduimNodes = 0;
746 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
747 while ( nIt->more() )
749 const SMDS_MeshNode* node = nIt->next();
750 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
754 const SMDS_EdgePosition* epos =
755 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
756 double u = epos->GetUParameter();
757 paramNodeMap.insert( make_pair( u, node ));
759 if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
760 // wrong U on edge, project
762 BRepAdaptor_Curve aCurve( edge );
763 proj.Initialize( aCurve, f, l );
764 paramNodeMap.clear();
765 nIt = eSubMesh->GetNodes();
766 for ( int iNode = 0; nIt->more(); ++iNode ) {
767 const SMDS_MeshNode* node = nIt->next();
768 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
770 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
772 if ( proj.IsDone() ) {
773 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
774 if ( proj.IsMin( i )) {
775 u = proj.Point( i ).Parameter();
779 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
781 paramNodeMap.insert( make_pair( u, node ));
784 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
785 if ( paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
786 return setErrorCode(ERR_UNEXPECTED);
789 // put U in [0,1] so that the first key-point has U==0
790 bool isSeam = helper.IsRealSeam( edge );
792 TParamNodeMap::iterator unIt = paramNodeMap.begin();
793 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
794 while ( unIt != paramNodeMap.end() )
796 TPoint* p = & myPoints[ iPoint ];
797 ePoints.push_back( p );
798 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
799 if ( isSeam && !isForward )
800 closeNodePointIDMap.insert( make_pair( node, iPoint ));
802 nodePointIDMap.insert ( make_pair( node, iPoint ));
805 p->myInitUV = project( node, projector );
807 double u = isForward ? (*unIt).first : (*unRIt).first;
808 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
809 p->myInitUV = C2d->Value( u ).XY();
811 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
816 // the reverse key-point
817 vPoint = & getShapePoints( v2 );
818 if ( vPoint->empty() )
820 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
821 if ( vSubMesh && vSubMesh->NbNodes() ) {
822 myKeyPointIDs.push_back( iPoint );
823 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
824 const SMDS_MeshNode* node = nIt->next();
825 if ( v2.Orientation() == TopAbs_REVERSED )
826 closeNodePointIDMap.insert( make_pair( node, iPoint ));
828 nodePointIDMap.insert( make_pair( node, iPoint ));
830 TPoint* keyPoint = &myPoints[ iPoint++ ];
831 vPoint->push_back( keyPoint );
833 keyPoint->myInitUV = project( node, projector );
835 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
836 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
839 if ( !vPoint->empty() )
840 ePoints.push_back( vPoint->front() );
842 // compute U of edge-points
845 double totalDist = 0;
846 list< TPoint* >::iterator pIt = ePoints.begin();
847 TPoint* prevP = *pIt;
848 prevP->myInitU = totalDist;
849 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
851 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
852 p->myInitU = totalDist;
855 if ( totalDist > DBL_MIN)
856 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
858 p->myInitU /= totalDist;
861 } // loop on edges of a wire
863 // Load in-face points and elements
865 if ( fSubMesh && fSubMesh->NbElements() )
867 list< TPoint* > & fPoints = getShapePoints( face );
868 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
869 while ( nIt->more() )
871 const SMDS_MeshNode* node = nIt->next();
872 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
874 nodePointIDMap.insert( make_pair( node, iPoint ));
875 TPoint* p = &myPoints[ iPoint++ ];
876 fPoints.push_back( p );
878 p->myInitUV = project( node, projector );
880 const SMDS_FacePosition* pos =
881 static_cast<const SMDS_FacePosition*>(node->GetPosition());
882 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
884 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
887 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
888 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
889 while ( elemIt->more() )
891 const SMDS_MeshElement* elem = elemIt->next();
892 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
893 myElemPointIDs.push_back( TElemDef() );
894 TElemDef& elemPoints = myElemPointIDs.back();
895 // find point indices corresponding to element nodes
896 while ( nIt->more() )
898 const SMDS_MeshNode* node = smdsNode( nIt->next() );
899 n_id = nodePointIDMap.find( node );
900 if ( n_id == nodePointIDMap.end() )
901 continue; // medium node
902 iPoint = n_id->second; // point index of interest
903 // for a node on a seam edge there are two points
904 if ( helper.IsRealSeam( node->getshapeId() ) &&
905 ( n_id = closeNodePointIDMap.find( node )) != not_found )
907 TPoint & p1 = myPoints[ iPoint ];
908 TPoint & p2 = myPoints[ n_id->second ];
909 // Select point closest to the rest nodes of element in UV space
910 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
911 const SMDS_MeshNode* notSeamNode = 0;
912 // find node not on a seam edge
913 while ( nIt2->more() && !notSeamNode ) {
914 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
915 if ( !helper.IsSeamShape( n->getshapeId() ))
918 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
919 double dist1 = uv.SquareDistance( p1.myInitUV );
920 double dist2 = uv.SquareDistance( p2.myInitUV );
922 iPoint = n_id->second;
924 elemPoints.push_back( iPoint );
928 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
930 myIsBoundaryPointsFound = true;
933 // Assure that U range is proportional to V range
936 vector< TPoint >::iterator pVecIt = myPoints.begin();
937 for ( ; pVecIt != myPoints.end(); pVecIt++ )
938 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
939 double minU, minV, maxU, maxV;
940 bndBox.Get( minU, minV, maxU, maxV );
941 double dU = maxU - minU, dV = maxV - minV;
942 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
945 // define where is the problem, in the face or in the mesh
946 TopExp_Explorer vExp( face, TopAbs_VERTEX );
947 for ( ; vExp.More(); vExp.Next() ) {
948 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
951 bndBox.Get( minU, minV, maxU, maxV );
952 dU = maxU - minU, dV = maxV - minV;
953 if ( dU <= DBL_MIN || dV <= DBL_MIN )
955 return setErrorCode( ERR_LOADF_NARROW_FACE );
957 // mesh is projected onto a line, e.g.
958 return setErrorCode( ERR_LOADF_CANT_PROJECT );
960 double ratio = dU / dV, maxratio = 3, scale;
962 if ( ratio > maxratio ) {
963 scale = ratio / maxratio;
966 else if ( ratio < 1./maxratio ) {
967 scale = maxratio / ratio;
972 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
973 TPoint & p = *pVecIt;
974 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
975 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
978 if ( myElemPointIDs.empty() ) {
979 MESSAGE( "No elements bound to the face");
980 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
983 return setErrorCode( ERR_OK );
986 //=======================================================================
987 //function : computeUVOnEdge
988 //purpose : compute coordinates of points on theEdge
989 //=======================================================================
991 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
992 const list< TPoint* > & ePoints )
994 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
996 Handle(Geom2d_Curve) C2d =
997 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
999 ePoints.back()->myInitU = 1.0;
1000 list< TPoint* >::const_iterator pIt = ePoints.begin();
1001 for ( pIt++; pIt != ePoints.end(); pIt++ )
1003 TPoint* point = *pIt;
1005 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1006 point->myU = ( f * ( 1 - du ) + l * du );
1008 point->myUV = C2d->Value( point->myU ).XY();
1012 //=======================================================================
1013 //function : intersectIsolines
1015 //=======================================================================
1017 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1018 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1022 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1023 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1024 resUV = 0.5 * ( loc1 + loc2 );
1025 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1026 // SKL 26.07.2007 for NPAL16567
1027 double d1 = (uv11-uv12).Modulus();
1028 double d2 = (uv21-uv22).Modulus();
1029 // double delta = d1*d2*1e-6; PAL17233
1030 double delta = min( d1, d2 ) / 10.;
1031 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1033 // double len1 = ( uv11 - uv12 ).Modulus();
1034 // double len2 = ( uv21 - uv22 ).Modulus();
1035 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1039 // gp_Lin2d line1( uv11, uv12 - uv11 );
1040 // gp_Lin2d line2( uv21, uv22 - uv21 );
1041 // double angle = Abs( line1.Angle( line2 ) );
1043 // IntAna2d_AnaIntersection inter;
1044 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1045 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1047 // gp_Pnt2d interUV = inter.Point(1).Value();
1048 // resUV += interUV.XY();
1049 // inter.Perform( line1, line2 );
1050 // interUV = inter.Point(1).Value();
1051 // resUV += interUV.XY();
1056 MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1057 ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1062 //=======================================================================
1063 //function : compUVByIsoIntersection
1065 //=======================================================================
1067 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1068 const gp_XY& theInitUV,
1070 bool & theIsDeformed )
1072 // compute UV by intersection of 2 iso lines
1073 //gp_Lin2d isoLine[2];
1074 gp_XY uv1[2], uv2[2];
1076 const double zero = DBL_MIN;
1077 for ( int iIso = 0; iIso < 2; iIso++ )
1079 // to build an iso line:
1080 // find 2 pairs of consequent edge-points such that the range of their
1081 // initial parameters encloses the in-face point initial parameter
1082 gp_XY UV[2], initUV[2];
1083 int nbUV = 0, iCoord = iIso + 1;
1084 double initParam = theInitUV.Coord( iCoord );
1086 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1087 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1089 const list< TPoint* > & bndPoints = * bndIt;
1090 TPoint* prevP = bndPoints.back(); // this is the first point
1091 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1092 bool coincPrev = false;
1093 // loop on the edge-points
1094 for ( ; pIt != bndPoints.end(); pIt++ )
1096 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1097 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1098 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1099 if (!coincPrev && // ignore if initParam coincides with prev point param
1100 sumOfDiff > zero && // ignore if both points coincide with initParam
1101 prevParamDiff * paramDiff <= zero )
1103 // find UV in parametric space of theFace
1104 double r = Abs(prevParamDiff) / sumOfDiff;
1105 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1108 // throw away uv most distant from <theInitUV>
1109 gp_XY vec0 = initUV[0] - theInitUV;
1110 gp_XY vec1 = initUV[1] - theInitUV;
1111 gp_XY vec = uvInit - theInitUV;
1112 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1113 double dist0 = vec0.SquareModulus();
1114 double dist1 = vec1.SquareModulus();
1115 double dist = vec .SquareModulus();
1116 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1117 i = ( dist0 < dist1 ? 1 : 0 );
1118 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1119 i = 3; // theInitUV must remain between
1123 initUV[ i ] = uvInit;
1124 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1126 coincPrev = ( Abs(paramDiff) <= zero );
1133 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1134 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1135 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1136 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1138 // an iso line should be normal to UV[0] - UV[1] direction
1139 // and be located at the same relative distance as from initial ends
1140 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1142 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1143 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1144 //isoLine[ iIso ] = iso.Normal( isoLoc );
1145 uv1[ iIso ] = UV[0];
1146 uv2[ iIso ] = UV[1];
1149 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1150 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1151 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1152 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1159 // ==========================================================
1160 // structure representing a node of a grid of iso-poly-lines
1161 // ==========================================================
1168 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1169 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1170 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1171 TIsoNode(double initU, double initV):
1172 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1173 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1174 bool IsUVComputed() const
1175 { return myUV.X() != 1e100; }
1176 bool IsMovable() const
1177 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1178 void SetNotMovable()
1179 { myIsMovable = false; }
1180 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1181 { myBndNodes[ iDir + i * 2 ] = node; }
1182 TIsoNode* GetBoundaryNode(int iDir, int i)
1183 { return myBndNodes[ iDir + i * 2 ]; }
1184 void SetNext(TIsoNode* node, int iDir, int isForward)
1185 { myNext[ iDir + isForward * 2 ] = node; }
1186 TIsoNode* GetNext(int iDir, int isForward)
1187 { return myNext[ iDir + isForward * 2 ]; }
1190 //=======================================================================
1191 //function : getNextNode
1193 //=======================================================================
1195 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1197 TIsoNode* n = node->myNext[ dir ];
1198 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1199 n = 0;//node->myBndNodes[ dir ];
1200 // MESSAGE("getNextNode: use bnd for node "<<
1201 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1205 //=======================================================================
1206 //function : checkQuads
1207 //purpose : check if newUV destortes quadrangles around node,
1208 // and if ( crit == FIX_OLD ) fix newUV in this case
1209 //=======================================================================
1211 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1213 static bool checkQuads (const TIsoNode* node,
1215 const bool reversed,
1216 const int crit = FIX_OLD,
1217 double fixSize = 0.)
1219 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1220 int nbOldFix = 0, nbOldImpr = 0;
1221 double newBadRate = 0, oldBadRate = 0;
1222 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1223 int i, dir1 = 0, dir2 = 3;
1224 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1226 if ( dir2 > 3 ) dir2 = 0;
1228 // walking counterclockwise around a quad,
1229 // nodes are in the order: node, n[0], n[1], n[2]
1230 n[0] = getNextNode( node, dir1 );
1231 n[2] = getNextNode( node, dir2 );
1232 if ( !n[0] || !n[2] ) continue;
1233 n[1] = getNextNode( n[0], dir2 );
1234 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1235 bool isTriangle = ( !n[1] );
1237 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1239 // if ( fixSize != 0 ) {
1240 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1241 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1242 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1243 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1245 // check if a quadrangle is degenerated
1247 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1248 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1251 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1254 // find min size of the diagonal node-n[1]
1255 double minDiag = fixSize;
1256 if ( minDiag == 0. ) {
1257 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1258 if ( !isTriangle ) {
1259 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1260 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1262 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1263 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1266 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1267 // ( behind means "to the right of")
1269 // 1. newUV is not behind 01 and 12 dirs
1270 // 2. or newUV is not behind 02 dir and n[2] is convex
1271 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1272 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1273 gp_Vec2d moveVec[3], outVec[3];
1274 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1276 bool isDiag = ( i == 2 );
1277 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1281 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1283 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1285 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1287 gp_Vec2d newDir( n[i]->myUV, newUV );
1288 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1290 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1291 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1292 if ( crit == FIX_OLD ) {
1293 wasIn[i] = ( outDir * oldDir < 0 );
1294 wasOk[i] = ( outDir * oldDir < -minDiag );
1296 newBadRate += outDir * newDir;
1298 oldBadRate += outDir * oldDir;
1301 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1302 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1303 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1304 moveVec[i] = ( oldDist - minDiag ) * outDir;
1309 // check if n[2] is convex
1312 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1314 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1315 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1316 newIsOk = ( newIsOk && isNewOk );
1317 newIsIn = ( newIsIn && isNewIn );
1319 if ( crit != FIX_OLD ) {
1320 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1321 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1325 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1326 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1327 oldIsIn = ( oldIsIn && isOldIn );
1328 oldIsOk = ( oldIsOk && isOldIn );
1331 if ( !isOldIn ) { // node is outside a quadrangle
1332 // move newUV inside a quadrangle
1333 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1334 // node and newUV are outside: push newUV inside
1336 if ( convex || isTriangle ) {
1337 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1340 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1341 double outSize = out.Magnitude();
1342 if ( outSize > DBL_MIN )
1345 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1346 uv = n[1]->myUV - minDiag * out.XY();
1348 oldUVFixed[ nbOldFix++ ] = uv;
1349 //node->myUV = newUV;
1351 else if ( !isOldOk ) {
1352 // try to fix old UV: move node inside as less as possible
1353 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1354 gp_XY uv1, uv2 = node->myUV;
1355 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1357 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1358 while ( !isOldOk ) {
1359 // find the least moveVec
1361 double minMove2 = 1e100;
1362 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1364 if ( moveVec[i].Coord(1) < 1e100 ) {
1365 double move2 = moveVec[i].SquareMagnitude();
1366 if ( move2 < minMove2 ) {
1375 // move node to newUV
1376 uv1 = node->myUV + moveVec[ iMin ].XY();
1377 uv2 += moveVec[ iMin ].XY();
1378 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1379 // check if uv1 is ok
1380 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1381 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1382 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1384 oldUVImpr[ nbOldImpr++ ] = uv1;
1386 // check if uv2 is ok
1387 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1388 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1389 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1391 oldUVImpr[ nbOldImpr++ ] = uv2;
1396 } // loop on 4 quadrangles around <node>
1398 if ( crit == CHECK_NEW_OK )
1400 if ( crit == CHECK_NEW_IN )
1409 if ( oldIsIn && nbOldImpr ) {
1410 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1411 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1412 gp_XY uv = oldUVImpr[ 0 ];
1413 for ( int i = 1; i < nbOldImpr; i++ )
1414 uv += oldUVImpr[ i ];
1416 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1421 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1424 if ( !oldIsIn && nbOldFix ) {
1425 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1426 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1427 gp_XY uv = oldUVFixed[ 0 ];
1428 for ( int i = 1; i < nbOldFix; i++ )
1429 uv += oldUVFixed[ i ];
1431 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1436 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1439 if ( newIsIn && oldIsIn )
1440 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1441 else if ( !newIsIn )
1448 //=======================================================================
1449 //function : compUVByElasticIsolines
1450 //purpose : compute UV as nodes of iso-poly-lines consisting of
1451 // segments keeping relative size as in the pattern
1452 //=======================================================================
1453 //#define DEB_COMPUVBYELASTICISOLINES
1454 bool SMESH_Pattern::
1455 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1456 const list< TPoint* >& thePntToCompute)
1458 return false; // PAL17233
1459 //cout << "============================== KEY POINTS =============================="<<endl;
1460 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1461 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1462 // TPoint& p = myPoints[ *kpIt ];
1463 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1464 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1466 //cout << "=============================="<<endl;
1468 // Define parameters of iso-grid nodes in U and V dir
1470 set< double > paramSet[ 2 ];
1471 list< list< TPoint* > >::const_iterator pListIt;
1472 list< TPoint* >::const_iterator pIt;
1473 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1474 const list< TPoint* > & pList = * pListIt;
1475 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1476 paramSet[0].insert( (*pIt)->myInitUV.X() );
1477 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1480 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1481 paramSet[0].insert( (*pIt)->myInitUV.X() );
1482 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1484 // unite close parameters and split too long segments
1487 for ( iDir = 0; iDir < 2; iDir++ )
1489 set< double > & params = paramSet[ iDir ];
1490 double range = ( *params.rbegin() - *params.begin() );
1491 double toler = range / 1e6;
1492 tol[ iDir ] = toler;
1493 // double maxSegment = range / params.size() / 2.;
1495 // set< double >::iterator parIt = params.begin();
1496 // double prevPar = *parIt;
1497 // for ( parIt++; parIt != params.end(); parIt++ )
1499 // double segLen = (*parIt) - prevPar;
1500 // if ( segLen < toler )
1501 // ;//params.erase( prevPar ); // unite
1502 // else if ( segLen > maxSegment )
1503 // params.insert( prevPar + 0.5 * segLen ); // split
1504 // prevPar = (*parIt);
1508 // Make nodes of a grid of iso-poly-lines
1510 list < TIsoNode > nodes;
1511 typedef list < TIsoNode *> TIsoLine;
1512 map < double, TIsoLine > isoMap[ 2 ];
1514 set< double > & params0 = paramSet[ 0 ];
1515 set< double >::iterator par0It = params0.begin();
1516 for ( ; par0It != params0.end(); par0It++ )
1518 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1519 set< double > & params1 = paramSet[ 1 ];
1520 set< double >::iterator par1It = params1.begin();
1521 for ( ; par1It != params1.end(); par1It++ )
1523 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1524 isoLine0.push_back( & nodes.back() );
1525 isoMap[1][ *par1It ].push_back( & nodes.back() );
1529 // Compute intersections of boundaries with iso-lines:
1530 // only boundary nodes will have computed UV so far
1533 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1534 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1535 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1537 const list< TPoint* > & bndPoints = * bndIt;
1538 TPoint* prevP = bndPoints.back(); // this is the first point
1539 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1540 // loop on the edge-points
1541 for ( ; pIt != bndPoints.end(); pIt++ )
1543 TPoint* point = *pIt;
1544 for ( iDir = 0; iDir < 2; iDir++ )
1546 const int iCoord = iDir + 1;
1547 const int iOtherCoord = 2 - iDir;
1548 double par1 = prevP->myInitUV.Coord( iCoord );
1549 double par2 = point->myInitUV.Coord( iCoord );
1550 double parDif = par2 - par1;
1551 if ( Abs( parDif ) <= DBL_MIN )
1553 // find iso-lines intersecting a bounadry
1554 double toler = tol[ 1 - iDir ];
1555 double minPar = Min ( par1, par2 );
1556 double maxPar = Max ( par1, par2 );
1557 map < double, TIsoLine >& isos = isoMap[ iDir ];
1558 map < double, TIsoLine >::iterator isoIt = isos.begin();
1559 for ( ; isoIt != isos.end(); isoIt++ )
1561 double isoParam = (*isoIt).first;
1562 if ( isoParam < minPar || isoParam > maxPar )
1564 double r = ( isoParam - par1 ) / parDif;
1565 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1566 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1567 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1568 // find existing node with otherPar or insert a new one
1569 TIsoLine & isoLine = (*isoIt).second;
1571 TIsoLine::iterator nIt = isoLine.begin();
1572 for ( ; nIt != isoLine.end(); nIt++ ) {
1573 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1574 if ( nodePar >= otherPar )
1578 if ( Abs( nodePar - otherPar ) <= toler )
1579 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1581 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1582 node = & nodes.back();
1583 isoLine.insert( nIt, node );
1585 node->SetNotMovable();
1587 uvBnd.Add( gp_Pnt2d( uv ));
1588 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1590 gp_XY tgt( point->myUV - prevP->myUV );
1591 if ( ::IsEqual( r, 1. ))
1592 node->myDir[ 0 ] = tgt;
1593 else if ( ::IsEqual( r, 0. ))
1594 node->myDir[ 1 ] = tgt;
1596 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1597 // keep boundary nodes corresponding to boundary points
1598 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1599 if ( bndNodes.empty() || bndNodes.back() != node )
1600 bndNodes.push_back( node );
1601 } // loop on isolines
1602 } // loop on 2 directions
1604 } // loop on boundary points
1605 } // loop on boundaries
1607 // Define orientation
1609 // find the point with the least X
1610 double leastX = DBL_MAX;
1611 TIsoNode * leftNode;
1612 list < TIsoNode >::iterator nodeIt = nodes.begin();
1613 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1614 TIsoNode & node = *nodeIt;
1615 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1616 leastX = node.myUV.X();
1619 // if ( node.IsUVComputed() ) {
1620 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1621 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1622 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1623 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1626 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1627 //SCRUTE( reversed );
1629 // Prepare internal nodes:
1631 // 2. compute ratios
1632 // 3. find boundary nodes for each node
1633 // 4. remove nodes out of the boundary
1634 for ( iDir = 0; iDir < 2; iDir++ )
1636 const int iCoord = 2 - iDir; // coord changing along an isoline
1637 map < double, TIsoLine >& isos = isoMap[ iDir ];
1638 map < double, TIsoLine >::iterator isoIt = isos.begin();
1639 for ( ; isoIt != isos.end(); isoIt++ )
1641 TIsoLine & isoLine = (*isoIt).second;
1642 bool firstCompNodeFound = false;
1643 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1644 nPrevIt = nIt = nNextIt = isoLine.begin();
1646 nNextIt++; nNextIt++;
1647 while ( nIt != isoLine.end() )
1649 // 1. connect prev - cur
1650 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1651 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1652 firstCompNodeFound = true;
1653 lastCompNodePos = nPrevIt;
1655 if ( firstCompNodeFound ) {
1656 node->SetNext( prevNode, iDir, 0 );
1657 prevNode->SetNext( node, iDir, 1 );
1660 if ( nNextIt != isoLine.end() ) {
1661 double par1 = prevNode->myInitUV.Coord( iCoord );
1662 double par2 = node->myInitUV.Coord( iCoord );
1663 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1664 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1666 // 3. find boundary nodes
1667 if ( node->IsUVComputed() )
1668 lastCompNodePos = nIt;
1669 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1670 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1671 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1672 if ( (*nIt2)->IsUVComputed() )
1674 if ( nIt2 != isoLine.end() ) {
1676 node->SetBoundaryNode( bndNode1, iDir, 0 );
1677 node->SetBoundaryNode( bndNode2, iDir, 1 );
1678 // cout << "--------------------------------------------------"<<endl;
1679 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1680 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1681 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1682 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1683 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1684 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1687 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1688 node->SetBoundaryNode( 0, iDir, 0 );
1689 node->SetBoundaryNode( 0, iDir, 1 );
1693 if ( nNextIt != isoLine.end() ) nNextIt++;
1694 // 4. remove nodes out of the boundary
1695 if ( !firstCompNodeFound )
1696 isoLine.pop_front();
1697 } // loop on isoLine nodes
1699 // remove nodes after the boundary
1700 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1701 // (*nIt)->SetNotMovable();
1702 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1703 } // loop on isolines
1704 } // loop on 2 directions
1706 // Compute local isoline direction for internal nodes
1709 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1710 map < double, TIsoLine >::iterator isoIt = isos.begin();
1711 for ( ; isoIt != isos.end(); isoIt++ )
1713 TIsoLine & isoLine = (*isoIt).second;
1714 TIsoLine::iterator nIt = isoLine.begin();
1715 for ( ; nIt != isoLine.end(); nIt++ )
1717 TIsoNode* node = *nIt;
1718 if ( node->IsUVComputed() || !node->IsMovable() )
1720 gp_Vec2d aTgt[2], aNorm[2];
1723 for ( iDir = 0; iDir < 2; iDir++ )
1725 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1726 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1727 if ( !bndNode1 || !bndNode2 ) {
1731 const int iCoord = 2 - iDir; // coord changing along an isoline
1732 double par1 = bndNode1->myInitUV.Coord( iCoord );
1733 double par2 = node->myInitUV.Coord( iCoord );
1734 double par3 = bndNode2->myInitUV.Coord( iCoord );
1735 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1737 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1738 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1739 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1740 else tgt1.Reverse();
1741 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1743 if ( ratio[ iDir ] < 0.5 )
1744 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1746 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1748 aNorm[ iDir ].Reverse(); // along iDir isoline
1750 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1751 // maybe angle is more than |PI|
1752 if ( Abs( angle ) > PI / 2. ) {
1753 // check direction of the last but one perpendicular isoline
1754 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1755 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1756 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1757 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1758 if ( isoDir * tgt2 < 0 )
1760 double angle2 = tgt1.Angle( isoDir );
1761 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1762 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1763 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1764 //MESSAGE("REVERSE ANGLE");
1767 if ( Abs( angle2 ) > Abs( angle ) ||
1768 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1769 //MESSAGE("Add PI");
1770 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1771 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1772 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1773 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1774 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1775 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1778 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1782 for ( iDir = 0; iDir < 2; iDir++ )
1784 aTgt[iDir].Normalize();
1785 aNorm[1-iDir].Normalize();
1786 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1789 node->myDir[iDir] = //aTgt[iDir];
1790 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1792 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1793 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1794 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1795 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1797 } // loop on iso nodes
1798 } // loop on isolines
1800 // Find nodes to start computing UV from
1802 list< TIsoNode* > startNodes;
1803 list< TIsoNode* >::iterator nIt = bndNodes.end();
1804 TIsoNode* node = *(--nIt);
1805 TIsoNode* prevNode = *(--nIt);
1806 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1808 TIsoNode* nextNode = *nIt;
1809 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1810 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1811 double initAngle = initTgt1.Angle( initTgt2 );
1812 double angle = node->myDir[0].Angle( node->myDir[1] );
1813 if ( reversed ) angle = -angle;
1814 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1815 // find a close internal node
1816 TIsoNode* nClose = 0;
1817 list< TIsoNode* > testNodes;
1818 testNodes.push_back( node );
1819 list< TIsoNode* >::iterator it = testNodes.begin();
1820 for ( ; !nClose && it != testNodes.end(); it++ )
1822 for (int i = 0; i < 4; i++ )
1824 nClose = (*it)->myNext[ i ];
1826 if ( !nClose->IsUVComputed() )
1829 testNodes.push_back( nClose );
1835 startNodes.push_back( nClose );
1836 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1837 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1838 // "initAngle: " << initAngle << " angle: " << angle << endl;
1839 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1840 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1841 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1842 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1848 // Compute starting UV of internal nodes
1850 list < TIsoNode* > internNodes;
1851 bool needIteration = true;
1852 if ( startNodes.empty() ) {
1853 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1854 needIteration = false;
1855 map < double, TIsoLine >& isos = isoMap[ 0 ];
1856 map < double, TIsoLine >::iterator isoIt = isos.begin();
1857 for ( ; isoIt != isos.end(); isoIt++ )
1859 TIsoLine & isoLine = (*isoIt).second;
1860 TIsoLine::iterator nIt = isoLine.begin();
1861 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1863 TIsoNode* node = *nIt;
1864 if ( !node->IsUVComputed() && node->IsMovable() ) {
1865 internNodes.push_back( node );
1867 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1868 node->myUV, needIteration ))
1869 node->myUV = node->myInitUV;
1873 if ( needIteration )
1874 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1876 TIsoNode* node = *nIt, *nClose = 0;
1877 list< TIsoNode* > testNodes;
1878 testNodes.push_back( node );
1879 list< TIsoNode* >::iterator it = testNodes.begin();
1880 for ( ; !nClose && it != testNodes.end(); it++ )
1882 for (int i = 0; i < 4; i++ )
1884 nClose = (*it)->myNext[ i ];
1886 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1889 testNodes.push_back( nClose );
1895 startNodes.push_back( nClose );
1899 double aMin[2], aMax[2], step[2];
1900 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1901 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1902 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1903 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1904 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1906 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1908 TIsoNode *node = *nIt;
1909 if ( node->IsUVComputed() || !node->IsMovable() )
1911 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1912 int nbComp = 0, nbPrev = 0;
1913 for ( iDir = 0; iDir < 2; iDir++ )
1915 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1916 TIsoNode* n = node->GetNext( iDir, 0 );
1917 if ( n->IsUVComputed() )
1920 startNodes.push_back( n );
1921 n = node->GetNext( iDir, 1 );
1922 if ( n->IsUVComputed() )
1925 startNodes.push_back( n );
1927 prevNode1 = prevNode2;
1930 if ( prevNode1 ) nbPrev++;
1931 if ( prevNode2 ) nbPrev++;
1934 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1935 double par = node->myInitUV.Coord( 2 - iDir );
1936 bool isEnd = ( prevPar > par );
1937 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1938 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1939 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1941 MESSAGE("Why we are here?");
1944 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1945 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1946 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1947 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1948 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1949 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1950 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1951 //" par: " << prevPar << endl;
1952 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1953 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1955 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1956 gp_XY & uv1 = prevNode1->myUV;
1957 gp_XY & uv2 = prevNode2->myUV;
1958 // dir = ( uv2 - uv1 );
1959 // double len = dir.Modulus();
1960 // if ( len > DBL_MIN )
1961 // dir /= len * 0.5;
1962 double r = node->myRatio[ iDir ];
1963 newUV += uv1 * ( 1 - r ) + uv2 * r;
1966 newUV += prevNode1->myUV + dir * step[ iDir ];
1972 if ( !nbComp ) continue;
1975 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1977 // check if a quadrangle is not distorted
1979 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1980 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1981 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1982 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1986 internNodes.push_back( node );
1991 static int maxNbIter = 100;
1992 #ifdef DEB_COMPUVBYELASTICISOLINES
1994 bool useNbMoveNode = 0;
1995 static int maxNbNodeMove = 100;
1998 if ( !useNbMoveNode )
1999 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2004 if ( !needIteration) break;
2005 #ifdef DEB_COMPUVBYELASTICISOLINES
2006 if ( nbIter >= maxNbIter ) break;
2009 list < TIsoNode* >::iterator nIt = internNodes.begin();
2010 for ( ; nIt != internNodes.end(); nIt++ ) {
2011 #ifdef DEB_COMPUVBYELASTICISOLINES
2013 cout << nbNodeMove <<" =================================================="<<endl;
2015 TIsoNode * node = *nIt;
2019 for ( iDir = 0; iDir < 2; iDir++ )
2021 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2022 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2023 double r = node->myRatio[ iDir ];
2024 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2025 // line[ iDir ].SetLocation( loc[ iDir ] );
2026 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2029 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2030 // double locR[2] = { 0, 0 };
2031 for ( iDir = 0; iDir < 2; iDir++ )
2033 const int iCoord = 2 - iDir; // coord changing along an isoline
2034 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2035 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2036 if ( !bndNode1 || !bndNode2 ) {
2039 double par1 = bndNode1->myInitUV.Coord( iCoord );
2040 double par2 = node->myInitUV.Coord( iCoord );
2041 double par3 = bndNode2->myInitUV.Coord( iCoord );
2042 double r = ( par2 - par1 ) / ( par3 - par1 );
2043 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2044 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2046 //locR[0] = locR[1] = 0.25;
2047 // intersect the 2 lines and move a node
2048 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2049 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2051 // double intR = 1 - locR[0] - locR[1];
2052 // gp_XY newUV = inter.Point(1).Value().XY();
2053 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2054 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2056 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2057 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2058 // avoid parallel isolines intersection
2059 checkQuads( node, newUV, reversed );
2061 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2063 } // intersection found
2064 #ifdef DEB_COMPUVBYELASTICISOLINES
2065 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2067 } // loop on internal nodes
2068 #ifdef DEB_COMPUVBYELASTICISOLINES
2069 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2071 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2073 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2075 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2076 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2077 #ifndef DEB_COMPUVBYELASTICISOLINES
2082 // Set computed UV to points
2084 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2085 TPoint* point = *pIt;
2086 //gp_XY oldUV = point->myUV;
2087 double minDist = DBL_MAX;
2088 list < TIsoNode >::iterator nIt = nodes.begin();
2089 for ( ; nIt != nodes.end(); nIt++ ) {
2090 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2091 if ( dist < minDist ) {
2093 point->myUV = (*nIt).myUV;
2102 //=======================================================================
2103 //function : setFirstEdge
2104 //purpose : choose the best first edge of theWire; return the summary distance
2105 // between point UV computed by isolines intersection and
2106 // eventual UV got from edge p-curves
2107 //=======================================================================
2109 //#define DBG_SETFIRSTEDGE
2110 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2112 int iE, nbEdges = theWire.size();
2116 // Transform UVs computed by iso to fit bnd box of a wire
2118 // max nb of points on an edge
2120 int eID = theFirstEdgeID;
2121 for ( iE = 0; iE < nbEdges; iE++ )
2122 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2124 // compute bnd boxes
2125 TopoDS_Face face = TopoDS::Face( myShape );
2126 Bnd_Box2d bndBox, eBndBox;
2127 eID = theFirstEdgeID;
2128 list< TopoDS_Edge >::iterator eIt;
2129 list< TPoint* >::iterator pIt;
2130 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2132 // UV by isos stored in TPoint.myXYZ
2133 list< TPoint* > & ePoints = getShapePoints( eID++ );
2134 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2136 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2138 // UV by an edge p-curve
2140 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2141 double dU = ( l - f ) / ( maxNbPnt - 1 );
2142 for ( int i = 0; i < maxNbPnt; i++ )
2143 eBndBox.Add( C2d->Value( f + i * dU ));
2146 // transform UVs by isos
2147 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2148 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2149 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2150 #ifdef DBG_SETFIRSTEDGE
2151 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2152 << eMinPar[1] << " - " << eMaxPar[1] );
2154 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2156 double dMin = eMinPar[i] - minPar[i];
2157 double dMax = eMaxPar[i] - maxPar[i];
2158 double dPar = maxPar[i] - minPar[i];
2159 eID = theFirstEdgeID;
2160 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2162 list< TPoint* > & ePoints = getShapePoints( eID++ );
2163 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2165 double par = (*pIt)->myXYZ.Coord( iC );
2166 double r = ( par - minPar[i] ) / dPar;
2167 par += ( 1 - r ) * dMin + r * dMax;
2168 (*pIt)->myXYZ.SetCoord( iC, par );
2174 double minDist = DBL_MAX;
2175 for ( iE = 0 ; iE < nbEdges; iE++ )
2177 #ifdef DBG_SETFIRSTEDGE
2178 MESSAGE ( " VARIANT " << iE );
2180 // evaluate the distance between UV computed by the 2 methods:
2181 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2183 int eID = theFirstEdgeID;
2184 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2186 list< TPoint* > & ePoints = getShapePoints( eID++ );
2187 computeUVOnEdge( *eIt, ePoints );
2188 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2190 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2191 #ifdef DBG_SETFIRSTEDGE
2192 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2193 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2197 #ifdef DBG_SETFIRSTEDGE
2198 MESSAGE ( "dist -- " << dist );
2200 if ( dist < minDist ) {
2202 eBest = theWire.front();
2204 // check variant with another first edge
2205 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2207 // put the best first edge to the theWire front
2208 if ( eBest != theWire.front() ) {
2209 eIt = find ( theWire.begin(), theWire.end(), eBest );
2210 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2216 //=======================================================================
2217 //function : sortSameSizeWires
2218 //purpose : sort wires in theWireList from theFromWire until theToWire,
2219 // the wires are set in the order to correspond to the order
2220 // of boundaries; after sorting, edges in the wires are put
2221 // in a good order, point UVs on edges are computed and points
2222 // are appended to theEdgesPointsList
2223 //=======================================================================
2225 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2226 const TListOfEdgesList::iterator& theFromWire,
2227 const TListOfEdgesList::iterator& theToWire,
2228 const int theFirstEdgeID,
2229 list< list< TPoint* > >& theEdgesPointsList )
2231 TopoDS_Face F = TopoDS::Face( myShape );
2232 int iW, nbWires = 0;
2233 TListOfEdgesList::iterator wlIt = theFromWire;
2234 while ( wlIt++ != theToWire )
2237 // Recompute key-point UVs by isolines intersection,
2238 // compute CG of key-points for each wire and bnd boxes of GCs
2241 gp_XY orig( gp::Origin2d().XY() );
2242 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2243 Bnd_Box2d bndBox, vBndBox;
2244 int eID = theFirstEdgeID;
2245 list< TopoDS_Edge >::iterator eIt;
2246 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2248 list< TopoDS_Edge > & wire = *wlIt;
2249 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2251 list< TPoint* > & ePoints = getShapePoints( eID++ );
2252 TPoint* p = ePoints.front();
2253 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2254 MESSAGE("cant sortSameSizeWires()");
2257 gcVec[iW] += p->myUV;
2258 bndBox.Add( gp_Pnt2d( p->myUV ));
2259 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2260 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2261 vGcVec[iW] += vXY.XY();
2263 // keep the computed UV to compare against by setFirstEdge()
2264 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2266 gcVec[iW] /= nbWires;
2267 vGcVec[iW] /= nbWires;
2268 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2269 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2272 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2274 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2275 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2276 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2277 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2279 double dMin = vMinPar[i] - minPar[i];
2280 double dMax = vMaxPar[i] - maxPar[i];
2281 double dPar = maxPar[i] - minPar[i];
2282 if ( Abs( dPar ) <= DBL_MIN )
2284 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2285 double par = gcVec[iW].Coord( iC );
2286 double r = ( par - minPar[i] ) / dPar;
2287 par += ( 1 - r ) * dMin + r * dMax;
2288 gcVec[iW].SetCoord( iC, par );
2292 // Define boundary - wire correspondence by GC closeness
2294 TListOfEdgesList tmpWList;
2295 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2296 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2297 TIntWirePosMap bndIndWirePosMap;
2298 vector< bool > bndFound( nbWires, false );
2299 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2301 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2302 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2303 double minDist = DBL_MAX;
2304 gp_XY & wGc = vGcVec[ iW ];
2306 for ( int iB = 0; iB < nbWires; iB++ ) {
2307 if ( bndFound[ iB ] ) continue;
2308 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2309 if ( dist < minDist ) {
2314 bndFound[ bIndex ] = true;
2315 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2320 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2321 eID = theFirstEdgeID;
2322 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2324 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2325 list < TopoDS_Edge > & wire = ( *wirePos );
2327 // choose the best first edge of a wire
2328 setFirstEdge( wire, eID );
2330 // compute eventual UV and fill theEdgesPointsList
2331 theEdgesPointsList.push_back( list< TPoint* >() );
2332 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2333 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2335 list< TPoint* > & ePoints = getShapePoints( eID++ );
2336 computeUVOnEdge( *eIt, ePoints );
2337 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2339 // put wire back to theWireList
2341 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2347 //=======================================================================
2349 //purpose : Compute nodes coordinates applying
2350 // the loaded pattern to <theFace>. The first key-point
2351 // will be mapped into <theVertexOnKeyPoint1>
2352 //=======================================================================
2354 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2355 const TopoDS_Vertex& theVertexOnKeyPoint1,
2356 const bool theReverse)
2358 MESSAGE(" ::Apply(face) " );
2359 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2360 if ( !setShapeToMesh( face ))
2363 // find points on edges, it fills myNbKeyPntInBoundary
2364 if ( !findBoundaryPoints() )
2367 // Define the edges order so that the first edge starts at
2368 // theVertexOnKeyPoint1
2370 list< TopoDS_Edge > eList;
2371 list< int > nbVertexInWires;
2372 int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2373 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2375 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2376 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2378 // check nb wires and edges
2379 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2380 l1.sort(); l2.sort();
2383 MESSAGE( "Wrong nb vertices in wires" );
2384 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2387 // here shapes get IDs, for the outer wire IDs are OK
2388 list<TopoDS_Edge>::iterator elIt = eList.begin();
2389 for ( ; elIt != eList.end(); elIt++ ) {
2390 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2391 bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
2392 // BEGIN: jfa for bug 0019943
2395 for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
2396 const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
2398 for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
2399 if (we.Current().IsSame(*elIt)) {
2401 if (nbe == 2) isClosed1 = true;
2406 // END: jfa for bug 0019943
2408 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
2410 int nbVertices = myShapeIDMap.Extent();
2412 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2413 myShapeIDMap.Add( *elIt );
2415 myShapeIDMap.Add( face );
2417 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2418 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2419 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2422 // points on edges to be used for UV computation of in-face points
2423 list< list< TPoint* > > edgesPointsList;
2424 edgesPointsList.push_back( list< TPoint* >() );
2425 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2426 list< TPoint* >::iterator pIt;
2428 // compute UV of points on the outer wire
2429 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2430 for (iE = 0, elIt = eList.begin();
2431 iE < nbEdgesInOuterWire && elIt != eList.end();
2434 list< TPoint* > & ePoints = getShapePoints( *elIt );
2436 computeUVOnEdge( *elIt, ePoints );
2437 // collect on-edge points (excluding the last one)
2438 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2441 // If there are several wires, define the order of edges of inner wires:
2442 // compute UV of inner edge-points using 2 methods: the one for in-face points
2443 // and the one for on-edge points and then choose the best edge order
2444 // by the best correspondance of the 2 results
2447 // compute UV of inner edge-points using the method for in-face points
2448 // and devide eList into a list of separate wires
2450 list< list< TopoDS_Edge > > wireList;
2451 list<TopoDS_Edge>::iterator eIt = elIt;
2452 list<int>::iterator nbEIt = nbVertexInWires.begin();
2453 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2455 int nbEdges = *nbEIt;
2456 wireList.push_back( list< TopoDS_Edge >() );
2457 list< TopoDS_Edge > & wire = wireList.back();
2458 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2460 list< TPoint* > & ePoints = getShapePoints( *eIt );
2461 pIt = ePoints.begin();
2462 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2464 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2465 MESSAGE("cant Apply(face)");
2468 // keep the computed UV to compare against by setFirstEdge()
2469 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2471 wire.push_back( *eIt );
2474 // remove inner edges from eList
2475 eList.erase( elIt, eList.end() );
2477 // sort wireList by nb edges in a wire
2478 sortBySize< TopoDS_Edge > ( wireList );
2480 // an ID of the first edge of a boundary
2481 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2482 // if ( nbSeamShapes > 0 )
2483 // id1 += 2; // 2 vertices more
2485 // find points - edge correspondence for wires of unique size,
2486 // edge order within a wire should be defined only
2488 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2489 while ( wlIt != wireList.end() )
2491 list< TopoDS_Edge >& wire = (*wlIt);
2492 int nbEdges = wire.size();
2494 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2496 // choose the best first edge of a wire
2497 setFirstEdge( wire, id1 );
2499 // compute eventual UV and collect on-edge points
2500 edgesPointsList.push_back( list< TPoint* >() );
2501 edgesPoints = & edgesPointsList.back();
2503 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2505 list< TPoint* > & ePoints = getShapePoints( eID++ );
2506 computeUVOnEdge( *eIt, ePoints );
2507 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2513 // find boundary - wire correspondence for several wires of same size
2515 id1 = nbVertices + nbEdgesInOuterWire + 1;
2516 wlIt = wireList.begin();
2517 while ( wlIt != wireList.end() )
2519 int nbSameSize = 0, nbEdges = (*wlIt).size();
2520 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2522 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2526 if ( nbSameSize > 0 )
2527 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2530 id1 += nbEdges * ( nbSameSize + 1 );
2533 // add well-ordered edges to eList
2535 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2537 list< TopoDS_Edge >& wire = (*wlIt);
2538 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2541 // re-fill myShapeIDMap - all shapes get good IDs
2543 myShapeIDMap.Clear();
2544 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2545 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2546 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2547 myShapeIDMap.Add( *elIt );
2548 myShapeIDMap.Add( face );
2550 } // there are inner wires
2552 // Compute XYZ of on-edge points
2554 TopLoc_Location loc;
2555 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2557 BRepAdaptor_Curve C3d( *elIt );
2558 list< TPoint* > & ePoints = getShapePoints( iE++ );
2559 pIt = ePoints.begin();
2560 for ( pIt++; pIt != ePoints.end(); pIt++ )
2562 TPoint* point = *pIt;
2563 point->myXYZ = C3d.Value( point->myU );
2567 // Compute UV and XYZ of in-face points
2569 // try to use a simple algo
2570 list< TPoint* > & fPoints = getShapePoints( face );
2571 bool isDeformed = false;
2572 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2573 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2574 (*pIt)->myUV, isDeformed )) {
2575 MESSAGE("cant Apply(face)");
2578 // try to use a complex algo if it is a difficult case
2579 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2581 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2582 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2583 (*pIt)->myUV, isDeformed )) {
2584 MESSAGE("cant Apply(face)");
2589 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2590 const gp_Trsf & aTrsf = loc.Transformation();
2591 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2593 TPoint * point = *pIt;
2594 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2595 if ( !loc.IsIdentity() )
2596 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2599 myIsComputed = true;
2601 return setErrorCode( ERR_OK );
2604 //=======================================================================
2606 //purpose : Compute nodes coordinates applying
2607 // the loaded pattern to <theFace>. The first key-point
2608 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2609 //=======================================================================
2611 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2612 const int theNodeIndexOnKeyPoint1,
2613 const bool theReverse)
2615 // MESSAGE(" ::Apply(MeshFace) " );
2617 if ( !IsLoaded() ) {
2618 MESSAGE( "Pattern not loaded" );
2619 return setErrorCode( ERR_APPL_NOT_LOADED );
2622 // check nb of nodes
2623 const int nbFaceNodes = theFace->NbCornerNodes();
2624 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2625 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2626 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2629 // find points on edges, it fills myNbKeyPntInBoundary
2630 if ( !findBoundaryPoints() )
2633 // check that there are no holes in a pattern
2634 if (myNbKeyPntInBoundary.size() > 1 ) {
2635 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2638 // Define the nodes order
2640 list< const SMDS_MeshNode* > nodes;
2641 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2642 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2644 while ( noIt->more() && iSub < nbFaceNodes ) {
2645 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2646 nodes.push_back( node );
2647 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2650 if ( n != nodes.end() ) {
2652 if ( n != --nodes.end() )
2653 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2656 else if ( n != nodes.begin() )
2657 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2659 list< gp_XYZ > xyzList;
2660 myOrderedNodes.resize( nbFaceNodes );
2661 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2662 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2663 myOrderedNodes[ iSub++] = *n;
2666 // Define a face plane
2668 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2669 gp_Pnt P ( *xyzIt++ );
2670 gp_Vec Vx( P, *xyzIt++ ), N;
2672 N = Vx ^ gp_Vec( P, *xyzIt++ );
2673 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2674 if ( N.SquareMagnitude() <= DBL_MIN )
2675 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2676 gp_Ax2 pos( P, N, Vx );
2678 // Compute UV of key-points on a plane
2679 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2681 gp_Vec vec ( pos.Location(), *xyzIt );
2682 TPoint* p = getShapePoints( iSub ).front();
2683 p->myUV.SetX( vec * pos.XDirection() );
2684 p->myUV.SetY( vec * pos.YDirection() );
2688 // points on edges to be used for UV computation of in-face points
2689 list< list< TPoint* > > edgesPointsList;
2690 edgesPointsList.push_back( list< TPoint* >() );
2691 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2692 list< TPoint* >::iterator pIt;
2694 // compute UV and XYZ of points on edges
2696 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2698 gp_XYZ& xyz1 = *xyzIt++;
2699 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2701 list< TPoint* > & ePoints = getShapePoints( iSub );
2702 ePoints.back()->myInitU = 1.0;
2703 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2704 while ( *pIt != ePoints.back() )
2707 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2708 gp_Vec vec ( pos.Location(), p->myXYZ );
2709 p->myUV.SetX( vec * pos.XDirection() );
2710 p->myUV.SetY( vec * pos.YDirection() );
2712 // collect on-edge points (excluding the last one)
2713 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2716 // Compute UV and XYZ of in-face points
2718 // try to use a simple algo to compute UV
2719 list< TPoint* > & fPoints = getShapePoints( iSub );
2720 bool isDeformed = false;
2721 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2722 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2723 (*pIt)->myUV, isDeformed )) {
2724 MESSAGE("cant Apply(face)");
2727 // try to use a complex algo if it is a difficult case
2728 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2730 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2731 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2732 (*pIt)->myUV, isDeformed )) {
2733 MESSAGE("cant Apply(face)");
2738 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2740 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2743 myIsComputed = true;
2745 return setErrorCode( ERR_OK );
2748 //=======================================================================
2750 //purpose : Compute nodes coordinates applying
2751 // the loaded pattern to <theFace>. The first key-point
2752 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2753 //=======================================================================
2755 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2756 const SMDS_MeshFace* theFace,
2757 const TopoDS_Shape& theSurface,
2758 const int theNodeIndexOnKeyPoint1,
2759 const bool theReverse)
2761 // MESSAGE(" ::Apply(MeshFace) " );
2762 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2763 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2765 const TopoDS_Face& face = TopoDS::Face( theSurface );
2766 TopLoc_Location loc;
2767 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2768 const gp_Trsf & aTrsf = loc.Transformation();
2770 if ( !IsLoaded() ) {
2771 MESSAGE( "Pattern not loaded" );
2772 return setErrorCode( ERR_APPL_NOT_LOADED );
2775 // check nb of nodes
2776 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2777 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2778 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2781 // find points on edges, it fills myNbKeyPntInBoundary
2782 if ( !findBoundaryPoints() )
2785 // check that there are no holes in a pattern
2786 if (myNbKeyPntInBoundary.size() > 1 ) {
2787 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2790 // Define the nodes order
2792 list< const SMDS_MeshNode* > nodes;
2793 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2794 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2796 while ( noIt->more() ) {
2797 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2798 nodes.push_back( node );
2799 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2802 if ( n != nodes.end() ) {
2804 if ( n != --nodes.end() )
2805 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2808 else if ( n != nodes.begin() )
2809 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2812 // find a node not on a seam edge, if necessary
2813 SMESH_MesherHelper helper( *theMesh );
2814 helper.SetSubShape( theSurface );
2815 const SMDS_MeshNode* inFaceNode = 0;
2816 if ( helper.GetNodeUVneedInFaceNode() )
2818 SMESH_MeshEditor editor( theMesh );
2819 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2820 int shapeID = editor.FindShape( *n );
2822 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2823 if ( !helper.IsSeamShape( shapeID ))
2828 // Set UV of key-points (i.e. of nodes of theFace )
2829 vector< gp_XY > keyUV( theFace->NbNodes() );
2830 myOrderedNodes.resize( theFace->NbNodes() );
2831 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2833 TPoint* p = getShapePoints( iSub ).front();
2834 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2835 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2837 keyUV[ iSub-1 ] = p->myUV;
2838 myOrderedNodes[ iSub-1 ] = *n;
2841 // points on edges to be used for UV computation of in-face points
2842 list< list< TPoint* > > edgesPointsList;
2843 edgesPointsList.push_back( list< TPoint* >() );
2844 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2845 list< TPoint* >::iterator pIt;
2847 // compute UV and XYZ of points on edges
2849 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2851 gp_XY& uv1 = keyUV[ i ];
2852 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2854 list< TPoint* > & ePoints = getShapePoints( iSub );
2855 ePoints.back()->myInitU = 1.0;
2856 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2857 while ( *pIt != ePoints.back() )
2860 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2861 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2862 if ( !loc.IsIdentity() )
2863 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2865 // collect on-edge points (excluding the last one)
2866 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2869 // Compute UV and XYZ of in-face points
2871 // try to use a simple algo to compute UV
2872 list< TPoint* > & fPoints = getShapePoints( iSub );
2873 bool isDeformed = false;
2874 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2875 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2876 (*pIt)->myUV, isDeformed )) {
2877 MESSAGE("cant Apply(face)");
2880 // try to use a complex algo if it is a difficult case
2881 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2883 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2884 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2885 (*pIt)->myUV, isDeformed )) {
2886 MESSAGE("cant Apply(face)");
2891 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2893 TPoint * point = *pIt;
2894 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2895 if ( !loc.IsIdentity() )
2896 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2899 myIsComputed = true;
2901 return setErrorCode( ERR_OK );
2904 //=======================================================================
2905 //function : undefinedXYZ
2907 //=======================================================================
2909 static const gp_XYZ& undefinedXYZ()
2911 static gp_XYZ xyz( 1.e100, 0., 0. );
2915 //=======================================================================
2916 //function : isDefined
2918 //=======================================================================
2920 inline static bool isDefined(const gp_XYZ& theXYZ)
2922 return theXYZ.X() < 1.e100;
2925 //=======================================================================
2927 //purpose : Compute nodes coordinates applying
2928 // the loaded pattern to <theFaces>. The first key-point
2929 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2930 //=======================================================================
2932 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2933 std::set<const SMDS_MeshFace*>& theFaces,
2934 const int theNodeIndexOnKeyPoint1,
2935 const bool theReverse)
2937 MESSAGE(" ::Apply(set<MeshFace>) " );
2939 if ( !IsLoaded() ) {
2940 MESSAGE( "Pattern not loaded" );
2941 return setErrorCode( ERR_APPL_NOT_LOADED );
2944 // find points on edges, it fills myNbKeyPntInBoundary
2945 if ( !findBoundaryPoints() )
2948 // check that there are no holes in a pattern
2949 if (myNbKeyPntInBoundary.size() > 1 ) {
2950 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2955 myElemXYZIDs.clear();
2956 myXYZIdToNodeMap.clear();
2958 myIdsOnBoundary.clear();
2959 myReverseConnectivity.clear();
2961 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2962 myElements.reserve( theFaces.size() );
2964 // to find point index
2965 map< TPoint*, int > pointIndex;
2966 for ( int i = 0; i < myPoints.size(); i++ )
2967 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2969 int ind1 = 0; // lowest point index for a face
2974 // SMESH_MeshEditor editor( theMesh );
2976 // apply to each face in theFaces set
2977 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2978 for ( ; face != theFaces.end(); ++face )
2980 // int curShapeId = editor.FindShape( *face );
2981 // if ( curShapeId != shapeID ) {
2982 // if ( curShapeId )
2983 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2986 // shapeID = curShapeId;
2989 if ( shape.IsNull() )
2990 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2992 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2994 MESSAGE( "Failed on " << *face );
2997 myElements.push_back( *face );
2999 // store computed points belonging to elements
3000 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3001 for ( ; ll != myElemPointIDs.end(); ++ll )
3003 myElemXYZIDs.push_back(TElemDef());
3004 TElemDef& xyzIds = myElemXYZIDs.back();
3005 TElemDef& pIds = *ll;
3006 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3007 int pIndex = *id + ind1;
3008 xyzIds.push_back( pIndex );
3009 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3010 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3013 // put points on links to myIdsOnBoundary,
3014 // they will be used to sew new elements on adjacent refined elements
3015 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3016 for ( int i = 0; i < nbNodes; i++ )
3018 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3019 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3020 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
3021 // make a link and a node set
3022 TNodeSet linkSet, node1Set;
3023 linkSet.insert( n1 );
3024 linkSet.insert( n2 );
3025 node1Set.insert( n1 );
3026 list< TPoint* >::iterator p = linkPoints.begin();
3028 // map the first link point to n1
3029 int nId = pointIndex[ *p ] + ind1;
3030 myXYZIdToNodeMap[ nId ] = n1;
3031 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3032 groups.push_back(list< int > ());
3033 groups.back().push_back( nId );
3035 // add the linkSet to the map
3036 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3037 groups.push_back(list< int > ());
3038 list< int >& indList = groups.back();
3039 // add points to the map excluding the end points
3040 for ( p++; *p != linkPoints.back(); p++ )
3041 indList.push_back( pointIndex[ *p ] + ind1 );
3043 ind1 += myPoints.size();
3046 return !myElemXYZIDs.empty();
3049 //=======================================================================
3051 //purpose : Compute nodes coordinates applying
3052 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3053 // will be mapped into <theNode000Index>-th node. The
3054 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3056 //=======================================================================
3058 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3059 const int theNode000Index,
3060 const int theNode001Index)
3062 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3064 if ( !IsLoaded() ) {
3065 MESSAGE( "Pattern not loaded" );
3066 return setErrorCode( ERR_APPL_NOT_LOADED );
3069 // bind ID to points
3070 if ( !findBoundaryPoints() )
3073 // check that there are no holes in a pattern
3074 if (myNbKeyPntInBoundary.size() > 1 ) {
3075 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3080 myElemXYZIDs.clear();
3081 myXYZIdToNodeMap.clear();
3083 myIdsOnBoundary.clear();
3084 myReverseConnectivity.clear();
3086 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3087 myElements.reserve( theVolumes.size() );
3089 // to find point index
3090 map< TPoint*, int > pointIndex;
3091 for ( int i = 0; i < myPoints.size(); i++ )
3092 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3094 int ind1 = 0; // lowest point index for an element
3096 // apply to each element in theVolumes set
3097 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3098 for ( ; vol != theVolumes.end(); ++vol )
3100 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3101 MESSAGE( "Failed on " << *vol );
3104 myElements.push_back( *vol );
3106 // store computed points belonging to elements
3107 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3108 for ( ; ll != myElemPointIDs.end(); ++ll )
3110 myElemXYZIDs.push_back(TElemDef());
3111 TElemDef& xyzIds = myElemXYZIDs.back();
3112 TElemDef& pIds = *ll;
3113 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3114 int pIndex = *id + ind1;
3115 xyzIds.push_back( pIndex );
3116 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3117 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3120 // put points on edges and faces to myIdsOnBoundary,
3121 // they will be used to sew new elements on adjacent refined elements
3122 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3124 // make a set of sub-points
3126 vector< int > subIDs;
3127 if ( SMESH_Block::IsVertexID( Id )) {
3128 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3130 else if ( SMESH_Block::IsEdgeID( Id )) {
3131 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3132 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3133 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3136 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3137 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3138 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3139 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3140 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3141 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3142 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3143 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3146 list< TPoint* > & points = getShapePoints( Id );
3147 list< TPoint* >::iterator p = points.begin();
3148 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3149 groups.push_back(list< int > ());
3150 list< int >& indList = groups.back();
3151 for ( ; p != points.end(); p++ )
3152 indList.push_back( pointIndex[ *p ] + ind1 );
3153 if ( subNodes.size() == 1 ) // vertex case
3154 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3156 ind1 += myPoints.size();
3159 return !myElemXYZIDs.empty();
3162 //=======================================================================
3164 //purpose : Create a pattern from the mesh built on <theBlock>
3165 //=======================================================================
3167 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3168 const TopoDS_Shell& theBlock)
3170 MESSAGE(" ::Load(volume) " );
3173 SMESHDS_SubMesh * aSubMesh;
3175 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3177 // load shapes in myShapeIDMap
3179 TopoDS_Vertex v1, v2;
3180 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3181 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3184 int nbNodes = 0, shapeID;
3185 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3187 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3188 aSubMesh = getSubmeshWithElements( theMesh, S );
3190 nbNodes += aSubMesh->NbNodes();
3192 myPoints.resize( nbNodes );
3194 // load U of points on edges
3195 TNodePointIDMap nodePointIDMap;
3197 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3199 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3200 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3201 aSubMesh = getSubmeshWithElements( theMesh, S );
3202 if ( ! aSubMesh ) continue;
3203 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3204 if ( !nIt->more() ) continue;
3206 // store a node and a point
3207 while ( nIt->more() ) {
3208 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3209 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3211 nodePointIDMap.insert( make_pair( node, iPoint ));
3212 if ( block.IsVertexID( shapeID ))
3213 myKeyPointIDs.push_back( iPoint );
3214 TPoint* p = & myPoints[ iPoint++ ];
3215 shapePoints.push_back( p );
3216 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3217 p->myInitXYZ.SetCoord( 0,0,0 );
3219 list< TPoint* >::iterator pIt = shapePoints.begin();
3222 switch ( S.ShapeType() )
3227 for ( ; pIt != shapePoints.end(); pIt++ ) {
3228 double * coef = block.GetShapeCoef( shapeID );
3229 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3230 if ( coef[ iCoord - 1] > 0 )
3231 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3233 if ( S.ShapeType() == TopAbs_VERTEX )
3236 const TopoDS_Edge& edge = TopoDS::Edge( S );
3238 BRep_Tool::Range( edge, f, l );
3239 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3240 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3241 pIt = shapePoints.begin();
3242 nIt = aSubMesh->GetNodes();
3243 for ( ; nIt->more(); pIt++ )
3245 const SMDS_MeshNode* node = nIt->next();
3246 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3248 const SMDS_EdgePosition* epos =
3249 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3250 double u = ( epos->GetUParameter() - f ) / ( l - f );
3251 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3256 for ( ; pIt != shapePoints.end(); pIt++ )
3258 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3259 MESSAGE( "!block.ComputeParameters()" );
3260 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3264 } // loop on block sub-shapes
3268 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3271 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3272 while ( elemIt->more() ) {
3273 const SMDS_MeshElement* elem = elemIt->next();
3274 myElemPointIDs.push_back( TElemDef() );
3275 TElemDef& elemPoints = myElemPointIDs.back();
3276 int nbNodes = elem->NbCornerNodes();
3277 for ( int i = 0;i < nbNodes; ++i )
3278 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3282 myIsBoundaryPointsFound = true;
3284 return setErrorCode( ERR_OK );
3287 //=======================================================================
3288 //function : getSubmeshWithElements
3289 //purpose : return submesh containing elements bound to theBlock in theMesh
3290 //=======================================================================
3292 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3293 const TopoDS_Shape& theShape)
3295 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3296 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3299 if ( theShape.ShapeType() == TopAbs_SHELL )
3301 // look for submesh of VOLUME
3302 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3303 for (; it.More(); it.Next()) {
3304 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3305 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3313 //=======================================================================
3315 //purpose : Compute nodes coordinates applying
3316 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3317 // will be mapped into <theVertex000>. The (0,0,1)
3318 // fifth key-point will be mapped into <theVertex001>.
3319 //=======================================================================
3321 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3322 const TopoDS_Vertex& theVertex000,
3323 const TopoDS_Vertex& theVertex001)
3325 MESSAGE(" ::Apply(volume) " );
3327 if (!findBoundaryPoints() || // bind ID to points
3328 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3331 SMESH_Block block; // bind ID to shape
3332 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3333 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3335 // compute XYZ of points on shapes
3337 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3339 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3340 list< TPoint* >::iterator pIt = shapePoints.begin();
3341 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3342 switch ( S.ShapeType() )
3344 case TopAbs_VERTEX: {
3346 for ( ; pIt != shapePoints.end(); pIt++ )
3347 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3352 for ( ; pIt != shapePoints.end(); pIt++ )
3353 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3358 for ( ; pIt != shapePoints.end(); pIt++ )
3359 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3363 for ( ; pIt != shapePoints.end(); pIt++ )
3364 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3366 } // loop on block sub-shapes
3368 myIsComputed = true;
3370 return setErrorCode( ERR_OK );
3373 //=======================================================================
3375 //purpose : Compute nodes coordinates applying
3376 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3377 // will be mapped into <theNode000Index>-th node. The
3378 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3380 //=======================================================================
3382 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3383 const int theNode000Index,
3384 const int theNode001Index)
3386 //MESSAGE(" ::Apply(MeshVolume) " );
3388 if (!findBoundaryPoints()) // bind ID to points
3391 SMESH_Block block; // bind ID to shape
3392 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3393 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3394 // compute XYZ of points on shapes
3396 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3398 list< TPoint* > & shapePoints = getShapePoints( ID );
3399 list< TPoint* >::iterator pIt = shapePoints.begin();
3401 if ( block.IsVertexID( ID ))
3402 for ( ; pIt != shapePoints.end(); pIt++ ) {
3403 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3405 else if ( block.IsEdgeID( ID ))
3406 for ( ; pIt != shapePoints.end(); pIt++ ) {
3407 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3409 else if ( block.IsFaceID( ID ))
3410 for ( ; pIt != shapePoints.end(); pIt++ ) {
3411 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3414 for ( ; pIt != shapePoints.end(); pIt++ )
3415 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3416 } // loop on block sub-shapes
3418 myIsComputed = true;
3420 return setErrorCode( ERR_OK );
3423 //=======================================================================
3424 //function : mergePoints
3425 //purpose : Merge XYZ on edges and/or faces.
3426 //=======================================================================
3428 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3430 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3431 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3433 list<list< int > >& groups = idListIt->second;
3434 if ( groups.size() < 2 )
3438 const TNodeSet& nodes = idListIt->first;
3439 double tol2 = 1.e-10;
3440 if ( nodes.size() > 1 ) {
3442 TNodeSet::const_iterator n = nodes.begin();
3443 for ( ; n != nodes.end(); ++n )
3444 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3445 double x, y, z, X, Y, Z;
3446 box.Get( x, y, z, X, Y, Z );
3447 gp_Pnt p( x, y, z ), P( X, Y, Z );
3448 tol2 = 1.e-4 * p.SquareDistance( P );
3451 // to unite groups on link
3452 bool unite = ( uniteGroups && nodes.size() == 2 );
3453 map< double, int > distIndMap;
3454 const SMDS_MeshNode* node = *nodes.begin();
3455 gp_Pnt P( node->X(), node->Y(), node->Z() );
3457 // compare points, replace indices
3459 list< int >::iterator ind1, ind2;
3460 list< list< int > >::iterator grpIt1, grpIt2;
3461 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3463 list< int >& indices1 = *grpIt1;
3465 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3467 list< int >& indices2 = *grpIt2;
3468 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3470 gp_XYZ& p1 = myXYZ[ *ind1 ];
3471 ind2 = indices2.begin();
3472 while ( ind2 != indices2.end() )
3474 gp_XYZ& p2 = myXYZ[ *ind2 ];
3475 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3476 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3478 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3479 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3480 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3481 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3483 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3484 myXYZ[ *ind2 ] = undefinedXYZ();
3485 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3487 ind2 = indices2.erase( ind2 );
3494 if ( unite ) { // sort indices using distIndMap
3495 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3497 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3498 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3499 distIndMap.insert( make_pair( dist, *ind1 ));
3503 if ( unite ) { // put all sorted indices into the first group
3504 list< int >& g = groups.front();
3506 map< double, int >::iterator dist_ind = distIndMap.begin();
3507 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3508 g.push_back( dist_ind->second );
3510 } // loop on myIdsOnBoundary
3513 //=======================================================================
3514 //function : makePolyElements
3515 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3516 //=======================================================================
3518 void SMESH_Pattern::
3519 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3520 const bool toCreatePolygons,
3521 const bool toCreatePolyedrs)
3523 myPolyElemXYZIDs.clear();
3524 myPolyElems.clear();
3525 myPolyElems.reserve( myIdsOnBoundary.size() );
3527 // make a set of refined elements
3528 TIDSortedElemSet avoidSet, elemSet;
3529 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3530 for(; itv!=myElements.end(); itv++) {
3531 const SMDS_MeshElement* el = (*itv);
3532 avoidSet.insert( el );
3534 //avoidSet.insert( myElements.begin(), myElements.end() );
3536 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3538 if ( toCreatePolygons )
3540 int lastFreeId = myXYZ.size();
3542 // loop on links of refined elements
3543 indListIt = myIdsOnBoundary.begin();
3544 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3546 const TNodeSet & linkNodes = indListIt->first;
3547 if ( linkNodes.size() != 2 )
3548 continue; // skip face
3549 const SMDS_MeshNode* n1 = * linkNodes.begin();
3550 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3552 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3553 if ( idGroups.empty() || idGroups.front().empty() )
3556 // find not refined face having n1-n2 link
3560 const SMDS_MeshElement* face =
3561 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3564 avoidSet.insert ( face );
3565 myPolyElems.push_back( face );
3567 // some links of <face> are split;
3568 // make list of xyz for <face>
3569 myPolyElemXYZIDs.push_back(TElemDef());
3570 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3571 // loop on links of a <face>
3572 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3573 int i = 0, nbNodes = face->NbNodes();
3574 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3575 while ( nIt->more() )
3576 nodes[ i++ ] = smdsNode( nIt->next() );
3577 nodes[ i ] = nodes[ 0 ];
3578 for ( i = 0; i < nbNodes; ++i )
3580 // look for point mapped on a link
3581 TNodeSet faceLinkNodes;
3582 faceLinkNodes.insert( nodes[ i ] );
3583 faceLinkNodes.insert( nodes[ i + 1 ] );
3584 if ( faceLinkNodes == linkNodes )
3585 nn_IdList = indListIt;
3587 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3588 // add face point ids
3589 faceNodeIds.push_back( ++lastFreeId );
3590 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3591 if ( nn_IdList != myIdsOnBoundary.end() )
3593 // there are points mapped on a link
3594 list< int >& mappedIds = nn_IdList->second.front();
3595 if ( isReversed( nodes[ i ], mappedIds ))
3596 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3598 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3600 } // loop on links of a <face>
3606 if ( myIs2D && idGroups.size() > 1 ) {
3608 // sew new elements on 2 refined elements sharing n1-n2 link
3610 list< int >& idsOnLink = idGroups.front();
3611 // temporarily add ids of link nodes to idsOnLink
3612 bool rev = isReversed( n1, idsOnLink );
3613 for ( int i = 0; i < 2; ++i )
3616 nodeSet.insert( i ? n2 : n1 );
3617 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3618 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3619 int nodeId = groups.front().front();
3621 if ( rev ) append = !append;
3623 idsOnLink.push_back( nodeId );
3625 idsOnLink.push_front( nodeId );
3627 list< int >::iterator id = idsOnLink.begin();
3628 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3630 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3631 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3632 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3634 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3635 // look for <id> in element definition
3636 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3637 ASSERT ( idDef != pIdList->end() );
3638 // look for 2 neighbour ids of <id> in element definition
3639 for ( int prev = 0; prev < 2; ++prev ) {
3640 TElemDef::iterator idDef2 = idDef;
3642 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3644 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3645 // look for idDef2 on a link starting from id
3646 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3647 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3648 // insert ids located on link between <id> and <id2>
3649 // into the element definition between idDef and idDef2
3651 for ( ; id2 != id; --id2 )
3652 pIdList->insert( idDef, *id2 );
3654 list< int >::iterator id1 = id;
3655 for ( ++id1, ++id2; id1 != id2; ++id1 )
3656 pIdList->insert( idDef2, *id1 );
3662 // remove ids of link nodes
3663 idsOnLink.pop_front();
3664 idsOnLink.pop_back();
3666 } // loop on myIdsOnBoundary
3667 } // if ( toCreatePolygons )
3669 if ( toCreatePolyedrs )
3671 // check volumes adjacent to the refined elements
3672 SMDS_VolumeTool volTool;
3673 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3674 for ( ; refinedElem != myElements.end(); ++refinedElem )
3676 // loop on nodes of refinedElem
3677 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3678 while ( nIt->more() ) {
3679 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3680 // loop on inverse elements of node
3681 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3682 while ( eIt->more() )
3684 const SMDS_MeshElement* elem = eIt->next();
3685 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3686 continue; // skip faces or refined elements
3687 // add polyhedron definition
3688 myPolyhedronQuantities.push_back(vector<int> ());
3689 myPolyElemXYZIDs.push_back(TElemDef());
3690 vector<int>& quantity = myPolyhedronQuantities.back();
3691 TElemDef & elemDef = myPolyElemXYZIDs.back();
3692 // get definitions of new elements on volume faces
3693 bool makePoly = false;
3694 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3696 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3697 volTool.NbFaceNodes( iF ),
3698 theNodes, elemDef, quantity))
3702 myPolyElems.push_back( elem );
3704 myPolyhedronQuantities.pop_back();
3705 myPolyElemXYZIDs.pop_back();
3713 //=======================================================================
3714 //function : getFacesDefinition
3715 //purpose : return faces definition for a volume face defined by theBndNodes
3716 //=======================================================================
3718 bool SMESH_Pattern::
3719 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3720 const int theNbBndNodes,
3721 const vector< const SMDS_MeshNode* >& theNodes,
3722 list< int >& theFaceDefs,
3723 vector<int>& theQuantity)
3725 bool makePoly = false;
3727 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3729 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3731 // make a set of all nodes on a face
3733 if ( !myIs2D ) { // for 2D, merge only edges
3734 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3735 if ( nn_IdList != myIdsOnBoundary.end() ) {
3736 list< int > & faceIds = nn_IdList->second.front();
3737 if ( !faceIds.empty() ) {
3739 ids.insert( faceIds.begin(), faceIds.end() );
3744 // add ids on links and bnd nodes
3745 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3746 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3747 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3749 // add id of iN-th bnd node
3751 nSet.insert( theBndNodes[ iN ] );
3752 nn_IdList = myIdsOnBoundary.find( nSet );
3753 int bndId = ++lastFreeId;
3754 if ( nn_IdList != myIdsOnBoundary.end() ) {
3755 bndId = nn_IdList->second.front().front();
3756 ids.insert( bndId );
3759 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3761 faceDef.push_back( bndId );
3762 // add ids on a link
3764 linkNodes.insert( theBndNodes[ iN ]);
3765 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3766 nn_IdList = myIdsOnBoundary.find( linkNodes );
3767 if ( nn_IdList != myIdsOnBoundary.end() ) {
3768 list< int > & linkIds = nn_IdList->second.front();
3769 if ( !linkIds.empty() )
3772 ids.insert( linkIds.begin(), linkIds.end() );
3773 if ( isReversed( theBndNodes[ iN ], linkIds ))
3774 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3776 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3781 // find faces definition of new volumes
3783 bool defsAdded = false;
3784 if ( !myIs2D ) { // for 2D, merge only edges
3785 SMDS_VolumeTool vol;
3786 set< TElemDef* > checkedVolDefs;
3787 set< int >::iterator id = ids.begin();
3788 for ( ; id != ids.end(); ++id )
3790 // definitions of volumes sharing id
3791 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3792 ASSERT( !defList.empty() );
3793 // loop on volume definitions
3794 list< TElemDef* >::iterator pIdList = defList.begin();
3795 for ( ; pIdList != defList.end(); ++pIdList)
3797 if ( !checkedVolDefs.insert( *pIdList ).second )
3798 continue; // skip already checked volume definition
3799 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3800 // loop on face defs of a volume
3801 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3802 if ( volType == SMDS_VolumeTool::UNKNOWN )
3804 int nbFaces = vol.NbFaces( volType );
3805 for ( int iF = 0; iF < nbFaces; ++iF )
3807 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3808 int iN, nbN = vol.NbFaceNodes( volType, iF );
3809 // check if all nodes of a faces are in <ids>
3811 for ( iN = 0; iN < nbN && all; ++iN ) {
3812 int nodeId = idVec[ nodeInds[ iN ]];
3813 all = ( ids.find( nodeId ) != ids.end() );
3816 // store a face definition
3817 for ( iN = 0; iN < nbN; ++iN ) {
3818 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3820 theQuantity.push_back( nbN );
3828 theQuantity.push_back( faceDef.size() );
3829 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3835 //=======================================================================
3836 //function : clearSubMesh
3838 //=======================================================================
3840 static bool clearSubMesh( SMESH_Mesh* theMesh,
3841 const TopoDS_Shape& theShape)
3843 bool removed = false;
3844 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3846 removed = !aSubMesh->IsEmpty();
3848 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3851 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3852 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3854 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3855 removed = eIt->more();
3856 while ( eIt->more() )
3857 aMeshDS->RemoveElement( eIt->next() );
3858 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3859 removed = removed || nIt->more();
3860 while ( nIt->more() )
3861 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3867 //=======================================================================
3868 //function : clearMesh
3869 //purpose : clear mesh elements existing on myShape in theMesh
3870 //=======================================================================
3872 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3875 if ( !myShape.IsNull() )
3877 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3878 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3879 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3881 clearSubMesh( theMesh, it.Value() );
3887 //=======================================================================
3888 //function : MakeMesh
3889 //purpose : Create nodes and elements in <theMesh> using nodes
3890 // coordinates computed by either of Apply...() methods
3891 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3892 // it does not care of nodes and elements already existing on
3893 // sub-shapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3894 //=======================================================================
3896 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3897 const bool toCreatePolygons,
3898 const bool toCreatePolyedrs)
3900 MESSAGE(" ::MakeMesh() " );
3901 if ( !myIsComputed )
3902 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3904 mergePoints( toCreatePolygons );
3906 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3908 // clear elements and nodes existing on myShape
3911 bool onMeshElements = ( !myElements.empty() );
3913 // Create missing nodes
3915 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3916 if ( onMeshElements )
3918 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3919 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3920 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3921 nodesVector[ i_node->first ] = i_node->second;
3923 for ( int i = 0; i < myXYZ.size(); ++i ) {
3924 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3925 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3932 nodesVector.resize( myPoints.size(), 0 );
3934 // to find point index
3935 map< TPoint*, int > pointIndex;
3936 for ( int i = 0; i < myPoints.size(); i++ )
3937 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3939 // loop on sub-shapes of myShape: create nodes
3940 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3941 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3944 //SMESHDS_SubMesh * subMeshDS = 0;
3945 if ( !myShapeIDMap.IsEmpty() ) {
3946 S = myShapeIDMap( idPointIt->first );
3947 //subMeshDS = aMeshDS->MeshElements( S );
3949 list< TPoint* > & points = idPointIt->second;
3950 list< TPoint* >::iterator pIt = points.begin();
3951 for ( ; pIt != points.end(); pIt++ )
3953 TPoint* point = *pIt;
3954 int pIndex = pointIndex[ point ];
3955 if ( nodesVector [ pIndex ] )
3957 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3960 nodesVector [ pIndex ] = node;
3962 if ( !S.IsNull() /*subMeshDS*/ ) {
3963 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3964 switch ( S.ShapeType() ) {
3965 case TopAbs_VERTEX: {
3966 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3969 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3972 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3973 point->myUV.X(), point->myUV.Y() ); break;
3976 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3985 if ( onMeshElements )
3987 // prepare data to create poly elements
3988 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3991 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3992 // sew old and new elements
3993 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3997 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4000 aMeshDS->compactMesh();
4002 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4003 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4004 // for ( ; i_sm != sm.end(); i_sm++ )
4006 // cout << " SM " << i_sm->first << " ";
4007 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4008 // //SMDS_ElemIteratorPtr GetElements();
4009 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4010 // while ( nit->more() )
4011 // cout << nit->next()->GetID() << " ";
4014 return setErrorCode( ERR_OK );
4017 //=======================================================================
4018 //function : createElements
4019 //purpose : add elements to the mesh
4020 //=======================================================================
4022 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4023 const vector<const SMDS_MeshNode* >& theNodesVector,
4024 const list< TElemDef > & theElemNodeIDs,
4025 const vector<const SMDS_MeshElement*>& theElements)
4027 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4028 SMESH_MeshEditor editor( theMesh );
4030 bool onMeshElements = !theElements.empty();
4032 // shapes and groups theElements are on
4033 vector< int > shapeIDs;
4034 vector< list< SMESHDS_Group* > > groups;
4035 set< const SMDS_MeshNode* > shellNodes;
4036 if ( onMeshElements )
4038 shapeIDs.resize( theElements.size() );
4039 groups.resize( theElements.size() );
4040 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4041 set<SMESHDS_GroupBase*>::const_iterator grIt;
4042 for ( int i = 0; i < theElements.size(); i++ )
4044 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4045 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4046 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4047 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4048 groups[ i ].push_back( group );
4051 // get all nodes bound to shells because their SpacePosition is not set
4052 // by SMESHDS_Mesh::SetNodeInVolume()
4053 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4054 if ( !aMainShape.IsNull() ) {
4055 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4056 for ( ; shellExp.More(); shellExp.Next() )
4058 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4060 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4061 while ( nIt->more() )
4062 shellNodes.insert( nIt->next() );
4067 // nb new elements per a refined element
4068 int nbNewElemsPerOld = 1;
4069 if ( onMeshElements )
4070 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4074 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4075 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4076 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4078 const TElemDef & elemNodeInd = *enIt;
4080 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4081 TElemDef::const_iterator id = elemNodeInd.begin();
4083 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4084 if ( *id < theNodesVector.size() )
4085 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4087 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4089 // dim of refined elem
4090 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4091 if ( onMeshElements ) {
4092 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4095 const SMDS_MeshElement* elem = 0;
4097 switch ( nbNodes ) {
4099 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4101 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4103 if ( !onMeshElements ) {// create a quadratic face
4104 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4105 nodes[4], nodes[5] ); break;
4106 } // else do not break but create a polygon
4108 if ( !onMeshElements ) {// create a quadratic face
4109 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4110 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4111 } // else do not break but create a polygon
4113 elem = aMeshDS->AddPolygonalFace( nodes );
4117 switch ( nbNodes ) {
4119 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4121 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4124 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4125 nodes[4], nodes[5] ); break;
4127 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4128 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4130 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4133 // set element on a shape
4134 if ( elem && onMeshElements ) // applied to mesh elements
4136 int shapeID = shapeIDs[ elemIndex ];
4137 if ( shapeID > 0 ) {
4138 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4139 // set nodes on a shape
4140 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4141 if ( S.ShapeType() == TopAbs_SOLID ) {
4142 TopoDS_Iterator shellIt( S );
4143 if ( shellIt.More() )
4144 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4146 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4147 while ( noIt->more() ) {
4148 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4149 if (!node->getshapeId() &&
4150 shellNodes.find( node ) == shellNodes.end() ) {
4151 if ( S.ShapeType() == TopAbs_FACE )
4152 aMeshDS->SetNodeOnFace( node, shapeID,
4153 Precision::Infinite(),// <- it's a sign that UV is not set
4154 Precision::Infinite());
4156 aMeshDS->SetNodeInVolume( node, shapeID );
4157 shellNodes.insert( node );
4162 // add elem in groups
4163 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4164 for ( ; g != groups[ elemIndex ].end(); ++g )
4165 (*g)->SMDSGroup().Add( elem );
4167 if ( elem && !myShape.IsNull() ) // applied to shape
4168 aMeshDS->SetMeshElementOnShape( elem, myShape );
4171 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4172 // so that operations with hypotheses will erase the mesh being built
4174 SMESH_subMesh * subMesh;
4175 if ( !myShape.IsNull() ) {
4176 subMesh = theMesh->GetSubMesh( myShape );
4178 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4180 if ( onMeshElements ) {
4181 list< int > elemIDs;
4182 for ( int i = 0; i < theElements.size(); i++ )
4184 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4186 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4188 elemIDs.push_back( theElements[ i ]->GetID() );
4190 // remove refined elements
4191 editor.Remove( elemIDs, false );
4195 //=======================================================================
4196 //function : isReversed
4197 //purpose : check xyz ids order in theIdsList taking into account
4198 // theFirstNode on a link
4199 //=======================================================================
4201 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4202 const list< int >& theIdsList) const
4204 if ( theIdsList.size() < 2 )
4207 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4209 list<int>::const_iterator id = theIdsList.begin();
4210 for ( int i = 0; i < 2; ++i, ++id ) {
4211 if ( *id < myXYZ.size() )
4212 P[ i ] = myXYZ[ *id ];
4214 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4215 i_n = myXYZIdToNodeMap.find( *id );
4216 ASSERT( i_n != myXYZIdToNodeMap.end() );
4217 const SMDS_MeshNode* n = i_n->second;
4218 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4221 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4225 //=======================================================================
4226 //function : arrangeBoundaries
4227 //purpose : if there are several wires, arrange boundaryPoints so that
4228 // the outer wire goes first and fix inner wires orientation
4229 // update myKeyPointIDs to correspond to the order of key-points
4230 // in boundaries; sort internal boundaries by the nb of key-points
4231 //=======================================================================
4233 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4235 typedef list< list< TPoint* > >::iterator TListOfListIt;
4236 TListOfListIt bndIt;
4237 list< TPoint* >::iterator pIt;
4239 int nbBoundaries = boundaryList.size();
4240 if ( nbBoundaries > 1 )
4242 // sort boundaries by nb of key-points
4243 if ( nbBoundaries > 2 )
4245 // move boundaries in tmp list
4246 list< list< TPoint* > > tmpList;
4247 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4248 // make a map nb-key-points to boundary-position-in-tmpList,
4249 // boundary-positions get ordered in it
4250 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4251 TNbKpBndPosMap nbKpBndPosMap;
4252 bndIt = tmpList.begin();
4253 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4254 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4255 int nb = *nbKpIt * nbBoundaries;
4256 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4258 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4260 // move boundaries back to boundaryList
4261 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4262 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4263 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4264 TListOfListIt bndPos1 = bndPos2++;
4265 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4269 // Look for the outer boundary: the one with the point with the least X
4270 double leastX = DBL_MAX;
4271 TListOfListIt outerBndPos;
4272 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4274 list< TPoint* >& boundary = (*bndIt);
4275 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4277 TPoint* point = *pIt;
4278 if ( point->myInitXYZ.X() < leastX ) {
4279 leastX = point->myInitXYZ.X();
4280 outerBndPos = bndIt;
4285 if ( outerBndPos != boundaryList.begin() )
4286 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4288 } // if nbBoundaries > 1
4290 // Check boundaries orientation and re-fill myKeyPointIDs
4292 set< TPoint* > keyPointSet;
4293 list< int >::iterator kpIt = myKeyPointIDs.begin();
4294 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4295 keyPointSet.insert( & myPoints[ *kpIt ]);
4296 myKeyPointIDs.clear();
4298 // update myNbKeyPntInBoundary also
4299 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4301 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4303 // find the point with the least X
4304 double leastX = DBL_MAX;
4305 list< TPoint* >::iterator xpIt;
4306 list< TPoint* >& boundary = (*bndIt);
4307 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4309 TPoint* point = *pIt;
4310 if ( point->myInitXYZ.X() < leastX ) {
4311 leastX = point->myInitXYZ.X();
4315 // find points next to the point with the least X
4316 TPoint* p = *xpIt, *pPrev, *pNext;
4317 if ( p == boundary.front() )
4318 pPrev = *(++boundary.rbegin());
4324 if ( p == boundary.back() )
4325 pNext = *(++boundary.begin());
4330 // vectors of boundary direction near <p>
4331 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4332 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4333 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4334 double yPrev = v1.Y() / sqrt( sqMag1 );
4335 double yNext = v2.Y() / sqrt( sqMag2 );
4336 double sumY = yPrev + yNext;
4338 if ( bndIt == boundaryList.begin() ) // outer boundary
4346 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4347 (*nbKpIt) = 0; // count nb of key-points again
4348 pIt = boundary.begin();
4349 for ( ; pIt != boundary.end(); pIt++)
4351 TPoint* point = *pIt;
4352 if ( keyPointSet.find( point ) == keyPointSet.end() )
4354 // find an index of a keypoint
4356 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4357 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4358 if ( &(*pVecIt) == point )
4360 myKeyPointIDs.push_back( index );
4363 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4366 } // loop on a list of boundaries
4368 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4371 //=======================================================================
4372 //function : findBoundaryPoints
4373 //purpose : if loaded from file, find points to map on edges and faces and
4374 // compute their parameters
4375 //=======================================================================
4377 bool SMESH_Pattern::findBoundaryPoints()
4379 if ( myIsBoundaryPointsFound ) return true;
4381 MESSAGE(" findBoundaryPoints() ");
4383 myNbKeyPntInBoundary.clear();
4387 set< TPoint* > pointsInElems;
4389 // Find free links of elements:
4390 // put links of all elements in a set and remove links encountered twice
4392 typedef pair< TPoint*, TPoint*> TLink;
4393 set< TLink > linkSet;
4394 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4395 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4397 TElemDef & elemPoints = *epIt;
4398 TElemDef::iterator pIt = elemPoints.begin();
4399 int prevP = elemPoints.back();
4400 for ( ; pIt != elemPoints.end(); pIt++ ) {
4401 TPoint* p1 = & myPoints[ prevP ];
4402 TPoint* p2 = & myPoints[ *pIt ];
4403 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4404 ASSERT( link.first != link.second );
4405 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4406 if ( !itUniq.second )
4407 linkSet.erase( itUniq.first );
4410 pointsInElems.insert( p1 );
4413 // Now linkSet contains only free links,
4414 // find the points order that they have in boundaries
4416 // 1. make a map of key-points
4417 set< TPoint* > keyPointSet;
4418 list< int >::iterator kpIt = myKeyPointIDs.begin();
4419 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4420 keyPointSet.insert( & myPoints[ *kpIt ]);
4422 // 2. chain up boundary points
4423 list< list< TPoint* > > boundaryList;
4424 boundaryList.push_back( list< TPoint* >() );
4425 list< TPoint* > * boundary = & boundaryList.back();
4427 TPoint *point1, *point2, *keypoint1;
4428 kpIt = myKeyPointIDs.begin();
4429 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4430 // loop on free links: look for the next point
4432 set< TLink >::iterator lIt = linkSet.begin();
4433 while ( lIt != linkSet.end() )
4435 if ( (*lIt).first == point1 )
4436 point2 = (*lIt).second;
4437 else if ( (*lIt).second == point1 )
4438 point2 = (*lIt).first;
4443 linkSet.erase( lIt );
4444 lIt = linkSet.begin();
4446 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4448 boundary->push_back( point2 );
4450 else // a key-point found
4452 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4454 if ( point2 != keypoint1 ) // its not the boundary end
4456 boundary->push_back( point2 );
4458 else // the boundary end reached
4460 boundary->push_front( keypoint1 );
4461 boundary->push_back( keypoint1 );
4462 myNbKeyPntInBoundary.push_back( iKeyPoint );
4463 if ( keyPointSet.empty() )
4464 break; // all boundaries containing key-points are found
4466 // prepare to search for the next boundary
4467 boundaryList.push_back( list< TPoint* >() );
4468 boundary = & boundaryList.back();
4469 point2 = keypoint1 = (*keyPointSet.begin());
4473 } // loop on the free links set
4475 if ( boundary->empty() ) {
4476 MESSAGE(" a separate key-point");
4477 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4480 // if there are several wires, arrange boundaryPoints so that
4481 // the outer wire goes first and fix inner wires orientation;
4482 // sort myKeyPointIDs to correspond to the order of key-points
4484 arrangeBoundaries( boundaryList );
4486 // Find correspondence shape ID - points,
4487 // compute points parameter on edge
4489 keyPointSet.clear();
4490 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4491 keyPointSet.insert( & myPoints[ *kpIt ]);
4493 set< TPoint* > edgePointSet; // to find in-face points
4494 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4495 int edgeID = myKeyPointIDs.size() + 1;
4497 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4498 for ( ; bndIt != boundaryList.end(); bndIt++ )
4500 boundary = & (*bndIt);
4501 double edgeLength = 0;
4502 list< TPoint* >::iterator pIt = boundary->begin();
4503 getShapePoints( edgeID ).push_back( *pIt );
4504 getShapePoints( vertexID++ ).push_back( *pIt );
4505 for ( pIt++; pIt != boundary->end(); pIt++)
4507 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4508 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4509 TPoint* point = *pIt;
4510 edgePointSet.insert( point );
4511 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4513 edgePoints.push_back( point );
4514 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4515 point->myInitU = edgeLength;
4519 // treat points on the edge which ends up: compute U [0,1]
4520 edgePoints.push_back( point );
4521 if ( edgePoints.size() > 2 ) {
4522 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4523 list< TPoint* >::iterator epIt = edgePoints.begin();
4524 for ( ; epIt != edgePoints.end(); epIt++ )
4525 (*epIt)->myInitU /= edgeLength;
4527 // begin the next edge treatment
4530 if ( point != boundary->front() ) { // not the first key-point again
4531 getShapePoints( edgeID ).push_back( point );
4532 getShapePoints( vertexID++ ).push_back( point );
4538 // find in-face points
4539 list< TPoint* > & facePoints = getShapePoints( edgeID );
4540 vector< TPoint >::iterator pVecIt = myPoints.begin();
4541 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4542 TPoint* point = &(*pVecIt);
4543 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4544 pointsInElems.find( point ) != pointsInElems.end())
4545 facePoints.push_back( point );
4552 // bind points to shapes according to point parameters
4553 vector< TPoint >::iterator pVecIt = myPoints.begin();
4554 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4555 TPoint* point = &(*pVecIt);
4556 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4557 getShapePoints( shapeID ).push_back( point );
4558 // detect key-points
4559 if ( SMESH_Block::IsVertexID( shapeID ))
4560 myKeyPointIDs.push_back( i );
4564 myIsBoundaryPointsFound = true;
4565 return myIsBoundaryPointsFound;
4568 //=======================================================================
4570 //purpose : clear fields
4571 //=======================================================================
4573 void SMESH_Pattern::Clear()
4575 myIsComputed = myIsBoundaryPointsFound = false;
4578 myKeyPointIDs.clear();
4579 myElemPointIDs.clear();
4580 myShapeIDToPointsMap.clear();
4581 myShapeIDMap.Clear();
4583 myNbKeyPntInBoundary.clear();
4586 myElemXYZIDs.clear();
4587 myXYZIdToNodeMap.clear();
4589 myOrderedNodes.clear();
4590 myPolyElems.clear();
4591 myPolyElemXYZIDs.clear();
4592 myPolyhedronQuantities.clear();
4593 myIdsOnBoundary.clear();
4594 myReverseConnectivity.clear();
4597 //================================================================================
4599 * \brief set ErrorCode and return true if it is Ok
4601 //================================================================================
4603 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4605 myErrorCode = theErrorCode;
4606 return myErrorCode == ERR_OK;
4609 //=======================================================================
4610 //function : setShapeToMesh
4611 //purpose : set a shape to be meshed. Return True if meshing is possible
4612 //=======================================================================
4614 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4616 if ( !IsLoaded() ) {
4617 MESSAGE( "Pattern not loaded" );
4618 return setErrorCode( ERR_APPL_NOT_LOADED );
4621 TopAbs_ShapeEnum aType = theShape.ShapeType();
4622 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4624 MESSAGE( "Pattern dimention mismatch" );
4625 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4628 // check if a face is closed
4629 int nbNodeOnSeamEdge = 0;
4631 TopTools_MapOfShape seamVertices;
4632 TopoDS_Face face = TopoDS::Face( theShape );
4633 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4634 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
4635 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4636 if ( BRep_Tool::IsClosed(ee, face) ) {
4637 // seam edge and vertices encounter twice in theFace
4638 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4639 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4644 // check nb of vertices
4645 TopTools_IndexedMapOfShape vMap;
4646 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4647 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4648 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4649 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4652 myElements.clear(); // not refine elements
4653 myElemXYZIDs.clear();
4655 myShapeIDMap.Clear();
4660 //=======================================================================
4661 //function : GetMappedPoints
4662 //purpose : Return nodes coordinates computed by Apply() method
4663 //=======================================================================
4665 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4668 if ( !myIsComputed )
4671 if ( myElements.empty() ) { // applied to shape
4672 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4673 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4674 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4676 else { // applied to mesh elements
4677 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4678 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4679 for ( ; xyz != myXYZ.end(); ++xyz )
4680 if ( !isDefined( *xyz ))
4681 thePoints.push_back( definedXYZ );
4683 thePoints.push_back( & (*xyz) );
4685 return !thePoints.empty();
4689 //=======================================================================
4690 //function : GetPoints
4691 //purpose : Return nodes coordinates of the pattern
4692 //=======================================================================
4694 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4701 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4702 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4703 thePoints.push_back( & (*pVecIt).myInitXYZ );
4705 return ( thePoints.size() > 0 );
4708 //=======================================================================
4709 //function : getShapePoints
4710 //purpose : return list of points located on theShape
4711 //=======================================================================
4713 list< SMESH_Pattern::TPoint* > &
4714 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4717 if ( !myShapeIDMap.Contains( theShape ))
4718 aShapeID = myShapeIDMap.Add( theShape );
4720 aShapeID = myShapeIDMap.FindIndex( theShape );
4722 return myShapeIDToPointsMap[ aShapeID ];
4725 //=======================================================================
4726 //function : getShapePoints
4727 //purpose : return list of points located on the shape
4728 //=======================================================================
4730 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4732 return myShapeIDToPointsMap[ theShapeID ];
4735 //=======================================================================
4736 //function : DumpPoints
4738 //=======================================================================
4740 void SMESH_Pattern::DumpPoints() const
4743 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4744 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4745 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4749 //=======================================================================
4750 //function : TPoint()
4752 //=======================================================================
4754 SMESH_Pattern::TPoint::TPoint()
4757 myInitXYZ.SetCoord(0,0,0);
4758 myInitUV.SetCoord(0.,0.);
4760 myXYZ.SetCoord(0,0,0);
4761 myUV.SetCoord(0.,0.);
4766 //=======================================================================
4767 //function : operator <<
4769 //=======================================================================
4771 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4773 gp_XYZ xyz = p.myInitXYZ;
4774 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4775 gp_XY xy = p.myInitUV;
4776 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4777 double u = p.myInitU;
4778 OS << " u( " << u << " )) " << &p << endl;
4779 xyz = p.myXYZ.XYZ();
4780 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4782 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4784 OS << " u( " << u << " ))" << endl;