1 // Copyright (C) 2007-2021 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_Pattern.hxx
24 // Created : Mon Aug 2 10:30:00 2004
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_Pattern.hxx"
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FacePosition.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshFace.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Group.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "SMESHDS_SubMesh.hxx"
38 #include "SMESH_Block.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MeshEditor.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_subMesh.hxx"
45 #include <BRepAdaptor_Curve.hxx>
46 #include <BRepTools.hxx>
47 #include <BRepTools_WireExplorer.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_Box.hxx>
50 #include <Bnd_Box2d.hxx>
52 #include <Extrema_ExtPC.hxx>
53 #include <Extrema_GenExtPS.hxx>
54 #include <Extrema_POnSurf.hxx>
55 #include <Geom2d_Curve.hxx>
56 #include <GeomAdaptor_Surface.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Surface.hxx>
59 #include <Precision.hxx>
60 #include <TopAbs_ShapeEnum.hxx>
62 #include <TopExp_Explorer.hxx>
63 #include <TopLoc_Location.hxx>
64 #include <TopTools_ListIteratorOfListOfShape.hxx>
66 #include <TopoDS_Edge.hxx>
67 #include <TopoDS_Face.hxx>
68 #include <TopoDS_Iterator.hxx>
69 #include <TopoDS_Shell.hxx>
70 #include <TopoDS_Vertex.hxx>
71 #include <TopoDS_Wire.hxx>
73 #include <gp_Lin2d.hxx>
74 #include <gp_Pnt2d.hxx>
75 #include <gp_Trsf.hxx>
79 #include <Basics_Utils.hxx>
80 #include "utilities.h"
84 typedef std::map< const SMDS_MeshElement*, int > TNodePointIDMap;
85 typedef std::list< TopoDS_Edge > TWire;
87 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
92 //=======================================================================
95 //=======================================================================
97 inline int getInt( const char * theSring )
99 if ( *theSring < '0' || *theSring > '9' )
103 int val = strtol( theSring, &ptr, 10 );
104 if ( ptr == theSring ||
105 // there must not be neither '.' nor ',' nor 'E' ...
106 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0' && *ptr != '\r'))
112 //=======================================================================
113 //function : getDouble
115 //=======================================================================
117 inline double getDouble( const char * theSring )
120 return strtod( theSring, &ptr );
123 //=======================================================================
124 //function : readLine
125 //purpose : Put token starting positions in theFields until '\n' or '\0'
126 // Return the number of the found tokens
127 //=======================================================================
129 int readLine (list <const char*> & theFields,
130 const char* & theLineBeg,
131 const bool theClearFields )
133 if ( theClearFields )
138 /* switch ( symbol ) { */
139 /* case white-space: */
140 /* look for a non-space symbol; */
141 /* case string-end: */
144 /* case comment beginning: */
145 /* skip all till a line-end; */
147 /* put its position in theFields, skip till a white-space;*/
153 bool stopReading = false;
156 bool isNumber = false;
157 switch ( *theLineBeg )
159 case ' ': // white space
164 case '\n': // a line ends
165 stopReading = ( nbRead > 0 );
170 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
174 case '\0': // file ends
177 case '-': // real number
180 isNumber = true; // fall through
182 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
184 theFields.push_back( theLineBeg );
187 while (*theLineBeg != ' ' &&
188 *theLineBeg != '\n' &&
189 *theLineBeg != '\0');
193 return 0; // incorrect file format
199 } while ( !stopReading );
204 //=======================================================================
205 //function : isRealSeam
206 //purpose : return true if an EDGE encounters twice in a FACE
207 //=======================================================================
209 // bool isRealSeam( const TopoDS_Edge& e, const TopoDS_Face& f )
211 // if ( BRep_Tool::IsClosed( e, f ))
214 // for (TopExp_Explorer exp( f, TopAbs_EDGE ); exp.More(); exp.Next())
215 // if ( exp.Current().IsSame( e ))
222 //=======================================================================
224 //purpose : load VERTEXes and EDGEs in a map. Return nb loaded VERTEXes
225 //=======================================================================
227 int loadVE( const list< TopoDS_Edge > & eList,
228 TopTools_IndexedMapOfOrientedShape & map )
230 list< TopoDS_Edge >::const_iterator eIt = eList.begin();
233 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
236 map.Add( TopExp::FirstVertex( *eIt, true ));
237 bool added = ( nbV < map.Extent() );
238 if ( !added ) { // vertex encountered twice
239 // a seam vertex have two corresponding key points
240 map.Add( TopExp::FirstVertex( *eIt, true ).Reversed());
246 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
254 //=======================================================================
255 //function : SMESH_Pattern
257 //=======================================================================
259 SMESH_Pattern::SMESH_Pattern (): myToKeepNodes(false)
263 //=======================================================================
265 //purpose : Load a pattern from <theFile>
266 //=======================================================================
268 bool SMESH_Pattern::Load (const char* theFileContents)
270 Kernel_Utils::Localizer loc;
274 // ! This is a comment
275 // NB_POINTS ! 1 integer - the number of points in the pattern.
276 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
277 // X2 Y2 [Z2] ! the pattern dimension is defined by the number of coordinates
279 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
280 // ! elements description goes after all
281 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
286 const char* lineBeg = theFileContents;
287 list <const char*> fields;
288 const bool clearFields = true;
290 // NB_POINTS ! 1 integer - the number of points in the pattern.
292 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
293 MESSAGE("Error reading NB_POINTS");
294 return setErrorCode( ERR_READ_NB_POINTS );
296 int nbPoints = getInt( fields.front() );
298 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
300 // read the first point coordinates to define pattern dimension
301 int dim = readLine( fields, lineBeg, clearFields );
307 MESSAGE("Error reading points: wrong nb of coordinates");
308 return setErrorCode( ERR_READ_POINT_COORDS );
310 if ( nbPoints <= dim ) {
311 MESSAGE(" Too few points ");
312 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
315 // read the rest points
317 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
318 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
319 MESSAGE("Error reading points : wrong nb of coordinates ");
320 return setErrorCode( ERR_READ_POINT_COORDS );
322 // store point coordinates
323 myPoints.resize( nbPoints );
324 list <const char*>::iterator fIt = fields.begin();
325 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
327 TPoint & p = myPoints[ iPoint ];
328 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
330 double coord = getDouble( *fIt );
331 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
332 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
334 return setErrorCode( ERR_READ_3D_COORD );
336 p.myInitXYZ.SetCoord( iCoord, coord );
338 p.myInitUV.SetCoord( iCoord, coord );
342 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
345 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
346 MESSAGE("Error: missing key-points");
348 return setErrorCode( ERR_READ_NO_KEYPOINT );
351 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
353 int pointIndex = getInt( *fIt );
354 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
355 MESSAGE("Error: invalid point index " << pointIndex );
357 return setErrorCode( ERR_READ_BAD_INDEX );
359 if ( idSet.insert( pointIndex ).second ) // unique?
360 myKeyPointIDs.push_back( pointIndex );
364 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
366 while ( readLine( fields, lineBeg, clearFields ))
368 myElemPointIDs.push_back( TElemDef() );
369 TElemDef& elemPoints = myElemPointIDs.back();
370 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
372 int pointIndex = getInt( *fIt );
373 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
374 MESSAGE("Error: invalid point index " << pointIndex );
376 return setErrorCode( ERR_READ_BAD_INDEX );
378 elemPoints.push_back( pointIndex );
380 // check the nb of nodes in element
382 switch ( elemPoints.size() ) {
383 case 3: if ( !myIs2D ) Ok = false; break;
387 case 8: if ( myIs2D ) Ok = false; break;
391 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
393 return setErrorCode( ERR_READ_ELEM_POINTS );
396 if ( myElemPointIDs.empty() ) {
397 MESSAGE("Error: no elements");
399 return setErrorCode( ERR_READ_NO_ELEMS );
402 findBoundaryPoints(); // sort key-points
404 return setErrorCode( ERR_OK );
407 //=======================================================================
409 //purpose : Save the loaded pattern into the file <theFileName>
410 //=======================================================================
412 bool SMESH_Pattern::Save (ostream& theFile)
414 Kernel_Utils::Localizer loc;
417 MESSAGE(" Pattern not loaded ");
418 return setErrorCode( ERR_SAVE_NOT_LOADED );
421 theFile << "!!! SALOME Mesh Pattern file" << endl;
422 theFile << "!!!" << endl;
423 theFile << "!!! Nb of points:" << endl;
424 theFile << myPoints.size() << endl;
428 // theFile.width( 8 );
429 // theFile.setf(ios::fixed);// use 123.45 floating notation
430 // theFile.setf(ios::right);
431 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
432 // theFile.setf(ios::showpoint); // do not show trailing zeros
433 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
434 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
435 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
436 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
437 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
438 theFile << " !- " << i << endl; // point id to ease reading by a human being
442 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
443 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
444 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
445 theFile << " " << *kpIt;
446 if ( !myKeyPointIDs.empty() )
450 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
451 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
452 for ( ; epIt != myElemPointIDs.end(); epIt++ )
454 const TElemDef & elemPoints = *epIt;
455 TElemDef::const_iterator iIt = elemPoints.begin();
456 for ( ; iIt != elemPoints.end(); iIt++ )
457 theFile << " " << *iIt;
463 return setErrorCode( ERR_OK );
466 //=======================================================================
467 //function : sortBySize
468 //purpose : sort theListOfList by size
469 //=======================================================================
471 template<typename T> struct TSizeCmp {
472 bool operator ()( const list < T > & l1, const list < T > & l2 )
473 const { return l1.size() < l2.size(); }
476 template<typename T> void sortBySize( list< list < T > > & theListOfList )
478 if ( theListOfList.size() > 2 ) {
479 TSizeCmp< T > SizeCmp;
480 theListOfList.sort( SizeCmp );
484 //=======================================================================
487 //=======================================================================
489 static gp_XY project (const SMDS_MeshNode* theNode,
490 Extrema_GenExtPS & theProjectorPS)
492 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
493 theProjectorPS.Perform( P );
494 if ( !theProjectorPS.IsDone() ) {
495 MESSAGE( "SMESH_Pattern: point projection FAILED");
498 double u =0, v =0, minVal = DBL_MAX;
499 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
500 if ( theProjectorPS.SquareDistance( i ) < minVal ) {
501 minVal = theProjectorPS.SquareDistance( i );
502 theProjectorPS.Point( i ).Parameter( u, v );
504 return gp_XY( u, v );
507 //=======================================================================
508 //function : areNodesBound
509 //purpose : true if all nodes of faces are bound to shapes
510 //=======================================================================
512 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
514 while ( faceItr->more() )
516 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
517 while ( nIt->more() )
519 const SMDS_MeshNode* node = smdsNode( nIt->next() );
520 if (node->getshapeId() <1) {
528 //=======================================================================
529 //function : isMeshBoundToShape
530 //purpose : return true if all 2d elements are bound to shape
531 // if aFaceSubmesh != NULL, then check faces bound to it
532 // else check all faces in aMeshDS
533 //=======================================================================
535 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
536 SMESHDS_SubMesh * aFaceSubmesh,
537 const bool isMainShape)
539 if ( isMainShape && aFaceSubmesh ) {
540 // check that all faces are bound to aFaceSubmesh
541 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
545 // check face nodes binding
546 if ( aFaceSubmesh ) {
547 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
548 return areNodesBound( fIt );
550 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
551 return areNodesBound( fIt );
554 //=======================================================================
556 //purpose : Create a pattern from the mesh built on <theFace>.
557 // <theProject>==true makes override nodes positions
558 // on <theFace> computed by mesher
559 //=======================================================================
561 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
562 const TopoDS_Face& theFace,
564 TopoDS_Vertex the1stVertex,
569 myToKeepNodes = theKeepNodes;
571 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
572 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
573 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
574 SMESH_MesherHelper helper( *theMesh );
575 helper.SetSubShape( theFace );
577 smIdType nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
578 smIdType nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
579 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
581 MESSAGE( "No elements bound to the face");
582 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
585 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
587 // check if face is closed
588 bool isClosed = helper.HasSeam();
589 list<TopoDS_Edge> eList;
590 list<TopoDS_Edge>::iterator elIt;
591 SMESH_Block::GetOrderedEdges( face, eList, myNbKeyPntInBoundary, the1stVertex );
593 // check that requested or needed projection is possible
594 bool isMainShape = theMesh->IsMainShape( face );
595 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
596 bool canProject = ( nbElems ? true : isMainShape );
598 canProject = false; // so far
600 if ( ( theProject || needProject ) && !canProject )
601 return setErrorCode( ERR_LOADF_CANT_PROJECT );
603 Extrema_GenExtPS projector;
604 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
605 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
608 TNodePointIDMap nodePointIDMap;
609 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
613 // ---------------------------------------------------------------
614 // The case where the submesh is projected to theFace
615 // ---------------------------------------------------------------
618 SMDS_ElemIteratorPtr fIt;
620 fIt = fSubMesh->GetElements();
622 fIt = aMeshDS->elementsIterator( SMDSAbs_Face );
624 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
625 while ( fIt->more() )
627 const SMDS_MeshElement* face = fIt->next();
628 myElemPointIDs.push_back( TElemDef() );
629 TElemDef& elemPoints = myElemPointIDs.back();
630 int nbNodes = face->NbCornerNodes();
631 for ( int i = 0;i < nbNodes; ++i )
633 const SMDS_MeshElement* node = face->GetNode( i );
634 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
635 if ( nIdIt->second == -1 )
636 nIdIt->second = iPoint++;
637 elemPoints.push_back( (*nIdIt).second );
640 myPoints.resize( iPoint );
642 // project all nodes of 2d elements to theFace
643 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
644 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
646 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
647 TPoint * p = & myPoints[ (*nIdIt).second ];
648 p->myInitUV = project( node, projector );
649 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
651 // find key-points: the points most close to UV of vertices
652 TopExp_Explorer vExp( face, TopAbs_VERTEX );
653 set<int> foundIndices;
654 for ( ; vExp.More(); vExp.Next() ) {
655 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
656 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
657 double minDist = DBL_MAX;
659 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
660 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
661 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
662 if ( dist < minDist ) {
667 if ( foundIndices.insert( index ).second ) // unique?
668 myKeyPointIDs.push_back( index );
670 myIsBoundaryPointsFound = false;
675 // ---------------------------------------------------------------------
676 // The case where a pattern is being made from the mesh built by mesher
677 // ---------------------------------------------------------------------
679 // Load shapes in the consequent order and count nb of points
681 loadVE( eList, myShapeIDMap );
682 myShapeIDMap.Add( face );
684 nbNodes += myShapeIDMap.Extent() - 1;
686 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
687 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
688 nbNodes += eSubMesh->NbNodes() + 1;
690 myPoints.resize( nbNodes );
692 // care of INTERNAL VERTEXes
693 TopExp_Explorer vExp( face, TopAbs_VERTEX, TopAbs_EDGE );
694 for ( ; vExp.More(); vExp.Next() )
696 const SMDS_MeshNode* node =
697 SMESH_Algo::VertexNode( TopoDS::Vertex( vExp.Current()), aMeshDS );
698 if ( !node || node->NbInverseElements( SMDSAbs_Face ) == 0 )
700 myPoints.resize( ++nbNodes );
701 list< TPoint* > & fPoints = getShapePoints( face );
702 nodePointIDMap.insert( make_pair( node, iPoint ));
703 TPoint* p = &myPoints[ iPoint++ ];
704 fPoints.push_back( p );
705 gp_XY uv = helper.GetNodeUV( face, node );
706 p->myInitUV.SetCoord( uv.X(), uv.Y() );
707 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
710 // Load U of points on edges
712 Bnd_Box2d edgesUVBox;
714 list<int>::iterator nbEinW = myNbKeyPntInBoundary.begin();
716 vector< TopoDS_Edge > eVec;
717 for ( elIt = eList.begin(); elIt != eList.end(); elIt++, iE++ )
719 if ( isClosed && ( iE == 0 || iE == *nbEinW ))
721 // new wire begins; put wire EDGEs in eVec
722 list<TopoDS_Edge>::iterator eEnd = elIt;
725 std::advance( eEnd, *nbEinW );
726 eVec.assign( elIt, eEnd );
729 TopoDS_Edge & edge = *elIt;
730 list< TPoint* > & ePoints = getShapePoints( edge );
732 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
733 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
735 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
736 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
737 // to make adjacent edges share key-point, we make v2 FORWARD too
738 // (as we have different points for same shape with different orientation)
741 // on closed face we must have REVERSED some of seam vertices
743 if ( helper.IsSeamShape( edge ) ) {
744 if ( helper.IsRealSeam( edge ) && !isForward ) {
745 // reverse on reversed SEAM edge
750 else { // on CLOSED edge (i.e. having one vertex with different orientations)
751 for ( int is2 = 0; is2 < 2; ++is2 ) {
752 TopoDS_Shape & v = is2 ? v2 : v1;
753 if ( helper.IsRealSeam( v ) ) {
754 // reverse or not depending on orientation of adjacent seam
755 int iSeam = helper.WrapIndex( iE + ( is2 ? +1 : -1 ), eVec.size() );
756 if ( eVec[ iSeam ].Orientation() == TopAbs_REVERSED )
763 // the forward key-point
764 list< TPoint* > * vPoint = & getShapePoints( v1 );
765 if ( vPoint->empty() )
767 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
768 if ( vSubMesh && vSubMesh->NbNodes() ) {
769 myKeyPointIDs.push_back( iPoint );
770 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
771 const SMDS_MeshNode* node = nIt->next();
772 if ( v1.Orientation() == TopAbs_REVERSED )
773 closeNodePointIDMap.insert( make_pair( node, iPoint ));
775 nodePointIDMap.insert( make_pair( node, iPoint ));
777 TPoint* keyPoint = &myPoints[ iPoint++ ];
778 vPoint->push_back( keyPoint );
780 keyPoint->myInitUV = project( node, projector );
782 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
783 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
784 edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
787 if ( !vPoint->empty() )
788 ePoints.push_back( vPoint->front() );
791 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
792 if ( eSubMesh && eSubMesh->NbNodes() )
794 // loop on nodes of an edge: sort them by param on edge
795 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
796 TParamNodeMap paramNodeMap;
797 int nbMeduimNodes = 0;
798 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
799 while ( nIt->more() )
801 const SMDS_MeshNode* node = nIt->next();
802 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
806 SMDS_EdgePositionPtr epos = node->GetPosition();
807 double u = epos->GetUParameter();
808 paramNodeMap.insert( make_pair( u, node ));
810 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes ) {
811 // wrong U on edge, project
813 BRepAdaptor_Curve aCurve( edge );
814 proj.Initialize( aCurve, f, l );
815 paramNodeMap.clear();
816 nIt = eSubMesh->GetNodes();
817 for ( int iNode = 0; nIt->more(); ++iNode ) {
818 const SMDS_MeshNode* node = nIt->next();
819 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
821 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
823 if ( proj.IsDone() ) {
824 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
825 if ( proj.IsMin( i )) {
826 u = proj.Point( i ).Parameter();
830 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
832 paramNodeMap.insert( make_pair( u, node ));
835 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
836 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
837 return setErrorCode(ERR_UNEXPECTED);
840 // put U in [0,1] so that the first key-point has U==0
841 bool isSeam = helper.IsRealSeam( edge );
843 TParamNodeMap::iterator unIt = paramNodeMap.begin();
844 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
845 while ( unIt != paramNodeMap.end() )
847 TPoint* p = & myPoints[ iPoint ];
848 ePoints.push_back( p );
849 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
850 if ( isSeam && !isForward )
851 closeNodePointIDMap.insert( make_pair( node, iPoint ));
853 nodePointIDMap.insert ( make_pair( node, iPoint ));
856 p->myInitUV = project( node, projector );
858 double u = isForward ? (*unIt).first : (*unRIt).first;
859 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
860 p->myInitUV = C2d->Value( u ).XY();
862 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
863 edgesUVBox.Add( gp_Pnt2d( p->myInitUV ));
868 // the reverse key-point
869 vPoint = & getShapePoints( v2 );
870 if ( vPoint->empty() )
872 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
873 if ( vSubMesh && vSubMesh->NbNodes() ) {
874 myKeyPointIDs.push_back( iPoint );
875 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
876 const SMDS_MeshNode* node = nIt->next();
877 if ( v2.Orientation() == TopAbs_REVERSED )
878 closeNodePointIDMap.insert( make_pair( node, iPoint ));
880 nodePointIDMap.insert( make_pair( node, iPoint ));
882 TPoint* keyPoint = &myPoints[ iPoint++ ];
883 vPoint->push_back( keyPoint );
885 keyPoint->myInitUV = project( node, projector );
887 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
888 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
889 edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
892 if ( !vPoint->empty() )
893 ePoints.push_back( vPoint->front() );
895 // compute U of edge-points
898 double totalDist = 0;
899 list< TPoint* >::iterator pIt = ePoints.begin();
900 TPoint* prevP = *pIt;
901 prevP->myInitU = totalDist;
902 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
904 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
905 p->myInitU = totalDist;
908 if ( totalDist > DBL_MIN)
909 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
911 p->myInitU /= totalDist;
914 } // loop on edges of a wire
916 // Load in-face points and elements
918 if ( fSubMesh && fSubMesh->NbElements() )
920 list< TPoint* > & fPoints = getShapePoints( face );
921 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
922 while ( nIt->more() )
924 const SMDS_MeshNode* node = nIt->next();
925 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
927 nodePointIDMap.insert( make_pair( node, iPoint ));
928 TPoint* p = &myPoints[ iPoint++ ];
929 fPoints.push_back( p );
930 if ( theProject || edgesUVBox.IsOut( p->myInitUV ) )
931 p->myInitUV = project( node, projector );
933 SMDS_FacePositionPtr pos = node->GetPosition();
934 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
936 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
939 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
940 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
941 while ( elemIt->more() )
943 const SMDS_MeshElement* elem = elemIt->next();
944 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
945 myElemPointIDs.push_back( TElemDef() );
946 TElemDef& elemPoints = myElemPointIDs.back();
947 // find point indices corresponding to element nodes
948 while ( nIt->more() )
950 const SMDS_MeshNode* node = smdsNode( nIt->next() );
951 n_id = nodePointIDMap.find( node );
952 if ( n_id == nodePointIDMap.end() )
953 continue; // medium node
954 iPoint = n_id->second; // point index of interest
955 // for a node on a seam edge there are two points
956 if ( helper.IsRealSeam( node->getshapeId() ) &&
957 ( n_id = closeNodePointIDMap.find( node )) != not_found )
959 TPoint & p1 = myPoints[ iPoint ];
960 TPoint & p2 = myPoints[ n_id->second ];
961 // Select point closest to the rest nodes of element in UV space
962 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
963 const SMDS_MeshNode* notSeamNode = 0;
964 // find node not on a seam edge
965 while ( nIt2->more() && !notSeamNode ) {
966 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
967 if ( !helper.IsSeamShape( n->getshapeId() ))
970 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
971 double dist1 = uv.SquareDistance( p1.myInitUV );
972 double dist2 = uv.SquareDistance( p2.myInitUV );
974 iPoint = n_id->second;
976 elemPoints.push_back( iPoint );
980 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
982 myIsBoundaryPointsFound = true;
987 myInNodes.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
989 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
990 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
991 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
993 nIdIt = closeNodePointIDMap.begin();
994 for ( ; nIdIt != closeNodePointIDMap.end(); nIdIt++ )
995 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
998 // Assure that U range is proportional to V range
1001 vector< TPoint >::iterator pVecIt = myPoints.begin();
1002 for ( ; pVecIt != myPoints.end(); pVecIt++ )
1003 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
1004 double minU, minV, maxU, maxV;
1005 bndBox.Get( minU, minV, maxU, maxV );
1006 double dU = maxU - minU, dV = maxV - minV;
1007 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
1010 // define where is the problem, in the face or in the mesh
1011 TopExp_Explorer vExp( face, TopAbs_VERTEX );
1012 for ( ; vExp.More(); vExp.Next() ) {
1013 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
1016 bndBox.Get( minU, minV, maxU, maxV );
1017 dU = maxU - minU, dV = maxV - minV;
1018 if ( dU <= DBL_MIN || dV <= DBL_MIN )
1020 return setErrorCode( ERR_LOADF_NARROW_FACE );
1022 // mesh is projected onto a line, e.g.
1023 return setErrorCode( ERR_LOADF_CANT_PROJECT );
1025 double ratio = dU / dV, maxratio = 3, scale;
1027 if ( ratio > maxratio ) {
1028 scale = ratio / maxratio;
1031 else if ( ratio < 1./maxratio ) {
1032 scale = maxratio / ratio;
1037 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
1038 TPoint & p = *pVecIt;
1039 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
1040 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
1043 if ( myElemPointIDs.empty() ) {
1044 MESSAGE( "No elements bound to the face");
1045 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
1048 return setErrorCode( ERR_OK );
1051 //=======================================================================
1052 //function : computeUVOnEdge
1053 //purpose : compute coordinates of points on theEdge
1054 //=======================================================================
1056 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
1057 const list< TPoint* > & ePoints )
1059 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
1061 Handle(Geom2d_Curve) C2d =
1062 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
1064 ePoints.back()->myInitU = 1.0;
1065 //ePoints.front()->myInitU = 0.0; //myUV = C2d->Value( isForward ? f : l ).XY();
1066 list< TPoint* >::const_iterator pIt = ePoints.begin();
1067 for ( pIt++; pIt != ePoints.end(); pIt++ )
1069 TPoint* point = *pIt;
1071 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1072 point->myU = ( f * ( 1 - du ) + l * du );
1074 point->myUV = C2d->Value( point->myU ).XY();
1078 //=======================================================================
1079 //function : intersectIsolines
1081 //=======================================================================
1083 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1084 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1088 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1089 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1090 resUV = 0.5 * ( loc1 + loc2 );
1091 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1092 // SKL 26.07.2007 for NPAL16567
1093 double d1 = (uv11-uv12).Modulus();
1094 double d2 = (uv21-uv22).Modulus();
1095 // double delta = d1*d2*1e-6; PAL17233
1096 double delta = min( d1, d2 ) / 10.;
1097 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1099 // double len1 = ( uv11 - uv12 ).Modulus();
1100 // double len2 = ( uv21 - uv22 ).Modulus();
1101 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1105 // gp_Lin2d line1( uv11, uv12 - uv11 );
1106 // gp_Lin2d line2( uv21, uv22 - uv21 );
1107 // double angle = Abs( line1.Angle( line2 ) );
1109 // IntAna2d_AnaIntersection inter;
1110 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1111 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1113 // gp_Pnt2d interUV = inter.Point(1).Value();
1114 // resUV += interUV.XY();
1115 // inter.Perform( line1, line2 );
1116 // interUV = inter.Point(1).Value();
1117 // resUV += interUV.XY();
1121 // if ( isDeformed ) {
1122 // MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1123 // ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1128 //=======================================================================
1129 //function : compUVByIsoIntersection
1131 //=======================================================================
1133 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1134 const gp_XY& theInitUV,
1136 bool & theIsDeformed )
1138 // compute UV by intersection of 2 iso lines
1139 //gp_Lin2d isoLine[2];
1140 gp_XY uv1[2], uv2[2];
1142 const double zero = DBL_MIN;
1143 for ( int iIso = 0; iIso < 2; iIso++ )
1145 // to build an iso line:
1146 // find 2 pairs of consequent edge-points such that the range of their
1147 // initial parameters encloses the in-face point initial parameter
1148 gp_XY UV[2], initUV[2];
1149 int nbUV = 0, iCoord = iIso + 1;
1150 double initParam = theInitUV.Coord( iCoord );
1152 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1153 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1155 const list< TPoint* > & bndPoints = * bndIt;
1156 TPoint* prevP = bndPoints.back(); // this is the first point
1157 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1158 bool coincPrev = false;
1159 // loop on the edge-points
1160 for ( ; pIt != bndPoints.end(); pIt++ )
1162 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1163 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1164 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1165 if (!coincPrev && // ignore if initParam coincides with prev point param
1166 sumOfDiff > zero && // ignore if both points coincide with initParam
1167 prevParamDiff * paramDiff <= zero )
1169 // find UV in parametric space of theFace
1170 double r = Abs(prevParamDiff) / sumOfDiff;
1171 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1174 // throw away uv most distant from <theInitUV>
1175 gp_XY vec0 = initUV[0] - theInitUV;
1176 gp_XY vec1 = initUV[1] - theInitUV;
1177 gp_XY vec = uvInit - theInitUV;
1178 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1179 double dist0 = vec0.SquareModulus();
1180 double dist1 = vec1.SquareModulus();
1181 double dist = vec .SquareModulus();
1182 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1183 i = ( dist0 < dist1 ? 1 : 0 );
1184 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1185 i = 3; // theInitUV must remain between
1189 initUV[ i ] = uvInit;
1190 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1192 coincPrev = ( Abs(paramDiff) <= zero );
1199 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1200 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1201 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1202 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1204 // an iso line should be normal to UV[0] - UV[1] direction
1205 // and be located at the same relative distance as from initial ends
1206 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1208 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1209 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1210 //isoLine[ iIso ] = iso.Normal( isoLoc );
1211 uv1[ iIso ] = UV[0];
1212 uv2[ iIso ] = UV[1];
1215 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1216 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1217 MESSAGE(" Can't intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1218 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1225 // ==========================================================
1226 // structure representing a node of a grid of iso-poly-lines
1227 // ==========================================================
1234 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1235 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1236 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1237 TIsoNode(double initU, double initV):
1238 myIsMovable(true), myInitUV( initU, initV ), myUV( 1e100, 1e100 )
1239 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1240 bool IsUVComputed() const
1241 { return myUV.X() != 1e100; }
1242 bool IsMovable() const
1243 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1244 void SetNotMovable()
1245 { myIsMovable = false; }
1246 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1247 { myBndNodes[ iDir + i * 2 ] = node; }
1248 TIsoNode* GetBoundaryNode(int iDir, int i)
1249 { return myBndNodes[ iDir + i * 2 ]; }
1250 void SetNext(TIsoNode* node, int iDir, int isForward)
1251 { myNext[ iDir + isForward * 2 ] = node; }
1252 TIsoNode* GetNext(int iDir, int isForward)
1253 { return myNext[ iDir + isForward * 2 ]; }
1256 //=======================================================================
1257 //function : getNextNode
1259 //=======================================================================
1261 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1263 TIsoNode* n = node->myNext[ dir ];
1264 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1265 n = 0;//node->myBndNodes[ dir ];
1266 // MESSAGE("getNextNode: use bnd for node "<<
1267 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1271 //=======================================================================
1272 //function : checkQuads
1273 //purpose : check if newUV destortes quadrangles around node,
1274 // and if ( crit == FIX_OLD ) fix newUV in this case
1275 //=======================================================================
1277 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1279 static bool checkQuads (const TIsoNode* node,
1281 const bool reversed,
1282 const int crit = FIX_OLD,
1283 double fixSize = 0.)
1285 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1286 int nbOldFix = 0, nbOldImpr = 0;
1287 double newBadRate = 0, oldBadRate = 0;
1288 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1289 int i, dir1 = 0, dir2 = 3;
1290 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1292 if ( dir2 > 3 ) dir2 = 0;
1294 // walking counterclockwise around a quad,
1295 // nodes are in the order: node, n[0], n[1], n[2]
1296 n[0] = getNextNode( node, dir1 );
1297 n[2] = getNextNode( node, dir2 );
1298 if ( !n[0] || !n[2] ) continue;
1299 n[1] = getNextNode( n[0], dir2 );
1300 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1301 bool isTriangle = ( !n[1] );
1303 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1305 // if ( fixSize != 0 ) {
1306 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1307 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1308 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1309 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1311 // check if a quadrangle is degenerated
1313 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1314 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1317 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1320 // find min size of the diagonal node-n[1]
1321 double minDiag = fixSize;
1322 if ( minDiag == 0. ) {
1323 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1324 if ( !isTriangle ) {
1325 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1326 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1328 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1329 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1332 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1333 // ( behind means "to the right of")
1335 // 1. newUV is not behind 01 and 12 dirs
1336 // 2. or newUV is not behind 02 dir and n[2] is convex
1337 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1338 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1339 gp_Vec2d moveVec[3], outVec[3];
1340 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1342 bool isDiag = ( i == 2 );
1343 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1347 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1349 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1351 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1353 gp_Vec2d newDir( n[i]->myUV, newUV );
1354 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1356 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1357 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1358 if ( crit == FIX_OLD ) {
1359 wasIn[i] = ( outDir * oldDir < 0 );
1360 wasOk[i] = ( outDir * oldDir < -minDiag );
1362 newBadRate += outDir * newDir;
1364 oldBadRate += outDir * oldDir;
1367 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1368 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1369 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1370 moveVec[i] = ( oldDist - minDiag ) * outDir;
1375 // check if n[2] is convex
1378 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1380 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1381 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1382 newIsOk = ( newIsOk && isNewOk );
1383 newIsIn = ( newIsIn && isNewIn );
1385 if ( crit != FIX_OLD ) {
1386 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1387 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1391 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1392 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1393 oldIsIn = ( oldIsIn && isOldIn );
1394 oldIsOk = ( oldIsOk && isOldIn );
1397 if ( !isOldIn ) { // node is outside a quadrangle
1398 // move newUV inside a quadrangle
1399 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1400 // node and newUV are outside: push newUV inside
1402 if ( convex || isTriangle ) {
1403 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1406 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1407 double outSize = out.Magnitude();
1408 if ( outSize > DBL_MIN )
1411 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1412 uv = n[1]->myUV - minDiag * out.XY();
1414 oldUVFixed[ nbOldFix++ ] = uv;
1415 //node->myUV = newUV;
1417 else if ( !isOldOk ) {
1418 // try to fix old UV: move node inside as less as possible
1419 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1420 gp_XY uv1, uv2 = node->myUV;
1421 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1423 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1424 while ( !isOldOk ) {
1425 // find the least moveVec
1427 double minMove2 = 1e100;
1428 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1430 if ( moveVec[i].Coord(1) < 1e100 ) {
1431 double move2 = moveVec[i].SquareMagnitude();
1432 if ( move2 < minMove2 ) {
1441 // move node to newUV
1442 uv1 = node->myUV + moveVec[ iMin ].XY();
1443 uv2 += moveVec[ iMin ].XY();
1444 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1445 // check if uv1 is ok
1446 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1447 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1448 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1450 oldUVImpr[ nbOldImpr++ ] = uv1;
1452 // check if uv2 is ok
1453 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1454 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1455 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1457 oldUVImpr[ nbOldImpr++ ] = uv2;
1462 } // loop on 4 quadrangles around <node>
1464 if ( crit == CHECK_NEW_OK )
1466 if ( crit == CHECK_NEW_IN )
1475 if ( oldIsIn && nbOldImpr ) {
1476 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1477 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1478 gp_XY uv = oldUVImpr[ 0 ];
1479 for ( int i = 1; i < nbOldImpr; i++ )
1480 uv += oldUVImpr[ i ];
1482 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1487 //MESSAGE(" Can't improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1490 if ( !oldIsIn && nbOldFix ) {
1491 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1492 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1493 gp_XY uv = oldUVFixed[ 0 ];
1494 for ( int i = 1; i < nbOldFix; i++ )
1495 uv += oldUVFixed[ i ];
1497 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1502 //MESSAGE(" Can't fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1505 if ( newIsIn && oldIsIn )
1506 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1507 else if ( !newIsIn )
1514 //=======================================================================
1515 //function : compUVByElasticIsolines
1516 //purpose : compute UV as nodes of iso-poly-lines consisting of
1517 // segments keeping relative size as in the pattern
1518 //=======================================================================
1519 //#define DEB_COMPUVBYELASTICISOLINES
1520 bool SMESH_Pattern::
1521 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1522 const list< TPoint* >& thePntToCompute)
1524 return false; // PAL17233
1525 //cout << "============================== KEY POINTS =============================="<<endl;
1526 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1527 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1528 // TPoint& p = myPoints[ *kpIt ];
1529 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1530 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1532 //cout << "=============================="<<endl;
1534 // Define parameters of iso-grid nodes in U and V dir
1536 set< double > paramSet[ 2 ];
1537 list< list< TPoint* > >::const_iterator pListIt;
1538 list< TPoint* >::const_iterator pIt;
1539 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1540 const list< TPoint* > & pList = * pListIt;
1541 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1542 paramSet[0].insert( (*pIt)->myInitUV.X() );
1543 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1546 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1547 paramSet[0].insert( (*pIt)->myInitUV.X() );
1548 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1550 // unite close parameters and split too long segments
1553 for ( iDir = 0; iDir < 2; iDir++ )
1555 set< double > & params = paramSet[ iDir ];
1556 double range = ( *params.rbegin() - *params.begin() );
1557 double toler = range / 1e6;
1558 tol[ iDir ] = toler;
1559 // double maxSegment = range / params.size() / 2.;
1561 // set< double >::iterator parIt = params.begin();
1562 // double prevPar = *parIt;
1563 // for ( parIt++; parIt != params.end(); parIt++ )
1565 // double segLen = (*parIt) - prevPar;
1566 // if ( segLen < toler )
1567 // ;//params.erase( prevPar ); // unite
1568 // else if ( segLen > maxSegment )
1569 // params.insert( prevPar + 0.5 * segLen ); // split
1570 // prevPar = (*parIt);
1574 // Make nodes of a grid of iso-poly-lines
1576 list < TIsoNode > nodes;
1577 typedef list < TIsoNode *> TIsoLine;
1578 map < double, TIsoLine > isoMap[ 2 ];
1580 set< double > & params0 = paramSet[ 0 ];
1581 set< double >::iterator par0It = params0.begin();
1582 for ( ; par0It != params0.end(); par0It++ )
1584 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1585 set< double > & params1 = paramSet[ 1 ];
1586 set< double >::iterator par1It = params1.begin();
1587 for ( ; par1It != params1.end(); par1It++ )
1589 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1590 isoLine0.push_back( & nodes.back() );
1591 isoMap[1][ *par1It ].push_back( & nodes.back() );
1595 // Compute intersections of boundaries with iso-lines:
1596 // only boundary nodes will have computed UV so far
1599 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1600 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1601 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1603 const list< TPoint* > & bndPoints = * bndIt;
1604 TPoint* prevP = bndPoints.back(); // this is the first point
1605 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1606 // loop on the edge-points
1607 for ( ; pIt != bndPoints.end(); pIt++ )
1609 TPoint* point = *pIt;
1610 for ( iDir = 0; iDir < 2; iDir++ )
1612 const int iCoord = iDir + 1;
1613 const int iOtherCoord = 2 - iDir;
1614 double par1 = prevP->myInitUV.Coord( iCoord );
1615 double par2 = point->myInitUV.Coord( iCoord );
1616 double parDif = par2 - par1;
1617 if ( Abs( parDif ) <= DBL_MIN )
1619 // find iso-lines intersecting a bounadry
1620 double toler = tol[ 1 - iDir ];
1621 double minPar = Min ( par1, par2 );
1622 double maxPar = Max ( par1, par2 );
1623 map < double, TIsoLine >& isos = isoMap[ iDir ];
1624 map < double, TIsoLine >::iterator isoIt = isos.begin();
1625 for ( ; isoIt != isos.end(); isoIt++ )
1627 double isoParam = (*isoIt).first;
1628 if ( isoParam < minPar || isoParam > maxPar )
1630 double r = ( isoParam - par1 ) / parDif;
1631 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1632 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1633 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1634 // find existing node with otherPar or insert a new one
1635 TIsoLine & isoLine = (*isoIt).second;
1637 TIsoLine::iterator nIt = isoLine.begin();
1638 for ( ; nIt != isoLine.end(); nIt++ ) {
1639 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1640 if ( nodePar >= otherPar )
1644 if ( Abs( nodePar - otherPar ) <= toler )
1645 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1647 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1648 node = & nodes.back();
1649 isoLine.insert( nIt, node );
1651 node->SetNotMovable();
1653 uvBnd.Add( gp_Pnt2d( uv ));
1654 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1656 gp_XY tgt( point->myUV - prevP->myUV );
1657 if ( ::IsEqual( r, 1. ))
1658 node->myDir[ 0 ] = tgt;
1659 else if ( ::IsEqual( r, 0. ))
1660 node->myDir[ 1 ] = tgt;
1662 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1663 // keep boundary nodes corresponding to boundary points
1664 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1665 if ( bndNodes.empty() || bndNodes.back() != node )
1666 bndNodes.push_back( node );
1667 } // loop on isolines
1668 } // loop on 2 directions
1670 } // loop on boundary points
1671 } // loop on boundaries
1673 // Define orientation
1675 // find the point with the least X
1676 double leastX = DBL_MAX;
1677 TIsoNode * leftNode;
1678 list < TIsoNode >::iterator nodeIt = nodes.begin();
1679 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1680 TIsoNode & node = *nodeIt;
1681 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1682 leastX = node.myUV.X();
1685 // if ( node.IsUVComputed() ) {
1686 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1687 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1688 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1689 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1692 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1693 //SCRUTE( reversed );
1695 // Prepare internal nodes:
1697 // 2. compute ratios
1698 // 3. find boundary nodes for each node
1699 // 4. remove nodes out of the boundary
1700 for ( iDir = 0; iDir < 2; iDir++ )
1702 const int iCoord = 2 - iDir; // coord changing along an isoline
1703 map < double, TIsoLine >& isos = isoMap[ iDir ];
1704 map < double, TIsoLine >::iterator isoIt = isos.begin();
1705 for ( ; isoIt != isos.end(); isoIt++ )
1707 TIsoLine & isoLine = (*isoIt).second;
1708 bool firstCompNodeFound = false;
1709 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1710 nPrevIt = nIt = nNextIt = isoLine.begin();
1712 nNextIt++; nNextIt++;
1713 while ( nIt != isoLine.end() )
1715 // 1. connect prev - cur
1716 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1717 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1718 firstCompNodeFound = true;
1719 lastCompNodePos = nPrevIt;
1721 if ( firstCompNodeFound ) {
1722 node->SetNext( prevNode, iDir, 0 );
1723 prevNode->SetNext( node, iDir, 1 );
1726 if ( nNextIt != isoLine.end() ) {
1727 double par1 = prevNode->myInitUV.Coord( iCoord );
1728 double par2 = node->myInitUV.Coord( iCoord );
1729 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1730 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1732 // 3. find boundary nodes
1733 if ( node->IsUVComputed() )
1734 lastCompNodePos = nIt;
1735 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1736 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1737 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1738 if ( (*nIt2)->IsUVComputed() )
1740 if ( nIt2 != isoLine.end() ) {
1742 node->SetBoundaryNode( bndNode1, iDir, 0 );
1743 node->SetBoundaryNode( bndNode2, iDir, 1 );
1744 // cout << "--------------------------------------------------"<<endl;
1745 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1746 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1747 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1748 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1749 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1750 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1753 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1754 node->SetBoundaryNode( 0, iDir, 0 );
1755 node->SetBoundaryNode( 0, iDir, 1 );
1759 if ( nNextIt != isoLine.end() ) nNextIt++;
1760 // 4. remove nodes out of the boundary
1761 if ( !firstCompNodeFound )
1762 isoLine.pop_front();
1763 } // loop on isoLine nodes
1765 // remove nodes after the boundary
1766 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1767 // (*nIt)->SetNotMovable();
1768 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1769 } // loop on isolines
1770 } // loop on 2 directions
1772 // Compute local isoline direction for internal nodes
1775 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1776 map < double, TIsoLine >::iterator isoIt = isos.begin();
1777 for ( ; isoIt != isos.end(); isoIt++ )
1779 TIsoLine & isoLine = (*isoIt).second;
1780 TIsoLine::iterator nIt = isoLine.begin();
1781 for ( ; nIt != isoLine.end(); nIt++ )
1783 TIsoNode* node = *nIt;
1784 if ( node->IsUVComputed() || !node->IsMovable() )
1786 gp_Vec2d aTgt[2], aNorm[2];
1789 for ( iDir = 0; iDir < 2; iDir++ )
1791 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1792 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1793 if ( !bndNode1 || !bndNode2 ) {
1797 const int iCoord = 2 - iDir; // coord changing along an isoline
1798 double par1 = bndNode1->myInitUV.Coord( iCoord );
1799 double par2 = node->myInitUV.Coord( iCoord );
1800 double par3 = bndNode2->myInitUV.Coord( iCoord );
1801 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1803 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1804 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1805 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1806 else tgt1.Reverse();
1807 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1809 if ( ratio[ iDir ] < 0.5 )
1810 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1812 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1814 aNorm[ iDir ].Reverse(); // along iDir isoline
1816 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1817 // maybe angle is more than |PI|
1818 if ( Abs( angle ) > PI / 2. ) {
1819 // check direction of the last but one perpendicular isoline
1820 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1821 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1822 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1823 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1824 if ( isoDir * tgt2 < 0 )
1826 double angle2 = tgt1.Angle( isoDir );
1827 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1828 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1829 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1830 //MESSAGE("REVERSE ANGLE");
1833 if ( Abs( angle2 ) > Abs( angle ) ||
1834 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1835 //MESSAGE("Add PI");
1836 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1837 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1838 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1839 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1840 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1841 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1844 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1848 for ( iDir = 0; iDir < 2; iDir++ )
1850 aTgt[iDir].Normalize();
1851 aNorm[1-iDir].Normalize();
1852 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1855 node->myDir[iDir] = //aTgt[iDir];
1856 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1858 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1859 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1860 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1861 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1863 } // loop on iso nodes
1864 } // loop on isolines
1866 // Find nodes to start computing UV from
1868 list< TIsoNode* > startNodes;
1869 list< TIsoNode* >::iterator nIt = bndNodes.end();
1870 TIsoNode* node = *(--nIt);
1871 TIsoNode* prevNode = *(--nIt);
1872 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1874 TIsoNode* nextNode = *nIt;
1875 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1876 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1877 double initAngle = initTgt1.Angle( initTgt2 );
1878 double angle = node->myDir[0].Angle( node->myDir[1] );
1879 if ( reversed ) angle = -angle;
1880 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1881 // find a close internal node
1882 TIsoNode* nClose = 0;
1883 list< TIsoNode* > testNodes;
1884 testNodes.push_back( node );
1885 list< TIsoNode* >::iterator it = testNodes.begin();
1886 for ( ; !nClose && it != testNodes.end(); it++ )
1888 for (int i = 0; i < 4; i++ )
1890 nClose = (*it)->myNext[ i ];
1892 if ( !nClose->IsUVComputed() )
1895 testNodes.push_back( nClose );
1901 startNodes.push_back( nClose );
1902 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1903 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1904 // "initAngle: " << initAngle << " angle: " << angle << endl;
1905 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1906 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1907 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1908 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1914 // Compute starting UV of internal nodes
1916 list < TIsoNode* > internNodes;
1917 bool needIteration = true;
1918 if ( startNodes.empty() ) {
1919 //MESSAGE( " Starting UV by compUVByIsoIntersection()");
1920 needIteration = false;
1921 map < double, TIsoLine >& isos = isoMap[ 0 ];
1922 map < double, TIsoLine >::iterator isoIt = isos.begin();
1923 for ( ; isoIt != isos.end(); isoIt++ )
1925 TIsoLine & isoLine = (*isoIt).second;
1926 TIsoLine::iterator nIt = isoLine.begin();
1927 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1929 TIsoNode* node = *nIt;
1930 if ( !node->IsUVComputed() && node->IsMovable() ) {
1931 internNodes.push_back( node );
1933 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1934 node->myUV, needIteration ))
1935 node->myUV = node->myInitUV;
1939 if ( needIteration )
1940 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1942 TIsoNode* node = *nIt, *nClose = 0;
1943 list< TIsoNode* > testNodes;
1944 testNodes.push_back( node );
1945 list< TIsoNode* >::iterator it = testNodes.begin();
1946 for ( ; !nClose && it != testNodes.end(); it++ )
1948 for (int i = 0; i < 4; i++ )
1950 nClose = (*it)->myNext[ i ];
1952 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1955 testNodes.push_back( nClose );
1961 startNodes.push_back( nClose );
1965 double aMin[2], aMax[2], step[2];
1966 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1967 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1968 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1969 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1970 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1972 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1974 TIsoNode *node = *nIt;
1975 if ( node->IsUVComputed() || !node->IsMovable() )
1977 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1978 int nbComp = 0, nbPrev = 0;
1979 for ( iDir = 0; iDir < 2; iDir++ )
1981 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1982 TIsoNode* n = node->GetNext( iDir, 0 );
1983 if ( n->IsUVComputed() )
1986 startNodes.push_back( n );
1987 n = node->GetNext( iDir, 1 );
1988 if ( n->IsUVComputed() )
1991 startNodes.push_back( n );
1993 prevNode1 = prevNode2;
1996 if ( prevNode1 ) nbPrev++;
1997 if ( prevNode2 ) nbPrev++;
2000 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
2001 double par = node->myInitUV.Coord( 2 - iDir );
2002 bool isEnd = ( prevPar > par );
2003 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
2004 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2005 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
2007 MESSAGE("Why we are here?");
2010 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
2011 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
2012 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
2013 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
2014 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
2015 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
2016 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
2017 //" par: " << prevPar << endl;
2018 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
2019 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
2021 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2022 gp_XY & uv1 = prevNode1->myUV;
2023 gp_XY & uv2 = prevNode2->myUV;
2024 // dir = ( uv2 - uv1 );
2025 // double len = dir.Modulus();
2026 // if ( len > DBL_MIN )
2027 // dir /= len * 0.5;
2028 double r = node->myRatio[ iDir ];
2029 newUV += uv1 * ( 1 - r ) + uv2 * r;
2032 newUV += prevNode1->myUV + dir * step[ iDir ];
2038 if ( !nbComp ) continue;
2041 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2043 // check if a quadrangle is not distorted
2045 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
2046 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
2047 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
2048 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
2052 internNodes.push_back( node );
2057 static int maxNbIter = 100;
2058 #ifdef DEB_COMPUVBYELASTICISOLINES
2060 bool useNbMoveNode = 0;
2061 static int maxNbNodeMove = 100;
2064 if ( !useNbMoveNode )
2065 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2070 if ( !needIteration) break;
2071 #ifdef DEB_COMPUVBYELASTICISOLINES
2072 if ( nbIter >= maxNbIter ) break;
2075 list < TIsoNode* >::iterator nIt = internNodes.begin();
2076 for ( ; nIt != internNodes.end(); nIt++ ) {
2077 #ifdef DEB_COMPUVBYELASTICISOLINES
2079 cout << nbNodeMove <<" =================================================="<<endl;
2081 TIsoNode * node = *nIt;
2085 for ( iDir = 0; iDir < 2; iDir++ )
2087 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2088 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2089 double r = node->myRatio[ iDir ];
2090 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2091 // line[ iDir ].SetLocation( loc[ iDir ] );
2092 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2095 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2096 // double locR[2] = { 0, 0 };
2097 for ( iDir = 0; iDir < 2; iDir++ )
2099 const int iCoord = 2 - iDir; // coord changing along an isoline
2100 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2101 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2102 if ( !bndNode1 || !bndNode2 ) {
2105 double par1 = bndNode1->myInitUV.Coord( iCoord );
2106 double par2 = node->myInitUV.Coord( iCoord );
2107 double par3 = bndNode2->myInitUV.Coord( iCoord );
2108 double r = ( par2 - par1 ) / ( par3 - par1 );
2109 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2110 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2112 //locR[0] = locR[1] = 0.25;
2113 // intersect the 2 lines and move a node
2114 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2115 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2117 // double intR = 1 - locR[0] - locR[1];
2118 // gp_XY newUV = inter.Point(1).Value().XY();
2119 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2120 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2122 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2123 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2124 // avoid parallel isolines intersection
2125 checkQuads( node, newUV, reversed );
2127 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2129 } // intersection found
2130 #ifdef DEB_COMPUVBYELASTICISOLINES
2131 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2133 } // loop on internal nodes
2134 #ifdef DEB_COMPUVBYELASTICISOLINES
2135 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2137 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2139 //MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2141 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2142 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2143 #ifndef DEB_COMPUVBYELASTICISOLINES
2148 // Set computed UV to points
2150 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2151 TPoint* point = *pIt;
2152 //gp_XY oldUV = point->myUV;
2153 double minDist = DBL_MAX;
2154 list < TIsoNode >::iterator nIt = nodes.begin();
2155 for ( ; nIt != nodes.end(); nIt++ ) {
2156 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2157 if ( dist < minDist ) {
2159 point->myUV = (*nIt).myUV;
2168 //=======================================================================
2169 //function : setFirstEdge
2170 //purpose : choose the best first edge of theWire; return the summary distance
2171 // between point UV computed by isolines intersection and
2172 // eventual UV got from edge p-curves
2173 //=======================================================================
2175 //#define DBG_SETFIRSTEDGE
2176 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2178 int iE, nbEdges = theWire.size();
2182 // Transform UVs computed by iso to fit bnd box of a wire
2184 // max nb of points on an edge
2186 int eID = theFirstEdgeID;
2187 for ( iE = 0; iE < nbEdges; iE++ )
2188 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2190 // compute bnd boxes
2191 TopoDS_Face face = TopoDS::Face( myShape );
2192 Bnd_Box2d bndBox, eBndBox;
2193 eID = theFirstEdgeID;
2194 list< TopoDS_Edge >::iterator eIt;
2195 list< TPoint* >::iterator pIt;
2196 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2198 // UV by isos stored in TPoint.myXYZ
2199 list< TPoint* > & ePoints = getShapePoints( eID++ );
2200 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2202 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2204 // UV by an edge p-curve
2206 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2207 double dU = ( l - f ) / ( maxNbPnt - 1 );
2208 for ( int i = 0; i < maxNbPnt; i++ )
2209 eBndBox.Add( C2d->Value( f + i * dU ));
2212 // transform UVs by isos
2213 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2214 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2215 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2216 #ifdef DBG_SETFIRSTEDGE
2217 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2218 << eMinPar[1] << " - " << eMaxPar[1] );
2220 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2222 double dMin = eMinPar[i] - minPar[i];
2223 double dMax = eMaxPar[i] - maxPar[i];
2224 double dPar = maxPar[i] - minPar[i];
2225 eID = theFirstEdgeID;
2226 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2228 list< TPoint* > & ePoints = getShapePoints( eID++ );
2229 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2231 double par = (*pIt)->myXYZ.Coord( iC );
2232 double r = ( par - minPar[i] ) / dPar;
2233 par += ( 1 - r ) * dMin + r * dMax;
2234 (*pIt)->myXYZ.SetCoord( iC, par );
2240 double minDist = DBL_MAX;
2241 for ( iE = 0 ; iE < nbEdges; iE++ )
2243 #ifdef DBG_SETFIRSTEDGE
2244 MESSAGE ( " VARIANT " << iE );
2246 // evaluate the distance between UV computed by the 2 methods:
2247 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2249 int eID = theFirstEdgeID;
2250 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2252 list< TPoint* > & ePoints = getShapePoints( eID++ );
2253 computeUVOnEdge( *eIt, ePoints );
2254 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2256 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2257 #ifdef DBG_SETFIRSTEDGE
2258 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2259 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2263 #ifdef DBG_SETFIRSTEDGE
2264 MESSAGE ( "dist -- " << dist );
2266 if ( dist < minDist ) {
2268 eBest = theWire.front();
2270 // check variant with another first edge
2271 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2273 // put the best first edge to the theWire front
2274 if ( eBest != theWire.front() ) {
2275 eIt = find ( theWire.begin(), theWire.end(), eBest );
2276 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2282 //=======================================================================
2283 //function : sortSameSizeWires
2284 //purpose : sort wires in theWireList from theFromWire until theToWire,
2285 // the wires are set in the order to correspond to the order
2286 // of boundaries; after sorting, edges in the wires are put
2287 // in a good order, point UVs on edges are computed and points
2288 // are appended to theEdgesPointsList
2289 //=======================================================================
2291 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2292 const TListOfEdgesList::iterator& theFromWire,
2293 const TListOfEdgesList::iterator& theToWire,
2294 const int theFirstEdgeID,
2295 list< list< TPoint* > >& theEdgesPointsList )
2297 TopoDS_Face F = TopoDS::Face( myShape );
2298 int iW, nbWires = 0;
2299 TListOfEdgesList::iterator wlIt = theFromWire;
2300 while ( wlIt++ != theToWire )
2303 // Recompute key-point UVs by isolines intersection,
2304 // compute CG of key-points for each wire and bnd boxes of GCs
2307 gp_XY orig( gp::Origin2d().XY() );
2308 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2309 Bnd_Box2d bndBox, vBndBox;
2310 int eID = theFirstEdgeID;
2311 list< TopoDS_Edge >::iterator eIt;
2312 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2314 list< TopoDS_Edge > & wire = *wlIt;
2315 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2317 list< TPoint* > & ePoints = getShapePoints( eID++ );
2318 TPoint* p = ePoints.front();
2319 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2320 MESSAGE("can't sortSameSizeWires()");
2323 gcVec[iW] += p->myUV;
2324 bndBox.Add( gp_Pnt2d( p->myUV ));
2325 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2326 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2327 vGcVec[iW] += vXY.XY();
2329 // keep the computed UV to compare against by setFirstEdge()
2330 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2332 gcVec[iW] /= nbWires;
2333 vGcVec[iW] /= nbWires;
2334 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2335 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2338 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2340 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2341 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2342 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2343 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2345 double dMin = vMinPar[i] - minPar[i];
2346 double dMax = vMaxPar[i] - maxPar[i];
2347 double dPar = maxPar[i] - minPar[i];
2348 if ( Abs( dPar ) <= DBL_MIN )
2350 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2351 double par = gcVec[iW].Coord( iC );
2352 double r = ( par - minPar[i] ) / dPar;
2353 par += ( 1 - r ) * dMin + r * dMax;
2354 gcVec[iW].SetCoord( iC, par );
2358 // Define boundary - wire correspondence by GC closeness
2360 TListOfEdgesList tmpWList;
2361 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2362 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2363 TIntWirePosMap bndIndWirePosMap;
2364 vector< bool > bndFound( nbWires, false );
2365 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2367 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2368 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2369 double minDist = DBL_MAX;
2370 gp_XY & wGc = vGcVec[ iW ];
2372 for ( int iB = 0; iB < nbWires; iB++ ) {
2373 if ( bndFound[ iB ] ) continue;
2374 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2375 if ( dist < minDist ) {
2380 bndFound[ bIndex ] = true;
2381 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2386 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2387 eID = theFirstEdgeID;
2388 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2390 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2391 list < TopoDS_Edge > & wire = ( *wirePos );
2393 // choose the best first edge of a wire
2394 setFirstEdge( wire, eID );
2396 // compute eventual UV and fill theEdgesPointsList
2397 theEdgesPointsList.push_back( list< TPoint* >() );
2398 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2399 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2401 list< TPoint* > & ePoints = getShapePoints( eID++ );
2402 computeUVOnEdge( *eIt, ePoints );
2403 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2405 // put wire back to theWireList
2407 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2413 //=======================================================================
2415 //purpose : Compute nodes coordinates applying
2416 // the loaded pattern to <theFace>. The first key-point
2417 // will be mapped into <theVertexOnKeyPoint1>
2418 //=======================================================================
2420 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2421 const TopoDS_Vertex& theVertexOnKeyPoint1,
2422 const bool theReverse)
2424 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2425 if ( !setShapeToMesh( face ))
2428 // find points on edges, it fills myNbKeyPntInBoundary
2429 if ( !findBoundaryPoints() )
2432 // Define the edges order so that the first edge starts at
2433 // theVertexOnKeyPoint1
2435 list< TopoDS_Edge > eList;
2436 list< int > nbVertexInWires;
2437 int nbWires = SMESH_Block::GetOrderedEdges( face, eList, nbVertexInWires, theVertexOnKeyPoint1);
2438 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2440 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2441 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2443 // check nb wires and edges
2444 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2445 l1.sort(); l2.sort();
2448 MESSAGE( "Wrong nb vertices in wires" );
2449 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2452 // here shapes get IDs, for the outer wire IDs are OK
2453 int nbVertices = loadVE( eList, myShapeIDMap );
2454 myShapeIDMap.Add( face );
2456 if ((int) myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2457 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2458 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2461 // points on edges to be used for UV computation of in-face points
2462 list< list< TPoint* > > edgesPointsList;
2463 edgesPointsList.push_back( list< TPoint* >() );
2464 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2465 list< TPoint* >::iterator pIt, pEnd;
2467 // compute UV of points on the outer wire
2468 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2469 list< TopoDS_Edge >::iterator elIt;
2470 for (iE = 0, elIt = eList.begin();
2471 iE < nbEdgesInOuterWire && elIt != eList.end();
2474 list< TPoint* > & ePoints = getShapePoints( *elIt );
2476 computeUVOnEdge( *elIt, ePoints );
2477 // collect on-edge points (excluding the last one)
2478 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2481 // If there are several wires, define the order of edges of inner wires:
2482 // compute UV of inner edge-points using 2 methods: the one for in-face points
2483 // and the one for on-edge points and then choose the best edge order
2484 // by the best correspondence of the 2 results.
2485 // The wires are sorted by number of edges to correspond to wires of the pattern
2488 // compute UV of inner edge-points using the method for in-face points
2489 // and divide eList into a list of separate wires
2491 list< TWire > wireList;
2492 list<TopoDS_Edge>::iterator eIt = elIt;
2493 list<int>::iterator nbEIt = nbVertexInWires.begin();
2494 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2496 int nbEdges = *nbEIt;
2497 wireList.push_back( list< TopoDS_Edge >() );
2498 TWire & wire = wireList.back();
2499 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2501 list< TPoint* > & ePoints = getShapePoints( *eIt );
2502 pIt = ePoints.begin();
2503 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2505 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2506 MESSAGE("can't Apply(face)");
2509 // keep the computed UV to compare against by setFirstEdge()
2510 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2512 wire.push_back( *eIt );
2515 // remove inner edges from eList
2516 eList.erase( elIt, eList.end() );
2518 // sort wireList by nb edges in a wire
2519 sortBySize< TopoDS_Edge > ( wireList );
2521 // an ID of the first edge of a boundary
2522 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2523 // if ( nbSeamShapes > 0 )
2524 // id1 += 2; // 2 vertices more
2526 // find points - edge correspondence for wires of unique size,
2527 // edge order within a wire should be defined only
2529 list< TWire >::iterator wlIt = wireList.begin();
2530 while ( wlIt != wireList.end() )
2532 TWire& wire = (*wlIt);
2533 size_t nbEdges = wire.size();
2535 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2537 // choose the best first edge of a wire
2538 setFirstEdge( wire, id1 );
2540 // compute eventual UV and collect on-edge points
2541 edgesPointsList.push_back( list< TPoint* >() );
2542 edgesPoints = & edgesPointsList.back();
2544 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2546 list< TPoint* > & ePoints = getShapePoints( eID++ );
2547 computeUVOnEdge( *eIt, ePoints );
2548 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2553 // skip same size wires
2554 while ( wlIt != wireList.end() && (*wlIt).size() == nbEdges )
2560 // find boundary - wire correspondence for several wires of same size
2562 id1 = nbVertices + nbEdgesInOuterWire + 1;
2563 wlIt = wireList.begin();
2564 while ( wlIt != wireList.end() )
2566 size_t nbSameSize = 0, nbEdges = (*wlIt).size();
2567 list< TWire >::iterator wlIt2 = wlIt;
2569 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2573 if ( nbSameSize > 0 )
2574 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2577 id1 += nbEdges * ( nbSameSize + 1 );
2580 // add well-ordered edges to eList
2582 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2584 TWire& wire = (*wlIt);
2585 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2588 // re-fill myShapeIDMap - all shapes get good IDs
2590 myShapeIDMap.Clear();
2591 nbVertices = loadVE( eList, myShapeIDMap );
2592 myShapeIDMap.Add( face );
2594 } // there are inner wires
2596 // Set XYZ of on-vertex points
2598 // for ( int iV = 1; iV <= nbVertices; ++iV )
2600 // const TopoDS_Vertex& V = TopoDS::Vertex( myShapeIDMap( iV ));
2601 // list< TPoint* > & vPoints = getShapePoints( iV );
2602 // if ( !vPoints.empty() )
2604 // //vPoints.front()->myUV = BRep_Tool::Parameters( V, theFace ).XY();
2605 // vPoints.front()->myXYZ = BRep_Tool::Pnt( V );
2609 // Compute XYZ of on-edge points
2611 TopLoc_Location loc;
2612 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2614 BRepAdaptor_Curve C3d( *elIt );
2615 list< TPoint* > & ePoints = getShapePoints( iE++ );
2616 for ( pIt = ++ePoints.begin(), pEnd = ePoints.end(); pIt != pEnd; pIt++ )
2618 TPoint* point = *pIt;
2619 point->myXYZ = C3d.Value( point->myU );
2623 // Compute UV and XYZ of in-face points
2625 // try to use a simple algo
2626 list< TPoint* > & fPoints = getShapePoints( face );
2627 bool isDeformed = false;
2628 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2629 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2630 (*pIt)->myUV, isDeformed )) {
2631 MESSAGE("can't Apply(face)");
2634 // try to use a complex algo if it is a difficult case
2635 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2637 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2638 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2639 (*pIt)->myUV, isDeformed )) {
2640 MESSAGE("can't Apply(face)");
2645 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2646 const gp_Trsf & aTrsf = loc.Transformation();
2647 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2649 TPoint * point = *pIt;
2650 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2651 if ( !loc.IsIdentity() )
2652 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2655 myIsComputed = true;
2657 return setErrorCode( ERR_OK );
2660 //=======================================================================
2662 //purpose : Compute nodes coordinates applying
2663 // the loaded pattern to <theFace>. The first key-point
2664 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2665 //=======================================================================
2667 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2668 const int theNodeIndexOnKeyPoint1,
2669 const bool theReverse)
2671 // MESSAGE(" ::Apply(MeshFace) " );
2673 if ( !IsLoaded() ) {
2674 MESSAGE( "Pattern not loaded" );
2675 return setErrorCode( ERR_APPL_NOT_LOADED );
2678 // check nb of nodes
2679 const int nbFaceNodes = theFace->NbCornerNodes();
2680 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2681 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2682 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2685 // find points on edges, it fills myNbKeyPntInBoundary
2686 if ( !findBoundaryPoints() )
2689 // check that there are no holes in a pattern
2690 if (myNbKeyPntInBoundary.size() > 1 ) {
2691 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2694 // Define the nodes order
2696 list< const SMDS_MeshNode* > nodes;
2697 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2698 SMDS_NodeIteratorPtr noIt = theFace->nodeIterator();
2700 while ( noIt->more() && iSub < nbFaceNodes ) {
2701 const SMDS_MeshNode* node = noIt->next();
2702 nodes.push_back( node );
2703 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2706 if ( n != nodes.end() ) {
2708 if ( n != --nodes.end() )
2709 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2712 else if ( n != nodes.begin() )
2713 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2715 list< gp_XYZ > xyzList;
2716 myOrderedNodes.resize( nbFaceNodes );
2717 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2718 xyzList.push_back( SMESH_TNodeXYZ( *n ));
2719 myOrderedNodes[ iSub++] = *n;
2722 // Define a face plane
2724 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2725 gp_Pnt P ( *xyzIt++ );
2726 gp_Vec Vx( P, *xyzIt++ ), N;
2728 N = Vx ^ gp_Vec( P, *xyzIt++ );
2729 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2730 if ( N.SquareMagnitude() <= DBL_MIN )
2731 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2732 gp_Ax2 pos( P, N, Vx );
2734 // Compute UV of key-points on a plane
2735 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2737 gp_Vec vec ( pos.Location(), *xyzIt );
2738 TPoint* p = getShapePoints( iSub ).front();
2739 p->myUV.SetX( vec * pos.XDirection() );
2740 p->myUV.SetY( vec * pos.YDirection() );
2744 // points on edges to be used for UV computation of in-face points
2745 list< list< TPoint* > > edgesPointsList;
2746 edgesPointsList.push_back( list< TPoint* >() );
2747 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2748 list< TPoint* >::iterator pIt;
2750 // compute UV and XYZ of points on edges
2752 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2754 gp_XYZ& xyz1 = *xyzIt++;
2755 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2757 list< TPoint* > & ePoints = getShapePoints( iSub );
2758 ePoints.back()->myInitU = 1.0;
2759 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2760 while ( *pIt != ePoints.back() )
2763 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2764 gp_Vec vec ( pos.Location(), p->myXYZ );
2765 p->myUV.SetX( vec * pos.XDirection() );
2766 p->myUV.SetY( vec * pos.YDirection() );
2768 // collect on-edge points (excluding the last one)
2769 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2772 // Compute UV and XYZ of in-face points
2774 // try to use a simple algo to compute UV
2775 list< TPoint* > & fPoints = getShapePoints( iSub );
2776 bool isDeformed = false;
2777 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2778 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2779 (*pIt)->myUV, isDeformed )) {
2780 MESSAGE("can't Apply(face)");
2783 // try to use a complex algo if it is a difficult case
2784 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2786 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2787 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2788 (*pIt)->myUV, isDeformed )) {
2789 MESSAGE("can't Apply(face)");
2794 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2796 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2799 myIsComputed = true;
2801 return setErrorCode( ERR_OK );
2804 //=======================================================================
2806 //purpose : Compute nodes coordinates applying
2807 // the loaded pattern to <theFace>. The first key-point
2808 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2809 //=======================================================================
2811 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2812 const SMDS_MeshFace* theFace,
2813 const TopoDS_Shape& theSurface,
2814 const int theNodeIndexOnKeyPoint1,
2815 const bool theReverse)
2817 // MESSAGE(" ::Apply(MeshFace) " );
2818 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2819 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2821 const TopoDS_Face& face = TopoDS::Face( theSurface );
2822 TopLoc_Location loc;
2823 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2824 const gp_Trsf & aTrsf = loc.Transformation();
2826 if ( !IsLoaded() ) {
2827 MESSAGE( "Pattern not loaded" );
2828 return setErrorCode( ERR_APPL_NOT_LOADED );
2831 // check nb of nodes
2832 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2833 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2834 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2837 // find points on edges, it fills myNbKeyPntInBoundary
2838 if ( !findBoundaryPoints() )
2841 // check that there are no holes in a pattern
2842 if (myNbKeyPntInBoundary.size() > 1 ) {
2843 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2846 // Define the nodes order
2848 list< const SMDS_MeshNode* > nodes;
2849 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2850 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2852 while ( noIt->more() ) {
2853 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2854 nodes.push_back( node );
2855 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2858 if ( n != nodes.end() ) {
2860 if ( n != --nodes.end() )
2861 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2864 else if ( n != nodes.begin() )
2865 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2868 // find a node not on a seam edge, if necessary
2869 SMESH_MesherHelper helper( *theMesh );
2870 helper.SetSubShape( theSurface );
2871 const SMDS_MeshNode* inFaceNode = 0;
2872 if ( helper.GetNodeUVneedInFaceNode() )
2874 SMESH_MeshEditor editor( theMesh );
2875 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2876 int shapeID = editor.FindShape( *n );
2878 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2879 if ( !helper.IsSeamShape( shapeID ))
2884 // Set UV of key-points (i.e. of nodes of theFace )
2885 vector< gp_XY > keyUV( theFace->NbNodes() );
2886 myOrderedNodes.resize( theFace->NbNodes() );
2887 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2889 TPoint* p = getShapePoints( iSub ).front();
2890 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2891 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2893 keyUV[ iSub-1 ] = p->myUV;
2894 myOrderedNodes[ iSub-1 ] = *n;
2897 // points on edges to be used for UV computation of in-face points
2898 list< list< TPoint* > > edgesPointsList;
2899 edgesPointsList.push_back( list< TPoint* >() );
2900 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2901 list< TPoint* >::iterator pIt;
2903 // compute UV and XYZ of points on edges
2905 for ( size_t i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2907 gp_XY& uv1 = keyUV[ i ];
2908 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2910 list< TPoint* > & ePoints = getShapePoints( iSub );
2911 ePoints.back()->myInitU = 1.0;
2912 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2913 while ( *pIt != ePoints.back() )
2916 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2917 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2918 if ( !loc.IsIdentity() )
2919 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2921 // collect on-edge points (excluding the last one)
2922 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2925 // Compute UV and XYZ of in-face points
2927 // try to use a simple algo to compute UV
2928 list< TPoint* > & fPoints = getShapePoints( iSub );
2929 bool isDeformed = false;
2930 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2931 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2932 (*pIt)->myUV, isDeformed )) {
2933 MESSAGE("can't Apply(face)");
2936 // try to use a complex algo if it is a difficult case
2937 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2939 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2940 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2941 (*pIt)->myUV, isDeformed )) {
2942 MESSAGE("can't Apply(face)");
2947 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2949 TPoint * point = *pIt;
2950 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2951 if ( !loc.IsIdentity() )
2952 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2955 myIsComputed = true;
2957 return setErrorCode( ERR_OK );
2960 //=======================================================================
2961 //function : undefinedXYZ
2963 //=======================================================================
2965 static const gp_XYZ& undefinedXYZ()
2967 static gp_XYZ xyz( 1.e100, 0., 0. );
2971 //=======================================================================
2972 //function : isDefined
2974 //=======================================================================
2976 inline static bool isDefined(const gp_XYZ& theXYZ)
2978 return theXYZ.X() < 1.e100;
2981 //=======================================================================
2983 //purpose : Compute nodes coordinates applying
2984 // the loaded pattern to <theFaces>. The first key-point
2985 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2986 //=======================================================================
2988 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2989 std::set<const SMDS_MeshFace*>& theFaces,
2990 const int theNodeIndexOnKeyPoint1,
2991 const bool theReverse)
2993 MESSAGE(" ::Apply(set<MeshFace>) " );
2995 if ( !IsLoaded() ) {
2996 MESSAGE( "Pattern not loaded" );
2997 return setErrorCode( ERR_APPL_NOT_LOADED );
3000 // find points on edges, it fills myNbKeyPntInBoundary
3001 if ( !findBoundaryPoints() )
3004 // check that there are no holes in a pattern
3005 if (myNbKeyPntInBoundary.size() > 1 ) {
3006 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3011 myElemXYZIDs.clear();
3012 myXYZIdToNodeMap.clear();
3014 myIdsOnBoundary.clear();
3015 myReverseConnectivity.clear();
3017 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
3018 myElements.reserve( theFaces.size() );
3020 int ind1 = 0; // lowest point index for a face
3025 // SMESH_MeshEditor editor( theMesh );
3027 // apply to each face in theFaces set
3028 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
3029 for ( ; face != theFaces.end(); ++face )
3031 // int curShapeId = editor.FindShape( *face );
3032 // if ( curShapeId != shapeID ) {
3033 // if ( curShapeId )
3034 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
3037 // shapeID = curShapeId;
3040 if ( shape.IsNull() )
3041 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
3043 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
3045 MESSAGE( "Failed on " << *face );
3048 myElements.push_back( *face );
3050 // store computed points belonging to elements
3051 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3052 for ( ; ll != myElemPointIDs.end(); ++ll )
3054 myElemXYZIDs.push_back(TElemDef());
3055 TElemDef& xyzIds = myElemXYZIDs.back();
3056 TElemDef& pIds = *ll;
3057 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3058 int pIndex = *id + ind1;
3059 xyzIds.push_back( pIndex );
3060 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3061 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3064 // put points on links to myIdsOnBoundary,
3065 // they will be used to sew new elements on adjacent refined elements
3066 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3067 for ( int i = 0; i < nbNodes; i++ )
3069 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3070 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3071 const SMDS_MeshNode* n2 = myOrderedNodes[( i+1 ) % nbNodes ];
3072 // make a link and a node set
3073 TNodeSet linkSet, node1Set;
3074 linkSet.insert( n1 );
3075 linkSet.insert( n2 );
3076 node1Set.insert( n1 );
3077 list< TPoint* >::iterator p = linkPoints.begin();
3079 // map the first link point to n1
3080 int nId = ( *p - &myPoints[0] ) + ind1;
3081 myXYZIdToNodeMap[ nId ] = n1;
3082 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3083 groups.push_back(list< int > ());
3084 groups.back().push_back( nId );
3086 // add the linkSet to the map
3087 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3088 groups.push_back(list< int > ());
3089 list< int >& indList = groups.back();
3090 // add points to the map excluding the end points
3091 for ( p++; *p != linkPoints.back(); p++ )
3092 indList.push_back( ( *p - &myPoints[0] ) + ind1 );
3094 ind1 += myPoints.size();
3097 return !myElemXYZIDs.empty();
3100 //=======================================================================
3102 //purpose : Compute nodes coordinates applying
3103 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3104 // will be mapped into <theNode000Index>-th node. The
3105 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3107 //=======================================================================
3109 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3110 const int theNode000Index,
3111 const int theNode001Index)
3113 if ( !IsLoaded() ) {
3114 MESSAGE( "Pattern not loaded" );
3115 return setErrorCode( ERR_APPL_NOT_LOADED );
3118 // bind ID to points
3119 if ( !findBoundaryPoints() )
3122 // check that there are no holes in a pattern
3123 if (myNbKeyPntInBoundary.size() > 1 ) {
3124 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3129 myElemXYZIDs.clear();
3130 myXYZIdToNodeMap.clear();
3132 myIdsOnBoundary.clear();
3133 myReverseConnectivity.clear();
3135 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3136 myElements.reserve( theVolumes.size() );
3138 // to find point index
3139 map< TPoint*, int > pointIndex;
3140 for ( size_t i = 0; i < myPoints.size(); i++ )
3141 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3143 int ind1 = 0; // lowest point index for an element
3145 // apply to each element in theVolumes set
3146 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3147 for ( ; vol != theVolumes.end(); ++vol )
3149 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3150 MESSAGE( "Failed on " << *vol );
3153 myElements.push_back( *vol );
3155 // store computed points belonging to elements
3156 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3157 for ( ; ll != myElemPointIDs.end(); ++ll )
3159 myElemXYZIDs.push_back(TElemDef());
3160 TElemDef& xyzIds = myElemXYZIDs.back();
3161 TElemDef& pIds = *ll;
3162 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3163 int pIndex = *id + ind1;
3164 xyzIds.push_back( pIndex );
3165 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3166 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3169 // put points on edges and faces to myIdsOnBoundary,
3170 // they will be used to sew new elements on adjacent refined elements
3171 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3173 // make a set of sub-points
3175 vector< int > subIDs;
3176 if ( SMESH_Block::IsVertexID( Id )) {
3177 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3179 else if ( SMESH_Block::IsEdgeID( Id )) {
3180 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3181 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3182 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3185 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3186 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3187 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3188 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3189 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3190 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3191 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3192 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3195 list< TPoint* > & points = getShapePoints( Id );
3196 list< TPoint* >::iterator p = points.begin();
3197 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3198 groups.push_back(list< int > ());
3199 list< int >& indList = groups.back();
3200 for ( ; p != points.end(); p++ )
3201 indList.push_back( pointIndex[ *p ] + ind1 );
3202 if ( subNodes.size() == 1 ) // vertex case
3203 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3205 ind1 += myPoints.size();
3208 return !myElemXYZIDs.empty();
3211 //=======================================================================
3213 //purpose : Create a pattern from the mesh built on <theBlock>
3214 //=======================================================================
3216 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3217 const TopoDS_Shell& theBlock,
3222 myToKeepNodes = theKeepNodes;
3223 SMESHDS_SubMesh * aSubMesh;
3225 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3227 // load shapes in myShapeIDMap
3229 TopoDS_Vertex v1, v2;
3230 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3231 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3234 smIdType nbNodes = 0; int shapeID;
3235 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3237 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3238 aSubMesh = getSubmeshWithElements( theMesh, S );
3240 nbNodes += aSubMesh->NbNodes();
3242 myPoints.resize( nbNodes );
3244 // load U of points on edges
3245 TNodePointIDMap nodePointIDMap;
3247 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3249 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3250 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3251 aSubMesh = getSubmeshWithElements( theMesh, S );
3252 if ( ! aSubMesh ) continue;
3253 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3254 if ( !nIt->more() ) continue;
3256 // store a node and a point
3257 while ( nIt->more() ) {
3258 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3259 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3261 nodePointIDMap.insert( make_pair( node, iPoint ));
3262 if ( block.IsVertexID( shapeID ))
3263 myKeyPointIDs.push_back( iPoint );
3264 TPoint* p = & myPoints[ iPoint++ ];
3265 shapePoints.push_back( p );
3266 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3267 p->myInitXYZ.SetCoord( 0,0,0 );
3269 list< TPoint* >::iterator pIt = shapePoints.begin();
3272 switch ( S.ShapeType() )
3277 for ( ; pIt != shapePoints.end(); pIt++ ) {
3278 double * coef = block.GetShapeCoef( shapeID );
3279 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3280 if ( coef[ iCoord - 1] > 0 )
3281 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3283 if ( S.ShapeType() == TopAbs_VERTEX )
3286 const TopoDS_Edge& edge = TopoDS::Edge( S );
3288 BRep_Tool::Range( edge, f, l );
3289 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3290 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3291 pIt = shapePoints.begin();
3292 nIt = aSubMesh->GetNodes();
3293 for ( ; nIt->more(); pIt++ )
3295 const SMDS_MeshNode* node = nIt->next();
3296 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3298 SMDS_EdgePositionPtr epos = node->GetPosition();
3299 double u = ( epos->GetUParameter() - f ) / ( l - f );
3300 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3305 for ( ; pIt != shapePoints.end(); pIt++ )
3307 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3308 MESSAGE( "!block.ComputeParameters()" );
3309 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3313 } // loop on block sub-shapes
3317 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3320 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3321 while ( elemIt->more() ) {
3322 const SMDS_MeshElement* elem = elemIt->next();
3323 myElemPointIDs.push_back( TElemDef() );
3324 TElemDef& elemPoints = myElemPointIDs.back();
3325 int nbNodes = elem->NbCornerNodes();
3326 for ( int i = 0;i < nbNodes; ++i )
3327 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3331 myIsBoundaryPointsFound = true;
3333 if ( myToKeepNodes )
3335 myInNodes.resize( nodePointIDMap.size() );
3336 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
3337 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
3338 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
3341 return setErrorCode( ERR_OK );
3344 //=======================================================================
3345 //function : getSubmeshWithElements
3346 //purpose : return submesh containing elements bound to theBlock in theMesh
3347 //=======================================================================
3349 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3350 const TopoDS_Shape& theShape)
3352 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3353 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3356 if ( theShape.ShapeType() == TopAbs_SHELL )
3358 // look for submesh of VOLUME
3359 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3360 for (; it.More(); it.Next()) {
3361 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3362 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3370 //=======================================================================
3372 //purpose : Compute nodes coordinates applying
3373 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3374 // will be mapped into <theVertex000>. The (0,0,1)
3375 // fifth key-point will be mapped into <theVertex001>.
3376 //=======================================================================
3378 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3379 const TopoDS_Vertex& theVertex000,
3380 const TopoDS_Vertex& theVertex001)
3382 if (!findBoundaryPoints() || // bind ID to points
3383 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3386 SMESH_Block block; // bind ID to shape
3387 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3388 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3390 // compute XYZ of points on shapes
3392 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3394 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3395 list< TPoint* >::iterator pIt = shapePoints.begin();
3396 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3397 switch ( S.ShapeType() )
3399 case TopAbs_VERTEX: {
3401 for ( ; pIt != shapePoints.end(); pIt++ )
3402 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3407 for ( ; pIt != shapePoints.end(); pIt++ )
3408 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3413 for ( ; pIt != shapePoints.end(); pIt++ )
3414 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3418 for ( ; pIt != shapePoints.end(); pIt++ )
3419 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3421 } // loop on block sub-shapes
3423 myIsComputed = true;
3425 return setErrorCode( ERR_OK );
3428 //=======================================================================
3430 //purpose : Compute nodes coordinates applying
3431 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3432 // will be mapped into <theNode000Index>-th node. The
3433 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3435 //=======================================================================
3437 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3438 const int theNode000Index,
3439 const int theNode001Index)
3441 if (!findBoundaryPoints()) // bind ID to points
3444 SMESH_Block block; // bind ID to shape
3445 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3446 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3447 // compute XYZ of points on shapes
3449 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3451 list< TPoint* > & shapePoints = getShapePoints( ID );
3452 list< TPoint* >::iterator pIt = shapePoints.begin();
3454 if ( block.IsVertexID( ID ))
3455 for ( ; pIt != shapePoints.end(); pIt++ ) {
3456 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3458 else if ( block.IsEdgeID( ID ))
3459 for ( ; pIt != shapePoints.end(); pIt++ ) {
3460 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3462 else if ( block.IsFaceID( ID ))
3463 for ( ; pIt != shapePoints.end(); pIt++ ) {
3464 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3467 for ( ; pIt != shapePoints.end(); pIt++ )
3468 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3469 } // loop on block sub-shapes
3471 myIsComputed = true;
3473 return setErrorCode( ERR_OK );
3476 //=======================================================================
3477 //function : mergePoints
3478 //purpose : Merge XYZ on edges and/or faces.
3479 //=======================================================================
3481 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3483 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3484 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3486 list<list< int > >& groups = idListIt->second;
3487 if ( groups.size() < 2 )
3491 const TNodeSet& nodes = idListIt->first;
3492 double tol2 = 1.e-10;
3493 if ( nodes.size() > 1 ) {
3495 TNodeSet::const_iterator n = nodes.begin();
3496 for ( ; n != nodes.end(); ++n )
3497 box.Add( gp_Pnt( SMESH_TNodeXYZ( *n )));
3498 double x, y, z, X, Y, Z;
3499 box.Get( x, y, z, X, Y, Z );
3500 gp_Pnt p( x, y, z ), P( X, Y, Z );
3501 tol2 = 1.e-4 * p.SquareDistance( P );
3504 // to unite groups on link
3505 bool unite = ( uniteGroups && nodes.size() == 2 );
3506 map< double, int > distIndMap;
3507 const SMDS_MeshNode* node = *nodes.begin();
3508 gp_Pnt P = SMESH_TNodeXYZ( node );
3510 // compare points, replace indices
3512 list< int >::iterator ind1, ind2;
3513 list< list< int > >::iterator grpIt1, grpIt2;
3514 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3516 list< int >& indices1 = *grpIt1;
3518 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3520 list< int >& indices2 = *grpIt2;
3521 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3523 gp_XYZ& p1 = myXYZ[ *ind1 ];
3524 ind2 = indices2.begin();
3525 while ( ind2 != indices2.end() )
3527 gp_XYZ& p2 = myXYZ[ *ind2 ];
3528 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3529 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3531 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3532 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3533 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3534 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3536 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3537 myXYZ[ *ind2 ] = undefinedXYZ();
3538 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3540 ind2 = indices2.erase( ind2 );
3547 if ( unite ) { // sort indices using distIndMap
3548 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3550 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3551 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3552 distIndMap.insert( make_pair( dist, *ind1 ));
3556 if ( unite ) { // put all sorted indices into the first group
3557 list< int >& g = groups.front();
3559 map< double, int >::iterator dist_ind = distIndMap.begin();
3560 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3561 g.push_back( dist_ind->second );
3563 } // loop on myIdsOnBoundary
3566 //=======================================================================
3567 //function : makePolyElements
3568 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3569 //=======================================================================
3571 void SMESH_Pattern::
3572 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3573 const bool toCreatePolygons,
3574 const bool toCreatePolyedrs)
3576 myPolyElemXYZIDs.clear();
3577 myPolyElems.clear();
3578 myPolyElems.reserve( myIdsOnBoundary.size() );
3580 // make a set of refined elements
3581 TIDSortedElemSet elemSet, avoidSet( myElements.begin(), myElements.end() );
3583 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3585 if ( toCreatePolygons )
3587 int lastFreeId = myXYZ.size();
3589 // loop on links of refined elements
3590 indListIt = myIdsOnBoundary.begin();
3591 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3593 const TNodeSet & linkNodes = indListIt->first;
3594 if ( linkNodes.size() != 2 )
3595 continue; // skip face
3596 const SMDS_MeshNode* n1 = * linkNodes.begin();
3597 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3599 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3600 if ( idGroups.empty() || idGroups.front().empty() )
3603 // find not refined face having n1-n2 link
3607 const SMDS_MeshElement* face =
3608 SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet );
3611 avoidSet.insert ( face );
3612 myPolyElems.push_back( face );
3614 // some links of <face> are split;
3615 // make list of xyz for <face>
3616 myPolyElemXYZIDs.push_back(TElemDef());
3617 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3618 // loop on links of a <face>
3619 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3620 int i = 0, nbNodes = face->NbNodes();
3621 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3622 while ( nIt->more() )
3623 nodes[ i++ ] = smdsNode( nIt->next() );
3624 nodes[ i ] = nodes[ 0 ];
3625 for ( i = 0; i < nbNodes; ++i )
3627 // look for point mapped on a link
3628 TNodeSet faceLinkNodes;
3629 faceLinkNodes.insert( nodes[ i ] );
3630 faceLinkNodes.insert( nodes[ i + 1 ] );
3631 if ( faceLinkNodes == linkNodes )
3632 nn_IdList = indListIt;
3634 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3635 // add face point ids
3636 faceNodeIds.push_back( ++lastFreeId );
3637 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3638 if ( nn_IdList != myIdsOnBoundary.end() )
3640 // there are points mapped on a link
3641 list< int >& mappedIds = nn_IdList->second.front();
3642 if ( isReversed( nodes[ i ], mappedIds ))
3643 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3645 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3647 } // loop on links of a <face>
3653 if ( myIs2D && idGroups.size() > 1 ) {
3655 // sew new elements on 2 refined elements sharing n1-n2 link
3657 list< int >& idsOnLink = idGroups.front();
3658 // temporarily add ids of link nodes to idsOnLink
3659 bool rev = isReversed( n1, idsOnLink );
3660 for ( int i = 0; i < 2; ++i )
3663 nodeSet.insert( i ? n2 : n1 );
3664 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3665 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3666 int nodeId = groups.front().front();
3668 if ( rev ) append = !append;
3670 idsOnLink.push_back( nodeId );
3672 idsOnLink.push_front( nodeId );
3674 list< int >::iterator id = idsOnLink.begin();
3675 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3677 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3678 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3679 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3681 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3682 // look for <id> in element definition
3683 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3684 ASSERT ( idDef != pIdList->end() );
3685 // look for 2 neighbour ids of <id> in element definition
3686 for ( int prev = 0; prev < 2; ++prev ) {
3687 TElemDef::iterator idDef2 = idDef;
3689 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3691 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3692 // look for idDef2 on a link starting from id
3693 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3694 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3695 // insert ids located on link between <id> and <id2>
3696 // into the element definition between idDef and idDef2
3698 for ( ; id2 != id; --id2 )
3699 pIdList->insert( idDef, *id2 );
3701 list< int >::iterator id1 = id;
3702 for ( ++id1, ++id2; id1 != id2; ++id1 )
3703 pIdList->insert( idDef2, *id1 );
3709 // remove ids of link nodes
3710 idsOnLink.pop_front();
3711 idsOnLink.pop_back();
3713 } // loop on myIdsOnBoundary
3714 } // if ( toCreatePolygons )
3716 if ( toCreatePolyedrs )
3718 // check volumes adjacent to the refined elements
3719 SMDS_VolumeTool volTool;
3720 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3721 for ( ; refinedElem != myElements.end(); ++refinedElem )
3723 // loop on nodes of refinedElem
3724 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3725 while ( nIt->more() ) {
3726 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3727 // loop on inverse elements of node
3728 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3729 while ( eIt->more() )
3731 const SMDS_MeshElement* elem = eIt->next();
3732 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3733 continue; // skip faces or refined elements
3734 // add polyhedron definition
3735 myPolyhedronQuantities.push_back(vector<int> ());
3736 myPolyElemXYZIDs.push_back(TElemDef());
3737 vector<int>& quantity = myPolyhedronQuantities.back();
3738 TElemDef & elemDef = myPolyElemXYZIDs.back();
3739 // get definitions of new elements on volume faces
3740 bool makePoly = false;
3741 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3743 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3744 volTool.NbFaceNodes( iF ),
3745 theNodes, elemDef, quantity))
3749 myPolyElems.push_back( elem );
3751 myPolyhedronQuantities.pop_back();
3752 myPolyElemXYZIDs.pop_back();
3760 //=======================================================================
3761 //function : getFacesDefinition
3762 //purpose : return faces definition for a volume face defined by theBndNodes
3763 //=======================================================================
3765 bool SMESH_Pattern::
3766 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3767 const int theNbBndNodes,
3768 const vector< const SMDS_MeshNode* >& theNodes,
3769 list< int >& theFaceDefs,
3770 vector<int>& theQuantity)
3772 bool makePoly = false;
3774 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3776 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3778 // make a set of all nodes on a face
3780 if ( !myIs2D ) { // for 2D, merge only edges
3781 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3782 if ( nn_IdList != myIdsOnBoundary.end() ) {
3783 list< int > & faceIds = nn_IdList->second.front();
3784 if ( !faceIds.empty() ) {
3786 ids.insert( faceIds.begin(), faceIds.end() );
3791 // add ids on links and bnd nodes
3792 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3793 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3794 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3796 // add id of iN-th bnd node
3798 nSet.insert( theBndNodes[ iN ] );
3799 nn_IdList = myIdsOnBoundary.find( nSet );
3800 int bndId = ++lastFreeId;
3801 if ( nn_IdList != myIdsOnBoundary.end() ) {
3802 bndId = nn_IdList->second.front().front();
3803 ids.insert( bndId );
3806 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3808 faceDef.push_back( bndId );
3809 // add ids on a link
3811 linkNodes.insert( theBndNodes[ iN ]);
3812 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3813 nn_IdList = myIdsOnBoundary.find( linkNodes );
3814 if ( nn_IdList != myIdsOnBoundary.end() ) {
3815 list< int > & linkIds = nn_IdList->second.front();
3816 if ( !linkIds.empty() )
3819 ids.insert( linkIds.begin(), linkIds.end() );
3820 if ( isReversed( theBndNodes[ iN ], linkIds ))
3821 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3823 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3828 // find faces definition of new volumes
3830 bool defsAdded = false;
3831 if ( !myIs2D ) { // for 2D, merge only edges
3832 SMDS_VolumeTool vol;
3833 set< TElemDef* > checkedVolDefs;
3834 set< int >::iterator id = ids.begin();
3835 for ( ; id != ids.end(); ++id )
3837 // definitions of volumes sharing id
3838 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3839 ASSERT( !defList.empty() );
3840 // loop on volume definitions
3841 list< TElemDef* >::iterator pIdList = defList.begin();
3842 for ( ; pIdList != defList.end(); ++pIdList)
3844 if ( !checkedVolDefs.insert( *pIdList ).second )
3845 continue; // skip already checked volume definition
3846 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3847 // loop on face defs of a volume
3848 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3849 if ( volType == SMDS_VolumeTool::UNKNOWN )
3851 int nbFaces = vol.NbFaces( volType );
3852 for ( int iF = 0; iF < nbFaces; ++iF )
3854 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3855 int iN, nbN = vol.NbFaceNodes( volType, iF );
3856 // check if all nodes of a faces are in <ids>
3858 for ( iN = 0; iN < nbN && all; ++iN ) {
3859 int nodeId = idVec[ nodeInds[ iN ]];
3860 all = ( ids.find( nodeId ) != ids.end() );
3863 // store a face definition
3864 for ( iN = 0; iN < nbN; ++iN ) {
3865 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3867 theQuantity.push_back( nbN );
3875 theQuantity.push_back( faceDef.size() );
3876 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3882 //=======================================================================
3883 //function : clearSubMesh
3885 //=======================================================================
3887 static bool clearSubMesh( SMESH_Mesh* theMesh,
3888 const TopoDS_Shape& theShape)
3890 bool removed = false;
3891 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3893 removed = !aSubMesh->IsEmpty();
3895 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3898 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3899 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3901 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3902 removed = eIt->more();
3903 while ( eIt->more() )
3904 aMeshDS->RemoveElement( eIt->next() );
3905 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3906 removed = removed || nIt->more();
3907 while ( nIt->more() )
3908 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3914 //=======================================================================
3915 //function : clearMesh
3916 //purpose : clear mesh elements existing on myShape in theMesh
3917 //=======================================================================
3919 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3922 if ( !myShape.IsNull() )
3924 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3925 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3926 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3928 clearSubMesh( theMesh, it.Value() );
3934 //=======================================================================
3935 //function : findExistingNodes
3936 //purpose : fills nodes vector with nodes existing on a given shape (IMP 22368)
3937 // Returns true if all nodes for all points on S are found
3938 //=======================================================================
3940 bool SMESH_Pattern::findExistingNodes( SMESH_Mesh* mesh,
3941 const TopoDS_Shape& S,
3942 const std::list< TPoint* > & points,
3943 vector< const SMDS_MeshNode* > & nodesVector)
3945 if ( S.IsNull() || points.empty() )
3948 SMESHDS_Mesh* aMeshDS = mesh->GetMeshDS();
3950 switch ( S.ShapeType() )
3954 int pIndex = points.back() - &myPoints[0];
3955 if ( !nodesVector[ pIndex ] )
3956 nodesVector[ pIndex ] = SMESH_Algo::VertexNode( TopoDS::Vertex( S ), aMeshDS );
3957 return nodesVector[ pIndex ];
3961 const TopoDS_Edge& edge = TopoDS::Edge( S );
3962 map< double, const SMDS_MeshNode* > paramsOfNodes;
3963 if ( !SMESH_Algo::GetSortedNodesOnEdge( aMeshDS, edge,
3964 /*ignoreMediumNodes=*/false,
3966 || paramsOfNodes.size() < 3 )
3968 // points on VERTEXes are included with wrong myU
3969 list< TPoint* >::const_reverse_iterator pItR = ++points.rbegin();
3970 list< TPoint* >::const_iterator pItF = ++points.begin();
3971 const bool isForward = ( (*pItF)->myU < (*pItR)->myU );
3972 map< double, const SMDS_MeshNode* >::iterator u2n = ++paramsOfNodes.begin();
3973 map< double, const SMDS_MeshNode* >::iterator u2nEnd = --paramsOfNodes.end();
3975 if ( paramsOfNodes.size() == points.size() )
3977 for ( ; u2n != u2nEnd; ++u2n )
3979 p = ( isForward ? *pItF : *pItR );
3980 int pIndex = p - &myPoints[0];
3981 if ( !nodesVector [ pIndex ] )
3982 nodesVector [ pIndex ] = u2n->second;
3990 const double tolFact = 0.05;
3991 while ( u2n != u2nEnd && pItF != points.end() )
3993 const double u = u2n->first;
3994 const SMDS_MeshNode* n = u2n->second;
3995 const double tol = ( (++u2n)->first - u ) * tolFact;
3998 p = ( isForward ? *pItF : *pItR );
3999 if ( Abs( u - p->myU ) < tol )
4001 int pIndex = p - &myPoints[0];
4002 if ( !nodesVector [ pIndex ] )
4003 nodesVector [ pIndex ] = n;
4009 while ( p->myU < u && ( ++pItF, ++pItR != points.rend() ));
4013 } // case TopAbs_EDGE:
4016 } // switch ( S.ShapeType() )
4021 //=======================================================================
4022 //function : MakeMesh
4023 //purpose : Create nodes and elements in <theMesh> using nodes
4024 // coordinates computed by either of Apply...() methods
4025 //=======================================================================
4027 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
4028 const bool toCreatePolygons,
4029 const bool toCreatePolyedrs)
4031 if ( !myIsComputed )
4032 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
4034 mergePoints( toCreatePolygons );
4036 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4038 // clear elements and nodes existing on myShape
4041 bool onMeshElements = ( !myElements.empty() );
4043 // Create missing nodes
4045 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
4046 if ( onMeshElements )
4048 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
4049 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
4050 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
4051 nodesVector[ i_node->first ] = i_node->second;
4053 for ( size_t i = 0; i < myXYZ.size(); ++i ) {
4054 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
4055 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
4059 if ( theMesh->HasShapeToMesh() )
4061 // set nodes on EDGEs (IMP 22368)
4062 SMESH_MesherHelper helper( *theMesh );
4063 helper.ToFixNodeParameters( true );
4064 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
4065 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
4067 list<list< int > >& groups = idListIt->second;
4068 const TNodeSet& nodes = idListIt->first;
4069 if ( nodes.size() != 2 )
4070 continue; // not a link
4071 const SMDS_MeshNode* n1 = *nodes.begin();
4072 const SMDS_MeshNode* n2 = *nodes.rbegin();
4073 TopoDS_Shape S1 = helper.GetSubShapeByNode( n1, aMeshDS );
4074 TopoDS_Shape S2 = helper.GetSubShapeByNode( n2, aMeshDS );
4075 if ( S1.IsNull() || S1.ShapeType() < TopAbs_EDGE ||
4076 S2.IsNull() || S2.ShapeType() < TopAbs_EDGE )
4079 if ( S1.ShapeType() == TopAbs_EDGE )
4081 if ( S1 == S2 || helper.IsSubShape( S2, S1 ))
4084 else if ( S2.ShapeType() == TopAbs_EDGE )
4086 if ( helper.IsSubShape( S1, S2 ))
4091 S = helper.GetCommonAncestor( S1, S2, *theMesh, TopAbs_EDGE );
4095 const TopoDS_Edge & E = TopoDS::Edge( S );
4096 helper.SetSubShape( E );
4097 list<list< int > >::iterator g = groups.begin();
4098 for ( ; g != groups.end(); ++g )
4100 list< int >& ids = *g;
4101 list< int >::iterator id = ids.begin();
4102 for ( ; id != ids.end(); ++id )
4103 if ( nodesVector[ *id ] && nodesVector[ *id ]->getshapeId() < 1 )
4106 aMeshDS->SetNodeOnEdge( nodesVector[ *id ], E, u );
4107 helper.CheckNodeU( E, nodesVector[ *id ], u, 1e-7, true );
4112 } // if ( onMeshElements )
4116 nodesVector.resize( myPoints.size(), 0 );
4118 // loop on sub-shapes of myShape: create nodes
4119 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
4120 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
4122 list< TPoint* > & points = idPointIt->second;
4124 if ( !myShapeIDMap.IsEmpty() )
4125 S = myShapeIDMap( idPointIt->first );
4127 // find existing nodes on EDGEs and VERTEXes
4128 if ( findExistingNodes( theMesh, S, points, nodesVector ))
4131 list< TPoint* >::iterator pIt = points.begin();
4132 for ( ; pIt != points.end(); pIt++ )
4134 TPoint* point = *pIt;
4135 int pIndex = point - &myPoints[0];
4136 if ( nodesVector [ pIndex ] )
4138 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
4141 nodesVector [ pIndex ] = node;
4143 if ( !S.IsNull() ) {
4145 switch ( S.ShapeType() ) {
4146 case TopAbs_VERTEX: {
4147 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
4150 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
4153 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
4154 point->myUV.X(), point->myUV.Y() ); break;
4157 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
4166 if ( onMeshElements )
4168 // prepare data to create poly elements
4169 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
4172 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
4173 // sew old and new elements
4174 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
4178 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4181 aMeshDS->Modified();
4182 aMeshDS->CompactMesh();
4184 if ( myToKeepNodes )
4185 myOutNodes.swap( nodesVector );
4187 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4188 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4189 // for ( ; i_sm != sm.end(); i_sm++ )
4191 // cout << " SM " << i_sm->first << " ";
4192 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4193 // //SMDS_ElemIteratorPtr GetElements();
4194 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4195 // while ( nit->more() )
4196 // cout << nit->next()->GetID() << " ";
4199 return setErrorCode( ERR_OK );
4202 //=======================================================================
4203 //function : createElements
4204 //purpose : add elements to the mesh
4205 //=======================================================================
4207 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4208 const vector<const SMDS_MeshNode* >& theNodesVector,
4209 const list< TElemDef > & theElemNodeIDs,
4210 const vector<const SMDS_MeshElement*>& theElements)
4212 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4213 SMESH_MeshEditor editor( theMesh );
4215 bool onMeshElements = !theElements.empty();
4217 // shapes and groups theElements are on
4218 vector< int > shapeIDs;
4219 vector< list< SMESHDS_Group* > > groups;
4220 set< const SMDS_MeshNode* > shellNodes;
4221 if ( onMeshElements )
4223 shapeIDs.resize( theElements.size() );
4224 groups.resize( theElements.size() );
4225 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4226 set<SMESHDS_GroupBase*>::const_iterator grIt;
4227 for ( size_t i = 0; i < theElements.size(); i++ )
4229 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4230 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4231 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4232 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4233 groups[ i ].push_back( group );
4236 // get all nodes bound to shells because their SpacePosition is not set
4237 // by SMESHDS_Mesh::SetNodeInVolume()
4238 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4239 if ( !aMainShape.IsNull() ) {
4240 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4241 for ( ; shellExp.More(); shellExp.Next() )
4243 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4245 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4246 while ( nIt->more() )
4247 shellNodes.insert( nIt->next() );
4252 // nb new elements per a refined element
4253 int nbNewElemsPerOld = 1;
4254 if ( onMeshElements )
4255 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4259 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4260 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4261 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4263 const TElemDef & elemNodeInd = *enIt;
4265 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4266 TElemDef::const_iterator id = elemNodeInd.begin();
4268 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4269 if ( *id < (int) theNodesVector.size() )
4270 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4272 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4274 // dim of refined elem
4275 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4276 if ( onMeshElements ) {
4277 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4280 const SMDS_MeshElement* elem = 0;
4282 switch ( nbNodes ) {
4284 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4286 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4288 if ( !onMeshElements ) {// create a quadratic face
4289 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4290 nodes[4], nodes[5] ); break;
4291 } // else do not break but create a polygon
4294 if ( !onMeshElements ) {// create a quadratic face
4295 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4296 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4297 } // else do not break but create a polygon
4300 elem = aMeshDS->AddPolygonalFace( nodes );
4304 switch ( nbNodes ) {
4306 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4308 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4311 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4312 nodes[4], nodes[5] ); break;
4314 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4315 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4317 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4320 // set element on a shape
4321 if ( elem && onMeshElements ) // applied to mesh elements
4323 int shapeID = shapeIDs[ elemIndex ];
4324 if ( shapeID > 0 ) {
4325 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4326 // set nodes on a shape
4327 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4328 if ( S.ShapeType() == TopAbs_SOLID ) {
4329 TopoDS_Iterator shellIt( S );
4330 if ( shellIt.More() )
4331 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4333 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4334 while ( noIt->more() ) {
4335 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4336 if ( node->getshapeId() < 1 &&
4337 shellNodes.find( node ) == shellNodes.end() )
4339 if ( S.ShapeType() == TopAbs_FACE )
4340 aMeshDS->SetNodeOnFace( node, shapeID,
4341 Precision::Infinite(),// <- it's a sign that UV is not set
4342 Precision::Infinite());
4344 aMeshDS->SetNodeInVolume( node, shapeID );
4345 shellNodes.insert( node );
4350 // add elem in groups
4351 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4352 for ( ; g != groups[ elemIndex ].end(); ++g )
4353 (*g)->SMDSGroup().Add( elem );
4355 if ( elem && !myShape.IsNull() ) // applied to shape
4356 aMeshDS->SetMeshElementOnShape( elem, myShape );
4359 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4360 // so that operations with hypotheses will erase the mesh being built
4362 SMESH_subMesh * subMesh;
4363 if ( !myShape.IsNull() ) {
4364 subMesh = theMesh->GetSubMesh( myShape );
4366 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4368 if ( onMeshElements ) {
4369 list< smIdType > elemIDs;
4370 for ( size_t i = 0; i < theElements.size(); i++ )
4372 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4374 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4376 elemIDs.push_back( theElements[ i ]->GetID() );
4378 // remove refined elements
4379 editor.Remove( elemIDs, false );
4383 //=======================================================================
4384 //function : isReversed
4385 //purpose : check xyz ids order in theIdsList taking into account
4386 // theFirstNode on a link
4387 //=======================================================================
4389 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4390 const list< int >& theIdsList) const
4392 if ( theIdsList.size() < 2 )
4395 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4397 list<int>::const_iterator id = theIdsList.begin();
4398 for ( int i = 0; i < 2; ++i, ++id ) {
4399 if ( *id < (int) myXYZ.size() )
4400 P[ i ] = myXYZ[ *id ];
4402 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4403 i_n = myXYZIdToNodeMap.find( *id );
4404 ASSERT( i_n != myXYZIdToNodeMap.end() );
4405 const SMDS_MeshNode* n = i_n->second;
4406 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4409 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4413 //=======================================================================
4414 //function : arrangeBoundaries
4415 //purpose : if there are several wires, arrange boundaryPoints so that
4416 // the outer wire goes first and fix inner wires orientation
4417 // update myKeyPointIDs to correspond to the order of key-points
4418 // in boundaries; sort internal boundaries by the nb of key-points
4419 //=======================================================================
4421 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4423 typedef list< list< TPoint* > >::iterator TListOfListIt;
4424 TListOfListIt bndIt;
4425 list< TPoint* >::iterator pIt;
4427 int nbBoundaries = boundaryList.size();
4428 if ( nbBoundaries > 1 )
4430 // sort boundaries by nb of key-points
4431 if ( nbBoundaries > 2 )
4433 // move boundaries in tmp list
4434 list< list< TPoint* > > tmpList;
4435 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4436 // make a map nb-key-points to boundary-position-in-tmpList,
4437 // boundary-positions get ordered in it
4438 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4439 TNbKpBndPosMap nbKpBndPosMap;
4440 bndIt = tmpList.begin();
4441 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4442 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4443 int nb = *nbKpIt * nbBoundaries;
4444 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4446 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4448 // move boundaries back to boundaryList
4449 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4450 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4451 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4452 TListOfListIt bndPos1 = bndPos2++;
4453 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4457 // Look for the outer boundary: the one with the point with the least X
4458 double leastX = DBL_MAX;
4459 TListOfListIt outerBndPos;
4460 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4462 list< TPoint* >& boundary = (*bndIt);
4463 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4465 TPoint* point = *pIt;
4466 if ( point->myInitXYZ.X() < leastX ) {
4467 leastX = point->myInitXYZ.X();
4468 outerBndPos = bndIt;
4473 if ( outerBndPos != boundaryList.begin() )
4474 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos );
4476 } // if nbBoundaries > 1
4478 // Check boundaries orientation and re-fill myKeyPointIDs
4480 set< TPoint* > keyPointSet;
4481 list< int >::iterator kpIt = myKeyPointIDs.begin();
4482 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4483 keyPointSet.insert( & myPoints[ *kpIt ]);
4484 myKeyPointIDs.clear();
4486 // update myNbKeyPntInBoundary also
4487 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4489 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4491 // find the point with the least X
4492 double leastX = DBL_MAX;
4493 list< TPoint* >::iterator xpIt;
4494 list< TPoint* >& boundary = (*bndIt);
4495 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4497 TPoint* point = *pIt;
4498 if ( point->myInitXYZ.X() < leastX ) {
4499 leastX = point->myInitXYZ.X();
4503 // find points next to the point with the least X
4504 TPoint* p = *xpIt, *pPrev, *pNext;
4505 if ( p == boundary.front() )
4506 pPrev = *(++boundary.rbegin());
4512 if ( p == boundary.back() )
4513 pNext = *(++boundary.begin());
4518 // vectors of boundary direction near <p>
4519 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4520 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4521 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4522 double yPrev = v1.Y() / sqrt( sqMag1 );
4523 double yNext = v2.Y() / sqrt( sqMag2 );
4524 double sumY = yPrev + yNext;
4526 if ( bndIt == boundaryList.begin() ) // outer boundary
4534 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4535 (*nbKpIt) = 0; // count nb of key-points again
4536 pIt = boundary.begin();
4537 for ( ; pIt != boundary.end(); pIt++)
4539 TPoint* point = *pIt;
4540 if ( keyPointSet.find( point ) == keyPointSet.end() )
4542 // find an index of a keypoint
4544 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4545 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4546 if ( &(*pVecIt) == point )
4548 myKeyPointIDs.push_back( index );
4551 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4554 } // loop on a list of boundaries
4556 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4559 //=======================================================================
4560 //function : findBoundaryPoints
4561 //purpose : if loaded from file, find points to map on edges and faces and
4562 // compute their parameters
4563 //=======================================================================
4565 bool SMESH_Pattern::findBoundaryPoints()
4567 if ( myIsBoundaryPointsFound ) return true;
4569 myNbKeyPntInBoundary.clear();
4573 set< TPoint* > pointsInElems;
4575 // Find free links of elements:
4576 // put links of all elements in a set and remove links encountered twice
4578 typedef pair< TPoint*, TPoint*> TLink;
4579 set< TLink > linkSet;
4580 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4581 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4583 TElemDef & elemPoints = *epIt;
4584 TElemDef::iterator pIt = elemPoints.begin();
4585 int prevP = elemPoints.back();
4586 for ( ; pIt != elemPoints.end(); pIt++ ) {
4587 TPoint* p1 = & myPoints[ prevP ];
4588 TPoint* p2 = & myPoints[ *pIt ];
4589 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4590 ASSERT( link.first != link.second );
4591 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4592 if ( !itUniq.second )
4593 linkSet.erase( itUniq.first );
4596 pointsInElems.insert( p1 );
4599 // Now linkSet contains only free links,
4600 // find the points order that they have in boundaries
4602 // 1. make a map of key-points
4603 set< TPoint* > keyPointSet;
4604 list< int >::iterator kpIt = myKeyPointIDs.begin();
4605 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4606 keyPointSet.insert( & myPoints[ *kpIt ]);
4608 // 2. chain up boundary points
4609 list< list< TPoint* > > boundaryList;
4610 boundaryList.push_back( list< TPoint* >() );
4611 list< TPoint* > * boundary = & boundaryList.back();
4613 TPoint *point1, *point2, *keypoint1;
4614 kpIt = myKeyPointIDs.begin();
4615 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4616 // loop on free links: look for the next point
4618 set< TLink >::iterator lIt = linkSet.begin();
4619 while ( lIt != linkSet.end() )
4621 if ( (*lIt).first == point1 )
4622 point2 = (*lIt).second;
4623 else if ( (*lIt).second == point1 )
4624 point2 = (*lIt).first;
4629 linkSet.erase( lIt );
4630 lIt = linkSet.begin();
4632 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4634 boundary->push_back( point2 );
4636 else // a key-point found
4638 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4640 if ( point2 != keypoint1 ) // its not the boundary end
4642 boundary->push_back( point2 );
4644 else // the boundary end reached
4646 boundary->push_front( keypoint1 );
4647 boundary->push_back( keypoint1 );
4648 myNbKeyPntInBoundary.push_back( iKeyPoint );
4649 if ( keyPointSet.empty() )
4650 break; // all boundaries containing key-points are found
4652 // prepare to search for the next boundary
4653 boundaryList.push_back( list< TPoint* >() );
4654 boundary = & boundaryList.back();
4655 point2 = keypoint1 = (*keyPointSet.begin());
4659 } // loop on the free links set
4661 if ( boundary->empty() ) {
4662 MESSAGE(" a separate key-point");
4663 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4666 // if there are several wires, arrange boundaryPoints so that
4667 // the outer wire goes first and fix inner wires orientation;
4668 // sort myKeyPointIDs to correspond to the order of key-points
4670 arrangeBoundaries( boundaryList );
4672 // Find correspondence shape ID - points,
4673 // compute points parameter on edge
4675 keyPointSet.clear();
4676 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4677 keyPointSet.insert( & myPoints[ *kpIt ]);
4679 set< TPoint* > edgePointSet; // to find in-face points
4680 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4681 int edgeID = myKeyPointIDs.size() + 1;
4683 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4684 for ( ; bndIt != boundaryList.end(); bndIt++ )
4686 boundary = & (*bndIt);
4687 double edgeLength = 0;
4688 list< TPoint* >::iterator pIt = boundary->begin();
4689 getShapePoints( edgeID ).push_back( *pIt );
4690 getShapePoints( vertexID++ ).push_back( *pIt );
4691 for ( pIt++; pIt != boundary->end(); pIt++)
4693 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4694 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4695 TPoint* point = *pIt;
4696 edgePointSet.insert( point );
4697 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4699 edgePoints.push_back( point );
4700 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4701 point->myInitU = edgeLength;
4705 // treat points on the edge which ends up: compute U [0,1]
4706 edgePoints.push_back( point );
4707 if ( edgePoints.size() > 2 ) {
4708 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4709 list< TPoint* >::iterator epIt = edgePoints.begin();
4710 for ( ; epIt != edgePoints.end(); epIt++ )
4711 (*epIt)->myInitU /= edgeLength;
4713 // begin the next edge treatment
4716 if ( point != boundary->front() ) { // not the first key-point again
4717 getShapePoints( edgeID ).push_back( point );
4718 getShapePoints( vertexID++ ).push_back( point );
4724 // find in-face points
4725 list< TPoint* > & facePoints = getShapePoints( edgeID );
4726 vector< TPoint >::iterator pVecIt = myPoints.begin();
4727 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4728 TPoint* point = &(*pVecIt);
4729 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4730 pointsInElems.find( point ) != pointsInElems.end())
4731 facePoints.push_back( point );
4738 // bind points to shapes according to point parameters
4739 vector< TPoint >::iterator pVecIt = myPoints.begin();
4740 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4741 TPoint* point = &(*pVecIt);
4742 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4743 getShapePoints( shapeID ).push_back( point );
4744 // detect key-points
4745 if ( SMESH_Block::IsVertexID( shapeID ))
4746 myKeyPointIDs.push_back( i );
4750 myIsBoundaryPointsFound = true;
4751 return myIsBoundaryPointsFound;
4754 //=======================================================================
4756 //purpose : clear fields
4757 //=======================================================================
4759 void SMESH_Pattern::Clear()
4761 myIsComputed = myIsBoundaryPointsFound = false;
4764 myKeyPointIDs.clear();
4765 myElemPointIDs.clear();
4766 myShapeIDToPointsMap.clear();
4767 myShapeIDMap.Clear();
4769 myNbKeyPntInBoundary.clear();
4772 myElemXYZIDs.clear();
4773 myXYZIdToNodeMap.clear();
4775 myOrderedNodes.clear();
4776 myPolyElems.clear();
4777 myPolyElemXYZIDs.clear();
4778 myPolyhedronQuantities.clear();
4779 myIdsOnBoundary.clear();
4780 myReverseConnectivity.clear();
4783 //================================================================================
4785 * \brief set ErrorCode and return true if it is Ok
4787 //================================================================================
4789 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4791 myErrorCode = theErrorCode;
4792 return myErrorCode == ERR_OK;
4795 //=======================================================================
4796 //function : setShapeToMesh
4797 //purpose : set a shape to be meshed. Return True if meshing is possible
4798 //=======================================================================
4800 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4802 if ( !IsLoaded() ) {
4803 MESSAGE( "Pattern not loaded" );
4804 return setErrorCode( ERR_APPL_NOT_LOADED );
4807 TopAbs_ShapeEnum aType = theShape.ShapeType();
4808 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4810 MESSAGE( "Pattern dimension mismatch" );
4811 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4814 // check if a face is closed
4815 int nbNodeOnSeamEdge = 0;
4817 TopTools_MapOfShape seamVertices;
4818 TopoDS_Face face = TopoDS::Face( theShape );
4819 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4820 for ( ; eExp.More() /*&& nbNodeOnSeamEdge == 0*/; eExp.Next() ) {
4821 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4822 if ( BRep_Tool::IsClosed(ee, face) ) {
4823 // seam edge and vertices encounter twice in theFace
4824 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4825 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4830 // check nb of vertices
4831 TopTools_IndexedMapOfShape vMap;
4832 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4833 if ( vMap.Extent() + nbNodeOnSeamEdge != (int)myKeyPointIDs.size() ) {
4834 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4835 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4838 myElements.clear(); // not refine elements
4839 myElemXYZIDs.clear();
4841 myShapeIDMap.Clear();
4846 //=======================================================================
4847 //function : GetMappedPoints
4848 //purpose : Return nodes coordinates computed by Apply() method
4849 //=======================================================================
4851 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4854 if ( !myIsComputed )
4857 if ( myElements.empty() ) { // applied to shape
4858 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4859 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4860 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4862 else { // applied to mesh elements
4863 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4864 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4865 for ( ; xyz != myXYZ.end(); ++xyz )
4866 if ( !isDefined( *xyz ))
4867 thePoints.push_back( definedXYZ );
4869 thePoints.push_back( & (*xyz) );
4871 return !thePoints.empty();
4875 //=======================================================================
4876 //function : GetPoints
4877 //purpose : Return nodes coordinates of the pattern
4878 //=======================================================================
4880 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4887 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4888 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4889 thePoints.push_back( & (*pVecIt).myInitXYZ );
4891 return ( thePoints.size() > 0 );
4894 //=======================================================================
4895 //function : getShapePoints
4896 //purpose : return list of points located on theShape
4897 //=======================================================================
4899 list< SMESH_Pattern::TPoint* > &
4900 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4903 if ( !myShapeIDMap.Contains( theShape ))
4904 aShapeID = myShapeIDMap.Add( theShape );
4906 aShapeID = myShapeIDMap.FindIndex( theShape );
4908 return myShapeIDToPointsMap[ aShapeID ];
4911 //=======================================================================
4912 //function : getShapePoints
4913 //purpose : return list of points located on the shape
4914 //=======================================================================
4916 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4918 return myShapeIDToPointsMap[ theShapeID ];
4921 //=======================================================================
4922 //function : DumpPoints
4924 //=======================================================================
4926 void SMESH_Pattern::DumpPoints() const
4929 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4930 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4931 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4935 //=======================================================================
4936 //function : TPoint()
4938 //=======================================================================
4940 SMESH_Pattern::TPoint::TPoint()
4943 myInitXYZ.SetCoord(7,7,7);
4944 myInitUV.SetCoord(7.,7.);
4946 myXYZ.SetCoord(7,7,7);
4947 myUV.SetCoord(7.,7.);
4952 //=======================================================================
4953 //function : operator <<
4955 //=======================================================================
4957 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4959 gp_XYZ xyz = p.myInitXYZ;
4960 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4961 gp_XY xy = p.myInitUV;
4962 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4963 double u = p.myInitU;
4964 OS << " u( " << u << " )) " << &p << endl;
4965 xyz = p.myXYZ.XYZ();
4966 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4968 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4970 OS << " u( " << u << " ))" << endl;