1 // Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License.
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // Lesser General Public License for more details.
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 // See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
20 // File : SMESH_Pattern.hxx
21 // Created : Mon Aug 2 10:30:00 2004
22 // Author : Edward AGAPOV (eap)
24 #include "SMESH_Pattern.hxx"
26 #include <BRepTools.hxx>
27 #include <BRepTools_WireExplorer.hxx>
28 #include <BRep_Tool.hxx>
29 #include <Bnd_Box.hxx>
30 #include <Bnd_Box2d.hxx>
32 #include <Extrema_GenExtPS.hxx>
33 #include <Extrema_POnSurf.hxx>
34 #include <Geom2d_Curve.hxx>
35 #include <GeomAdaptor_Surface.hxx>
36 #include <Geom_Curve.hxx>
37 #include <Geom_Surface.hxx>
38 #include <IntAna2d_AnaIntersection.hxx>
39 #include <TopAbs_ShapeEnum.hxx>
41 #include <TopLoc_Location.hxx>
43 #include <TopoDS_Edge.hxx>
44 #include <TopoDS_Face.hxx>
45 #include <TopoDS_Iterator.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Vertex.hxx>
48 #include <TopoDS_Wire.hxx>
49 #include <TopTools_ListIteratorOfListOfShape.hxx>
51 #include <gp_Lin2d.hxx>
52 #include <gp_Pnt2d.hxx>
53 #include <gp_Trsf.hxx>
57 #include "SMDS_EdgePosition.hxx"
58 #include "SMDS_FacePosition.hxx"
59 #include "SMDS_MeshElement.hxx"
60 #include "SMDS_MeshFace.hxx"
61 #include "SMDS_MeshNode.hxx"
62 #include "SMDS_VolumeTool.hxx"
63 #include "SMESHDS_Group.hxx"
64 #include "SMESHDS_Mesh.hxx"
65 #include "SMESHDS_SubMesh.hxx"
66 #include "SMESH_Block.hxx"
67 #include "SMESH_Mesh.hxx"
68 #include "SMESH_MeshEditor.hxx"
69 #include "SMESH_subMesh.hxx"
71 #include "utilities.h"
75 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
77 //=======================================================================
78 //function : SMESH_Pattern
80 //=======================================================================
82 SMESH_Pattern::SMESH_Pattern ()
85 //=======================================================================
88 //=======================================================================
90 static inline int getInt( const char * theSring )
92 if ( *theSring < '0' || *theSring > '9' )
96 int val = strtol( theSring, &ptr, 10 );
97 if ( ptr == theSring ||
98 // there must not be neither '.' nor ',' nor 'E' ...
99 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
105 //=======================================================================
106 //function : getDouble
108 //=======================================================================
110 static inline double getDouble( const char * theSring )
113 return strtod( theSring, &ptr );
116 //=======================================================================
117 //function : readLine
118 //purpose : Put token starting positions in theFields until '\n' or '\0'
119 // Return the number of the found tokens
120 //=======================================================================
122 static int readLine (list <const char*> & theFields,
123 const char* & theLineBeg,
124 const bool theClearFields )
126 if ( theClearFields )
131 /* switch ( symbol ) { */
132 /* case white-space: */
133 /* look for a non-space symbol; */
134 /* case string-end: */
137 /* case comment beginning: */
138 /* skip all till a line-end; */
140 /* put its position in theFields, skip till a white-space;*/
146 bool stopReading = false;
149 bool isNumber = false;
150 switch ( *theLineBeg )
152 case ' ': // white space
157 case '\n': // a line ends
158 stopReading = ( nbRead > 0 );
163 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
167 case '\0': // file ends
170 case '-': // real number
175 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
177 theFields.push_back( theLineBeg );
180 while (*theLineBeg != ' ' &&
181 *theLineBeg != '\n' &&
182 *theLineBeg != '\0');
186 return 0; // incorrect file format
192 } while ( !stopReading );
197 //=======================================================================
199 //purpose : Load a pattern from <theFile>
200 //=======================================================================
202 bool SMESH_Pattern::Load (const char* theFileContents)
204 MESSAGE("Load( file ) ");
208 // ! This is a comment
209 // NB_POINTS ! 1 integer - the number of points in the pattern.
210 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
211 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
213 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
214 // ! elements description goes after all
215 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
220 const char* lineBeg = theFileContents;
221 list <const char*> fields;
222 const bool clearFields = true;
224 // NB_POINTS ! 1 integer - the number of points in the pattern.
226 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
227 MESSAGE("Error reading NB_POINTS");
228 return setErrorCode( ERR_READ_NB_POINTS );
230 int nbPoints = getInt( fields.front() );
232 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
234 // read the first point coordinates to define pattern dimention
235 int dim = readLine( fields, lineBeg, clearFields );
241 MESSAGE("Error reading points: wrong nb of coordinates");
242 return setErrorCode( ERR_READ_POINT_COORDS );
244 if ( nbPoints <= dim ) {
245 MESSAGE(" Too few points ");
246 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
249 // read the rest points
251 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
252 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
253 MESSAGE("Error reading points : wrong nb of coordinates ");
254 return setErrorCode( ERR_READ_POINT_COORDS );
256 // store point coordinates
257 myPoints.resize( nbPoints );
258 list <const char*>::iterator fIt = fields.begin();
259 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
261 TPoint & p = myPoints[ iPoint ];
262 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
264 double coord = getDouble( *fIt );
265 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
266 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
268 return setErrorCode( ERR_READ_3D_COORD );
270 p.myInitXYZ.SetCoord( iCoord, coord );
272 p.myInitUV.SetCoord( iCoord, coord );
276 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
279 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
280 MESSAGE("Error: missing key-points");
282 return setErrorCode( ERR_READ_NO_KEYPOINT );
285 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
287 int pointIndex = getInt( *fIt );
288 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
289 MESSAGE("Error: invalid point index " << pointIndex );
291 return setErrorCode( ERR_READ_BAD_INDEX );
293 if ( idSet.insert( pointIndex ).second ) // unique?
294 myKeyPointIDs.push_back( pointIndex );
298 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
300 while ( readLine( fields, lineBeg, clearFields ))
302 myElemPointIDs.push_back( TElemDef() );
303 TElemDef& elemPoints = myElemPointIDs.back();
304 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
306 int pointIndex = getInt( *fIt );
307 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
308 MESSAGE("Error: invalid point index " << pointIndex );
310 return setErrorCode( ERR_READ_BAD_INDEX );
312 elemPoints.push_back( pointIndex );
314 // check the nb of nodes in element
316 switch ( elemPoints.size() ) {
317 case 3: if ( !myIs2D ) Ok = false; break;
321 case 8: if ( myIs2D ) Ok = false; break;
325 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
327 return setErrorCode( ERR_READ_ELEM_POINTS );
330 if ( myElemPointIDs.empty() ) {
331 MESSAGE("Error: no elements");
333 return setErrorCode( ERR_READ_NO_ELEMS );
336 findBoundaryPoints(); // sort key-points
338 return setErrorCode( ERR_OK );
341 //=======================================================================
343 //purpose : Save the loaded pattern into the file <theFileName>
344 //=======================================================================
346 bool SMESH_Pattern::Save (ostream& theFile)
348 MESSAGE(" ::Save(file) " );
350 MESSAGE(" Pattern not loaded ");
351 return setErrorCode( ERR_SAVE_NOT_LOADED );
354 theFile << "!!! SALOME Mesh Pattern file" << endl;
355 theFile << "!!!" << endl;
356 theFile << "!!! Nb of points:" << endl;
357 theFile << myPoints.size() << endl;
361 // theFile.width( 8 );
362 // theFile.setf(ios::fixed);// use 123.45 floating notation
363 // theFile.setf(ios::right);
364 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
365 // theFile.setf(ios::showpoint); // do not show trailing zeros
366 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
367 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
368 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
369 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
370 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
371 theFile << " !- " << i << endl; // point id to ease reading by a human being
375 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
376 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
377 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
378 theFile << " " << *kpIt;
379 if ( !myKeyPointIDs.empty() )
383 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
384 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
385 for ( ; epIt != myElemPointIDs.end(); epIt++ )
387 const TElemDef & elemPoints = *epIt;
388 TElemDef::const_iterator iIt = elemPoints.begin();
389 for ( ; iIt != elemPoints.end(); iIt++ )
390 theFile << " " << *iIt;
396 return setErrorCode( ERR_OK );
399 //=======================================================================
400 //function : sortBySize
401 //purpose : sort theListOfList by size
402 //=======================================================================
404 template<typename T> struct TSizeCmp {
405 bool operator ()( const list < T > & l1, const list < T > & l2 )
406 const { return l1.size() < l2.size(); }
409 template<typename T> void sortBySize( list< list < T > > & theListOfList )
411 if ( theListOfList.size() > 2 ) {
412 TSizeCmp< T > SizeCmp;
413 theListOfList.sort( SizeCmp );
417 //=======================================================================
418 //function : getOrderedEdges
419 //purpose : return nb wires and a list of oredered edges
420 //=======================================================================
422 static int getOrderedEdges (const TopoDS_Face& theFace,
423 const TopoDS_Vertex& theFirstVertex,
424 list< TopoDS_Edge >& theEdges,
425 list< int > & theNbVertexInWires)
427 // put wires in a list, so that an outer wire comes first
428 list<TopoDS_Wire> aWireList;
429 TopoDS_Wire anOuterWire = BRepTools::OuterWire( theFace );
430 aWireList.push_back( anOuterWire );
431 for ( TopoDS_Iterator wIt (theFace); wIt.More(); wIt.Next() )
432 if ( !anOuterWire.IsSame( wIt.Value() ))
433 aWireList.push_back( TopoDS::Wire( wIt.Value() ));
435 // loop on edges of wires
436 theNbVertexInWires.clear();
437 list<TopoDS_Wire>::iterator wlIt = aWireList.begin();
438 for ( ; wlIt != aWireList.end(); wlIt++ )
441 BRepTools_WireExplorer wExp( *wlIt, theFace );
442 for ( iE = 0; wExp.More(); wExp.Next(), iE++ )
444 TopoDS_Edge edge = wExp.Current();
445 edge = TopoDS::Edge( edge.Oriented( wExp.Orientation() ));
446 theEdges.push_back( edge );
448 theNbVertexInWires.push_back( iE );
450 if ( wlIt == aWireList.begin() && theEdges.size() > 1 ) { // the outer wire
451 // orient closed edges
452 list< TopoDS_Edge >::iterator eIt, eIt2;
453 for ( eIt = theEdges.begin(); eIt != theEdges.end(); eIt++ )
455 TopoDS_Edge& edge = *eIt;
456 if ( TopExp::FirstVertex( edge ).IsSame( TopExp::LastVertex( edge ) ))
459 bool isNext = ( eIt2 == theEdges.begin() );
460 TopoDS_Edge edge2 = isNext ? *(++eIt2) : *(--eIt2);
462 Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( edge, theFace, f1,l1 );
463 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( edge2, theFace, f2,l2 );
464 gp_Pnt2d pf = c1->Value( edge.Orientation() == TopAbs_FORWARD ? f1 : l1 );
465 gp_Pnt2d pl = c1->Value( edge.Orientation() == TopAbs_FORWARD ? l1 : f1 );
466 bool isFirst = ( edge2.Orientation() == TopAbs_FORWARD ? isNext : !isNext );
467 gp_Pnt2d p2 = c2->Value( isFirst ? f2 : l2 );
468 isFirst = ( p2.SquareDistance( pf ) < p2.SquareDistance( pl ));
469 if ( isNext ? isFirst : !isFirst )
473 // rotate theEdges until it begins from theFirstVertex
474 if ( ! theFirstVertex.IsNull() )
475 while ( !theFirstVertex.IsSame( TopExp::FirstVertex( theEdges.front(), true )))
477 theEdges.splice(theEdges.end(), theEdges,
478 theEdges.begin(), ++ theEdges.begin());
479 if ( iE++ > theNbVertexInWires.back() )
480 break; // break infinite loop
485 return aWireList.size();
488 //=======================================================================
491 //=======================================================================
493 static gp_XY project (const SMDS_MeshNode* theNode,
494 Extrema_GenExtPS & theProjectorPS)
496 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
497 theProjectorPS.Perform( P );
498 if ( !theProjectorPS.IsDone() ) {
499 MESSAGE( "SMESH_Pattern: point projection FAILED");
502 double u, v, minVal = DBL_MAX;
503 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
504 if ( theProjectorPS.Value( i ) < minVal ) {
505 minVal = theProjectorPS.Value( i );
506 theProjectorPS.Point( i ).Parameter( u, v );
508 return gp_XY( u, v );
511 //=======================================================================
512 //function : areNodesBound
513 //purpose : true if all nodes of faces are bound to shapes
514 //=======================================================================
516 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
518 while ( faceItr->more() )
520 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
521 while ( nIt->more() )
523 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nIt->next() );
524 SMDS_PositionPtr pos = node->GetPosition();
525 if ( !pos || !pos->GetShapeId() ) {
533 //=======================================================================
534 //function : isMeshBoundToShape
535 //purpose : return true if all 2d elements are bound to shape
536 // if aFaceSubmesh != NULL, then check faces bound to it
537 // else check all faces in aMeshDS
538 //=======================================================================
540 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
541 SMESHDS_SubMesh * aFaceSubmesh,
542 const bool isMainShape)
545 // check that all faces are bound to aFaceSubmesh
546 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
550 // check face nodes binding
551 if ( aFaceSubmesh ) {
552 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
553 return areNodesBound( fIt );
555 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
556 return areNodesBound( fIt );
559 //=======================================================================
561 //purpose : Create a pattern from the mesh built on <theFace>.
562 // <theProject>==true makes override nodes positions
563 // on <theFace> computed by mesher
564 //=======================================================================
566 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
567 const TopoDS_Face& theFace,
570 MESSAGE(" ::Load(face) " );
574 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
575 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
577 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
578 int 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 that face is not closed
589 list<TopoDS_Edge> eList;
590 getOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
591 list<TopoDS_Edge>::iterator elIt = eList.begin();
592 for ( ; elIt != eList.end() ; elIt++ )
593 if ( BRep_Tool::IsClosed( *elIt , face ))
594 return setErrorCode( ERR_LOADF_CLOSED_FACE );
596 // check that requested or needed projection is possible
597 bool isMainShape = theMesh->IsMainShape( face );
598 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
599 bool canProject = ( nbElems ? true : isMainShape );
601 if ( ( theProject || needProject ) && !canProject )
602 return setErrorCode( ERR_LOADF_CANT_PROJECT );
604 Extrema_GenExtPS projector;
605 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
606 if ( theProject || needProject )
607 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
610 TNodePointIDMap nodePointIDMap;
614 MESSAGE("Project the submesh");
615 // ---------------------------------------------------------------
616 // The case where the submesh is projected to theFace
617 // ---------------------------------------------------------------
620 list< const SMDS_MeshElement* > faces;
622 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
623 while ( fIt->more() ) {
624 const SMDS_MeshElement* f = fIt->next();
625 if ( f && f->GetType() == SMDSAbs_Face )
626 faces.push_back( f );
630 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
631 while ( fIt->more() )
632 faces.push_back( fIt->next() );
635 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
636 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
637 for ( ; fIt != faces.end(); ++fIt )
639 myElemPointIDs.push_back( TElemDef() );
640 TElemDef& elemPoints = myElemPointIDs.back();
641 SMDS_ElemIteratorPtr nIt = (*fIt)->nodesIterator();
642 while ( nIt->more() )
644 const SMDS_MeshElement* node = nIt->next();
645 TNodePointIDMap::iterator nIdIt = nodePointIDMap.find( node );
646 if ( nIdIt == nodePointIDMap.end() )
648 elemPoints.push_back( iPoint );
649 nodePointIDMap.insert( make_pair( node, iPoint++ ));
652 elemPoints.push_back( (*nIdIt).second );
655 myPoints.resize( iPoint );
657 // project all nodes of 2d elements to theFace
658 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
659 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
661 const SMDS_MeshNode* node =
662 static_cast<const SMDS_MeshNode*>( (*nIdIt).first );
663 TPoint * p = & myPoints[ (*nIdIt).second ];
664 p->myInitUV = project( node, projector );
665 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
667 // find key-points: the points most close to UV of vertices
668 TopExp_Explorer vExp( face, TopAbs_VERTEX );
669 set<int> foundIndices;
670 for ( ; vExp.More(); vExp.Next() ) {
671 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
672 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
673 double minDist = DBL_MAX;
675 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
676 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
677 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
678 if ( dist < minDist ) {
683 if ( foundIndices.insert( index ).second ) // unique?
684 myKeyPointIDs.push_back( index );
686 myIsBoundaryPointsFound = false;
691 // ---------------------------------------------------------------------
692 // The case where a pattern is being made from the mesh built by mesher
693 // ---------------------------------------------------------------------
695 // Load shapes in the consequent order and count nb of points
698 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
699 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
700 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt );
702 nbNodes += eSubMesh->NbNodes() + 1;
705 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
706 myShapeIDMap.Add( *elIt );
708 myShapeIDMap.Add( face );
710 myPoints.resize( nbNodes );
712 // Load U of points on edges
714 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
716 TopoDS_Edge & edge = *elIt;
717 list< TPoint* > & ePoints = getShapePoints( edge );
719 Handle(Geom2d_Curve) C2d;
721 C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
722 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
724 // the forward key-point
725 TopoDS_Shape v = TopExp::FirstVertex( edge, true );
726 list< TPoint* > & vPoint = getShapePoints( v );
727 if ( vPoint.empty() )
729 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v );
730 if ( vSubMesh && vSubMesh->NbNodes() ) {
731 myKeyPointIDs.push_back( iPoint );
732 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
733 const SMDS_MeshNode* node = nIt->next();
734 nodePointIDMap.insert( make_pair( node, iPoint ));
736 TPoint* keyPoint = &myPoints[ iPoint++ ];
737 vPoint.push_back( keyPoint );
739 keyPoint->myInitUV = project( node, projector );
741 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
742 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
745 if ( !vPoint.empty() )
746 ePoints.push_back( vPoint.front() );
749 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
750 if ( eSubMesh && eSubMesh->NbNodes() )
752 // loop on nodes of an edge: sort them by param on edge
753 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
754 TParamNodeMap paramNodeMap;
755 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
756 while ( nIt->more() )
758 const SMDS_MeshNode* node =
759 static_cast<const SMDS_MeshNode*>( nIt->next() );
760 const SMDS_EdgePosition* epos =
761 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
762 double u = epos->GetUParameter();
763 paramNodeMap.insert( TParamNodeMap::value_type( u, node ));
765 // put U in [0,1] so that the first key-point has U==0
767 TParamNodeMap::iterator unIt = paramNodeMap.begin();
768 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
769 while ( unIt != paramNodeMap.end() )
771 TPoint* p = & myPoints[ iPoint ];
772 ePoints.push_back( p );
773 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
774 nodePointIDMap.insert ( make_pair( node, iPoint ));
777 p->myInitUV = project( node, projector );
779 double u = isForward ? (*unIt).first : (*unRIt).first;
780 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
781 p->myInitUV = C2d->Value( u ).XY();
783 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
788 // the reverse key-point
789 v = TopExp::LastVertex( edge, true ).Reversed();
790 list< TPoint* > & vPoint2 = getShapePoints( v );
791 if ( vPoint2.empty() )
793 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v );
794 if ( vSubMesh && vSubMesh->NbNodes() ) {
795 myKeyPointIDs.push_back( iPoint );
796 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
797 const SMDS_MeshNode* node = nIt->next();
798 nodePointIDMap.insert( make_pair( node, iPoint ));
800 TPoint* keyPoint = &myPoints[ iPoint++ ];
801 vPoint2.push_back( keyPoint );
803 keyPoint->myInitUV = project( node, projector );
805 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
806 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
809 if ( !vPoint2.empty() )
810 ePoints.push_back( vPoint2.front() );
812 // compute U of edge-points
815 double totalDist = 0;
816 list< TPoint* >::iterator pIt = ePoints.begin();
817 TPoint* prevP = *pIt;
818 prevP->myInitU = totalDist;
819 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
821 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
822 p->myInitU = totalDist;
825 if ( totalDist > DBL_MIN)
826 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
828 p->myInitU /= totalDist;
831 } // loop on edges of a wire
833 // Load in-face points and elements
835 if ( fSubMesh && fSubMesh->NbElements() )
837 list< TPoint* > & fPoints = getShapePoints( face );
838 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
839 while ( nIt->more() )
841 const SMDS_MeshNode* node =
842 static_cast<const SMDS_MeshNode*>( nIt->next() );
843 nodePointIDMap.insert( make_pair( node, iPoint ));
844 TPoint* p = &myPoints[ iPoint++ ];
845 fPoints.push_back( p );
847 p->myInitUV = project( node, projector );
849 const SMDS_FacePosition* pos =
850 static_cast<const SMDS_FacePosition*>(node->GetPosition().get());
851 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
853 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
856 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
857 while ( elemIt->more() ) {
858 SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
859 myElemPointIDs.push_back( TElemDef() );
860 TElemDef& elemPoints = myElemPointIDs.back();
861 while ( nIt->more() )
862 elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
866 myIsBoundaryPointsFound = true;
869 // Assure that U range is proportional to V range
872 vector< TPoint >::iterator pVecIt = myPoints.begin();
873 for ( ; pVecIt != myPoints.end(); pVecIt++ )
874 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
875 double minU, minV, maxU, maxV;
876 bndBox.Get( minU, minV, maxU, maxV );
877 double dU = maxU - minU, dV = maxV - minV;
878 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
881 // define where is the problem, in the face or in the mesh
882 TopExp_Explorer vExp( face, TopAbs_VERTEX );
883 for ( ; vExp.More(); vExp.Next() ) {
884 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
887 bndBox.Get( minU, minV, maxU, maxV );
888 dU = maxU - minU, dV = maxV - minV;
889 if ( dU <= DBL_MIN || dV <= DBL_MIN )
891 return setErrorCode( ERR_LOADF_NARROW_FACE );
893 // mesh is projected onto a line, e.g.
894 return setErrorCode( ERR_LOADF_CANT_PROJECT );
896 double ratio = dU / dV, maxratio = 3, scale;
898 if ( ratio > maxratio ) {
899 scale = ratio / maxratio;
902 else if ( ratio < 1./maxratio ) {
903 scale = maxratio / ratio;
908 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
909 TPoint & p = *pVecIt;
910 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
911 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
914 if ( myElemPointIDs.empty() ) {
915 MESSAGE( "No elements bound to the face");
916 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
919 return setErrorCode( ERR_OK );
922 //=======================================================================
923 //function : computeUVOnEdge
924 //purpose : compute coordinates of points on theEdge
925 //=======================================================================
927 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
928 const list< TPoint* > & ePoints )
930 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
932 Handle(Geom2d_Curve) C2d =
933 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
935 ePoints.back()->myInitU = 1.0;
936 list< TPoint* >::const_iterator pIt = ePoints.begin();
937 for ( pIt++; pIt != ePoints.end(); pIt++ )
939 TPoint* point = *pIt;
941 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
942 point->myU = ( f * ( 1 - du ) + l * du );
944 point->myUV = C2d->Value( point->myU ).XY();
948 //=======================================================================
949 //function : intersectIsolines
951 //=======================================================================
953 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
954 const gp_XY& uv21, const gp_XY& uv22, const double r2,
958 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
959 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
960 resUV = 0.5 * ( loc1 + loc2 );
961 isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
962 // double len1 = ( uv11 - uv12 ).Modulus();
963 // double len2 = ( uv21 - uv22 ).Modulus();
964 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
968 // gp_Lin2d line1( uv11, uv12 - uv11 );
969 // gp_Lin2d line2( uv21, uv22 - uv21 );
970 // double angle = Abs( line1.Angle( line2 ) );
972 // IntAna2d_AnaIntersection inter;
973 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
974 // if ( inter.IsDone() && inter.NbPoints() == 1 )
976 // gp_Pnt2d interUV = inter.Point(1).Value();
977 // resUV += interUV.XY();
978 // inter.Perform( line1, line2 );
979 // interUV = inter.Point(1).Value();
980 // resUV += interUV.XY();
987 //=======================================================================
988 //function : compUVByIsoIntersection
990 //=======================================================================
992 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
993 const gp_XY& theInitUV,
995 bool & theIsDeformed )
997 // compute UV by intersection of 2 iso lines
998 //gp_Lin2d isoLine[2];
999 gp_XY uv1[2], uv2[2];
1001 const double zero = DBL_MIN;
1002 for ( int iIso = 0; iIso < 2; iIso++ )
1004 // to build an iso line:
1005 // find 2 pairs of consequent edge-points such that the range of their
1006 // initial parameters encloses the in-face point initial parameter
1007 gp_XY UV[2], initUV[2];
1008 int nbUV = 0, iCoord = iIso + 1;
1009 double initParam = theInitUV.Coord( iCoord );
1011 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1012 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1014 const list< TPoint* > & bndPoints = * bndIt;
1015 TPoint* prevP = bndPoints.back(); // this is the first point
1016 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1017 bool coincPrev = false;
1018 // loop on the edge-points
1019 for ( ; pIt != bndPoints.end(); pIt++ )
1021 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1022 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1023 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1024 if (!coincPrev && // ignore if initParam coincides with prev point param
1025 sumOfDiff > zero && // ignore if both points coincide with initParam
1026 prevParamDiff * paramDiff <= zero )
1028 // find UV in parametric space of theFace
1029 double r = Abs(prevParamDiff) / sumOfDiff;
1030 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1033 // throw away uv most distant from <theInitUV>
1034 gp_XY vec0 = initUV[0] - theInitUV;
1035 gp_XY vec1 = initUV[1] - theInitUV;
1036 gp_XY vec = uvInit - theInitUV;
1037 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1038 double dist0 = vec0.SquareModulus();
1039 double dist1 = vec1.SquareModulus();
1040 double dist = vec .SquareModulus();
1041 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1042 i = ( dist0 < dist1 ? 1 : 0 );
1043 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1044 i = 3; // theInitUV must remain between
1048 initUV[ i ] = uvInit;
1049 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1051 coincPrev = ( Abs(paramDiff) <= zero );
1058 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1059 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1060 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1061 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1063 // an iso line should be normal to UV[0] - UV[1] direction
1064 // and be located at the same relative distance as from initial ends
1065 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1067 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1068 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1069 //isoLine[ iIso ] = iso.Normal( isoLoc );
1070 uv1[ iIso ] = UV[0];
1071 uv2[ iIso ] = UV[1];
1074 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1075 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1076 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1077 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1084 // ==========================================================
1085 // structure representing a node of a grid of iso-poly-lines
1086 // ==========================================================
1093 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1094 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1095 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1096 TIsoNode(double initU, double initV):
1097 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1098 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1099 bool IsUVComputed() const
1100 { return myUV.X() != 1e100; }
1101 bool IsMovable() const
1102 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1103 void SetNotMovable()
1104 { myIsMovable = false; }
1105 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1106 { myBndNodes[ iDir + i * 2 ] = node; }
1107 TIsoNode* GetBoundaryNode(int iDir, int i)
1108 { return myBndNodes[ iDir + i * 2 ]; }
1109 void SetNext(TIsoNode* node, int iDir, int isForward)
1110 { myNext[ iDir + isForward * 2 ] = node; }
1111 TIsoNode* GetNext(int iDir, int isForward)
1112 { return myNext[ iDir + isForward * 2 ]; }
1115 //=======================================================================
1116 //function : getNextNode
1118 //=======================================================================
1120 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1122 TIsoNode* n = node->myNext[ dir ];
1123 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1124 n = 0;//node->myBndNodes[ dir ];
1125 // MESSAGE("getNextNode: use bnd for node "<<
1126 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1130 //=======================================================================
1131 //function : checkQuads
1132 //purpose : check if newUV destortes quadrangles around node,
1133 // and if ( crit == FIX_OLD ) fix newUV in this case
1134 //=======================================================================
1136 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1138 static bool checkQuads (const TIsoNode* node,
1140 const bool reversed,
1141 const int crit = FIX_OLD,
1142 double fixSize = 0.)
1144 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1145 int nbOldFix = 0, nbOldImpr = 0;
1146 double newBadRate = 0, oldBadRate = 0;
1147 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1148 int i, dir1 = 0, dir2 = 3;
1149 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1151 if ( dir2 > 3 ) dir2 = 0;
1153 // walking counterclockwise around a quad,
1154 // nodes are in the order: node, n[0], n[1], n[2]
1155 n[0] = getNextNode( node, dir1 );
1156 n[2] = getNextNode( node, dir2 );
1157 if ( !n[0] || !n[2] ) continue;
1158 n[1] = getNextNode( n[0], dir2 );
1159 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1160 bool isTriangle = ( !n[1] );
1162 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1164 // if ( fixSize != 0 ) {
1165 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1166 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1167 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1168 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1170 // check if a quadrangle is degenerated
1172 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1173 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1176 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1179 // find min size of the diagonal node-n[1]
1180 double minDiag = fixSize;
1181 if ( minDiag == 0. ) {
1182 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1183 if ( !isTriangle ) {
1184 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1185 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1187 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1188 minDiag = sqrt( maxLen2 ) * PI / 60.; // ~ maxLen * Sin( 3 deg )
1191 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1192 // ( behind means "to the right of")
1194 // 1. newUV is not behind 01 and 12 dirs
1195 // 2. or newUV is not behind 02 dir and n[2] is convex
1196 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1197 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1198 gp_Vec2d moveVec[3], outVec[3];
1199 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1201 bool isDiag = ( i == 2 );
1202 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1206 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1208 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1210 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1212 gp_Vec2d newDir( n[i]->myUV, newUV );
1213 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1215 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1216 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1217 if ( crit == FIX_OLD ) {
1218 wasIn[i] = ( outDir * oldDir < 0 );
1219 wasOk[i] = ( outDir * oldDir < -minDiag );
1221 newBadRate += outDir * newDir;
1223 oldBadRate += outDir * oldDir;
1226 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1227 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1228 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1229 moveVec[i] = ( oldDist - minDiag ) * outDir;
1234 // check if n[2] is convex
1237 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1239 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1240 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1241 newIsOk = ( newIsOk && isNewOk );
1242 newIsIn = ( newIsIn && isNewIn );
1244 if ( crit != FIX_OLD ) {
1245 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1246 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1250 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1251 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1252 oldIsIn = ( oldIsIn && isOldIn );
1253 oldIsOk = ( oldIsOk && isOldIn );
1256 if ( !isOldIn ) { // node is outside a quadrangle
1257 // move newUV inside a quadrangle
1258 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1259 // node and newUV are outside: push newUV inside
1261 if ( convex || isTriangle ) {
1262 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1265 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1266 double outSize = out.Magnitude();
1267 if ( outSize > DBL_MIN )
1270 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1271 uv = n[1]->myUV - minDiag * out.XY();
1273 oldUVFixed[ nbOldFix++ ] = uv;
1274 //node->myUV = newUV;
1276 else if ( !isOldOk ) {
1277 // try to fix old UV: move node inside as less as possible
1278 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1279 gp_XY uv1, uv2 = node->myUV;
1280 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1282 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1283 while ( !isOldOk ) {
1284 // find the least moveVec
1286 double minMove2 = 1e100;
1287 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1289 if ( moveVec[i].Coord(1) < 1e100 ) {
1290 double move2 = moveVec[i].SquareMagnitude();
1291 if ( move2 < minMove2 ) {
1300 // move node to newUV
1301 uv1 = node->myUV + moveVec[ iMin ].XY();
1302 uv2 += moveVec[ iMin ].XY();
1303 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1304 // check if uv1 is ok
1305 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1306 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1307 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1309 oldUVImpr[ nbOldImpr++ ] = uv1;
1311 // check if uv2 is ok
1312 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1313 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1314 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1316 oldUVImpr[ nbOldImpr++ ] = uv2;
1321 } // loop on 4 quadrangles around <node>
1323 if ( crit == CHECK_NEW_OK )
1325 if ( crit == CHECK_NEW_IN )
1334 if ( oldIsIn && nbOldImpr ) {
1335 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1336 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1337 gp_XY uv = oldUVImpr[ 0 ];
1338 for ( int i = 1; i < nbOldImpr; i++ )
1339 uv += oldUVImpr[ i ];
1341 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1346 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1349 if ( !oldIsIn && nbOldFix ) {
1350 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1351 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1352 gp_XY uv = oldUVFixed[ 0 ];
1353 for ( int i = 1; i < nbOldFix; i++ )
1354 uv += oldUVFixed[ i ];
1356 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1361 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1364 if ( newIsIn && oldIsIn )
1365 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1366 else if ( !newIsIn )
1373 //=======================================================================
1374 //function : compUVByElasticIsolines
1375 //purpose : compute UV as nodes of iso-poly-lines consisting of
1376 // segments keeping relative size as in the pattern
1377 //=======================================================================
1378 //#define DEB_COMPUVBYELASTICISOLINES
1379 bool SMESH_Pattern::
1380 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1381 const list< TPoint* >& thePntToCompute)
1383 //cout << "============================== KEY POINTS =============================="<<endl;
1384 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1385 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1386 // TPoint& p = myPoints[ *kpIt ];
1387 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1388 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1390 //cout << "=============================="<<endl;
1392 // Define parameters of iso-grid nodes in U and V dir
1394 set< double > paramSet[ 2 ];
1395 list< list< TPoint* > >::const_iterator pListIt;
1396 list< TPoint* >::const_iterator pIt;
1397 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1398 const list< TPoint* > & pList = * pListIt;
1399 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1400 paramSet[0].insert( (*pIt)->myInitUV.X() );
1401 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1404 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1405 paramSet[0].insert( (*pIt)->myInitUV.X() );
1406 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1408 // unite close parameters and split too long segments
1411 for ( iDir = 0; iDir < 2; iDir++ )
1413 set< double > & params = paramSet[ iDir ];
1414 double range = ( *params.rbegin() - *params.begin() );
1415 double toler = range / 1e6;
1416 tol[ iDir ] = toler;
1417 // double maxSegment = range / params.size() / 2.;
1419 // set< double >::iterator parIt = params.begin();
1420 // double prevPar = *parIt;
1421 // for ( parIt++; parIt != params.end(); parIt++ )
1423 // double segLen = (*parIt) - prevPar;
1424 // if ( segLen < toler )
1425 // ;//params.erase( prevPar ); // unite
1426 // else if ( segLen > maxSegment )
1427 // params.insert( prevPar + 0.5 * segLen ); // split
1428 // prevPar = (*parIt);
1432 // Make nodes of a grid of iso-poly-lines
1434 list < TIsoNode > nodes;
1435 typedef list < TIsoNode *> TIsoLine;
1436 map < double, TIsoLine > isoMap[ 2 ];
1438 set< double > & params0 = paramSet[ 0 ];
1439 set< double >::iterator par0It = params0.begin();
1440 for ( ; par0It != params0.end(); par0It++ )
1442 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1443 set< double > & params1 = paramSet[ 1 ];
1444 set< double >::iterator par1It = params1.begin();
1445 for ( ; par1It != params1.end(); par1It++ )
1447 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1448 isoLine0.push_back( & nodes.back() );
1449 isoMap[1][ *par1It ].push_back( & nodes.back() );
1453 // Compute intersections of boundaries with iso-lines:
1454 // only boundary nodes will have computed UV so far
1457 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1458 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1459 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1461 const list< TPoint* > & bndPoints = * bndIt;
1462 TPoint* prevP = bndPoints.back(); // this is the first point
1463 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1464 // loop on the edge-points
1465 for ( ; pIt != bndPoints.end(); pIt++ )
1467 TPoint* point = *pIt;
1468 for ( iDir = 0; iDir < 2; iDir++ )
1470 const int iCoord = iDir + 1;
1471 const int iOtherCoord = 2 - iDir;
1472 double par1 = prevP->myInitUV.Coord( iCoord );
1473 double par2 = point->myInitUV.Coord( iCoord );
1474 double parDif = par2 - par1;
1475 if ( Abs( parDif ) <= DBL_MIN )
1477 // find iso-lines intersecting a bounadry
1478 double toler = tol[ 1 - iDir ];
1479 double minPar = Min ( par1, par2 );
1480 double maxPar = Max ( par1, par2 );
1481 map < double, TIsoLine >& isos = isoMap[ iDir ];
1482 map < double, TIsoLine >::iterator isoIt = isos.begin();
1483 for ( ; isoIt != isos.end(); isoIt++ )
1485 double isoParam = (*isoIt).first;
1486 if ( isoParam < minPar || isoParam > maxPar )
1488 double r = ( isoParam - par1 ) / parDif;
1489 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1490 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1491 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1492 // find existing node with otherPar or insert a new one
1493 TIsoLine & isoLine = (*isoIt).second;
1495 TIsoLine::iterator nIt = isoLine.begin();
1496 for ( ; nIt != isoLine.end(); nIt++ ) {
1497 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1498 if ( nodePar >= otherPar )
1502 if ( Abs( nodePar - otherPar ) <= toler )
1503 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1505 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1506 node = & nodes.back();
1507 isoLine.insert( nIt, node );
1509 node->SetNotMovable();
1511 uvBnd.Add( gp_Pnt2d( uv ));
1512 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1514 gp_XY tgt( point->myUV - prevP->myUV );
1515 if ( ::IsEqual( r, 1. ))
1516 node->myDir[ 0 ] = tgt;
1517 else if ( ::IsEqual( r, 0. ))
1518 node->myDir[ 1 ] = tgt;
1520 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1521 // keep boundary nodes corresponding to boundary points
1522 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1523 if ( bndNodes.empty() || bndNodes.back() != node )
1524 bndNodes.push_back( node );
1525 } // loop on isolines
1526 } // loop on 2 directions
1528 } // loop on boundary points
1529 } // loop on boundaries
1531 // Define orientation
1533 // find the point with the least X
1534 double leastX = DBL_MAX;
1535 TIsoNode * leftNode;
1536 list < TIsoNode >::iterator nodeIt = nodes.begin();
1537 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1538 TIsoNode & node = *nodeIt;
1539 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1540 leastX = node.myUV.X();
1543 // if ( node.IsUVComputed() ) {
1544 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1545 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1546 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1547 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1550 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1551 //SCRUTE( reversed );
1553 // Prepare internal nodes:
1555 // 2. compute ratios
1556 // 3. find boundary nodes for each node
1557 // 4. remove nodes out of the boundary
1558 for ( iDir = 0; iDir < 2; iDir++ )
1560 const int iCoord = 2 - iDir; // coord changing along an isoline
1561 map < double, TIsoLine >& isos = isoMap[ iDir ];
1562 map < double, TIsoLine >::iterator isoIt = isos.begin();
1563 for ( ; isoIt != isos.end(); isoIt++ )
1565 TIsoLine & isoLine = (*isoIt).second;
1566 bool firstCompNodeFound = false;
1567 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1568 nPrevIt = nIt = nNextIt = isoLine.begin();
1570 nNextIt++; nNextIt++;
1571 while ( nIt != isoLine.end() )
1573 // 1. connect prev - cur
1574 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1575 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1576 firstCompNodeFound = true;
1577 lastCompNodePos = nPrevIt;
1579 if ( firstCompNodeFound ) {
1580 node->SetNext( prevNode, iDir, 0 );
1581 prevNode->SetNext( node, iDir, 1 );
1584 if ( nNextIt != isoLine.end() ) {
1585 double par1 = prevNode->myInitUV.Coord( iCoord );
1586 double par2 = node->myInitUV.Coord( iCoord );
1587 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1588 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1590 // 3. find boundary nodes
1591 if ( node->IsUVComputed() )
1592 lastCompNodePos = nIt;
1593 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1594 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1595 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1596 if ( (*nIt2)->IsUVComputed() )
1598 if ( nIt2 != isoLine.end() ) {
1600 node->SetBoundaryNode( bndNode1, iDir, 0 );
1601 node->SetBoundaryNode( bndNode2, iDir, 1 );
1602 // cout << "--------------------------------------------------"<<endl;
1603 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1604 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1605 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1606 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1607 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1608 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1612 if ( nNextIt != isoLine.end() ) nNextIt++;
1613 // 4. remove nodes out of the boundary
1614 if ( !firstCompNodeFound )
1615 isoLine.pop_front();
1616 } // loop on isoLine nodes
1618 // remove nodes after the boundary
1619 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1620 // (*nIt)->SetNotMovable();
1621 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1622 } // loop on isolines
1623 } // loop on 2 directions
1625 // Compute local isoline direction for internal nodes
1628 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1629 map < double, TIsoLine >::iterator isoIt = isos.begin();
1630 for ( ; isoIt != isos.end(); isoIt++ )
1632 TIsoLine & isoLine = (*isoIt).second;
1633 TIsoLine::iterator nIt = isoLine.begin();
1634 for ( ; nIt != isoLine.end(); nIt++ )
1636 TIsoNode* node = *nIt;
1637 if ( node->IsUVComputed() || !node->IsMovable() )
1639 gp_Vec2d aTgt[2], aNorm[2];
1642 for ( iDir = 0; iDir < 2; iDir++ )
1644 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1645 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1646 if ( !bndNode1 || !bndNode2 ) {
1650 const int iCoord = 2 - iDir; // coord changing along an isoline
1651 double par1 = bndNode1->myInitUV.Coord( iCoord );
1652 double par2 = node->myInitUV.Coord( iCoord );
1653 double par3 = bndNode2->myInitUV.Coord( iCoord );
1654 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1656 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1657 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1658 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1659 else tgt1.Reverse();
1660 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1662 if ( ratio[ iDir ] < 0.5 )
1663 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1665 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1667 aNorm[ iDir ].Reverse(); // along iDir isoline
1669 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1670 // maybe angle is more than |PI|
1671 if ( Abs( angle ) > PI / 2. ) {
1672 // check direction of the last but one perpendicular isoline
1673 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1674 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1675 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1676 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1677 if ( isoDir * tgt2 < 0 )
1679 double angle2 = tgt1.Angle( isoDir );
1680 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1681 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1682 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1683 //MESSAGE("REVERSE ANGLE");
1686 if ( Abs( angle2 ) > Abs( angle ) ||
1687 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1688 //MESSAGE("Add PI");
1689 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1690 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1691 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1692 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1693 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1694 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1697 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1701 for ( iDir = 0; iDir < 2; iDir++ )
1703 aTgt[iDir].Normalize();
1704 aNorm[1-iDir].Normalize();
1705 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1708 node->myDir[iDir] = //aTgt[iDir];
1709 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1711 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1712 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1713 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1714 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1716 } // loop on iso nodes
1717 } // loop on isolines
1719 // Find nodes to start computing UV from
1721 list< TIsoNode* > startNodes;
1722 list< TIsoNode* >::iterator nIt = bndNodes.end();
1723 TIsoNode* node = *(--nIt);
1724 TIsoNode* prevNode = *(--nIt);
1725 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1727 TIsoNode* nextNode = *nIt;
1728 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1729 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1730 double initAngle = initTgt1.Angle( initTgt2 );
1731 double angle = node->myDir[0].Angle( node->myDir[1] );
1732 if ( reversed ) angle = -angle;
1733 if ( initAngle > angle && initAngle - angle > PI / 2.1 ) {
1734 // find a close internal node
1735 TIsoNode* nClose = 0;
1736 list< TIsoNode* > testNodes;
1737 testNodes.push_back( node );
1738 list< TIsoNode* >::iterator it = testNodes.begin();
1739 for ( ; !nClose && it != testNodes.end(); it++ )
1741 for (int i = 0; i < 4; i++ )
1743 nClose = (*it)->myNext[ i ];
1745 if ( !nClose->IsUVComputed() )
1748 testNodes.push_back( nClose );
1754 startNodes.push_back( nClose );
1755 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1756 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1757 // "initAngle: " << initAngle << " angle: " << angle << endl;
1758 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1759 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1760 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1761 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1767 // Compute starting UV of internal nodes
1769 list < TIsoNode* > internNodes;
1770 bool needIteration = true;
1771 if ( startNodes.empty() ) {
1772 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1773 needIteration = false;
1774 map < double, TIsoLine >& isos = isoMap[ 0 ];
1775 map < double, TIsoLine >::iterator isoIt = isos.begin();
1776 for ( ; isoIt != isos.end(); isoIt++ )
1778 TIsoLine & isoLine = (*isoIt).second;
1779 TIsoLine::iterator nIt = isoLine.begin();
1780 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1782 TIsoNode* node = *nIt;
1783 if ( !node->IsUVComputed() && node->IsMovable() ) {
1784 internNodes.push_back( node );
1786 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1787 node->myUV, needIteration ))
1788 node->myUV = node->myInitUV;
1792 if ( needIteration )
1793 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1795 TIsoNode* node = *nIt, *nClose = 0;
1796 list< TIsoNode* > testNodes;
1797 testNodes.push_back( node );
1798 list< TIsoNode* >::iterator it = testNodes.begin();
1799 for ( ; !nClose && it != testNodes.end(); it++ )
1801 for (int i = 0; i < 4; i++ )
1803 nClose = (*it)->myNext[ i ];
1805 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1808 testNodes.push_back( nClose );
1814 startNodes.push_back( nClose );
1818 double aMin[2], aMax[2], step[2];
1819 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1820 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1821 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1822 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1823 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1825 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1827 TIsoNode* prevN[2], *node = *nIt;
1828 if ( node->IsUVComputed() || !node->IsMovable() )
1830 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1831 int nbComp = 0, nbPrev = 0;
1832 for ( iDir = 0; iDir < 2; iDir++ )
1834 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1835 TIsoNode* n = node->GetNext( iDir, 0 );
1836 if ( n->IsUVComputed() )
1839 startNodes.push_back( n );
1840 n = node->GetNext( iDir, 1 );
1841 if ( n->IsUVComputed() )
1844 startNodes.push_back( n );
1846 prevNode1 = prevNode2;
1849 if ( prevNode1 ) nbPrev++;
1850 if ( prevNode2 ) nbPrev++;
1853 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1854 double par = node->myInitUV.Coord( 2 - iDir );
1855 bool isEnd = ( prevPar > par );
1856 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1857 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1858 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1859 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1860 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1861 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1862 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1863 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1864 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1865 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1866 //" par: " << prevPar << endl;
1867 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1868 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1870 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1871 gp_XY & uv1 = prevNode1->myUV;
1872 gp_XY & uv2 = prevNode2->myUV;
1873 // dir = ( uv2 - uv1 );
1874 // double len = dir.Modulus();
1875 // if ( len > DBL_MIN )
1876 // dir /= len * 0.5;
1877 double r = node->myRatio[ iDir ];
1878 newUV += uv1 * ( 1 - r ) + uv2 * r;
1881 newUV += prevNode1->myUV + dir * step[ iDir ];
1884 prevN[ iDir ] = prevNode1;
1890 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1892 // check if a quadrangle is not distorted
1894 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1895 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1896 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1897 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1901 internNodes.push_back( node );
1906 static int maxNbIter = 100;
1907 #ifdef DEB_COMPUVBYELASTICISOLINES
1909 bool useNbMoveNode = 0;
1910 static int maxNbNodeMove = 100;
1913 if ( !useNbMoveNode )
1914 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1919 if ( !needIteration) break;
1920 #ifdef DEB_COMPUVBYELASTICISOLINES
1921 if ( nbIter >= maxNbIter ) break;
1924 list < TIsoNode* >::iterator nIt = internNodes.begin();
1925 for ( ; nIt != internNodes.end(); nIt++ ) {
1926 #ifdef DEB_COMPUVBYELASTICISOLINES
1928 cout << nbNodeMove <<" =================================================="<<endl;
1930 TIsoNode * node = *nIt;
1934 for ( iDir = 0; iDir < 2; iDir++ )
1936 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
1937 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
1938 double r = node->myRatio[ iDir ];
1939 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
1940 // line[ iDir ].SetLocation( loc[ iDir ] );
1941 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
1944 double locR[2] = { 0, 0 };
1945 for ( iDir = 0; iDir < 2; iDir++ )
1947 const int iCoord = 2 - iDir; // coord changing along an isoline
1948 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1949 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1950 double par1 = bndNode1->myInitUV.Coord( iCoord );
1951 double par2 = node->myInitUV.Coord( iCoord );
1952 double par3 = bndNode2->myInitUV.Coord( iCoord );
1953 double r = ( par2 - par1 ) / ( par3 - par1 );
1954 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
1955 locR[ iDir ] = ( 1 - r * r ) * 0.25;
1957 //locR[0] = locR[1] = 0.25;
1958 // intersect the 2 lines and move a node
1959 //IntAna2d_AnaIntersection inter( line[0], line[1] );
1960 if ( /*inter.IsDone() && inter.NbPoints() ==*/ 1 )
1962 // double intR = 1 - locR[0] - locR[1];
1963 // gp_XY newUV = inter.Point(1).Value().XY();
1964 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
1965 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
1967 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
1968 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
1969 // avoid parallel isolines intersection
1970 checkQuads( node, newUV, reversed );
1972 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
1974 } // intersection found
1975 #ifdef DEB_COMPUVBYELASTICISOLINES
1976 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
1978 } // loop on internal nodes
1979 #ifdef DEB_COMPUVBYELASTICISOLINES
1980 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
1982 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
1984 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
1986 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
1987 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
1988 #ifndef DEB_COMPUVBYELASTICISOLINES
1993 // Set computed UV to points
1995 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1996 TPoint* point = *pIt;
1997 //gp_XY oldUV = point->myUV;
1998 double minDist = DBL_MAX;
1999 list < TIsoNode >::iterator nIt = nodes.begin();
2000 for ( ; nIt != nodes.end(); nIt++ ) {
2001 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2002 if ( dist < minDist ) {
2004 point->myUV = (*nIt).myUV;
2014 //=======================================================================
2015 //function : setFirstEdge
2016 //purpose : choose the best first edge of theWire; return the summary distance
2017 // between point UV computed by isolines intersection and
2018 // eventual UV got from edge p-curves
2019 //=======================================================================
2021 //#define DBG_SETFIRSTEDGE
2022 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2024 int iE, nbEdges = theWire.size();
2028 // Transform UVs computed by iso to fit bnd box of a wire
2030 // max nb of points on an edge
2032 int eID = theFirstEdgeID;
2033 for ( iE = 0; iE < nbEdges; iE++ )
2034 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2036 // compute bnd boxes
2037 TopoDS_Face face = TopoDS::Face( myShape );
2038 Bnd_Box2d bndBox, eBndBox;
2039 eID = theFirstEdgeID;
2040 list< TopoDS_Edge >::iterator eIt;
2041 list< TPoint* >::iterator pIt;
2042 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2044 // UV by isos stored in TPoint.myXYZ
2045 list< TPoint* > & ePoints = getShapePoints( eID++ );
2046 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2048 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2050 // UV by an edge p-curve
2052 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2053 double dU = ( l - f ) / ( maxNbPnt - 1 );
2054 for ( int i = 0; i < maxNbPnt; i++ )
2055 eBndBox.Add( C2d->Value( f + i * dU ));
2058 // transform UVs by isos
2059 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2060 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2061 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2062 #ifdef DBG_SETFIRSTEDGE
2063 cout << "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2064 << eMinPar[1] << " - " << eMaxPar[1] << endl;
2066 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2068 double dMin = eMinPar[i] - minPar[i];
2069 double dMax = eMaxPar[i] - maxPar[i];
2070 double dPar = maxPar[i] - minPar[i];
2071 eID = theFirstEdgeID;
2072 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2074 list< TPoint* > & ePoints = getShapePoints( eID++ );
2075 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2077 double par = (*pIt)->myXYZ.Coord( iC );
2078 double r = ( par - minPar[i] ) / dPar;
2079 par += ( 1 - r ) * dMin + r * dMax;
2080 (*pIt)->myXYZ.SetCoord( iC, par );
2086 double minDist = DBL_MAX;
2087 for ( iE = 0 ; iE < nbEdges; iE++ )
2089 #ifdef DBG_SETFIRSTEDGE
2090 cout << " VARIANT " << iE << endl;
2092 // evaluate the distance between UV computed by the 2 methods:
2093 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2095 int eID = theFirstEdgeID;
2096 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2098 list< TPoint* > & ePoints = getShapePoints( eID++ );
2099 computeUVOnEdge( *eIt, ePoints );
2100 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2102 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2103 #ifdef DBG_SETFIRSTEDGE
2104 cout << " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2105 p->myUV.X() << ", " << p->myUV.Y() << ") " << endl;
2109 #ifdef DBG_SETFIRSTEDGE
2110 cout << "dist -- " << dist << endl;
2112 if ( dist < minDist ) {
2114 eBest = theWire.front();
2116 // check variant with another first edge
2117 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2119 // put the best first edge to the theWire front
2120 if ( eBest != theWire.front() ) {
2121 eIt = find ( theWire.begin(), theWire.end(), eBest );
2122 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2128 //=======================================================================
2129 //function : sortSameSizeWires
2130 //purpose : sort wires in theWireList from theFromWire until theToWire,
2131 // the wires are set in the order to correspond to the order
2132 // of boundaries; after sorting, edges in the wires are put
2133 // in a good order, point UVs on edges are computed and points
2134 // are appended to theEdgesPointsList
2135 //=======================================================================
2137 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2138 const TListOfEdgesList::iterator& theFromWire,
2139 const TListOfEdgesList::iterator& theToWire,
2140 const int theFirstEdgeID,
2141 list< list< TPoint* > >& theEdgesPointsList )
2143 TopoDS_Face F = TopoDS::Face( myShape );
2144 int iW, nbWires = 0;
2145 TListOfEdgesList::iterator wlIt = theFromWire;
2146 while ( wlIt++ != theToWire )
2149 // Recompute key-point UVs by isolines intersection,
2150 // compute CG of key-points for each wire and bnd boxes of GCs
2153 gp_XY orig( gp::Origin2d().XY() );
2154 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2155 Bnd_Box2d bndBox, vBndBox;
2156 int eID = theFirstEdgeID;
2157 list< TopoDS_Edge >::iterator eIt;
2158 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2160 list< TopoDS_Edge > & wire = *wlIt;
2161 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2163 list< TPoint* > & ePoints = getShapePoints( eID++ );
2164 TPoint* p = ePoints.front();
2165 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2166 MESSAGE("cant sortSameSizeWires()");
2169 gcVec[iW] += p->myUV;
2170 bndBox.Add( gp_Pnt2d( p->myUV ));
2171 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2172 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2173 vGcVec[iW] += vXY.XY();
2175 // keep the computed UV to compare against by setFirstEdge()
2176 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2178 gcVec[iW] /= nbWires;
2179 vGcVec[iW] /= nbWires;
2180 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2181 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2184 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2186 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2187 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2188 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2189 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2191 double dMin = vMinPar[i] - minPar[i];
2192 double dMax = vMaxPar[i] - maxPar[i];
2193 double dPar = maxPar[i] - minPar[i];
2194 if ( Abs( dPar ) <= DBL_MIN )
2196 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2197 double par = gcVec[iW].Coord( iC );
2198 double r = ( par - minPar[i] ) / dPar;
2199 par += ( 1 - r ) * dMin + r * dMax;
2200 gcVec[iW].SetCoord( iC, par );
2204 // Define boundary - wire correspondence by GC closeness
2206 TListOfEdgesList tmpWList;
2207 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2208 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2209 TIntWirePosMap bndIndWirePosMap;
2210 vector< bool > bndFound( nbWires, false );
2211 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2213 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2214 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2215 double minDist = DBL_MAX;
2216 gp_XY & wGc = vGcVec[ iW ];
2218 for ( int iB = 0; iB < nbWires; iB++ ) {
2219 if ( bndFound[ iB ] ) continue;
2220 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2221 if ( dist < minDist ) {
2226 bndFound[ bIndex ] = true;
2227 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2232 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2233 eID = theFirstEdgeID;
2234 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2236 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2237 list < TopoDS_Edge > & wire = ( *wirePos );
2239 // choose the best first edge of a wire
2240 setFirstEdge( wire, eID );
2242 // compute eventual UV and fill theEdgesPointsList
2243 theEdgesPointsList.push_back( list< TPoint* >() );
2244 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2245 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2247 list< TPoint* > & ePoints = getShapePoints( eID++ );
2248 computeUVOnEdge( *eIt, ePoints );
2249 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2251 // put wire back to theWireList
2253 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2259 //=======================================================================
2261 //purpose : Compute nodes coordinates applying
2262 // the loaded pattern to <theFace>. The first key-point
2263 // will be mapped into <theVertexOnKeyPoint1>
2264 //=======================================================================
2266 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2267 const TopoDS_Vertex& theVertexOnKeyPoint1,
2268 const bool theReverse)
2270 MESSAGE(" ::Apply(face) " );
2271 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2272 if ( !setShapeToMesh( face ))
2275 // find points on edges, it fills myNbKeyPntInBoundary
2276 if ( !findBoundaryPoints() )
2279 // Define the edges order so that the first edge starts at
2280 // theVertexOnKeyPoint1
2282 list< TopoDS_Edge > eList;
2283 list< int > nbVertexInWires;
2284 int nbWires = getOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2285 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2287 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2288 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2290 // check nb wires and edges
2291 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2292 l1.sort(); l2.sort();
2295 MESSAGE( "Wrong nb vertices in wires" );
2296 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2299 // here shapes get IDs, for the outer wire IDs are OK
2300 list<TopoDS_Edge>::iterator elIt = eList.begin();
2301 for ( ; elIt != eList.end(); elIt++ ) {
2302 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2303 if ( BRep_Tool::IsClosed( *elIt, theFace ) )
2304 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));
2306 int nbVertices = myShapeIDMap.Extent();
2308 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2309 myShapeIDMap.Add( *elIt );
2311 myShapeIDMap.Add( face );
2313 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent()/* + nbSeamShapes*/ ) {
2314 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2315 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2318 // points on edges to be used for UV computation of in-face points
2319 list< list< TPoint* > > edgesPointsList;
2320 edgesPointsList.push_back( list< TPoint* >() );
2321 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2322 list< TPoint* >::iterator pIt;
2324 // compute UV of points on the outer wire
2325 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2326 for (iE = 0, elIt = eList.begin();
2327 iE < nbEdgesInOuterWire && elIt != eList.end();
2330 list< TPoint* > & ePoints = getShapePoints( *elIt );
2332 computeUVOnEdge( *elIt, ePoints );
2333 // collect on-edge points (excluding the last one)
2334 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2337 // If there are several wires, define the order of edges of inner wires:
2338 // compute UV of inner edge-points using 2 methods: the one for in-face points
2339 // and the one for on-edge points and then choose the best edge order
2340 // by the best correspondance of the 2 results
2343 // compute UV of inner edge-points using the method for in-face points
2344 // and devide eList into a list of separate wires
2346 list< list< TopoDS_Edge > > wireList;
2347 list<TopoDS_Edge>::iterator eIt = elIt;
2348 list<int>::iterator nbEIt = nbVertexInWires.begin();
2349 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2351 int nbEdges = *nbEIt;
2352 wireList.push_back( list< TopoDS_Edge >() );
2353 list< TopoDS_Edge > & wire = wireList.back();
2354 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2356 list< TPoint* > & ePoints = getShapePoints( *eIt );
2357 pIt = ePoints.begin();
2358 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2360 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2361 MESSAGE("cant Apply(face)");
2364 // keep the computed UV to compare against by setFirstEdge()
2365 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2367 wire.push_back( *eIt );
2370 // remove inner edges from eList
2371 eList.erase( elIt, eList.end() );
2373 // sort wireList by nb edges in a wire
2374 sortBySize< TopoDS_Edge > ( wireList );
2376 // an ID of the first edge of a boundary
2377 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2378 // if ( nbSeamShapes > 0 )
2379 // id1 += 2; // 2 vertices more
2381 // find points - edge correspondence for wires of unique size,
2382 // edge order within a wire should be defined only
2384 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2385 while ( wlIt != wireList.end() )
2387 list< TopoDS_Edge >& wire = (*wlIt);
2388 int nbEdges = wire.size();
2390 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2392 // choose the best first edge of a wire
2393 setFirstEdge( wire, id1 );
2395 // compute eventual UV and collect on-edge points
2396 edgesPointsList.push_back( list< TPoint* >() );
2397 edgesPoints = & edgesPointsList.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()));
2409 // find boundary - wire correspondence for several wires of same size
2411 id1 = nbVertices + nbEdgesInOuterWire + 1;
2412 wlIt = wireList.begin();
2413 while ( wlIt != wireList.end() )
2415 int nbSameSize = 0, nbEdges = (*wlIt).size();
2416 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2418 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2422 if ( nbSameSize > 0 )
2423 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2426 id1 += nbEdges * ( nbSameSize + 1 );
2429 // add well-ordered edges to eList
2431 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2433 list< TopoDS_Edge >& wire = (*wlIt);
2434 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2437 // re-fill myShapeIDMap - all shapes get good IDs
2439 myShapeIDMap.Clear();
2440 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2441 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2442 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2443 myShapeIDMap.Add( *elIt );
2444 myShapeIDMap.Add( face );
2446 } // there are inner wires
2448 // Compute XYZ of on-edge points
2450 TopLoc_Location loc;
2451 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2454 Handle(Geom_Curve) C3d = BRep_Tool::Curve( *elIt, loc, f, l );
2455 const gp_Trsf & aTrsf = loc.Transformation();
2456 list< TPoint* > & ePoints = getShapePoints( iE++ );
2457 pIt = ePoints.begin();
2458 for ( pIt++; pIt != ePoints.end(); pIt++ )
2460 TPoint* point = *pIt;
2461 point->myXYZ = C3d->Value( point->myU );
2462 if ( !loc.IsIdentity() )
2463 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2467 // Compute UV and XYZ of in-face points
2469 // try to use a simple algo
2470 list< TPoint* > & fPoints = getShapePoints( face );
2471 bool isDeformed = false;
2472 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2473 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2474 (*pIt)->myUV, isDeformed )) {
2475 MESSAGE("cant Apply(face)");
2478 // try to use a complex algo if it is a difficult case
2479 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2481 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2482 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2483 (*pIt)->myUV, isDeformed )) {
2484 MESSAGE("cant Apply(face)");
2489 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2490 const gp_Trsf & aTrsf = loc.Transformation();
2491 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2493 TPoint * point = *pIt;
2494 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2495 if ( !loc.IsIdentity() )
2496 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2499 myIsComputed = true;
2501 return setErrorCode( ERR_OK );
2504 //=======================================================================
2506 //purpose : Compute nodes coordinates applying
2507 // the loaded pattern to <theFace>. The first key-point
2508 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2509 //=======================================================================
2511 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2512 const int theNodeIndexOnKeyPoint1,
2513 const bool theReverse)
2515 // MESSAGE(" ::Apply(MeshFace) " );
2517 if ( !IsLoaded() ) {
2518 MESSAGE( "Pattern not loaded" );
2519 return setErrorCode( ERR_APPL_NOT_LOADED );
2522 // check nb of nodes
2523 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2524 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2525 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2528 // find points on edges, it fills myNbKeyPntInBoundary
2529 if ( !findBoundaryPoints() )
2532 // check that there are no holes in a pattern
2533 if (myNbKeyPntInBoundary.size() > 1 ) {
2534 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2537 // Define the nodes order
2539 list< const SMDS_MeshNode* > nodes;
2540 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2541 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2543 while ( noIt->more() ) {
2544 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( noIt->next() );
2545 nodes.push_back( node );
2546 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2549 if ( n != nodes.end() ) {
2551 if ( n != --nodes.end() )
2552 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2555 else if ( n != nodes.begin() )
2556 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2558 list< gp_XYZ > xyzList;
2559 myOrderedNodes.resize( theFace->NbNodes() );
2560 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2561 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2562 myOrderedNodes[ iSub++] = *n;
2565 // Define a face plane
2567 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2568 gp_Pnt P ( *xyzIt++ );
2569 gp_Vec Vx( P, *xyzIt++ ), N;
2571 N = Vx ^ gp_Vec( P, *xyzIt++ );
2572 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2573 if ( N.SquareMagnitude() <= DBL_MIN )
2574 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2575 gp_Ax2 pos( P, N, Vx );
2577 // Compute UV of key-points on a plane
2578 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2580 gp_Vec vec ( pos.Location(), *xyzIt );
2581 TPoint* p = getShapePoints( iSub ).front();
2582 p->myUV.SetX( vec * pos.XDirection() );
2583 p->myUV.SetY( vec * pos.YDirection() );
2587 // points on edges to be used for UV computation of in-face points
2588 list< list< TPoint* > > edgesPointsList;
2589 edgesPointsList.push_back( list< TPoint* >() );
2590 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2591 list< TPoint* >::iterator pIt;
2593 // compute UV and XYZ of points on edges
2595 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2597 gp_XYZ& xyz1 = *xyzIt++;
2598 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2600 list< TPoint* > & ePoints = getShapePoints( iSub );
2601 ePoints.back()->myInitU = 1.0;
2602 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2603 while ( *pIt != ePoints.back() )
2606 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2607 gp_Vec vec ( pos.Location(), p->myXYZ );
2608 p->myUV.SetX( vec * pos.XDirection() );
2609 p->myUV.SetY( vec * pos.YDirection() );
2611 // collect on-edge points (excluding the last one)
2612 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2615 // Compute UV and XYZ of in-face points
2617 // try to use a simple algo to compute UV
2618 list< TPoint* > & fPoints = getShapePoints( iSub );
2619 bool isDeformed = false;
2620 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2621 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2622 (*pIt)->myUV, isDeformed )) {
2623 MESSAGE("cant Apply(face)");
2626 // try to use a complex algo if it is a difficult case
2627 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2629 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2630 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2631 (*pIt)->myUV, isDeformed )) {
2632 MESSAGE("cant Apply(face)");
2637 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2639 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2642 myIsComputed = true;
2644 return setErrorCode( ERR_OK );
2647 //=======================================================================
2648 //function : undefinedXYZ
2650 //=======================================================================
2652 static const gp_XYZ& undefinedXYZ()
2654 static gp_XYZ xyz( 1.e100, 0., 0. );
2658 //=======================================================================
2659 //function : isDefined
2661 //=======================================================================
2663 inline static bool isDefined(const gp_XYZ& theXYZ)
2665 return theXYZ.X() < 1.e100;
2668 //=======================================================================
2670 //purpose : Compute nodes coordinates applying
2671 // the loaded pattern to <theFaces>. The first key-point
2672 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2673 //=======================================================================
2675 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshFace*>& theFaces,
2676 const int theNodeIndexOnKeyPoint1,
2677 const bool theReverse)
2679 MESSAGE(" ::Apply(set<MeshFace>) " );
2681 if ( !IsLoaded() ) {
2682 MESSAGE( "Pattern not loaded" );
2683 return setErrorCode( ERR_APPL_NOT_LOADED );
2686 // find points on edges, it fills myNbKeyPntInBoundary
2687 if ( !findBoundaryPoints() )
2690 // check that there are no holes in a pattern
2691 if (myNbKeyPntInBoundary.size() > 1 ) {
2692 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2697 myElemXYZIDs.clear();
2698 myXYZIdToNodeMap.clear();
2700 myIdsOnBoundary.clear();
2701 myReverseConnectivity.clear();
2703 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2704 myElements.reserve( theFaces.size() );
2706 // to find point index
2707 map< TPoint*, int > pointIndex;
2708 for ( int i = 0; i < myPoints.size(); i++ )
2709 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2711 int ind1 = 0; // lowest point index for a face
2713 // apply to each face in theFaces set
2714 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2715 for ( ; face != theFaces.end(); ++face )
2717 if ( !Apply( *face, theNodeIndexOnKeyPoint1, theReverse )) {
2718 MESSAGE( "Failed on " << *face );
2721 myElements.push_back( *face );
2723 // store computed points belonging to elements
2724 list< TElemDef >::iterator ll = myElemPointIDs.begin();
2725 for ( ; ll != myElemPointIDs.end(); ++ll )
2727 myElemXYZIDs.push_back(TElemDef());
2728 TElemDef& xyzIds = myElemXYZIDs.back();
2729 TElemDef& pIds = *ll;
2730 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
2731 int pIndex = *id + ind1;
2732 xyzIds.push_back( pIndex );
2733 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
2734 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
2737 // put points on links to myIdsOnBoundary,
2738 // they will be used to sew new elements on adjacent refined elements
2739 int nbNodes = (*face)->NbNodes(), eID = nbNodes + 1;
2740 for ( int i = 0; i < nbNodes; i++ )
2742 list< TPoint* > & linkPoints = getShapePoints( eID++ );
2743 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
2744 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
2745 // make a link and a node set
2746 TNodeSet linkSet, node1Set;
2747 linkSet.insert( n1 );
2748 linkSet.insert( n2 );
2749 node1Set.insert( n1 );
2750 list< TPoint* >::iterator p = linkPoints.begin();
2752 // map the first link point to n1
2753 int nId = pointIndex[ *p ] + ind1;
2754 myXYZIdToNodeMap[ nId ] = n1;
2755 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
2756 groups.push_back(list< int > ());
2757 groups.back().push_back( nId );
2759 // add the linkSet to the map
2760 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
2761 groups.push_back(list< int > ());
2762 list< int >& indList = groups.back();
2763 // add points to the map excluding the end points
2764 for ( p++; *p != linkPoints.back(); p++ )
2765 indList.push_back( pointIndex[ *p ] + ind1 );
2767 ind1 += myPoints.size();
2770 return !myElemXYZIDs.empty();
2773 //=======================================================================
2775 //purpose : Compute nodes coordinates applying
2776 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
2777 // will be mapped into <theNode000Index>-th node. The
2778 // (0,0,1) key-point will be mapped into <theNode000Index>-th
2780 //=======================================================================
2782 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
2783 const int theNode000Index,
2784 const int theNode001Index)
2786 MESSAGE(" ::Apply(set<MeshVolumes>) " );
2788 if ( !IsLoaded() ) {
2789 MESSAGE( "Pattern not loaded" );
2790 return setErrorCode( ERR_APPL_NOT_LOADED );
2793 // bind ID to points
2794 if ( !findBoundaryPoints() )
2797 // check that there are no holes in a pattern
2798 if (myNbKeyPntInBoundary.size() > 1 ) {
2799 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2804 myElemXYZIDs.clear();
2805 myXYZIdToNodeMap.clear();
2807 myIdsOnBoundary.clear();
2808 myReverseConnectivity.clear();
2810 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
2811 myElements.reserve( theVolumes.size() );
2813 // to find point index
2814 map< TPoint*, int > pointIndex;
2815 for ( int i = 0; i < myPoints.size(); i++ )
2816 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2818 int ind1 = 0; // lowest point index for an element
2820 // apply to each element in theVolumes set
2821 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
2822 for ( ; vol != theVolumes.end(); ++vol )
2824 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
2825 MESSAGE( "Failed on " << *vol );
2828 myElements.push_back( *vol );
2830 // store computed points belonging to elements
2831 list< TElemDef >::iterator ll = myElemPointIDs.begin();
2832 for ( ; ll != myElemPointIDs.end(); ++ll )
2834 myElemXYZIDs.push_back(TElemDef());
2835 TElemDef& xyzIds = myElemXYZIDs.back();
2836 TElemDef& pIds = *ll;
2837 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
2838 int pIndex = *id + ind1;
2839 xyzIds.push_back( pIndex );
2840 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
2841 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
2844 // put points on edges and faces to myIdsOnBoundary,
2845 // they will be used to sew new elements on adjacent refined elements
2846 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
2848 // make a set of sub-points
2850 vector< int > subIDs;
2851 if ( SMESH_Block::IsVertexID( Id )) {
2852 subNodes.insert( myOrderedNodes[ Id - 1 ]);
2854 else if ( SMESH_Block::IsEdgeID( Id )) {
2855 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
2856 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
2857 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
2860 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
2861 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
2862 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
2863 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
2864 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
2865 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
2866 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
2867 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
2870 list< TPoint* > & points = getShapePoints( Id );
2871 list< TPoint* >::iterator p = points.begin();
2872 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
2873 groups.push_back(list< int > ());
2874 list< int >& indList = groups.back();
2875 for ( ; p != points.end(); p++ )
2876 indList.push_back( pointIndex[ *p ] + ind1 );
2877 if ( subNodes.size() == 1 ) // vertex case
2878 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
2880 ind1 += myPoints.size();
2883 return !myElemXYZIDs.empty();
2886 //=======================================================================
2888 //purpose : Create a pattern from the mesh built on <theBlock>
2889 //=======================================================================
2891 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
2892 const TopoDS_Shell& theBlock)
2894 MESSAGE(" ::Load(volume) " );
2897 SMESHDS_SubMesh * aSubMesh;
2899 // load shapes in myShapeIDMap
2901 TopoDS_Vertex v1, v2;
2902 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
2903 return setErrorCode( ERR_LOADV_BAD_SHAPE );
2906 int nbNodes = 0, shapeID;
2907 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
2909 const TopoDS_Shape& S = myShapeIDMap( shapeID );
2910 aSubMesh = getSubmeshWithElements( theMesh, S );
2912 nbNodes += aSubMesh->NbNodes();
2914 myPoints.resize( nbNodes );
2916 // load U of points on edges
2917 TNodePointIDMap nodePointIDMap;
2919 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
2921 const TopoDS_Shape& S = myShapeIDMap( shapeID );
2922 list< TPoint* > & shapePoints = getShapePoints( shapeID );
2923 aSubMesh = getSubmeshWithElements( theMesh, S );
2924 if ( ! aSubMesh ) continue;
2925 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
2926 if ( !nIt->more() ) continue;
2928 // store a node and a point
2929 while ( nIt->more() ) {
2930 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nIt->next() );
2931 nodePointIDMap.insert( make_pair( node, iPoint ));
2932 if ( block.IsVertexID( shapeID ))
2933 myKeyPointIDs.push_back( iPoint );
2934 TPoint* p = & myPoints[ iPoint++ ];
2935 shapePoints.push_back( p );
2936 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
2937 p->myInitXYZ.SetCoord( 0,0,0 );
2939 list< TPoint* >::iterator pIt = shapePoints.begin();
2942 switch ( S.ShapeType() )
2947 for ( ; pIt != shapePoints.end(); pIt++ ) {
2948 double * coef = block.GetShapeCoef( shapeID );
2949 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
2950 if ( coef[ iCoord - 1] > 0 )
2951 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
2953 if ( S.ShapeType() == TopAbs_VERTEX )
2956 const TopoDS_Edge& edge = TopoDS::Edge( S );
2958 BRep_Tool::Range( edge, f, l );
2959 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
2960 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
2961 pIt = shapePoints.begin();
2962 nIt = aSubMesh->GetNodes();
2963 for ( ; nIt->more(); pIt++ )
2965 const SMDS_MeshNode* node =
2966 static_cast<const SMDS_MeshNode*>( nIt->next() );
2967 const SMDS_EdgePosition* epos =
2968 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
2969 double u = ( epos->GetUParameter() - f ) / ( l - f );
2970 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
2975 for ( ; pIt != shapePoints.end(); pIt++ )
2977 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
2978 MESSAGE( "!block.ComputeParameters()" );
2979 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
2983 } // loop on block sub-shapes
2987 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
2990 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
2991 while ( elemIt->more() ) {
2992 SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
2993 myElemPointIDs.push_back( TElemDef() );
2994 TElemDef& elemPoints = myElemPointIDs.back();
2995 while ( nIt->more() )
2996 elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
3000 myIsBoundaryPointsFound = true;
3002 return setErrorCode( ERR_OK );
3005 //=======================================================================
3006 //function : getSubmeshWithElements
3007 //purpose : return submesh containing elements bound to theBlock in theMesh
3008 //=======================================================================
3010 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3011 const TopoDS_Shape& theShape)
3013 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3014 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3017 if ( theShape.ShapeType() == TopAbs_SHELL )
3019 // look for submesh of VOLUME
3020 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3021 for (; it.More(); it.Next()) {
3022 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3023 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3031 //=======================================================================
3033 //purpose : Compute nodes coordinates applying
3034 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3035 // will be mapped into <theVertex000>. The (0,0,1)
3036 // fifth key-point will be mapped into <theVertex001>.
3037 //=======================================================================
3039 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3040 const TopoDS_Vertex& theVertex000,
3041 const TopoDS_Vertex& theVertex001)
3043 MESSAGE(" ::Apply(volume) " );
3045 if (!findBoundaryPoints() || // bind ID to points
3046 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3049 SMESH_Block block; // bind ID to shape
3050 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3051 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3053 // compute XYZ of points on shapes
3055 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3057 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3058 list< TPoint* >::iterator pIt = shapePoints.begin();
3059 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3060 switch ( S.ShapeType() )
3062 case TopAbs_VERTEX: {
3064 for ( ; pIt != shapePoints.end(); pIt++ )
3065 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3070 for ( ; pIt != shapePoints.end(); pIt++ )
3071 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3076 for ( ; pIt != shapePoints.end(); pIt++ )
3077 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3081 for ( ; pIt != shapePoints.end(); pIt++ )
3082 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3084 } // loop on block sub-shapes
3086 myIsComputed = true;
3088 return setErrorCode( ERR_OK );
3091 //=======================================================================
3093 //purpose : Compute nodes coordinates applying
3094 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3095 // will be mapped into <theNode000Index>-th node. The
3096 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3098 //=======================================================================
3100 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3101 const int theNode000Index,
3102 const int theNode001Index)
3104 //MESSAGE(" ::Apply(MeshVolume) " );
3106 if (!findBoundaryPoints()) // bind ID to points
3109 SMESH_Block block; // bind ID to shape
3110 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3111 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3112 // compute XYZ of points on shapes
3114 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3116 list< TPoint* > & shapePoints = getShapePoints( ID );
3117 list< TPoint* >::iterator pIt = shapePoints.begin();
3119 if ( block.IsVertexID( ID ))
3120 for ( ; pIt != shapePoints.end(); pIt++ ) {
3121 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3123 else if ( block.IsEdgeID( ID ))
3124 for ( ; pIt != shapePoints.end(); pIt++ ) {
3125 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3127 else if ( block.IsFaceID( ID ))
3128 for ( ; pIt != shapePoints.end(); pIt++ ) {
3129 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3132 for ( ; pIt != shapePoints.end(); pIt++ )
3133 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3134 } // loop on block sub-shapes
3136 myIsComputed = true;
3138 return setErrorCode( ERR_OK );
3141 //=======================================================================
3142 //function : mergePoints
3143 //purpose : Merge XYZ on edges and/or faces.
3144 //=======================================================================
3146 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3148 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3149 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3151 list<list< int > >& groups = idListIt->second;
3152 if ( groups.size() < 2 )
3156 const TNodeSet& nodes = idListIt->first;
3157 double tol2 = 1.e-10;
3158 if ( nodes.size() > 1 ) {
3160 TNodeSet::const_iterator n = nodes.begin();
3161 for ( ; n != nodes.end(); ++n )
3162 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3163 double x, y, z, X, Y, Z;
3164 box.Get( x, y, z, X, Y, Z );
3165 gp_Pnt p( x, y, z ), P( X, Y, Z );
3166 tol2 = 1.e-4 * p.SquareDistance( P );
3169 // to unite groups on link
3170 bool unite = ( uniteGroups && nodes.size() == 2 );
3171 map< double, int > distIndMap;
3172 const SMDS_MeshNode* node = *nodes.begin();
3173 gp_Pnt P( node->X(), node->Y(), node->Z() );
3175 // compare points, replace indices
3177 list< int >::iterator ind1, ind2;
3178 list< list< int > >::iterator grpIt1, grpIt2;
3179 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3181 list< int >& indices1 = *grpIt1;
3183 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3185 list< int >& indices2 = *grpIt2;
3186 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3188 gp_XYZ& p1 = myXYZ[ *ind1 ];
3189 ind2 = indices2.begin();
3190 while ( ind2 != indices2.end() )
3192 gp_XYZ& p2 = myXYZ[ *ind2 ];
3193 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3194 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3196 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3197 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3198 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3199 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3201 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3202 myXYZ[ *ind2 ] = undefinedXYZ();
3203 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3205 ind2 = indices2.erase( ind2 );
3212 if ( unite ) { // sort indices using distIndMap
3213 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3215 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3216 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3217 distIndMap.insert( make_pair( dist, *ind1 ));
3221 if ( unite ) { // put all sorted indices into the first group
3222 list< int >& g = groups.front();
3224 map< double, int >::iterator dist_ind = distIndMap.begin();
3225 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3226 g.push_back( dist_ind->second );
3228 } // loop on myIdsOnBoundary
3231 //=======================================================================
3232 //function : makePolyElements
3233 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3234 //=======================================================================
3236 void SMESH_Pattern::
3237 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3238 const bool toCreatePolygons,
3239 const bool toCreatePolyedrs)
3241 myPolyElemXYZIDs.clear();
3242 myPolyElems.clear();
3243 myPolyElems.reserve( myIdsOnBoundary.size() );
3245 // make a set of refined elements
3246 map<int,const SMDS_MeshElement* > avoidSet, elemSet;
3247 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3248 for(; itv!=myElements.end(); itv++) {
3249 const SMDS_MeshElement* el = (*itv);
3250 avoidSet.insert( make_pair(el->GetID(),el) );
3252 //avoidSet.insert( myElements.begin(), myElements.end() );
3254 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3256 if ( toCreatePolygons )
3258 int lastFreeId = myXYZ.size();
3260 // loop on links of refined elements
3261 indListIt = myIdsOnBoundary.begin();
3262 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3264 const TNodeSet & linkNodes = indListIt->first;
3265 if ( linkNodes.size() != 2 )
3266 continue; // skip face
3267 const SMDS_MeshNode* n1 = * linkNodes.begin();
3268 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3270 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3271 if ( idGroups.empty() || idGroups.front().empty() )
3274 // find not refined face having n1-n2 link
3278 const SMDS_MeshElement* face =
3279 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3282 avoidSet.insert ( make_pair(face->GetID(),face) );
3283 myPolyElems.push_back( face );
3285 // some links of <face> are split;
3286 // make list of xyz for <face>
3287 myPolyElemXYZIDs.push_back(TElemDef());
3288 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3289 // loop on links of a <face>
3290 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3291 int i = 0, nbNodes = face->NbNodes();
3292 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3293 while ( nIt->more() )
3294 nodes[ i++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3295 nodes[ i ] = nodes[ 0 ];
3296 for ( i = 0; i < nbNodes; ++i )
3298 // look for point mapped on a link
3299 TNodeSet faceLinkNodes;
3300 faceLinkNodes.insert( nodes[ i ] );
3301 faceLinkNodes.insert( nodes[ i + 1 ] );
3302 if ( faceLinkNodes == linkNodes )
3303 nn_IdList = indListIt;
3305 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3306 // add face point ids
3307 faceNodeIds.push_back( ++lastFreeId );
3308 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3309 if ( nn_IdList != myIdsOnBoundary.end() )
3311 // there are points mapped on a link
3312 list< int >& mappedIds = nn_IdList->second.front();
3313 if ( isReversed( nodes[ i ], mappedIds ))
3314 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3316 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3318 } // loop on links of a <face>
3324 if ( myIs2D && idGroups.size() > 1 ) {
3326 // sew new elements on 2 refined elements sharing n1-n2 link
3328 list< int >& idsOnLink = idGroups.front();
3329 // temporarily add ids of link nodes to idsOnLink
3330 bool rev = isReversed( n1, idsOnLink );
3331 for ( int i = 0; i < 2; ++i )
3334 nodeSet.insert( i ? n2 : n1 );
3335 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3336 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3337 int nodeId = groups.front().front();
3339 if ( rev ) append = !append;
3341 idsOnLink.push_back( nodeId );
3343 idsOnLink.push_front( nodeId );
3345 list< int >::iterator id = idsOnLink.begin();
3346 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3348 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3349 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3350 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3352 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3353 // look for <id> in element definition
3354 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3355 ASSERT ( idDef != pIdList->end() );
3356 // look for 2 neighbour ids of <id> in element definition
3357 for ( int prev = 0; prev < 2; ++prev ) {
3358 TElemDef::iterator idDef2 = idDef;
3360 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3362 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3363 // look for idDef2 on a link starting from id
3364 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3365 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3366 // insert ids located on link between <id> and <id2>
3367 // into the element definition between idDef and idDef2
3369 for ( ; id2 != id; --id2 )
3370 pIdList->insert( idDef, *id2 );
3372 list< int >::iterator id1 = id;
3373 for ( ++id1, ++id2; id1 != id2; ++id1 )
3374 pIdList->insert( idDef2, *id1 );
3380 // remove ids of link nodes
3381 idsOnLink.pop_front();
3382 idsOnLink.pop_back();
3384 } // loop on myIdsOnBoundary
3385 } // if ( toCreatePolygons )
3387 if ( toCreatePolyedrs )
3389 // check volumes adjacent to the refined elements
3390 SMDS_VolumeTool volTool;
3391 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3392 for ( ; refinedElem != myElements.end(); ++refinedElem )
3394 // loop on nodes of refinedElem
3395 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3396 while ( nIt->more() ) {
3397 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nIt->next() );
3398 // loop on inverse elements of node
3399 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3400 while ( eIt->more() )
3402 const SMDS_MeshElement* elem = eIt->next();
3403 if ( !volTool.Set( elem ) || !avoidSet.insert( make_pair(elem->GetID(),elem) ).second )
3404 continue; // skip faces or refined elements
3405 // add polyhedron definition
3406 myPolyhedronQuantities.push_back(vector<int> ());
3407 myPolyElemXYZIDs.push_back(TElemDef());
3408 vector<int>& quantity = myPolyhedronQuantities.back();
3409 TElemDef & elemDef = myPolyElemXYZIDs.back();
3410 // get definitions of new elements on volume faces
3411 bool makePoly = false;
3412 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3414 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3415 volTool.NbFaceNodes( iF ),
3416 theNodes, elemDef, quantity))
3420 myPolyElems.push_back( elem );
3422 myPolyhedronQuantities.pop_back();
3423 myPolyElemXYZIDs.pop_back();
3431 //=======================================================================
3432 //function : getFacesDefinition
3433 //purpose : return faces definition for a volume face defined by theBndNodes
3434 //=======================================================================
3436 bool SMESH_Pattern::
3437 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3438 const int theNbBndNodes,
3439 const vector< const SMDS_MeshNode* >& theNodes,
3440 list< int >& theFaceDefs,
3441 vector<int>& theQuantity)
3443 bool makePoly = false;
3444 // cout << "FROM FACE NODES: " <<endl;
3445 // for ( int i = 0; i < theNbBndNodes; ++i )
3446 // cout << theBndNodes[ i ];
3448 set< const SMDS_MeshNode* > bndNodeSet;
3449 for ( int i = 0; i < theNbBndNodes; ++i )
3450 bndNodeSet.insert( theBndNodes[ i ]);
3452 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3454 // make a set of all nodes on a face
3456 if ( !myIs2D ) { // for 2D, merge only edges
3457 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3458 if ( nn_IdList != myIdsOnBoundary.end() ) {
3460 list< int > & faceIds = nn_IdList->second.front();
3461 ids.insert( faceIds.begin(), faceIds.end() );
3464 //bool hasIdsInFace = !ids.empty();
3466 // add ids on links and bnd nodes
3467 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3468 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3469 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3471 // add id of iN-th bnd node
3473 nSet.insert( theBndNodes[ iN ] );
3474 nn_IdList = myIdsOnBoundary.find( nSet );
3475 int bndId = ++lastFreeId;
3476 if ( nn_IdList != myIdsOnBoundary.end() ) {
3477 bndId = nn_IdList->second.front().front();
3478 ids.insert( bndId );
3481 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3482 faceDef.push_back( bndId );
3483 // add ids on a link
3485 linkNodes.insert( theBndNodes[ iN ]);
3486 linkNodes.insert( theBndNodes[ iN + 1 == theNbBndNodes ? 0 : iN + 1 ]);
3487 nn_IdList = myIdsOnBoundary.find( linkNodes );
3488 if ( nn_IdList != myIdsOnBoundary.end() ) {
3490 list< int > & linkIds = nn_IdList->second.front();
3491 ids.insert( linkIds.begin(), linkIds.end() );
3492 if ( isReversed( theBndNodes[ iN ], linkIds ))
3493 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3495 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3499 // find faces definition of new volumes
3501 bool defsAdded = false;
3502 if ( !myIs2D ) { // for 2D, merge only edges
3503 SMDS_VolumeTool vol;
3504 set< TElemDef* > checkedVolDefs;
3505 set< int >::iterator id = ids.begin();
3506 for ( ; id != ids.end(); ++id )
3508 // definitions of volumes sharing id
3509 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3510 ASSERT( !defList.empty() );
3511 // loop on volume definitions
3512 list< TElemDef* >::iterator pIdList = defList.begin();
3513 for ( ; pIdList != defList.end(); ++pIdList)
3515 if ( !checkedVolDefs.insert( *pIdList ).second )
3516 continue; // skip already checked volume definition
3517 vector< int > idVec;
3518 idVec.reserve( (*pIdList)->size() );
3519 idVec.insert( idVec.begin(), (*pIdList)->begin(), (*pIdList)->end() );
3520 // loop on face defs of a volume
3521 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3522 if ( volType == SMDS_VolumeTool::UNKNOWN )
3524 int nbFaces = vol.NbFaces( volType );
3525 for ( int iF = 0; iF < nbFaces; ++iF )
3527 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3528 int iN, nbN = vol.NbFaceNodes( volType, iF );
3529 // check if all nodes of a faces are in <ids>
3531 for ( iN = 0; iN < nbN && all; ++iN ) {
3532 int nodeId = idVec[ nodeInds[ iN ]];
3533 all = ( ids.find( nodeId ) != ids.end() );
3536 // store a face definition
3537 for ( iN = 0; iN < nbN; ++iN ) {
3538 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3540 theQuantity.push_back( nbN );
3548 theQuantity.push_back( faceDef.size() );
3549 theFaceDefs.splice( theFaceDefs.end(), faceDef, faceDef.begin(), faceDef.end() );
3555 //=======================================================================
3556 //function : clearSubMesh
3558 //=======================================================================
3560 static bool clearSubMesh( SMESH_Mesh* theMesh,
3561 const TopoDS_Shape& theShape)
3563 bool removed = false;
3564 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3566 if ( aSubMesh->GetSubMeshDS() ) {
3568 aSubMesh->GetSubMeshDS()->NbElements() || aSubMesh->GetSubMeshDS()->NbNodes();
3569 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3573 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3574 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3576 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3577 removed = eIt->more();
3578 while ( eIt->more() )
3579 aMeshDS->RemoveElement( eIt->next() );
3580 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3581 removed = removed || nIt->more();
3582 while ( nIt->more() )
3583 aMeshDS->RemoveNode( static_cast<const SMDS_MeshNode*>( nIt->next() ));
3589 //=======================================================================
3590 //function : clearMesh
3591 //purpose : clear mesh elements existing on myShape in theMesh
3592 //=======================================================================
3594 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3597 if ( !myShape.IsNull() )
3599 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3600 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3601 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3603 clearSubMesh( theMesh, it.Value() );
3609 //=======================================================================
3610 //function : MakeMesh
3611 //purpose : Create nodes and elements in <theMesh> using nodes
3612 // coordinates computed by either of Apply...() methods
3613 //=======================================================================
3615 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3616 const bool toCreatePolygons,
3617 const bool toCreatePolyedrs)
3619 MESSAGE(" ::MakeMesh() " );
3620 if ( !myIsComputed )
3621 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3623 mergePoints( toCreatePolygons );
3625 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3627 // clear elements and nodes existing on myShape
3630 bool onMeshElements = ( !myElements.empty() );
3632 // Create missing nodes
3634 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3635 if ( onMeshElements )
3637 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3638 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3639 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3640 nodesVector[ i_node->first ] = i_node->second;
3642 for ( int i = 0; i < myXYZ.size(); ++i ) {
3643 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3644 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3651 nodesVector.resize( myPoints.size(), 0 );
3653 // to find point index
3654 map< TPoint*, int > pointIndex;
3655 for ( int i = 0; i < myPoints.size(); i++ )
3656 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3658 // loop on sub-shapes of myShape: create nodes
3659 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3660 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3663 SMESHDS_SubMesh * subMeshDS = 0;
3664 if ( !myShapeIDMap.IsEmpty() ) {
3665 S = myShapeIDMap( idPointIt->first );
3666 subMeshDS = aMeshDS->MeshElements( S );
3668 list< TPoint* > & points = idPointIt->second;
3669 list< TPoint* >::iterator pIt = points.begin();
3670 for ( ; pIt != points.end(); pIt++ )
3672 TPoint* point = *pIt;
3673 int pIndex = pointIndex[ point ];
3674 if ( nodesVector [ pIndex ] )
3676 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3679 nodesVector [ pIndex ] = node;
3682 switch ( S.ShapeType() ) {
3683 case TopAbs_VERTEX: {
3684 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S ));
3688 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ));
3689 SMDS_EdgePosition* epos =
3690 dynamic_cast<SMDS_EdgePosition *>(node->GetPosition().get());
3691 epos->SetUParameter( point->myU );
3695 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ));
3696 SMDS_FacePosition* pos =
3697 dynamic_cast<SMDS_FacePosition *>(node->GetPosition().get());
3698 pos->SetUParameter( point->myUV.X() );
3699 pos->SetVParameter( point->myUV.Y() );
3703 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3712 if ( onMeshElements )
3714 // prepare data to create poly elements
3715 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3718 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3719 // sew old and new elements
3720 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3724 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
3727 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
3728 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
3729 // for ( ; i_sm != sm.end(); i_sm++ )
3731 // cout << " SM " << i_sm->first << " ";
3732 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
3733 // //SMDS_ElemIteratorPtr GetElements();
3734 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
3735 // while ( nit->more() )
3736 // cout << nit->next()->GetID() << " ";
3739 return setErrorCode( ERR_OK );
3742 //=======================================================================
3743 //function : createElements
3744 //purpose : add elements to the mesh
3745 //=======================================================================
3747 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
3748 const vector<const SMDS_MeshNode* >& theNodesVector,
3749 const list< TElemDef > & theElemNodeIDs,
3750 const vector<const SMDS_MeshElement*>& theElements)
3752 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3753 SMESH_MeshEditor editor( theMesh );
3755 bool onMeshElements = !theElements.empty();
3757 // shapes and groups theElements are on
3758 vector< int > shapeIDs;
3759 vector< list< SMESHDS_Group* > > groups;
3760 set< const SMDS_MeshNode* > shellNodes;
3761 if ( onMeshElements )
3763 shapeIDs.resize( theElements.size() );
3764 groups.resize( theElements.size() );
3765 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
3766 set<SMESHDS_GroupBase*>::const_iterator grIt;
3767 for ( int i = 0; i < theElements.size(); i++ )
3769 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
3770 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
3771 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
3772 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
3773 groups[ i ].push_back( group );
3776 // get all nodes bound to shells because their SpacePosition is not set
3777 // by SMESHDS_Mesh::SetNodeInVolume()
3778 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
3779 if ( !aMainShape.IsNull() ) {
3780 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
3781 for ( ; shellExp.More(); shellExp.Next() )
3783 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
3785 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3786 while ( nIt->more() )
3787 shellNodes.insert( nIt->next() );
3792 // nb new elements per a refined element
3793 int nbNewElemsPerOld = 1;
3794 if ( onMeshElements )
3795 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
3799 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
3800 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
3801 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
3803 const TElemDef & elemNodeInd = *enIt;
3805 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
3806 TElemDef::const_iterator id = elemNodeInd.begin();
3808 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
3809 if ( *id < theNodesVector.size() )
3810 nodes[ nbNodes++ ] = theNodesVector[ *id ];
3812 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
3814 // dim of refined elem
3815 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
3816 if ( onMeshElements ) {
3817 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
3820 const SMDS_MeshElement* elem = 0;
3822 switch ( nbNodes ) {
3824 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
3826 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
3828 elem = aMeshDS->AddPolygonalFace( nodes );
3832 switch ( nbNodes ) {
3834 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
3836 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
3839 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
3840 nodes[4], nodes[5] ); break;
3842 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
3843 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
3845 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
3848 // set element on a shape
3849 if ( elem && onMeshElements ) // applied to mesh elements
3851 int shapeID = shapeIDs[ elemIndex ];
3852 if ( shapeID > 0 ) {
3853 aMeshDS->SetMeshElementOnShape( elem, shapeID );
3854 // set nodes on a shape
3855 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
3856 if ( S.ShapeType() == TopAbs_SOLID ) {
3857 TopoDS_Iterator shellIt( S );
3858 if ( shellIt.More() )
3859 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
3861 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
3862 while ( noIt->more() ) {
3863 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>
3864 ( static_cast<const SMDS_MeshNode*>( noIt->next() ));
3865 if (!node->GetPosition()->GetShapeId() &&
3866 shellNodes.find( node ) == shellNodes.end() ) {
3867 if ( S.ShapeType() == TopAbs_FACE )
3868 aMeshDS->SetNodeOnFace( node, shapeID );
3870 aMeshDS->SetNodeInVolume( node, shapeID );
3871 shellNodes.insert( node );
3876 // add elem in groups
3877 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
3878 for ( ; g != groups[ elemIndex ].end(); ++g )
3879 (*g)->SMDSGroup().Add( elem );
3881 if ( elem && !myShape.IsNull() ) // applied to shape
3882 aMeshDS->SetMeshElementOnShape( elem, myShape );
3885 // make that SMESH_subMesh::_computeState == COMPUTE_OK
3886 // so that operations with hypotheses will erase the mesh being built
3888 SMESH_subMesh * subMesh;
3889 if ( !myShape.IsNull() ) {
3890 subMesh = theMesh->GetSubMeshContaining( myShape );
3892 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3894 if ( onMeshElements ) {
3895 list< int > elemIDs;
3896 for ( int i = 0; i < theElements.size(); i++ )
3898 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
3900 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3902 elemIDs.push_back( theElements[ i ]->GetID() );
3904 // remove refined elements
3905 editor.Remove( elemIDs, false );
3909 //=======================================================================
3910 //function : isReversed
3911 //purpose : check xyz ids order in theIdsList taking into account
3912 // theFirstNode on a link
3913 //=======================================================================
3915 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
3916 const list< int >& theIdsList) const
3918 if ( theIdsList.size() < 2 )
3921 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
3923 list<int>::const_iterator id = theIdsList.begin();
3924 for ( int i = 0; i < 2; ++i, ++id ) {
3925 if ( *id < myXYZ.size() )
3926 P[ i ] = myXYZ[ *id ];
3928 map< int, const SMDS_MeshNode*>::const_iterator i_n;
3929 i_n = myXYZIdToNodeMap.find( *id );
3930 ASSERT( i_n != myXYZIdToNodeMap.end() );
3931 const SMDS_MeshNode* n = i_n->second;
3932 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
3935 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
3939 //=======================================================================
3940 //function : arrangeBoundaries
3941 //purpose : if there are several wires, arrange boundaryPoints so that
3942 // the outer wire goes first and fix inner wires orientation
3943 // update myKeyPointIDs to correspond to the order of key-points
3944 // in boundaries; sort internal boundaries by the nb of key-points
3945 //=======================================================================
3947 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
3949 typedef list< list< TPoint* > >::iterator TListOfListIt;
3950 TListOfListIt bndIt;
3951 list< TPoint* >::iterator pIt;
3953 int nbBoundaries = boundaryList.size();
3954 if ( nbBoundaries > 1 )
3956 // sort boundaries by nb of key-points
3957 if ( nbBoundaries > 2 )
3959 // move boundaries in tmp list
3960 list< list< TPoint* > > tmpList;
3961 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
3962 // make a map nb-key-points to boundary-position-in-tmpList,
3963 // boundary-positions get ordered in it
3964 typedef map< int, TListOfListIt > TNbKpBndPosMap;
3965 TNbKpBndPosMap nbKpBndPosMap;
3966 bndIt = tmpList.begin();
3967 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
3968 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
3969 int nb = *nbKpIt * nbBoundaries;
3970 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
3972 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
3974 // move boundaries back to boundaryList
3975 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
3976 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
3977 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
3978 TListOfListIt bndPos1 = bndPos2++;
3979 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
3983 // Look for the outer boundary: the one with the point with the least X
3984 double leastX = DBL_MAX;
3985 TListOfListIt outerBndPos;
3986 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
3988 list< TPoint* >& boundary = (*bndIt);
3989 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
3991 TPoint* point = *pIt;
3992 if ( point->myInitXYZ.X() < leastX ) {
3993 leastX = point->myInitXYZ.X();
3994 outerBndPos = bndIt;
3999 if ( outerBndPos != boundaryList.begin() )
4000 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4002 } // if nbBoundaries > 1
4004 // Check boundaries orientation and re-fill myKeyPointIDs
4006 set< TPoint* > keyPointSet;
4007 list< int >::iterator kpIt = myKeyPointIDs.begin();
4008 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4009 keyPointSet.insert( & myPoints[ *kpIt ]);
4010 myKeyPointIDs.clear();
4012 // update myNbKeyPntInBoundary also
4013 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4015 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4017 // find the point with the least X
4018 double leastX = DBL_MAX;
4019 list< TPoint* >::iterator xpIt;
4020 list< TPoint* >& boundary = (*bndIt);
4021 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4023 TPoint* point = *pIt;
4024 if ( point->myInitXYZ.X() < leastX ) {
4025 leastX = point->myInitXYZ.X();
4029 // find points next to the point with the least X
4030 TPoint* p = *xpIt, *pPrev, *pNext;
4031 if ( p == boundary.front() )
4032 pPrev = *(++boundary.rbegin());
4038 if ( p == boundary.back() )
4039 pNext = *(++boundary.begin());
4044 // vectors of boundary direction near <p>
4045 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4046 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4047 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4048 double yPrev = v1.Y() / sqrt( sqMag1 );
4049 double yNext = v2.Y() / sqrt( sqMag2 );
4050 double sumY = yPrev + yNext;
4052 if ( bndIt == boundaryList.begin() ) // outer boundary
4060 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4061 (*nbKpIt) = 0; // count nb of key-points again
4062 pIt = boundary.begin();
4063 for ( ; pIt != boundary.end(); pIt++)
4065 TPoint* point = *pIt;
4066 if ( keyPointSet.find( point ) == keyPointSet.end() )
4068 // find an index of a keypoint
4070 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4071 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4072 if ( &(*pVecIt) == point )
4074 myKeyPointIDs.push_back( index );
4077 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4080 } // loop on a list of boundaries
4082 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4085 //=======================================================================
4086 //function : findBoundaryPoints
4087 //purpose : if loaded from file, find points to map on edges and faces and
4088 // compute their parameters
4089 //=======================================================================
4091 bool SMESH_Pattern::findBoundaryPoints()
4093 if ( myIsBoundaryPointsFound ) return true;
4095 MESSAGE(" findBoundaryPoints() ");
4097 myNbKeyPntInBoundary.clear();
4101 set< TPoint* > pointsInElems;
4103 // Find free links of elements:
4104 // put links of all elements in a set and remove links encountered twice
4106 typedef pair< TPoint*, TPoint*> TLink;
4107 set< TLink > linkSet;
4108 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4109 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4111 TElemDef & elemPoints = *epIt;
4112 TElemDef::iterator pIt = elemPoints.begin();
4113 int prevP = elemPoints.back();
4114 for ( ; pIt != elemPoints.end(); pIt++ ) {
4115 TPoint* p1 = & myPoints[ prevP ];
4116 TPoint* p2 = & myPoints[ *pIt ];
4117 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4118 ASSERT( link.first != link.second );
4119 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4120 if ( !itUniq.second )
4121 linkSet.erase( itUniq.first );
4124 pointsInElems.insert( p1 );
4127 // Now linkSet contains only free links,
4128 // find the points order that they have in boundaries
4130 // 1. make a map of key-points
4131 set< TPoint* > keyPointSet;
4132 list< int >::iterator kpIt = myKeyPointIDs.begin();
4133 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4134 keyPointSet.insert( & myPoints[ *kpIt ]);
4136 // 2. chain up boundary points
4137 list< list< TPoint* > > boundaryList;
4138 boundaryList.push_back( list< TPoint* >() );
4139 list< TPoint* > * boundary = & boundaryList.back();
4141 TPoint *point1, *point2, *keypoint1;
4142 kpIt = myKeyPointIDs.begin();
4143 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4144 // loop on free links: look for the next point
4146 set< TLink >::iterator lIt = linkSet.begin();
4147 while ( lIt != linkSet.end() )
4149 if ( (*lIt).first == point1 )
4150 point2 = (*lIt).second;
4151 else if ( (*lIt).second == point1 )
4152 point2 = (*lIt).first;
4157 linkSet.erase( lIt );
4158 lIt = linkSet.begin();
4160 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4162 boundary->push_back( point2 );
4164 else // a key-point found
4166 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4168 if ( point2 != keypoint1 ) // its not the boundary end
4170 boundary->push_back( point2 );
4172 else // the boundary end reached
4174 boundary->push_front( keypoint1 );
4175 boundary->push_back( keypoint1 );
4176 myNbKeyPntInBoundary.push_back( iKeyPoint );
4177 if ( keyPointSet.empty() )
4178 break; // all boundaries containing key-points are found
4180 // prepare to search for the next boundary
4181 boundaryList.push_back( list< TPoint* >() );
4182 boundary = & boundaryList.back();
4183 point2 = keypoint1 = (*keyPointSet.begin());
4187 } // loop on the free links set
4189 if ( boundary->empty() ) {
4190 MESSAGE(" a separate key-point");
4191 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4194 // if there are several wires, arrange boundaryPoints so that
4195 // the outer wire goes first and fix inner wires orientation;
4196 // sort myKeyPointIDs to correspond to the order of key-points
4198 arrangeBoundaries( boundaryList );
4200 // Find correspondence shape ID - points,
4201 // compute points parameter on edge
4203 keyPointSet.clear();
4204 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4205 keyPointSet.insert( & myPoints[ *kpIt ]);
4207 set< TPoint* > edgePointSet; // to find in-face points
4208 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4209 int edgeID = myKeyPointIDs.size() + 1;
4211 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4212 for ( ; bndIt != boundaryList.end(); bndIt++ )
4214 boundary = & (*bndIt);
4215 double edgeLength = 0;
4216 list< TPoint* >::iterator pIt = boundary->begin();
4217 getShapePoints( edgeID ).push_back( *pIt );
4218 getShapePoints( vertexID++ ).push_back( *pIt );
4219 for ( pIt++; pIt != boundary->end(); pIt++)
4221 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4222 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4223 TPoint* point = *pIt;
4224 edgePointSet.insert( point );
4225 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4227 edgePoints.push_back( point );
4228 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4229 point->myInitU = edgeLength;
4233 // treat points on the edge which ends up: compute U [0,1]
4234 edgePoints.push_back( point );
4235 if ( edgePoints.size() > 2 ) {
4236 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4237 list< TPoint* >::iterator epIt = edgePoints.begin();
4238 for ( ; epIt != edgePoints.end(); epIt++ )
4239 (*epIt)->myInitU /= edgeLength;
4241 // begin the next edge treatment
4244 if ( point != boundary->front() ) { // not the first key-point again
4245 getShapePoints( edgeID ).push_back( point );
4246 getShapePoints( vertexID++ ).push_back( point );
4252 // find in-face points
4253 list< TPoint* > & facePoints = getShapePoints( edgeID );
4254 vector< TPoint >::iterator pVecIt = myPoints.begin();
4255 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4256 TPoint* point = &(*pVecIt);
4257 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4258 pointsInElems.find( point ) != pointsInElems.end())
4259 facePoints.push_back( point );
4266 // bind points to shapes according to point parameters
4267 vector< TPoint >::iterator pVecIt = myPoints.begin();
4268 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4269 TPoint* point = &(*pVecIt);
4270 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4271 getShapePoints( shapeID ).push_back( point );
4272 // detect key-points
4273 if ( SMESH_Block::IsVertexID( shapeID ))
4274 myKeyPointIDs.push_back( i );
4278 myIsBoundaryPointsFound = true;
4279 return myIsBoundaryPointsFound;
4282 //=======================================================================
4284 //purpose : clear fields
4285 //=======================================================================
4287 void SMESH_Pattern::Clear()
4289 myIsComputed = myIsBoundaryPointsFound = false;
4292 myKeyPointIDs.clear();
4293 myElemPointIDs.clear();
4294 myShapeIDToPointsMap.clear();
4295 myShapeIDMap.Clear();
4297 myNbKeyPntInBoundary.clear();
4300 //=======================================================================
4301 //function : setShapeToMesh
4302 //purpose : set a shape to be meshed. Return True if meshing is possible
4303 //=======================================================================
4305 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4307 if ( !IsLoaded() ) {
4308 MESSAGE( "Pattern not loaded" );
4309 return setErrorCode( ERR_APPL_NOT_LOADED );
4312 TopAbs_ShapeEnum aType = theShape.ShapeType();
4313 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4315 MESSAGE( "Pattern dimention mismatch" );
4316 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4319 // check if a face is closed
4320 int nbNodeOnSeamEdge = 0;
4322 TopoDS_Face face = TopoDS::Face( theShape );
4323 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4324 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() )
4325 if ( BRep_Tool::IsClosed( TopoDS::Edge( eExp.Current() ), face ))
4326 nbNodeOnSeamEdge = 2;
4329 // check nb of vertices
4330 TopTools_IndexedMapOfShape vMap;
4331 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4332 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4333 MESSAGE( myKeyPointIDs.size() << " != " << vMap.Extent() );
4334 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4337 myElements.clear(); // not refine elements
4338 myElemXYZIDs.clear();
4340 myShapeIDMap.Clear();
4345 //=======================================================================
4346 //function : GetMappedPoints
4347 //purpose : Return nodes coordinates computed by Apply() method
4348 //=======================================================================
4350 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4353 if ( !myIsComputed )
4356 if ( myElements.empty() ) { // applied to shape
4357 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4358 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4359 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4361 else { // applied to mesh elements
4362 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4363 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4364 for ( ; xyz != myXYZ.end(); ++xyz )
4365 if ( !isDefined( *xyz ))
4366 thePoints.push_back( definedXYZ );
4368 thePoints.push_back( & (*xyz) );
4370 return !thePoints.empty();
4374 //=======================================================================
4375 //function : GetPoints
4376 //purpose : Return nodes coordinates of the pattern
4377 //=======================================================================
4379 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4386 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4387 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4388 thePoints.push_back( & (*pVecIt).myInitXYZ );
4390 return ( thePoints.size() > 0 );
4393 //=======================================================================
4394 //function : getShapePoints
4395 //purpose : return list of points located on theShape
4396 //=======================================================================
4398 list< SMESH_Pattern::TPoint* > &
4399 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4402 if ( !myShapeIDMap.Contains( theShape ))
4403 aShapeID = myShapeIDMap.Add( theShape );
4405 aShapeID = myShapeIDMap.FindIndex( theShape );
4407 return myShapeIDToPointsMap[ aShapeID ];
4410 //=======================================================================
4411 //function : getShapePoints
4412 //purpose : return list of points located on the shape
4413 //=======================================================================
4415 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4417 return myShapeIDToPointsMap[ theShapeID ];
4420 //=======================================================================
4421 //function : DumpPoints
4423 //=======================================================================
4425 void SMESH_Pattern::DumpPoints() const
4428 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4429 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4430 cout << i << ": " << *pVecIt;
4434 //=======================================================================
4435 //function : TPoint()
4437 //=======================================================================
4439 SMESH_Pattern::TPoint::TPoint()
4442 myInitXYZ.SetCoord(0,0,0);
4443 myInitUV.SetCoord(0.,0.);
4445 myXYZ.SetCoord(0,0,0);
4446 myUV.SetCoord(0.,0.);
4451 //=======================================================================
4452 //function : operator <<
4454 //=======================================================================
4456 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4458 gp_XYZ xyz = p.myInitXYZ;
4459 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4460 gp_XY xy = p.myInitUV;
4461 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4462 double u = p.myInitU;
4463 OS << " u( " << u << " )) " << &p << endl;
4464 xyz = p.myXYZ.XYZ();
4465 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4467 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4469 OS << " u( " << u << " ))" << endl;