1 // SMESH SMESH : idl implementation based on 'SMESH' unit's classes
3 // Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
24 // File : SMESH_MeshEditor.cxx
25 // Created : Mon Apr 12 16:10:22 2004
26 // Author : Edward AGAPOV (eap)
29 #include "SMESH_MeshEditor.hxx"
31 #include "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
35 #include "SMDS_FacePosition.hxx"
36 #include "SMDS_SpacePosition.hxx"
38 #include "SMESHDS_Group.hxx"
39 #include "SMESHDS_Mesh.hxx"
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_ControlsDef.hxx"
44 #include "utilities.h"
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopTools_ListOfShape.hxx>
52 #include <gp_Trsf.hxx>
58 #include <BRep_Tool.hxx>
59 #include <Geom_Curve.hxx>
60 #include <Geom_Surface.hxx>
61 #include <Geom2d_Curve.hxx>
62 #include <Extrema_GenExtPS.hxx>
63 #include <Extrema_POnSurf.hxx>
64 #include <GeomAdaptor_Surface.hxx>
66 #include <TColStd_ListOfInteger.hxx>
71 using namespace SMESH::Controls;
73 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*> TNodeNodeMap;
74 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> > TElemOfNodeListMap;
75 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
76 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
77 typedef TNodeOfNodeListMap::iterator TNodeOfNodeListMapItr;
78 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
81 //=======================================================================
82 //function : SMESH_MeshEditor
84 //=======================================================================
86 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
91 //=======================================================================
93 //purpose : Remove a node or an element.
94 // Modify a compute state of sub-meshes which become empty
95 //=======================================================================
97 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
101 SMESHDS_Mesh* aMesh = GetMeshDS();
102 set< SMESH_subMesh *> smmap;
104 list<int>::const_iterator it = theIDs.begin();
105 for ( ; it != theIDs.end(); it++ )
107 const SMDS_MeshElement * elem;
109 elem = aMesh->FindNode( *it );
111 elem = aMesh->FindElement( *it );
115 // Find sub-meshes to notify about modification
116 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
117 while ( nodeIt->more() )
119 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
120 const SMDS_PositionPtr& aPosition = node->GetPosition();
121 if ( aPosition.get() ) {
122 int aShapeID = aPosition->GetShapeId();
124 TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
125 SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
134 aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
136 aMesh->RemoveElement( elem );
139 // Notify sub-meshes about modification
140 if ( !smmap.empty() ) {
141 set< SMESH_subMesh *>::iterator smIt;
142 for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
143 (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
148 //=======================================================================
149 //function : FindShape
150 //purpose : Return an index of the shape theElem is on
151 // or zero if a shape not found
152 //=======================================================================
154 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
156 SMESHDS_Mesh * aMesh = GetMeshDS();
157 if ( aMesh->ShapeToMesh().IsNull() )
160 if ( theElem->GetType() == SMDSAbs_Node )
162 const SMDS_PositionPtr& aPosition =
163 static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
164 if ( aPosition.get() )
165 return aPosition->GetShapeId();
170 TopoDS_Shape aShape; // the shape a node is on
171 SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
172 while ( nodeIt->more() )
174 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
175 const SMDS_PositionPtr& aPosition = node->GetPosition();
176 if ( aPosition.get() ) {
177 int aShapeID = aPosition->GetShapeId();
178 SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
181 if ( sm->Contains( theElem ))
183 if ( aShape.IsNull() )
184 aShape = aMesh->IndexToShape( aShapeID );
188 //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
193 // None of nodes is on a proper shape,
194 // find the shape among ancestors of aShape on which a node is
195 if ( aShape.IsNull() ) {
196 //MESSAGE ("::FindShape() - NONE node is on shape")
199 TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
200 for ( ; ancIt.More(); ancIt.Next() )
202 SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
203 if ( sm && sm->Contains( theElem ))
204 return aMesh->ShapeToIndex( ancIt.Value() );
207 //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
211 //=======================================================================
212 //function : InverseDiag
213 //purpose : Replace two neighbour triangles with ones built on the same 4 nodes
214 // but having other common link.
215 // Return False if args are improper
216 //=======================================================================
218 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
219 const SMDS_MeshElement * theTria2 )
221 if (!theTria1 || !theTria2)
223 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
224 if (!F1) return false;
225 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
226 if (!F2) return false;
228 // 1 +--+ A theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
229 // | /| theTria2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
233 // put nodes in array and find out indices of the same ones
234 const SMDS_MeshNode* aNodes [6];
235 int sameInd [] = { 0, 0, 0, 0, 0, 0 };
237 SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
240 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
242 if ( i > 2 ) // theTria2
243 // find same node of theTria1
244 for ( int j = 0; j < 3; j++ )
245 if ( aNodes[ i ] == aNodes[ j ]) {
254 return false; // theTria1 is not a triangle
255 it = theTria2->nodesIterator();
257 if ( i == 6 && it->more() )
258 return false; // theTria2 is not a triangle
261 // find indices of 1,2 and of A,B in theTria1
262 int iA = 0, iB = 0, i1 = 0, i2 = 0;
263 for ( i = 0; i < 6; i++ )
265 if ( sameInd [ i ] == 0 )
272 // nodes 1 and 2 should not be the same
273 if ( aNodes[ i1 ] == aNodes[ i2 ] )
278 aNodes[ iA ] = aNodes[ i2 ];
280 aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
282 //MESSAGE( theTria1 << theTria2 );
284 GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
285 GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
287 //MESSAGE( theTria1 << theTria2 );
292 //=======================================================================
293 //function : findTriangles
294 //purpose : find triangles sharing theNode1-theNode2 link
295 //=======================================================================
297 static bool findTriangles(const SMDS_MeshNode * theNode1,
298 const SMDS_MeshNode * theNode2,
299 const SMDS_MeshElement*& theTria1,
300 const SMDS_MeshElement*& theTria2)
302 if ( !theNode1 || !theNode2 ) return false;
304 theTria1 = theTria2 = 0;
306 set< const SMDS_MeshElement* > emap;
307 SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
309 const SMDS_MeshElement* elem = it->next();
310 if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
313 it = theNode2->GetInverseElementIterator();
315 const SMDS_MeshElement* elem = it->next();
316 if ( elem->GetType() == SMDSAbs_Face &&
317 emap.find( elem ) != emap.end() )
325 return ( theTria1 && theTria2 );
328 //=======================================================================
329 //function : InverseDiag
330 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
331 // with ones built on the same 4 nodes but having other common link.
332 // Return false if proper faces not found
333 //=======================================================================
335 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
336 const SMDS_MeshNode * theNode2)
338 MESSAGE( "::InverseDiag()" );
340 const SMDS_MeshElement *tr1, *tr2;
341 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
344 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
345 if (!F1) return false;
346 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
347 if (!F2) return false;
349 // 1 +--+ A tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
350 // | /| tr2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
354 // put nodes in array
355 // and find indices of 1,2 and of A in tr1 and of B in tr2
356 int i, iA1 = 0, i1 = 0;
357 const SMDS_MeshNode* aNodes1 [3];
358 SMDS_ElemIteratorPtr it;
359 for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
360 aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
361 if ( aNodes1[ i ] == theNode1 )
362 iA1 = i; // node A in tr1
363 else if ( aNodes1[ i ] != theNode2 )
367 const SMDS_MeshNode* aNodes2 [3];
368 for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
369 aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
370 if ( aNodes2[ i ] == theNode2 )
371 iB2 = i; // node B in tr2
372 else if ( aNodes2[ i ] != theNode1 )
376 // nodes 1 and 2 should not be the same
377 if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
381 aNodes1[ iA1 ] = aNodes2[ i2 ];
383 aNodes2[ iB2 ] = aNodes1[ i1 ];
385 //MESSAGE( tr1 << tr2 );
387 GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
388 GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
390 //MESSAGE( tr1 << tr2 );
396 //=======================================================================
397 //function : getQuadrangleNodes
398 //purpose : fill theQuadNodes - nodes of a quadrangle resulting from
399 // fusion of triangles tr1 and tr2 having shared link on
400 // theNode1 and theNode2
401 //=======================================================================
403 bool getQuadrangleNodes(const SMDS_MeshNode * theQuadNodes [],
404 const SMDS_MeshNode * theNode1,
405 const SMDS_MeshNode * theNode2,
406 const SMDS_MeshElement * tr1,
407 const SMDS_MeshElement * tr2 )
409 // find the 4-th node to insert into tr1
410 const SMDS_MeshNode* n4 = 0;
411 SMDS_ElemIteratorPtr it = tr2->nodesIterator();
412 while ( !n4 && it->more() )
414 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
415 bool isDiag = ( n == theNode1 || n == theNode2 );
419 // Make an array of nodes to be in a quadrangle
420 int iNode = 0, iFirstDiag = -1;
421 it = tr1->nodesIterator();
424 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
425 bool isDiag = ( n == theNode1 || n == theNode2 );
428 if ( iFirstDiag < 0 )
430 else if ( iNode - iFirstDiag == 1 )
431 theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
435 return false; // tr1 and tr2 should not have all the same nodes
437 theQuadNodes[ iNode++ ] = n;
439 if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
440 theQuadNodes[ iNode ] = n4;
445 //=======================================================================
446 //function : DeleteDiag
447 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
448 // with a quadrangle built on the same 4 nodes.
449 // Return false if proper faces not found
450 //=======================================================================
452 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
453 const SMDS_MeshNode * theNode2)
455 MESSAGE( "::DeleteDiag()" );
457 const SMDS_MeshElement *tr1, *tr2;
458 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
461 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
462 if (!F1) return false;
463 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
464 if (!F2) return false;
466 const SMDS_MeshNode* aNodes [ 4 ];
467 if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
470 //MESSAGE( endl << tr1 << tr2 );
472 GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
473 GetMeshDS()->RemoveElement( tr2 );
475 //MESSAGE( endl << tr1 );
480 //=======================================================================
481 //function : Reorient
482 //purpose : Reverse theElement orientation
483 //=======================================================================
485 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
489 SMDS_ElemIteratorPtr it = theElem->nodesIterator();
490 if ( !it || !it->more() )
493 switch ( theElem->GetType() ) {
498 int i = theElem->NbNodes();
499 vector<const SMDS_MeshNode*> aNodes( i );
501 aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
502 return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
506 if (theElem->IsPoly()) {
507 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
508 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
510 MESSAGE("Warning: bad volumic element");
514 int nbFaces = aPolyedre->NbFaces();
515 vector<const SMDS_MeshNode *> poly_nodes;
516 vector<int> quantities (nbFaces);
518 // reverse each face of the polyedre
519 for (int iface = 1; iface <= nbFaces; iface++) {
520 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
521 quantities[iface - 1] = nbFaceNodes;
523 for (inode = nbFaceNodes; inode >= 1; inode--) {
524 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
525 poly_nodes.push_back(curNode);
529 return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
532 SMDS_VolumeTool vTool;
533 if ( !vTool.Set( theElem ))
536 return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
545 //=======================================================================
546 //function : getBadRate
548 //=======================================================================
550 static double getBadRate (const SMDS_MeshElement* theElem,
551 SMESH::Controls::NumericalFunctorPtr& theCrit)
553 SMESH::Controls::TSequenceOfXYZ P;
554 if ( !theElem || !theCrit->GetPoints( theElem, P ))
556 return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
557 //return theCrit->GetBadRate( theCrit->GetValue( theElem->GetID() ), theElem->NbNodes() );
560 //=======================================================================
561 //function : QuadToTri
562 //purpose : Cut quadrangles into triangles.
563 // theCrit is used to select a diagonal to cut
564 //=======================================================================
566 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> & theElems,
567 SMESH::Controls::NumericalFunctorPtr theCrit)
569 MESSAGE( "::QuadToTri()" );
571 if ( !theCrit.get() )
574 SMESHDS_Mesh * aMesh = GetMeshDS();
576 set< const SMDS_MeshElement * >::iterator itElem;
577 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
579 const SMDS_MeshElement* elem = (*itElem);
580 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
583 // retrieve element nodes
584 const SMDS_MeshNode* aNodes [4];
585 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
587 while ( itN->more() )
588 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
590 // compare two sets of possible triangles
591 double aBadRate1, aBadRate2; // to what extent a set is bad
592 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
593 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
594 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
596 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
597 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
598 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
600 int aShapeId = FindShape( elem );
601 //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
602 // << " ShapeID = " << aShapeId << endl << elem );
604 if ( aBadRate1 <= aBadRate2 ) {
605 // tr1 + tr2 is better
606 aMesh->ChangeElementNodes( elem, aNodes, 3 );
607 //MESSAGE( endl << elem );
609 elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
612 // tr3 + tr4 is better
613 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
614 //MESSAGE( endl << elem );
616 elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
618 //MESSAGE( endl << elem );
620 // put a new triangle on the same shape
622 aMesh->SetMeshElementOnShape( elem, aShapeId );
628 //=======================================================================
629 //function : BestSplit
630 //purpose : Find better diagonal for cutting.
631 //=======================================================================
632 int SMESH_MeshEditor::BestSplit (const SMDS_MeshElement* theQuad,
633 SMESH::Controls::NumericalFunctorPtr theCrit)
638 if (!theQuad || theQuad->GetType() != SMDSAbs_Face || theQuad->NbNodes() != 4)
641 // retrieve element nodes
642 const SMDS_MeshNode* aNodes [4];
643 SMDS_ElemIteratorPtr itN = theQuad->nodesIterator();
646 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
648 // compare two sets of possible triangles
649 double aBadRate1, aBadRate2; // to what extent a set is bad
650 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
651 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
652 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
654 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
655 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
656 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
658 if (aBadRate1 <= aBadRate2) // tr1 + tr2 is better
659 return 1; // diagonal 1-3
661 return 2; // diagonal 2-4
664 //=======================================================================
665 //function : AddToSameGroups
666 //purpose : add elemToAdd to the groups the elemInGroups belongs to
667 //=======================================================================
669 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
670 const SMDS_MeshElement* elemInGroups,
671 SMESHDS_Mesh * aMesh)
673 const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
674 set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
675 for ( ; grIt != groups.end(); grIt++ ) {
676 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
677 if ( group && group->SMDSGroup().Contains( elemInGroups ))
678 group->SMDSGroup().Add( elemToAdd );
682 //=======================================================================
683 //function : QuadToTri
684 //purpose : Cut quadrangles into triangles.
685 // theCrit is used to select a diagonal to cut
686 //=======================================================================
688 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
689 const bool the13Diag)
691 MESSAGE( "::QuadToTri()" );
693 SMESHDS_Mesh * aMesh = GetMeshDS();
695 set< const SMDS_MeshElement * >::iterator itElem;
696 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
698 const SMDS_MeshElement* elem = (*itElem);
699 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
702 // retrieve element nodes
703 const SMDS_MeshNode* aNodes [4];
704 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
706 while ( itN->more() )
707 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
709 int aShapeId = FindShape( elem );
710 const SMDS_MeshElement* newElem = 0;
713 aMesh->ChangeElementNodes( elem, aNodes, 3 );
714 newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
718 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
719 newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
722 // put a new triangle on the same shape and add to the same groups
725 aMesh->SetMeshElementOnShape( newElem, aShapeId );
727 AddToSameGroups( newElem, elem, aMesh );
733 //=======================================================================
734 //function : getAngle
736 //=======================================================================
738 double getAngle(const SMDS_MeshElement * tr1,
739 const SMDS_MeshElement * tr2,
740 const SMDS_MeshNode * n1,
741 const SMDS_MeshNode * n2)
743 double angle = 2*PI; // bad angle
746 SMESH::Controls::TSequenceOfXYZ P1, P2;
747 if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
748 !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
750 gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
751 if ( N1.SquareMagnitude() <= gp::Resolution() )
753 gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
754 if ( N2.SquareMagnitude() <= gp::Resolution() )
757 // find the first diagonal node n1 in the triangles:
758 // take in account a diagonal link orientation
759 const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
760 for ( int t = 0; t < 2; t++ )
762 SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
763 int i = 0, iDiag = -1;
764 while ( it->more()) {
765 const SMDS_MeshElement *n = it->next();
766 if ( n == n1 || n == n2 )
770 if ( i - iDiag == 1 )
771 nFirst[ t ] = ( n == n1 ? n2 : n1 );
779 if ( nFirst[ 0 ] == nFirst[ 1 ] )
782 angle = N1.Angle( N2 );
787 // =================================================
788 // class generating a unique ID for a pair of nodes
789 // and able to return nodes by that ID
790 // =================================================
795 LinkID_Gen( const SMESHDS_Mesh* theMesh )
796 :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
799 long GetLinkID (const SMDS_MeshNode * n1,
800 const SMDS_MeshNode * n2) const
802 return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
805 bool GetNodes (const long theLinkID,
806 const SMDS_MeshNode* & theNode1,
807 const SMDS_MeshNode* & theNode2) const
809 theNode1 = myMesh->FindNode( theLinkID / myMaxID );
810 if ( !theNode1 ) return false;
811 theNode2 = myMesh->FindNode( theLinkID % myMaxID );
812 if ( !theNode2 ) return false;
818 const SMESHDS_Mesh* myMesh;
822 //=======================================================================
823 //function : TriToQuad
824 //purpose : Fuse neighbour triangles into quadrangles.
825 // theCrit is used to select a neighbour to fuse with.
826 // theMaxAngle is a max angle between element normals at which
827 // fusion is still performed.
828 //=======================================================================
830 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> & theElems,
831 SMESH::Controls::NumericalFunctorPtr theCrit,
832 const double theMaxAngle)
834 MESSAGE( "::TriToQuad()" );
836 if ( !theCrit.get() )
839 SMESHDS_Mesh * aMesh = GetMeshDS();
840 LinkID_Gen aLinkID_Gen( aMesh );
843 // Prepare data for algo: build
844 // 1. map of elements with their linkIDs
845 // 2. map of linkIDs with their elements
847 map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
848 map< long, list< const SMDS_MeshElement* > >::iterator itLE;
849 map< const SMDS_MeshElement*, set< long > > mapEl_setLi;
850 map< const SMDS_MeshElement*, set< long > >::iterator itEL;
852 set<const SMDS_MeshElement*>::iterator itElem;
853 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
855 const SMDS_MeshElement* elem = (*itElem);
856 if ( !elem || elem->NbNodes() != 3 )
859 // retrieve element nodes
860 const SMDS_MeshNode* aNodes [4];
861 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
863 while ( itN->more() )
864 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
866 aNodes[ 3 ] = aNodes[ 0 ];
869 for ( i = 0; i < 3; i++ )
871 long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
872 // check if elements sharing a link can be fused
873 itLE = mapLi_listEl.find( linkID );
874 if ( itLE != mapLi_listEl.end() )
876 if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
878 const SMDS_MeshElement* elem2 = (*itLE).second.front();
879 // if ( FindShape( elem ) != FindShape( elem2 ))
880 // continue; // do not fuse triangles laying on different shapes
881 if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
882 continue; // avoid making badly shaped quads
883 (*itLE).second.push_back( elem );
886 mapLi_listEl[ linkID ].push_back( elem );
887 mapEl_setLi [ elem ].insert( linkID );
890 // Clean the maps from the links shared by a sole element, ie
891 // links to which only one element is bound in mapLi_listEl
893 for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
895 int nbElems = (*itLE).second.size();
897 const SMDS_MeshElement* elem = (*itLE).second.front();
898 long link = (*itLE).first;
899 mapEl_setLi[ elem ].erase( link );
900 if ( mapEl_setLi[ elem ].empty() )
901 mapEl_setLi.erase( elem );
905 // Algo: fuse triangles into quadrangles
907 while ( ! mapEl_setLi.empty() )
909 // Look for the start element:
910 // the element having the least nb of shared links
912 const SMDS_MeshElement* startElem = 0;
914 for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
916 int nbLinks = (*itEL).second.size();
917 if ( nbLinks < minNbLinks )
919 startElem = (*itEL).first;
920 minNbLinks = nbLinks;
921 if ( minNbLinks == 1 )
926 // search elements to fuse starting from startElem or links of elements
927 // fused earlyer - startLinks
928 list< long > startLinks;
929 while ( startElem || !startLinks.empty() )
931 while ( !startElem && !startLinks.empty() )
933 // Get an element to start, by a link
934 long linkId = startLinks.front();
935 startLinks.pop_front();
936 itLE = mapLi_listEl.find( linkId );
937 if ( itLE != mapLi_listEl.end() )
939 list< const SMDS_MeshElement* > & listElem = (*itLE).second;
940 list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
941 for ( ; itE != listElem.end() ; itE++ )
942 if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
944 mapLi_listEl.erase( itLE );
950 // Get candidates to be fused
952 const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
955 ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
956 set< long >& setLi = mapEl_setLi[ tr1 ];
957 ASSERT( !setLi.empty() );
958 set< long >::iterator itLi;
959 for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
961 long linkID = (*itLi);
962 itLE = mapLi_listEl.find( linkID );
963 if ( itLE == mapLi_listEl.end() )
965 const SMDS_MeshElement* elem = (*itLE).second.front();
967 elem = (*itLE).second.back();
968 mapLi_listEl.erase( itLE );
969 if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
982 // add other links of elem to list of links to re-start from
983 set< long >& links = mapEl_setLi[ elem ];
984 set< long >::iterator it;
985 for ( it = links.begin(); it != links.end(); it++ )
987 long linkID2 = (*it);
988 if ( linkID2 != linkID )
989 startLinks.push_back( linkID2 );
993 // Get nodes of possible quadrangles
995 const SMDS_MeshNode *n12 [4], *n13 [4];
996 bool Ok12 = false, Ok13 = false;
997 const SMDS_MeshNode *linkNode1, *linkNode2;
999 aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
1000 getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
1003 aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
1004 getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
1007 // Choose a pair to fuse
1011 SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
1012 SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
1013 double aBadRate12 = getBadRate( &quad12, theCrit );
1014 double aBadRate13 = getBadRate( &quad13, theCrit );
1015 if ( aBadRate13 < aBadRate12 )
1023 // and remove fused elems and removed links from the maps
1025 mapEl_setLi.erase( tr1 );
1028 mapEl_setLi.erase( tr2 );
1029 mapLi_listEl.erase( link12 );
1030 aMesh->ChangeElementNodes( tr1, n12, 4 );
1031 aMesh->RemoveElement( tr2 );
1035 mapEl_setLi.erase( tr3 );
1036 mapLi_listEl.erase( link13 );
1037 aMesh->ChangeElementNodes( tr1, n13, 4 );
1038 aMesh->RemoveElement( tr3 );
1041 // Next element to fuse: the rejected one
1043 startElem = Ok12 ? tr3 : tr2;
1045 } // if ( startElem )
1046 } // while ( startElem || !startLinks.empty() )
1047 } // while ( ! mapEl_setLi.empty() )
1053 /*#define DUMPSO(txt) \
1054 // cout << txt << endl;
1055 //=============================================================================
1059 //=============================================================================
1060 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1064 int tmp = idNodes[ i1 ];
1065 idNodes[ i1 ] = idNodes[ i2 ];
1066 idNodes[ i2 ] = tmp;
1067 gp_Pnt Ptmp = P[ i1 ];
1070 DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1073 //=======================================================================
1074 //function : SortQuadNodes
1075 //purpose : Set 4 nodes of a quadrangle face in a good order.
1076 // Swap 1<->2 or 2<->3 nodes and correspondingly return
1078 //=======================================================================
1080 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1085 for ( i = 0; i < 4; i++ ) {
1086 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1088 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1091 gp_Vec V1(P[0], P[1]);
1092 gp_Vec V2(P[0], P[2]);
1093 gp_Vec V3(P[0], P[3]);
1095 gp_Vec Cross1 = V1 ^ V2;
1096 gp_Vec Cross2 = V2 ^ V3;
1099 if (Cross1.Dot(Cross2) < 0)
1104 if (Cross1.Dot(Cross2) < 0)
1108 swap ( i, i + 1, idNodes, P );
1110 // for ( int ii = 0; ii < 4; ii++ ) {
1111 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1112 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1118 //=======================================================================
1119 //function : SortHexaNodes
1120 //purpose : Set 8 nodes of a hexahedron in a good order.
1121 // Return success status
1122 //=======================================================================
1124 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1129 DUMPSO( "INPUT: ========================================");
1130 for ( i = 0; i < 8; i++ ) {
1131 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1132 if ( !n ) return false;
1133 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1134 DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1136 DUMPSO( "========================================");
1139 set<int> faceNodes; // ids of bottom face nodes, to be found
1140 set<int> checkedId1; // ids of tried 2-nd nodes
1141 Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1142 const Standard_Real tol = 1.e-6; // tolerance to find nodes in plane
1143 int iMin, iLoop1 = 0;
1145 // Loop to try the 2-nd nodes
1147 while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1149 // Find not checked 2-nd node
1150 for ( i = 1; i < 8; i++ )
1151 if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1152 int id1 = idNodes[i];
1153 swap ( 1, i, idNodes, P );
1154 checkedId1.insert ( id1 );
1158 // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1159 // ie that all but meybe one (id3 which is on the same face) nodes
1160 // lay on the same side from the triangle plane.
1162 bool manyInPlane = false; // more than 4 nodes lay in plane
1164 while ( ++iLoop2 < 6 ) {
1166 // get 1-2-3 plane coeffs
1167 Standard_Real A, B, C, D;
1168 gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1169 if ( N.SquareMagnitude() > gp::Resolution() )
1171 gp_Pln pln ( P[0], N );
1172 pln.Coefficients( A, B, C, D );
1174 // find the node (iMin) closest to pln
1175 Standard_Real dist[ 8 ], minDist = DBL_MAX;
1177 for ( i = 3; i < 8; i++ ) {
1178 dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1179 if ( fabs( dist[i] ) < minDist ) {
1180 minDist = fabs( dist[i] );
1183 if ( fabs( dist[i] ) <= tol )
1184 idInPln.insert( idNodes[i] );
1187 // there should not be more than 4 nodes in bottom plane
1188 if ( idInPln.size() > 1 )
1190 DUMPSO( "### idInPln.size() = " << idInPln.size());
1191 // idInPlane does not contain the first 3 nodes
1192 if ( manyInPlane || idInPln.size() == 5)
1193 return false; // all nodes in one plane
1196 // set the 1-st node to be not in plane
1197 for ( i = 3; i < 8; i++ ) {
1198 if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1199 DUMPSO( "### Reset 0-th node");
1200 swap( 0, i, idNodes, P );
1205 // reset to re-check second nodes
1206 leastDist = DBL_MAX;
1210 break; // from iLoop2;
1213 // check that the other 4 nodes are on the same side
1214 bool sameSide = true;
1215 bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1216 for ( i = 3; sameSide && i < 8; i++ ) {
1218 sameSide = ( isNeg == dist[i] <= 0.);
1221 // keep best solution
1222 if ( sameSide && minDist < leastDist ) {
1223 leastDist = minDist;
1225 faceNodes.insert( idNodes[ 1 ] );
1226 faceNodes.insert( idNodes[ 2 ] );
1227 faceNodes.insert( idNodes[ iMin ] );
1228 DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1229 << " leastDist = " << leastDist);
1230 if ( leastDist <= DBL_MIN )
1235 // set next 3-d node to check
1236 int iNext = 2 + iLoop2;
1238 DUMPSO( "Try 2-nd");
1239 swap ( 2, iNext, idNodes, P );
1241 } // while ( iLoop2 < 6 )
1244 if ( faceNodes.empty() ) return false;
1246 // Put the faceNodes in proper places
1247 for ( i = 4; i < 8; i++ ) {
1248 if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1249 // find a place to put
1251 while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1253 DUMPSO( "Set faceNodes");
1254 swap ( iTo, i, idNodes, P );
1259 // Set nodes of the found bottom face in good order
1260 DUMPSO( " Found bottom face: ");
1261 i = SortQuadNodes( theMesh, idNodes );
1263 gp_Pnt Ptmp = P[ i ];
1268 // for ( int ii = 0; ii < 4; ii++ ) {
1269 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1270 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1273 // Gravity center of the top and bottom faces
1274 gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1275 gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1277 // Get direction from the bottom to the top face
1278 gp_Vec upDir ( aGCb, aGCt );
1279 Standard_Real upDirSize = upDir.Magnitude();
1280 if ( upDirSize <= gp::Resolution() ) return false;
1283 // Assure that the bottom face normal points up
1284 gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1285 Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1286 if ( Nb.Dot( upDir ) < 0 ) {
1287 DUMPSO( "Reverse bottom face");
1288 swap( 1, 3, idNodes, P );
1291 // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1292 Standard_Real minDist = DBL_MAX;
1293 for ( i = 4; i < 8; i++ ) {
1294 // projection of P[i] to the plane defined by P[0] and upDir
1295 gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1296 Standard_Real sqDist = P[0].SquareDistance( Pp );
1297 if ( sqDist < minDist ) {
1302 DUMPSO( "Set 4-th");
1303 swap ( 4, iMin, idNodes, P );
1305 // Set nodes of the top face in good order
1306 DUMPSO( "Sort top face");
1307 i = SortQuadNodes( theMesh, &idNodes[4] );
1310 gp_Pnt Ptmp = P[ i ];
1315 // Assure that direction of the top face normal is from the bottom face
1316 gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1317 Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1318 if ( Nt.Dot( upDir ) < 0 ) {
1319 DUMPSO( "Reverse top face");
1320 swap( 5, 7, idNodes, P );
1323 // DUMPSO( "OUTPUT: ========================================");
1324 // for ( i = 0; i < 8; i++ ) {
1325 // float *p = ugrid->GetPoint(idNodes[i]);
1326 // DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1332 //=======================================================================
1333 //function : laplacianSmooth
1334 //purpose : pulls theNode toward the center of surrounding nodes directly
1335 // connected to that node along an element edge
1336 //=======================================================================
1338 void laplacianSmooth(const SMDS_MeshNode* theNode,
1339 const Handle(Geom_Surface)& theSurface,
1340 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1342 // find surrounding nodes
1344 set< const SMDS_MeshNode* > nodeSet;
1345 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1346 while ( elemIt->more() )
1348 const SMDS_MeshElement* elem = elemIt->next();
1349 if ( elem->GetType() != SMDSAbs_Face )
1352 // put all nodes in array
1353 int nbNodes = 0, iNode = 0;
1354 vector< const SMDS_MeshNode*> aNodes( elem->NbNodes() );
1355 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1356 while ( itN->more() )
1358 aNodes[ nbNodes ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1359 if ( aNodes[ nbNodes ] == theNode )
1360 iNode = nbNodes; // index of theNode within aNodes
1364 int iAfter = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1365 nodeSet.insert( aNodes[ iAfter ]);
1366 int iBefore = ( iNode == 0 ) ? nbNodes - 1 : iNode - 1;
1367 nodeSet.insert( aNodes[ iBefore ]);
1370 // compute new coodrs
1372 double coord[] = { 0., 0., 0. };
1373 set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1374 for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1375 const SMDS_MeshNode* node = (*nodeSetIt);
1376 if ( theSurface.IsNull() ) { // smooth in 3D
1377 coord[0] += node->X();
1378 coord[1] += node->Y();
1379 coord[2] += node->Z();
1381 else { // smooth in 2D
1382 ASSERT( theUVMap.find( node ) != theUVMap.end() );
1383 gp_XY* uv = theUVMap[ node ];
1384 coord[0] += uv->X();
1385 coord[1] += uv->Y();
1388 int nbNodes = nodeSet.size();
1391 coord[0] /= nbNodes;
1392 coord[1] /= nbNodes;
1394 if ( !theSurface.IsNull() ) {
1395 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1396 theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
1397 gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
1403 coord[2] /= nbNodes;
1407 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
1410 //=======================================================================
1411 //function : centroidalSmooth
1412 //purpose : pulls theNode toward the element-area-weighted centroid of the
1413 // surrounding elements
1414 //=======================================================================
1416 void centroidalSmooth(const SMDS_MeshNode* theNode,
1417 const Handle(Geom_Surface)& theSurface,
1418 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1420 gp_XYZ aNewXYZ(0.,0.,0.);
1421 SMESH::Controls::Area anAreaFunc;
1422 double totalArea = 0.;
1427 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1428 while ( elemIt->more() )
1430 const SMDS_MeshElement* elem = elemIt->next();
1431 if ( elem->GetType() != SMDSAbs_Face )
1435 gp_XYZ elemCenter(0.,0.,0.);
1436 SMESH::Controls::TSequenceOfXYZ aNodePoints;
1437 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1438 while ( itN->more() )
1440 const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1441 gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1442 aNodePoints.push_back( aP );
1443 if ( !theSurface.IsNull() ) { // smooth in 2D
1444 ASSERT( theUVMap.find( aNode ) != theUVMap.end() );
1445 gp_XY* uv = theUVMap[ aNode ];
1446 aP.SetCoord( uv->X(), uv->Y(), 0. );
1450 double elemArea = anAreaFunc.GetValue( aNodePoints );
1451 totalArea += elemArea;
1452 elemCenter /= elem->NbNodes();
1453 aNewXYZ += elemCenter * elemArea;
1455 aNewXYZ /= totalArea;
1456 if ( !theSurface.IsNull() ) {
1457 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1458 theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
1459 aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
1464 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
1467 //=======================================================================
1468 //function : getClosestUV
1469 //purpose : return UV of closest projection
1470 //=======================================================================
1472 static bool getClosestUV (Extrema_GenExtPS& projector,
1473 const gp_Pnt& point,
1476 projector.Perform( point );
1477 if ( projector.IsDone() ) {
1478 double u, v, minVal = DBL_MAX;
1479 for ( int i = projector.NbExt(); i > 0; i-- )
1480 if ( projector.Value( i ) < minVal ) {
1481 minVal = projector.Value( i );
1482 projector.Point( i ).Parameter( u, v );
1484 result.SetCoord( u, v );
1490 //=======================================================================
1492 //purpose : Smooth theElements during theNbIterations or until a worst
1493 // element has aspect ratio <= theTgtAspectRatio.
1494 // Aspect Ratio varies in range [1.0, inf].
1495 // If theElements is empty, the whole mesh is smoothed.
1496 // theFixedNodes contains additionally fixed nodes. Nodes built
1497 // on edges and boundary nodes are always fixed.
1498 //=======================================================================
1500 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1501 set<const SMDS_MeshNode*> & theFixedNodes,
1502 const SmoothMethod theSmoothMethod,
1503 const int theNbIterations,
1504 double theTgtAspectRatio,
1507 MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1509 if ( theTgtAspectRatio < 1.0 )
1510 theTgtAspectRatio = 1.0;
1512 SMESH::Controls::AspectRatio aQualityFunc;
1514 SMESHDS_Mesh* aMesh = GetMeshDS();
1516 if ( theElems.empty() ) {
1517 // add all faces to theElems
1518 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1519 while ( fIt->more() )
1520 theElems.insert( fIt->next() );
1522 // get all face ids theElems are on
1523 set< int > faceIdSet;
1524 set< const SMDS_MeshElement* >::iterator itElem;
1526 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1527 int fId = FindShape( *itElem );
1528 // check that corresponding submesh exists and a shape is face
1530 faceIdSet.find( fId ) == faceIdSet.end() &&
1531 aMesh->MeshElements( fId )) {
1532 TopoDS_Shape F = aMesh->IndexToShape( fId );
1533 if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
1534 faceIdSet.insert( fId );
1537 faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
1539 // ===============================================
1540 // smooth elements on each TopoDS_Face separately
1541 // ===============================================
1543 set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
1544 for ( ; fId != faceIdSet.rend(); ++fId )
1546 // get face surface and submesh
1547 Handle(Geom_Surface) surface;
1548 SMESHDS_SubMesh* faceSubMesh = 0;
1550 double fToler2 = 0, vPeriod = 0., uPeriod = 0., f,l;
1551 double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
1552 bool isUPeriodic = false, isVPeriodic = false;
1554 face = TopoDS::Face( aMesh->IndexToShape( *fId ));
1555 surface = BRep_Tool::Surface( face );
1556 faceSubMesh = aMesh->MeshElements( *fId );
1557 fToler2 = BRep_Tool::Tolerance( face );
1558 fToler2 *= fToler2 * 10.;
1559 isUPeriodic = surface->IsUPeriodic();
1561 vPeriod = surface->UPeriod();
1562 isVPeriodic = surface->IsVPeriodic();
1564 uPeriod = surface->VPeriod();
1565 surface->Bounds( u1, u2, v1, v2 );
1567 // ---------------------------------------------------------
1568 // for elements on a face, find movable and fixed nodes and
1569 // compute UV for them
1570 // ---------------------------------------------------------
1571 bool checkBoundaryNodes = false;
1572 set<const SMDS_MeshNode*> setMovableNodes;
1573 map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
1574 list< gp_XY > listUV; // uvs the 2 uvMaps refer to
1575 list< const SMDS_MeshElement* > elemsOnFace;
1577 Extrema_GenExtPS projector;
1578 GeomAdaptor_Surface surfAdaptor;
1579 if ( !surface.IsNull() ) {
1580 surfAdaptor.Load( surface );
1581 projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
1583 int nbElemOnFace = 0;
1584 itElem = theElems.begin();
1585 // loop on not yet smoothed elements: look for elems on a face
1586 while ( itElem != theElems.end() )
1588 if ( faceSubMesh && nbElemOnFace == faceSubMesh->NbElements() )
1589 break; // all elements found
1591 const SMDS_MeshElement* elem = (*itElem);
1592 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
1593 ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
1597 elemsOnFace.push_back( elem );
1598 theElems.erase( itElem++ );
1601 // get movable nodes of elem
1602 const SMDS_MeshNode* node;
1603 SMDS_TypeOfPosition posType;
1604 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1605 while ( itN->more() ) {
1606 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1607 const SMDS_PositionPtr& pos = node->GetPosition();
1608 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1609 if (posType != SMDS_TOP_EDGE &&
1610 posType != SMDS_TOP_VERTEX &&
1611 theFixedNodes.find( node ) == theFixedNodes.end())
1613 // check if all faces around the node are on faceSubMesh
1614 // because a node on edge may be bound to face
1615 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1617 if ( faceSubMesh ) {
1618 while ( eIt->more() && all ) {
1619 const SMDS_MeshElement* e = eIt->next();
1620 if ( e->GetType() == SMDSAbs_Face )
1621 all = faceSubMesh->Contains( e );
1625 setMovableNodes.insert( node );
1627 checkBoundaryNodes = true;
1629 if ( posType == SMDS_TOP_3DSPACE )
1630 checkBoundaryNodes = true;
1633 if ( surface.IsNull() )
1636 // get nodes to check UV
1637 list< const SMDS_MeshNode* > uvCheckNodes;
1638 itN = elem->nodesIterator();
1639 while ( itN->more() ) {
1640 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1641 if ( uvMap.find( node ) == uvMap.end() )
1642 uvCheckNodes.push_back( node );
1643 // add nodes of elems sharing node
1644 // SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1645 // while ( eIt->more() ) {
1646 // const SMDS_MeshElement* e = eIt->next();
1647 // if ( e != elem && e->GetType() == SMDSAbs_Face ) {
1648 // SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1649 // while ( nIt->more() ) {
1650 // const SMDS_MeshNode* n =
1651 // static_cast<const SMDS_MeshNode*>( nIt->next() );
1652 // if ( uvMap.find( n ) == uvMap.end() )
1653 // uvCheckNodes.push_back( n );
1659 list< const SMDS_MeshNode* >::iterator n = uvCheckNodes.begin();
1660 for ( ; n != uvCheckNodes.end(); ++n )
1664 const SMDS_PositionPtr& pos = node->GetPosition();
1665 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1667 switch ( posType ) {
1668 case SMDS_TOP_FACE: {
1669 SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
1670 uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
1673 case SMDS_TOP_EDGE: {
1674 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1675 Handle(Geom2d_Curve) pcurve;
1676 if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
1677 pcurve = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), face, f,l );
1678 if ( !pcurve.IsNull() ) {
1679 double u = (( SMDS_EdgePosition* ) pos.get() )->GetUParameter();
1680 uv = pcurve->Value( u ).XY();
1684 case SMDS_TOP_VERTEX: {
1685 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1686 if ( !S.IsNull() && S.ShapeType() == TopAbs_VERTEX )
1687 uv = BRep_Tool::Parameters( TopoDS::Vertex( S ), face ).XY();
1692 // check existing UV
1693 bool project = true;
1694 gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
1695 double dist1 = DBL_MAX, dist2 = 0;
1696 if ( posType != SMDS_TOP_3DSPACE ) {
1697 dist1 = pNode.SquareDistance( surface->Value( uv.X(), uv.Y() ));
1698 project = dist1 > fToler2;
1700 if ( project ) { // compute new UV
1702 if ( !getClosestUV( projector, pNode, newUV )) {
1703 MESSAGE("Node Projection Failed " << node);
1707 newUV.SetX( ElCLib::InPeriod( newUV.X(), u1, u2 ));
1709 newUV.SetY( ElCLib::InPeriod( newUV.Y(), v1, v2 ));
1711 if ( posType != SMDS_TOP_3DSPACE )
1712 dist2 = pNode.SquareDistance( surface->Value( newUV.X(), newUV.Y() ));
1713 if ( dist2 < dist1 )
1717 // store UV in the map
1718 listUV.push_back( uv );
1719 uvMap.insert( make_pair( node, &listUV.back() ));
1721 } // loop on not yet smoothed elements
1723 if ( !faceSubMesh || nbElemOnFace != faceSubMesh->NbElements() )
1724 checkBoundaryNodes = true;
1726 // fix nodes on mesh boundary
1728 if ( checkBoundaryNodes )
1730 typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
1731 map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
1732 map< TLink, int >::iterator link_nb;
1733 // put all elements links to linkNbMap
1734 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1735 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1737 // put elem nodes in array
1738 vector< const SMDS_MeshNode* > nodes;
1739 nodes.reserve( (*elemIt)->NbNodes() + 1 );
1740 SMDS_ElemIteratorPtr itN = (*elemIt)->nodesIterator();
1741 while ( itN->more() )
1742 nodes.push_back( static_cast<const SMDS_MeshNode*>( itN->next() ));
1743 nodes.push_back( nodes.front() );
1744 // loop on elem links: insert them in linkNbMap
1745 for ( int iN = 1; iN < nodes.size(); ++iN ) {
1747 if ( nodes[ iN-1 ]->GetID() < nodes[ iN ]->GetID() )
1748 link = make_pair( nodes[ iN-1 ], nodes[ iN ] );
1750 link = make_pair( nodes[ iN ], nodes[ iN-1 ] );
1751 link_nb = linkNbMap.find( link );
1752 if ( link_nb == linkNbMap.end() )
1753 linkNbMap.insert( make_pair ( link, 1 ));
1758 // remove nodes that are in links encountered only once from setMovableNodes
1759 for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
1760 if ( link_nb->second == 1 ) {
1761 setMovableNodes.erase( link_nb->first.first );
1762 setMovableNodes.erase( link_nb->first.second );
1767 // -----------------------------------------------------
1768 // for nodes on seam edge, compute one more UV ( uvMap2 );
1769 // find movable nodes linked to nodes on seam and which
1770 // are to be smoothed using the second UV ( uvMap2 )
1771 // -----------------------------------------------------
1773 set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
1774 if ( !surface.IsNull() )
1776 TopExp_Explorer eExp( face, TopAbs_EDGE );
1777 for ( ; eExp.More(); eExp.Next() )
1779 TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
1780 if ( !BRep_Tool::IsClosed( edge, face ))
1782 SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
1783 if ( !sm ) continue;
1784 // find out which parameter varies for a node on seam
1787 Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1788 if ( pcurve.IsNull() ) continue;
1789 uv1 = pcurve->Value( f );
1791 pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1792 if ( pcurve.IsNull() ) continue;
1793 uv2 = pcurve->Value( f );
1794 int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
1796 if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
1797 gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
1799 // get nodes on seam and its vertices
1800 list< const SMDS_MeshNode* > seamNodes;
1801 SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
1802 while ( nSeamIt->more() )
1803 seamNodes.push_back( nSeamIt->next() );
1804 TopExp_Explorer vExp( edge, TopAbs_VERTEX );
1805 for ( ; vExp.More(); vExp.Next() ) {
1806 sm = aMesh->MeshElements( vExp.Current() );
1808 nSeamIt = sm->GetNodes();
1809 while ( nSeamIt->more() )
1810 seamNodes.push_back( nSeamIt->next() );
1813 // loop on nodes on seam
1814 list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
1815 for ( ; noSeIt != seamNodes.end(); ++noSeIt )
1817 const SMDS_MeshNode* nSeam = *noSeIt;
1818 map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
1819 if ( n_uv == uvMap.end() )
1822 n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
1823 // set the second UV
1824 listUV.push_back( *n_uv->second );
1825 listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
1826 if ( uvMap2.empty() )
1827 uvMap2 = uvMap; // copy the uvMap contents
1828 uvMap2[ nSeam ] = &listUV.back();
1830 // collect movable nodes linked to ones on seam in nodesNearSeam
1831 SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator();
1832 while ( eIt->more() )
1834 const SMDS_MeshElement* e = eIt->next();
1835 if ( e->GetType() != SMDSAbs_Face )
1837 int nbUseMap1 = 0, nbUseMap2 = 0;
1838 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1839 while ( nIt->more() )
1841 const SMDS_MeshNode* n =
1842 static_cast<const SMDS_MeshNode*>( nIt->next() );
1844 setMovableNodes.find( n ) == setMovableNodes.end() )
1846 // add only nodes being closer to uv2 than to uv1
1847 gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
1848 0.5 * ( n->Y() + nSeam->Y() ),
1849 0.5 * ( n->Z() + nSeam->Z() ));
1851 getClosestUV( projector, pMid, uv );
1852 if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
1853 nodesNearSeam.insert( n );
1859 // for centroidalSmooth all element nodes must
1860 // be on one side of a seam
1861 if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 )
1863 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1864 while ( nIt->more() ) {
1865 const SMDS_MeshNode* n =
1866 static_cast<const SMDS_MeshNode*>( nIt->next() );
1867 setMovableNodes.erase( n );
1871 } // loop on nodes on seam
1872 } // loop on edge of a face
1873 } // if ( !face.IsNull() )
1875 if ( setMovableNodes.empty() ) {
1876 MESSAGE( "Face id : " << *fId << " - NO SMOOTHING: no nodes to move!!!");
1877 continue; // goto next face
1885 double maxRatio = -1., maxDisplacement = -1.;
1886 set<const SMDS_MeshNode*>::iterator nodeToMove;
1887 for ( it = 0; it < theNbIterations; it++ )
1889 maxDisplacement = 0.;
1890 nodeToMove = setMovableNodes.begin();
1891 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1893 const SMDS_MeshNode* node = (*nodeToMove);
1894 gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1897 bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
1898 if ( theSmoothMethod == LAPLACIAN )
1899 laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
1901 centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
1903 // node displacement
1904 gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1905 Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1906 if ( aDispl > maxDisplacement )
1907 maxDisplacement = aDispl;
1909 // no node movement => exit
1910 if ( maxDisplacement < 1.e-16 ) {
1911 MESSAGE("-- no node movement --");
1915 // check elements quality
1917 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1918 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1920 const SMDS_MeshElement* elem = (*elemIt);
1921 if ( !elem || elem->GetType() != SMDSAbs_Face )
1923 SMESH::Controls::TSequenceOfXYZ aPoints;
1924 if ( aQualityFunc.GetPoints( elem, aPoints )) {
1925 double aValue = aQualityFunc.GetValue( aPoints );
1926 if ( aValue > maxRatio )
1930 if ( maxRatio <= theTgtAspectRatio ) {
1931 MESSAGE("-- quality achived --");
1934 if (it+1 == theNbIterations) {
1935 MESSAGE("-- Iteration limit exceeded --");
1937 } // smoothing iterations
1939 MESSAGE(" Face id: " << *fId <<
1940 " Nb iterstions: " << it <<
1941 " Displacement: " << maxDisplacement <<
1942 " Aspect Ratio " << maxRatio);
1944 // ---------------------------------------
1945 // new nodes positions are computed,
1946 // record movement in DS and set new UV
1947 // ---------------------------------------
1949 nodeToMove = setMovableNodes.begin();
1950 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1952 SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
1953 aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
1954 map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
1955 if ( node_uv != uvMap.end() ) {
1956 gp_XY* uv = node_uv->second;
1958 ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
1962 } // loop on face ids
1965 //=======================================================================
1966 //function : isReverse
1967 //purpose : Return true if normal of prevNodes is not co-directied with
1968 // gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1969 // iNotSame is where prevNodes and nextNodes are different
1970 //=======================================================================
1972 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1973 const SMDS_MeshNode* nextNodes[],
1977 int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1978 int iAfterNotSame = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1980 const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1981 const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1982 const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1983 const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1985 gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1986 gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1987 gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1988 gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1990 gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1992 return (vA ^ vB) * vN < 0.0;
1995 //=======================================================================
1996 //function : sweepElement
1998 //=======================================================================
2000 static void sweepElement(SMESHDS_Mesh* aMesh,
2001 const SMDS_MeshElement* elem,
2002 const vector<TNodeOfNodeListMapItr> & newNodesItVec,
2003 list<const SMDS_MeshElement*>& newElems)
2005 // Loop on elem nodes:
2006 // find new nodes and detect same nodes indices
2007 int nbNodes = elem->NbNodes();
2008 list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
2009 const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
2010 int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
2012 for ( iNode = 0; iNode < nbNodes; iNode++ )
2014 TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
2015 const SMDS_MeshNode* node = nnIt->first;
2016 const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
2017 if ( listNewNodes.empty() )
2020 itNN[ iNode ] = listNewNodes.begin();
2021 prevNod[ iNode ] = node;
2022 nextNod[ iNode ] = listNewNodes.front();
2023 if ( prevNod[ iNode ] != nextNod [ iNode ])
2024 iNotSameNode = iNode;
2030 if ( nbSame == nbNodes || nbSame > 2) {
2031 MESSAGE( " Too many same nodes of element " << elem->GetID() );
2035 int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
2037 iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
2038 iAfterSame = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
2039 iOpposSame = ( iSameNode - 2 < 0 ? iSameNode + 2 : iSameNode - 2 );
2042 // check element orientation
2044 if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
2045 //MESSAGE("Reversed elem " << elem );
2049 int iAB = iAfterSame + iBeforeSame;
2050 iBeforeSame = iAB - iBeforeSame;
2051 iAfterSame = iAB - iAfterSame;
2055 // make new elements
2056 int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
2057 for (iStep = 0; iStep < nbSteps; iStep++ )
2060 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2061 nextNod[ iNode ] = *itNN[ iNode ];
2064 SMDS_MeshElement* aNewElem = 0;
2071 aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
2077 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2078 nextNod[ 1 ], nextNod[ 0 ] );
2080 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2081 nextNod[ iNotSameNode ] );
2084 case 3: { // TRIANGLE
2086 if ( nbSame == 0 ) // --- pentahedron
2087 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2088 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
2090 else if ( nbSame == 1 ) // --- pyramid
2091 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2092 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2093 nextNod[ iSameNode ]);
2095 else // 2 same nodes: --- tetrahedron
2096 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2097 nextNod[ iNotSameNode ]);
2100 case 4: { // QUADRANGLE
2102 if ( nbSame == 0 ) // --- hexahedron
2103 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
2104 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
2106 else if ( nbSame == 1 ) // --- pyramid + pentahedron
2108 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2109 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2110 nextNod[ iSameNode ]);
2111 newElems.push_back( aNewElem );
2112 aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iOpposSame ],
2113 prevNod[ iBeforeSame ], nextNod[ iAfterSame ],
2114 nextNod[ iOpposSame ], nextNod[ iBeforeSame ] );
2116 else if ( nbSame == 2 ) // pentahedron
2118 if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
2119 // iBeforeSame is same too
2120 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
2121 nextNod[ iOpposSame ], prevNod[ iSameNode ],
2122 prevNod[ iAfterSame ], nextNod[ iAfterSame ]);
2124 // iAfterSame is same too
2125 aNewElem = aMesh->AddVolume (prevNod[ iSameNode ], prevNod[ iBeforeSame ],
2126 nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
2127 prevNod[ iOpposSame ], nextNod[ iOpposSame ]);
2132 // realized for extrusion only
2133 vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2134 vector<int> quantities (nbNodes + 2);
2136 quantities[0] = nbNodes; // bottom of prism
2137 for (int inode = 0; inode < nbNodes; inode++) {
2138 polyedre_nodes[inode] = prevNod[inode];
2141 quantities[1] = nbNodes; // top of prism
2142 for (int inode = 0; inode < nbNodes; inode++) {
2143 polyedre_nodes[nbNodes + inode] = nextNod[inode];
2146 for (int iface = 0; iface < nbNodes; iface++) {
2147 quantities[iface + 2] = 4;
2148 int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2149 polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2150 polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2151 polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2152 polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2154 aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2158 newElems.push_back( aNewElem );
2160 // set new prev nodes
2161 for ( iNode = 0; iNode < nbNodes; iNode++ )
2162 prevNod[ iNode ] = nextNod[ iNode ];
2167 //=======================================================================
2168 //function : makeWalls
2169 //purpose : create 1D and 2D elements around swept elements
2170 //=======================================================================
2172 static void makeWalls (SMESHDS_Mesh* aMesh,
2173 TNodeOfNodeListMap & mapNewNodes,
2174 TElemOfElemListMap & newElemsMap,
2175 TElemOfVecOfNnlmiMap & elemNewNodesMap,
2176 set<const SMDS_MeshElement*>& elemSet)
2178 ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
2180 // Find nodes belonging to only one initial element - sweep them to get edges.
2182 TNodeOfNodeListMapItr nList = mapNewNodes.begin();
2183 for ( ; nList != mapNewNodes.end(); nList++ )
2185 const SMDS_MeshNode* node =
2186 static_cast<const SMDS_MeshNode*>( nList->first );
2187 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2188 int nbInitElems = 0;
2189 while ( eIt->more() && nbInitElems < 2 )
2190 if ( elemSet.find( eIt->next() ) != elemSet.end() )
2192 if ( nbInitElems < 2 ) {
2193 vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2194 list<const SMDS_MeshElement*> newEdges;
2195 sweepElement( aMesh, node, newNodesItVec, newEdges );
2199 // Make a ceiling for each element ie an equal element of last new nodes.
2200 // Find free links of faces - make edges and sweep them into faces.
2202 TElemOfElemListMap::iterator itElem = newElemsMap.begin();
2203 TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2204 for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
2206 const SMDS_MeshElement* elem = itElem->first;
2207 vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2209 if ( elem->GetType() == SMDSAbs_Edge )
2211 // create a ceiling edge
2212 aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2213 vecNewNodes[ 1 ]->second.back() );
2215 if ( elem->GetType() != SMDSAbs_Face )
2218 bool hasFreeLinks = false;
2220 set<const SMDS_MeshElement*> avoidSet;
2221 avoidSet.insert( elem );
2223 // loop on a face nodes
2224 set<const SMDS_MeshNode*> aFaceLastNodes;
2225 int iNode, nbNodes = vecNewNodes.size();
2226 for ( iNode = 0; iNode < nbNodes; iNode++ )
2228 aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
2229 // look for free links of a face
2230 int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
2231 const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
2232 const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
2233 // check if a link is free
2234 if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
2236 hasFreeLinks = true;
2237 // make an edge and a ceiling for a new edge
2238 if ( !aMesh->FindEdge( n1, n2 ))
2239 aMesh->AddEdge( n1, n2 );
2240 n1 = vecNewNodes[ iNode ]->second.back();
2241 n2 = vecNewNodes[ iNext ]->second.back();
2242 if ( !aMesh->FindEdge( n1, n2 ))
2243 aMesh->AddEdge( n1, n2 );
2246 // sweep free links into faces
2250 list<const SMDS_MeshElement*> & newVolumes = itElem->second;
2251 int iStep, nbSteps = vecNewNodes[0]->second.size();
2252 int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
2254 set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
2255 for ( iNode = 0; iNode < nbNodes; iNode++ )
2256 initNodeSet.insert( vecNewNodes[ iNode ]->first );
2258 for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
2260 list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
2262 while ( iVol++ < volNb ) v++;
2263 // find indices of free faces of a volume
2265 SMDS_VolumeTool vTool( *v );
2266 int iF, nbF = vTool.NbFaces();
2267 for ( iF = 0; iF < nbF; iF ++ )
2268 if (vTool.IsFreeFace( iF ) &&
2269 vTool.GetFaceNodes( iF, faceNodeSet ) &&
2270 initNodeSet != faceNodeSet) // except an initial face
2271 fInd.push_back( iF );
2275 // create faces for all steps
2276 for ( iStep = 0; iStep < nbSteps; iStep++ )
2279 vTool.SetExternalNormal();
2280 list< int >::iterator ind = fInd.begin();
2281 for ( ; ind != fInd.end(); ind++ )
2283 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
2284 switch ( vTool.NbFaceNodes( *ind ) ) {
2286 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
2288 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
2291 int nbPolygonNodes = vTool.NbFaceNodes( *ind );
2292 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2293 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2294 polygon_nodes[inode] = nodes[inode];
2296 aMesh->AddPolygonalFace(polygon_nodes);
2301 // go to the next volume
2303 while ( iVol++ < nbVolumesByStep ) v++;
2306 } // sweep free links into faces
2308 // make a ceiling face with a normal external to a volume
2310 SMDS_VolumeTool lastVol( itElem->second.back() );
2311 int iF = lastVol.GetFaceIndex( aFaceLastNodes );
2314 lastVol.SetExternalNormal();
2315 const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
2316 switch ( lastVol.NbFaceNodes( iF ) ) {
2318 if (!hasFreeLinks ||
2319 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
2320 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2323 if (!hasFreeLinks ||
2324 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
2325 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] );
2329 int nbPolygonNodes = lastVol.NbFaceNodes( iF );
2330 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2331 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2332 polygon_nodes[inode] = nodes[inode];
2334 if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
2335 aMesh->AddPolygonalFace(polygon_nodes);
2341 } // loop on swept elements
2344 //=======================================================================
2345 //function : RotationSweep
2347 //=======================================================================
2349 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
2350 const gp_Ax1& theAxis,
2351 const double theAngle,
2352 const int theNbSteps,
2353 const double theTol)
2355 MESSAGE( "RotationSweep()");
2357 aTrsf.SetRotation( theAxis, theAngle );
2359 gp_Lin aLine( theAxis );
2360 double aSqTol = theTol * theTol;
2362 SMESHDS_Mesh* aMesh = GetMeshDS();
2364 TNodeOfNodeListMap mapNewNodes;
2365 TElemOfVecOfNnlmiMap mapElemNewNodes;
2366 TElemOfElemListMap newElemsMap;
2369 set< const SMDS_MeshElement* >::iterator itElem;
2370 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2372 const SMDS_MeshElement* elem = (*itElem);
2375 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2376 newNodesItVec.reserve( elem->NbNodes() );
2378 // loop on elem nodes
2379 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2380 while ( itN->more() ) {
2382 // check if a node has been already sweeped
2383 const SMDS_MeshNode* node =
2384 static_cast<const SMDS_MeshNode*>( itN->next() );
2385 TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
2386 if ( nIt == mapNewNodes.end() )
2388 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2389 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2392 gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
2394 aXYZ.Coord( coord[0], coord[1], coord[2] );
2395 bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
2396 const SMDS_MeshNode * newNode = node;
2397 for ( int i = 0; i < theNbSteps; i++ ) {
2399 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2400 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2402 listNewNodes.push_back( newNode );
2405 newNodesItVec.push_back( nIt );
2407 // make new elements
2408 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2411 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2416 //=======================================================================
2417 //function : CreateNode
2419 //=======================================================================
2420 const SMDS_MeshNode* SMESH_MeshEditor::CreateNode(const double x,
2423 const double tolnode,
2424 SMESH_SequenceOfNode& aNodes)
2427 SMESHDS_Mesh * aMesh = myMesh->GetMeshDS();
2429 // try to search in sequence of existing nodes
2430 // if aNodes.Length()>0 we 'nave to use given sequence
2431 // else - use all nodes of mesh
2432 if(aNodes.Length()>0) {
2434 for(i=1; i<=aNodes.Length(); i++) {
2435 gp_Pnt P2(aNodes.Value(i)->X(),aNodes.Value(i)->Y(),aNodes.Value(i)->Z());
2436 if(P1.Distance(P2)<tolnode)
2437 return aNodes.Value(i);
2441 SMDS_NodeIteratorPtr itn = aMesh->nodesIterator();
2442 while(itn->more()) {
2443 const SMDS_MeshNode* aN = static_cast<const SMDS_MeshNode*> (itn->next());
2444 gp_Pnt P2(aN->X(),aN->Y(),aN->Z());
2445 if(P1.Distance(P2)<tolnode)
2450 // create new node and return it
2451 const SMDS_MeshNode* NewNode = aMesh->AddNode(x,y,z);
2456 //=======================================================================
2457 //function : ExtrusionSweep
2459 //=======================================================================
2461 void SMESH_MeshEditor::ExtrusionSweep
2462 (set<const SMDS_MeshElement*> & theElems,
2463 const gp_Vec& theStep,
2464 const int theNbSteps,
2465 TElemOfElemListMap& newElemsMap,
2467 const double theTolerance)
2469 ExtrusParam aParams;
2470 aParams.myDir = gp_Dir(theStep);
2471 aParams.myNodes.Clear();
2472 aParams.mySteps = new TColStd_HSequenceOfReal;
2474 for(i=1; i<=theNbSteps; i++)
2475 aParams.mySteps->Append(theStep.Magnitude());
2477 ExtrusionSweep(theElems,aParams,newElemsMap,theFlags,theTolerance);
2482 //=======================================================================
2483 //function : ExtrusionSweep
2485 //=======================================================================
2487 void SMESH_MeshEditor::ExtrusionSweep
2488 (set<const SMDS_MeshElement*> & theElems,
2489 ExtrusParam& theParams,
2490 TElemOfElemListMap& newElemsMap,
2492 const double theTolerance)
2494 SMESHDS_Mesh* aMesh = GetMeshDS();
2496 TNodeOfNodeListMap mapNewNodes;
2497 TElemOfVecOfNnlmiMap mapElemNewNodes;
2500 set< const SMDS_MeshElement* >::iterator itElem;
2501 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2503 // check element type
2504 const SMDS_MeshElement* elem = (*itElem);
2508 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2509 newNodesItVec.reserve( elem->NbNodes() );
2511 // loop on elem nodes
2512 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2513 while ( itN->more() ) {
2515 // check if a node has been already sweeped
2516 const SMDS_MeshNode* node =
2517 static_cast<const SMDS_MeshNode*>( itN->next() );
2518 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2519 if ( nIt == mapNewNodes.end() )
2521 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2522 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2525 double coord[] = { node->X(), node->Y(), node->Z() };
2526 int nbsteps = theParams.mySteps->Length();
2527 for ( int i = 0; i < nbsteps; i++ ) {
2528 //aTrsf.Transforms( coord[0], coord[1], coord[2] );
2529 coord[0] = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
2530 coord[1] = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
2531 coord[2] = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
2532 if( theFlags & EXTRUSION_FLAG_SEW ) {
2533 const SMDS_MeshNode * newNode = CreateNode(coord[0], coord[1], coord[2],
2534 theTolerance, theParams.myNodes);
2535 listNewNodes.push_back( newNode );
2538 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2539 listNewNodes.push_back( newNode );
2543 newNodesItVec.push_back( nIt );
2545 // make new elements
2546 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2548 if( theFlags & EXTRUSION_FLAG_BOUNDARY ) {
2549 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2554 //=======================================================================
2555 //class : SMESH_MeshEditor_PathPoint
2556 //purpose : auxiliary class
2557 //=======================================================================
2558 class SMESH_MeshEditor_PathPoint {
2560 SMESH_MeshEditor_PathPoint() {
2561 myPnt.SetCoord(99., 99., 99.);
2562 myTgt.SetCoord(1.,0.,0.);
2566 void SetPnt(const gp_Pnt& aP3D){
2569 void SetTangent(const gp_Dir& aTgt){
2572 void SetAngle(const double& aBeta){
2575 void SetParameter(const double& aPrm){
2578 const gp_Pnt& Pnt()const{
2581 const gp_Dir& Tangent()const{
2584 double Angle()const{
2587 double Parameter()const{
2598 //=======================================================================
2599 //function : ExtrusionAlongTrack
2601 //=======================================================================
2602 SMESH_MeshEditor::Extrusion_Error
2603 SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2604 SMESH_subMesh* theTrack,
2605 const SMDS_MeshNode* theN1,
2606 const bool theHasAngles,
2607 std::list<double>& theAngles,
2608 const bool theHasRefPoint,
2609 const gp_Pnt& theRefPoint)
2611 MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2612 int j, aNbTP, aNbE, aNb;
2613 double aT1, aT2, aT, aAngle, aX, aY, aZ;
2614 std::list<double> aPrms;
2615 std::list<double>::iterator aItD;
2616 std::set< const SMDS_MeshElement* >::iterator itElem;
2618 Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2622 Handle(Geom_Curve) aC3D;
2623 TopoDS_Edge aTrackEdge;
2624 TopoDS_Vertex aV1, aV2;
2626 SMDS_ElemIteratorPtr aItE;
2627 SMDS_NodeIteratorPtr aItN;
2628 SMDSAbs_ElementType aTypeE;
2630 TNodeOfNodeListMap mapNewNodes;
2631 TElemOfVecOfNnlmiMap mapElemNewNodes;
2632 TElemOfElemListMap newElemsMap;
2635 aTolVec2=aTolVec*aTolVec;
2638 aNbE = theElements.size();
2641 return EXTR_NO_ELEMENTS;
2643 // 1.1 Track Pattern
2646 SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2648 aItE = pSubMeshDS->GetElements();
2649 while ( aItE->more() ) {
2650 const SMDS_MeshElement* pE = aItE->next();
2651 aTypeE = pE->GetType();
2652 // Pattern must contain links only
2653 if ( aTypeE != SMDSAbs_Edge )
2654 return EXTR_PATH_NOT_EDGE;
2657 const TopoDS_Shape& aS = theTrack->GetSubShape();
2658 // Sub shape for the Pattern must be an Edge
2659 if ( aS.ShapeType() != TopAbs_EDGE )
2660 return EXTR_BAD_PATH_SHAPE;
2662 aTrackEdge = TopoDS::Edge( aS );
2663 // the Edge must not be degenerated
2664 if ( BRep_Tool::Degenerated( aTrackEdge ) )
2665 return EXTR_BAD_PATH_SHAPE;
2667 TopExp::Vertices( aTrackEdge, aV1, aV2 );
2668 aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2669 aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2671 aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2672 const SMDS_MeshNode* aN1 = aItN->next();
2674 aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2675 const SMDS_MeshNode* aN2 = aItN->next();
2677 // starting node must be aN1 or aN2
2678 if ( !( aN1 == theN1 || aN2 == theN1 ) )
2679 return EXTR_BAD_STARTING_NODE;
2681 aNbTP = pSubMeshDS->NbNodes() + 2;
2684 vector<double> aAngles( aNbTP );
2686 for ( j=0; j < aNbTP; ++j ) {
2690 if ( theHasAngles ) {
2691 aItD = theAngles.begin();
2692 for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2694 aAngles[j] = aAngle;
2698 // 2. Collect parameters on the track edge
2699 aPrms.push_back( aT1 );
2700 aPrms.push_back( aT2 );
2702 aItN = pSubMeshDS->GetNodes();
2703 while ( aItN->more() ) {
2704 const SMDS_MeshNode* pNode = aItN->next();
2705 const SMDS_EdgePosition* pEPos =
2706 static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2707 aT = pEPos->GetUParameter();
2708 aPrms.push_back( aT );
2713 if ( aN1 == theN1 ) {
2725 SMESH_MeshEditor_PathPoint aPP;
2726 vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2728 aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2730 aItD = aPrms.begin();
2731 for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2733 aC3D->D1( aT, aP3D, aVec );
2734 aL2 = aVec.SquareMagnitude();
2735 if ( aL2 < aTolVec2 )
2736 return EXTR_CANT_GET_TANGENT;
2738 gp_Dir aTgt( aVec );
2739 aAngle = aAngles[j];
2742 aPP.SetTangent( aTgt );
2743 aPP.SetAngle( aAngle );
2744 aPP.SetParameter( aT );
2748 // 3. Center of rotation aV0
2750 if ( !theHasRefPoint ) {
2752 aGC.SetCoord( 0.,0.,0. );
2754 itElem = theElements.begin();
2755 for ( ; itElem != theElements.end(); itElem++ ) {
2756 const SMDS_MeshElement* elem = (*itElem);
2758 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2759 while ( itN->more() ) {
2760 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2765 if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2766 list<const SMDS_MeshNode*> aLNx;
2767 mapNewNodes[node] = aLNx;
2769 gp_XYZ aXYZ( aX, aY, aZ );
2777 } // if (!theHasRefPoint) {
2778 mapNewNodes.clear();
2780 // 4. Processing the elements
2781 SMESHDS_Mesh* aMesh = GetMeshDS();
2783 for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2784 // check element type
2785 const SMDS_MeshElement* elem = (*itElem);
2786 aTypeE = elem->GetType();
2787 if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2790 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2791 newNodesItVec.reserve( elem->NbNodes() );
2793 // loop on elem nodes
2794 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2795 while ( itN->more() ) {
2797 // check if a node has been already processed
2798 const SMDS_MeshNode* node =
2799 static_cast<const SMDS_MeshNode*>( itN->next() );
2800 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2801 if ( nIt == mapNewNodes.end() ) {
2802 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2803 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2806 aX = node->X(); aY = node->Y(); aZ = node->Z();
2808 Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2809 gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2810 gp_Ax1 anAx1, anAxT1T0;
2811 gp_Dir aDT1x, aDT0x, aDT1T0;
2816 aPN0.SetCoord(aX, aY, aZ);
2818 const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2820 aDT0x= aPP0.Tangent();
2822 for ( j = 1; j < aNbTP; ++j ) {
2823 const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2825 aDT1x = aPP1.Tangent();
2826 aAngle1x = aPP1.Angle();
2828 gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
2830 gp_Vec aV01x( aP0x, aP1x );
2831 aTrsf.SetTranslation( aV01x );
2834 aV1x = aV0x.Transformed( aTrsf );
2835 aPN1 = aPN0.Transformed( aTrsf );
2837 // rotation 1 [ T1,T0 ]
2838 aAngleT1T0=-aDT1x.Angle( aDT0x );
2839 if (fabs(aAngleT1T0) > aTolAng) {
2841 anAxT1T0.SetLocation( aV1x );
2842 anAxT1T0.SetDirection( aDT1T0 );
2843 aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2845 aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2849 if ( theHasAngles ) {
2850 anAx1.SetLocation( aV1x );
2851 anAx1.SetDirection( aDT1x );
2852 aTrsfRot.SetRotation( anAx1, aAngle1x );
2854 aPN1 = aPN1.Transformed( aTrsfRot );
2861 const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2862 listNewNodes.push_back( newNode );
2870 newNodesItVec.push_back( nIt );
2872 // make new elements
2873 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2876 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2881 //=======================================================================
2882 //function : Transform
2884 //=======================================================================
2886 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2887 const gp_Trsf& theTrsf,
2891 switch ( theTrsf.Form() ) {
2897 needReverse = false;
2900 SMESHDS_Mesh* aMesh = GetMeshDS();
2902 // map old node to new one
2903 TNodeNodeMap nodeMap;
2905 // elements sharing moved nodes; those of them which have all
2906 // nodes mirrored but are not in theElems are to be reversed
2907 set<const SMDS_MeshElement*> inverseElemSet;
2910 set< const SMDS_MeshElement* >::iterator itElem;
2911 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2913 const SMDS_MeshElement* elem = (*itElem);
2917 // loop on elem nodes
2918 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2919 while ( itN->more() ) {
2921 // check if a node has been already transformed
2922 const SMDS_MeshNode* node =
2923 static_cast<const SMDS_MeshNode*>( itN->next() );
2924 if (nodeMap.find( node ) != nodeMap.end() )
2928 coord[0] = node->X();
2929 coord[1] = node->Y();
2930 coord[2] = node->Z();
2931 theTrsf.Transforms( coord[0], coord[1], coord[2] );
2932 const SMDS_MeshNode * newNode = node;
2934 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2936 aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2937 // node position on shape becomes invalid
2938 const_cast< SMDS_MeshNode* > ( node )->SetPosition
2939 ( SMDS_SpacePosition::originSpacePosition() );
2941 nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2943 // keep inverse elements
2944 if ( !theCopy && needReverse ) {
2945 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2946 while ( invElemIt->more() )
2947 inverseElemSet.insert( invElemIt->next() );
2952 // either new elements are to be created
2953 // or a mirrored element are to be reversed
2954 if ( !theCopy && !needReverse)
2957 if ( !inverseElemSet.empty()) {
2958 set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2959 for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2960 theElems.insert( *invElemIt );
2963 // replicate or reverse elements
2966 REV_TETRA = 0, // = nbNodes - 4
2967 REV_PYRAMID = 1, // = nbNodes - 4
2968 REV_PENTA = 2, // = nbNodes - 4
2970 REV_HEXA = 4, // = nbNodes - 4
2974 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_TETRA
2975 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_PYRAMID
2976 { 2, 1, 0, 5, 4, 3, 0, 0 }, // REV_PENTA
2977 { 2, 1, 0, 3, 0, 0, 0, 0 }, // REV_FACE
2978 { 2, 1, 0, 3, 6, 5, 4, 7 }, // REV_HEXA
2979 { 0, 1, 2, 3, 4, 5, 6, 7 } // FORWARD
2982 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2984 const SMDS_MeshElement* elem = (*itElem);
2985 if ( !elem || elem->GetType() == SMDSAbs_Node )
2988 int nbNodes = elem->NbNodes();
2989 int elemType = elem->GetType();
2991 if (elem->IsPoly()) {
2992 // Polygon or Polyhedral Volume
2993 switch ( elemType ) {
2996 vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
2998 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2999 while (itN->more()) {
3000 const SMDS_MeshNode* node =
3001 static_cast<const SMDS_MeshNode*>(itN->next());
3002 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
3003 if (nodeMapIt == nodeMap.end())
3004 break; // not all nodes transformed
3006 // reverse mirrored faces and volumes
3007 poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
3009 poly_nodes[iNode] = (*nodeMapIt).second;
3013 if ( iNode != nbNodes )
3014 continue; // not all nodes transformed
3017 aMesh->AddPolygonalFace(poly_nodes);
3019 aMesh->ChangePolygonNodes(elem, poly_nodes);
3023 case SMDSAbs_Volume:
3025 // ATTENTION: Reversing is not yet done!!!
3026 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3027 (const SMDS_PolyhedralVolumeOfNodes*) elem;
3029 MESSAGE("Warning: bad volumic element");
3033 vector<const SMDS_MeshNode*> poly_nodes;
3034 vector<int> quantities;
3036 bool allTransformed = true;
3037 int nbFaces = aPolyedre->NbFaces();
3038 for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
3039 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3040 for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
3041 const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
3042 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
3043 if (nodeMapIt == nodeMap.end()) {
3044 allTransformed = false; // not all nodes transformed
3046 poly_nodes.push_back((*nodeMapIt).second);
3049 quantities.push_back(nbFaceNodes);
3051 if ( !allTransformed )
3052 continue; // not all nodes transformed
3055 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
3057 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3067 int* i = index[ FORWARD ];
3068 if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
3069 if ( elemType == SMDSAbs_Face )
3070 i = index[ REV_FACE ];
3072 i = index[ nbNodes - 4 ];
3074 // find transformed nodes
3075 const SMDS_MeshNode* nodes[8];
3077 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3078 while ( itN->more() )
3080 const SMDS_MeshNode* node =
3081 static_cast<const SMDS_MeshNode*>( itN->next() );
3082 TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
3083 if ( nodeMapIt == nodeMap.end() )
3084 break; // not all nodes transformed
3085 nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
3087 if ( iNode != nbNodes )
3088 continue; // not all nodes transformed
3092 // add a new element
3093 switch ( elemType ) {
3095 aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
3099 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
3101 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
3103 case SMDSAbs_Volume:
3105 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
3106 else if ( nbNodes == 8 )
3107 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3108 nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
3109 else if ( nbNodes == 6 )
3110 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3111 nodes[ 4 ], nodes[ 5 ]);
3112 else if ( nbNodes == 5 )
3113 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3121 // reverse element as it was reversed by transformation
3123 aMesh->ChangeElementNodes( elem, nodes, nbNodes );
3128 //=======================================================================
3129 //function : FindCoincidentNodes
3130 //purpose : Return list of group of nodes close to each other within theTolerance
3131 // Search among theNodes or in the whole mesh if theNodes is empty.
3132 //=======================================================================
3134 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
3135 const double theTolerance,
3136 TListOfListOfNodes & theGroupsOfNodes)
3138 double tol2 = theTolerance * theTolerance;
3140 list<const SMDS_MeshNode*> nodes;
3141 if ( theNodes.empty() )
3142 { // get all nodes in the mesh
3143 SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
3144 while ( nIt->more() )
3145 nodes.push_back( nIt->next() );
3149 nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
3152 list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
3153 for ( ; it1 != nodes.end(); it1++ )
3155 const SMDS_MeshNode* n1 = *it1;
3156 gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
3158 list<const SMDS_MeshNode*> * groupPtr = 0;
3160 for ( it2++; it2 != nodes.end(); it2++ )
3162 const SMDS_MeshNode* n2 = *it2;
3163 gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
3164 if ( p1.SquareDistance( p2 ) <= tol2 )
3167 theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
3168 groupPtr = & theGroupsOfNodes.back();
3169 groupPtr->push_back( n1 );
3171 groupPtr->push_back( n2 );
3172 it2 = nodes.erase( it2 );
3179 //=======================================================================
3180 //function : SimplifyFace
3182 //=======================================================================
3183 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
3184 vector<const SMDS_MeshNode *>& poly_nodes,
3185 vector<int>& quantities) const
3187 int nbNodes = faceNodes.size();
3192 set<const SMDS_MeshNode*> nodeSet;
3194 // get simple seq of nodes
3195 const SMDS_MeshNode* simpleNodes[ nbNodes ];
3196 int iSimple = 0, nbUnique = 0;
3198 simpleNodes[iSimple++] = faceNodes[0];
3200 for (int iCur = 1; iCur < nbNodes; iCur++) {
3201 if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
3202 simpleNodes[iSimple++] = faceNodes[iCur];
3203 if (nodeSet.insert( faceNodes[iCur] ).second)
3207 int nbSimple = iSimple;
3208 if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
3218 bool foundLoop = (nbSimple > nbUnique);
3221 set<const SMDS_MeshNode*> loopSet;
3222 for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
3223 const SMDS_MeshNode* n = simpleNodes[iSimple];
3224 if (!loopSet.insert( n ).second) {
3228 int iC = 0, curLast = iSimple;
3229 for (; iC < curLast; iC++) {
3230 if (simpleNodes[iC] == n) break;
3232 int loopLen = curLast - iC;
3234 // create sub-element
3236 quantities.push_back(loopLen);
3237 for (; iC < curLast; iC++) {
3238 poly_nodes.push_back(simpleNodes[iC]);
3241 // shift the rest nodes (place from the first loop position)
3242 for (iC = curLast + 1; iC < nbSimple; iC++) {
3243 simpleNodes[iC - loopLen] = simpleNodes[iC];
3245 nbSimple -= loopLen;
3248 } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
3249 } // while (foundLoop)
3253 quantities.push_back(iSimple);
3254 for (int i = 0; i < iSimple; i++)
3255 poly_nodes.push_back(simpleNodes[i]);
3261 //=======================================================================
3262 //function : MergeNodes
3263 //purpose : In each group, the cdr of nodes are substituted by the first one
3265 //=======================================================================
3267 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
3269 SMESHDS_Mesh* aMesh = GetMeshDS();
3271 TNodeNodeMap nodeNodeMap; // node to replace - new node
3272 set<const SMDS_MeshElement*> elems; // all elements with changed nodes
3273 list< int > rmElemIds, rmNodeIds;
3275 // Fill nodeNodeMap and elems
3277 TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
3278 for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
3280 list<const SMDS_MeshNode*>& nodes = *grIt;
3281 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
3282 const SMDS_MeshNode* nToKeep = *nIt;
3283 for ( ; nIt != nodes.end(); nIt++ )
3285 const SMDS_MeshNode* nToRemove = *nIt;
3286 nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
3287 if ( nToRemove != nToKeep ) {
3288 rmNodeIds.push_back( nToRemove->GetID() );
3289 AddToSameGroups( nToKeep, nToRemove, aMesh );
3292 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3293 while ( invElemIt->more() )
3294 elems.insert( invElemIt->next() );
3297 // Change element nodes or remove an element
3299 set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
3300 for ( ; eIt != elems.end(); eIt++ )
3302 const SMDS_MeshElement* elem = *eIt;
3303 int nbNodes = elem->NbNodes();
3304 int aShapeId = FindShape( elem );
3306 set<const SMDS_MeshNode*> nodeSet;
3307 const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
3308 int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
3310 // get new seq of nodes
3311 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3312 while ( itN->more() )
3314 const SMDS_MeshNode* n =
3315 static_cast<const SMDS_MeshNode*>( itN->next() );
3317 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
3318 if ( nnIt != nodeNodeMap.end() ) { // n sticks
3320 iRepl[ nbRepl++ ] = iCur;
3322 curNodes[ iCur ] = n;
3323 bool isUnique = nodeSet.insert( n ).second;
3325 uniqueNodes[ iUnique++ ] = n;
3329 // Analyse element topology after replacement
3332 int nbUniqueNodes = nodeSet.size();
3333 if ( nbNodes != nbUniqueNodes ) // some nodes stick
3335 // Polygons and Polyhedral volumes
3336 if (elem->IsPoly()) {
3338 if (elem->GetType() == SMDSAbs_Face) {
3340 vector<const SMDS_MeshNode *> face_nodes (nbNodes);
3342 for (; inode < nbNodes; inode++) {
3343 face_nodes[inode] = curNodes[inode];
3346 vector<const SMDS_MeshNode *> polygons_nodes;
3347 vector<int> quantities;
3348 int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
3352 for (int iface = 0; iface < nbNew - 1; iface++) {
3353 int nbNodes = quantities[iface];
3354 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
3355 for (int ii = 0; ii < nbNodes; ii++, inode++) {
3356 poly_nodes[ii] = polygons_nodes[inode];
3358 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
3360 aMesh->SetMeshElementOnShape(newElem, aShapeId);
3362 aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
3364 rmElemIds.push_back(elem->GetID());
3367 } else if (elem->GetType() == SMDSAbs_Volume) {
3368 // Polyhedral volume
3369 if (nbUniqueNodes < 4) {
3370 rmElemIds.push_back(elem->GetID());
3372 // each face has to be analized in order to check volume validity
3373 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3374 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3376 int nbFaces = aPolyedre->NbFaces();
3378 vector<const SMDS_MeshNode *> poly_nodes;
3379 vector<int> quantities;
3381 for (int iface = 1; iface <= nbFaces; iface++) {
3382 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3383 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
3385 for (int inode = 1; inode <= nbFaceNodes; inode++) {
3386 const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
3387 TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
3388 if (nnIt != nodeNodeMap.end()) { // faceNode sticks
3389 faceNode = (*nnIt).second;
3391 faceNodes[inode - 1] = faceNode;
3394 SimplifyFace(faceNodes, poly_nodes, quantities);
3397 if (quantities.size() > 3) {
3398 // to be done: remove coincident faces
3401 if (quantities.size() > 3)
3402 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3404 rmElemIds.push_back(elem->GetID());
3407 rmElemIds.push_back(elem->GetID());
3417 switch ( nbNodes ) {
3418 case 2: ///////////////////////////////////// EDGE
3419 isOk = false; break;
3420 case 3: ///////////////////////////////////// TRIANGLE
3421 isOk = false; break;
3423 if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
3425 else { //////////////////////////////////// QUADRANGLE
3426 if ( nbUniqueNodes < 3 )
3428 else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
3429 isOk = false; // opposite nodes stick
3432 case 6: ///////////////////////////////////// PENTAHEDRON
3433 if ( nbUniqueNodes == 4 ) {
3434 // ---------------------------------> tetrahedron
3436 iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
3437 // all top nodes stick: reverse a bottom
3438 uniqueNodes[ 0 ] = curNodes [ 1 ];
3439 uniqueNodes[ 1 ] = curNodes [ 0 ];
3441 else if (nbRepl == 3 &&
3442 iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
3443 // all bottom nodes stick: set a top before
3444 uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
3445 uniqueNodes[ 0 ] = curNodes [ 3 ];
3446 uniqueNodes[ 1 ] = curNodes [ 4 ];
3447 uniqueNodes[ 2 ] = curNodes [ 5 ];
3449 else if (nbRepl == 4 &&
3450 iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
3451 // a lateral face turns into a line: reverse a bottom
3452 uniqueNodes[ 0 ] = curNodes [ 1 ];
3453 uniqueNodes[ 1 ] = curNodes [ 0 ];
3458 else if ( nbUniqueNodes == 5 ) {
3459 // PENTAHEDRON --------------------> 2 tetrahedrons
3460 if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
3461 // a bottom node sticks with a linked top one
3463 SMDS_MeshElement* newElem =
3464 aMesh->AddVolume(curNodes[ 3 ],
3467 curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
3469 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3470 // 2. : reverse a bottom
3471 uniqueNodes[ 0 ] = curNodes [ 1 ];
3472 uniqueNodes[ 1 ] = curNodes [ 0 ];
3481 case 8: { //////////////////////////////////// HEXAHEDRON
3483 SMDS_VolumeTool hexa (elem);
3484 hexa.SetExternalNormal();
3485 if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
3486 //////////////////////// ---> tetrahedron
3487 for ( int iFace = 0; iFace < 6; iFace++ ) {
3488 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3489 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3490 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3491 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3492 // one face turns into a point ...
3493 int iOppFace = hexa.GetOppFaceIndex( iFace );
3494 ind = hexa.GetFaceNodesIndices( iOppFace );
3496 iUnique = 2; // reverse a tetrahedron bottom
3497 for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
3498 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3500 else if ( iUnique >= 0 )
3501 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3503 if ( nbStick == 1 ) {
3504 // ... and the opposite one - into a triangle.
3506 ind = hexa.GetFaceNodesIndices( iFace );
3507 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
3514 else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
3515 //////////////////// HEXAHEDRON ---> 2 tetrahedrons
3516 for ( int iFace = 0; iFace < 6; iFace++ ) {
3517 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3518 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3519 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3520 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3521 // one face turns into a point ...
3522 int iOppFace = hexa.GetOppFaceIndex( iFace );
3523 ind = hexa.GetFaceNodesIndices( iOppFace );
3525 iUnique = 2; // reverse a tetrahedron 1 bottom
3526 for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
3527 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3529 else if ( iUnique >= 0 )
3530 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3532 if ( nbStick == 0 ) {
3533 // ... and the opposite one is a quadrangle
3535 const int* indTop = hexa.GetFaceNodesIndices( iFace );
3536 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
3539 SMDS_MeshElement* newElem =
3540 aMesh->AddVolume(curNodes[ind[ 0 ]],
3543 curNodes[indTop[ 0 ]]);
3545 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3552 else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
3553 ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
3554 // find indices of quad and tri faces
3555 int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
3556 for ( iFace = 0; iFace < 6; iFace++ ) {
3557 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3559 for ( iCur = 0; iCur < 4; iCur++ )
3560 nodeSet.insert( curNodes[ind[ iCur ]] );
3561 nbUniqueNodes = nodeSet.size();
3562 if ( nbUniqueNodes == 3 )
3563 iTriFace[ nbTri++ ] = iFace;
3564 else if ( nbUniqueNodes == 4 )
3565 iQuadFace[ nbQuad++ ] = iFace;
3567 if (nbQuad == 2 && nbTri == 4 &&
3568 hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
3569 // 2 opposite quadrangles stuck with a diagonal;
3570 // sample groups of merged indices: (0-4)(2-6)
3571 // --------------------------------------------> 2 tetrahedrons
3572 const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
3573 const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
3574 int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
3575 if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
3576 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
3577 // stuck with 0-2 diagonal
3585 else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
3586 curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
3587 // stuck with 1-3 diagonal
3599 uniqueNodes[ 0 ] = curNodes [ i0 ];
3600 uniqueNodes[ 1 ] = curNodes [ i1d ];
3601 uniqueNodes[ 2 ] = curNodes [ i3d ];
3602 uniqueNodes[ 3 ] = curNodes [ i0t ];
3605 SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
3610 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3613 else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
3614 ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
3615 // --------------------------------------------> prism
3616 // find 2 opposite triangles
3618 for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
3619 if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
3620 // find indices of kept and replaced nodes
3621 // and fill unique nodes of 2 opposite triangles
3622 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
3623 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
3624 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
3625 // fill unique nodes
3628 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
3629 const SMDS_MeshNode* n = curNodes[ind1[ iCur ]];
3630 const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
3632 // iCur of a linked node of the opposite face (make normals co-directed):
3633 int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
3634 // check that correspondent corners of triangles are linked
3635 if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
3638 uniqueNodes[ iUnique ] = n;
3639 uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
3648 } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
3654 } // switch ( nbNodes )
3656 } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
3659 if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
3660 // Change nodes of polyedre
3661 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3662 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3664 int nbFaces = aPolyedre->NbFaces();
3666 vector<const SMDS_MeshNode *> poly_nodes;
3667 vector<int> quantities (nbFaces);
3669 for (int iface = 1; iface <= nbFaces; iface++) {
3670 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3671 quantities[iface - 1] = nbFaceNodes;
3673 for (inode = 1; inode <= nbFaceNodes; inode++) {
3674 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
3676 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
3677 if (nnIt != nodeNodeMap.end()) { // curNode sticks
3678 curNode = (*nnIt).second;
3680 poly_nodes.push_back(curNode);
3683 aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
3686 // Change regular element or polygon
3687 aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
3690 // Remove invalid regular element or invalid polygon
3691 rmElemIds.push_back( elem->GetID() );
3694 } // loop on elements
3696 // Remove equal nodes and bad elements
3698 Remove( rmNodeIds, true );
3699 Remove( rmElemIds, false );
3703 //=======================================================================
3704 //function : MergeEqualElements
3705 //purpose : Remove all but one of elements built on the same nodes.
3706 //=======================================================================
3708 void SMESH_MeshEditor::MergeEqualElements()
3710 SMESHDS_Mesh* aMesh = GetMeshDS();
3712 SMDS_EdgeIteratorPtr eIt = aMesh->edgesIterator();
3713 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
3714 SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
3716 list< int > rmElemIds; // IDs of elems to remove
3718 for ( int iDim = 1; iDim <= 3; iDim++ ) {
3720 set< set <const SMDS_MeshElement*> > setOfNodeSet;
3724 const SMDS_MeshElement* elem = 0;
3726 if ( eIt->more() ) elem = eIt->next();
3727 } else if ( iDim == 2 ) {
3728 if ( fIt->more() ) elem = fIt->next();
3730 if ( vIt->more() ) elem = vIt->next();
3735 set <const SMDS_MeshElement*> nodeSet;
3736 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3737 while ( nodeIt->more() )
3738 nodeSet.insert( nodeIt->next() );
3741 bool isUnique = setOfNodeSet.insert( nodeSet ).second;
3743 rmElemIds.push_back( elem->GetID() );
3747 Remove( rmElemIds, false );
3750 //=======================================================================
3751 //function : FindFaceInSet
3752 //purpose : Return a face having linked nodes n1 and n2 and which is
3753 // - not in avoidSet,
3754 // - in elemSet provided that !elemSet.empty()
3755 //=======================================================================
3757 const SMDS_MeshElement*
3758 SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode* n1,
3759 const SMDS_MeshNode* n2,
3760 const set<const SMDS_MeshElement*>& elemSet,
3761 const set<const SMDS_MeshElement*>& avoidSet)
3764 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
3765 while ( invElemIt->more() ) { // loop on inverse elements of n1
3766 const SMDS_MeshElement* elem = invElemIt->next();
3767 if (elem->GetType() != SMDSAbs_Face ||
3768 avoidSet.find( elem ) != avoidSet.end() )
3770 if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
3772 // get face nodes and find index of n1
3773 int i1, nbN = elem->NbNodes(), iNode = 0;
3774 const SMDS_MeshNode* faceNodes[ nbN ], *n;
3775 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3776 while ( nIt->more() ) {
3777 faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3778 if ( faceNodes[ iNode++ ] == n1 )
3781 // find a n2 linked to n1
3782 for ( iNode = 0; iNode < 2; iNode++ ) {
3783 if ( iNode ) // node before n1
3784 n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
3785 else // node after n1
3786 n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
3794 //=======================================================================
3795 //function : findAdjacentFace
3797 //=======================================================================
3799 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
3800 const SMDS_MeshNode* n2,
3801 const SMDS_MeshElement* elem)
3803 set<const SMDS_MeshElement*> elemSet, avoidSet;
3805 avoidSet.insert ( elem );
3806 return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3809 //=======================================================================
3810 //function : findFreeBorder
3812 //=======================================================================
3814 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
3816 static bool findFreeBorder (const SMDS_MeshNode* theFirstNode,
3817 const SMDS_MeshNode* theSecondNode,
3818 const SMDS_MeshNode* theLastNode,
3819 list< const SMDS_MeshNode* > & theNodes,
3820 list< const SMDS_MeshElement* > & theFaces)
3822 if ( !theFirstNode || !theSecondNode )
3824 // find border face between theFirstNode and theSecondNode
3825 const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
3829 theFaces.push_back( curElem );
3830 theNodes.push_back( theFirstNode );
3831 theNodes.push_back( theSecondNode );
3833 const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
3834 set < const SMDS_MeshElement* > foundElems;
3835 bool needTheLast = ( theLastNode != 0 );
3837 while ( nStart != theLastNode )
3839 if ( nStart == theFirstNode )
3840 return !needTheLast;
3842 // find all free border faces sharing form nStart
3844 list< const SMDS_MeshElement* > curElemList;
3845 list< const SMDS_MeshNode* > nStartList;
3846 SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
3847 while ( invElemIt->more() ) {
3848 const SMDS_MeshElement* e = invElemIt->next();
3849 if ( e == curElem || foundElems.insert( e ).second )
3852 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3853 int iNode = 0, nbNodes = e->NbNodes();
3854 while ( nIt->more() )
3855 nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3856 nodes[ iNode ] = nodes[ 0 ];
3858 for ( iNode = 0; iNode < nbNodes; iNode++ )
3859 if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
3860 (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
3861 ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
3863 nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
3864 curElemList.push_back( e );
3868 // analyse the found
3870 int nbNewBorders = curElemList.size();
3871 if ( nbNewBorders == 0 ) {
3872 // no free border furthermore
3873 return !needTheLast;
3875 else if ( nbNewBorders == 1 ) {
3876 // one more element found
3878 nStart = nStartList.front();
3879 curElem = curElemList.front();
3880 theFaces.push_back( curElem );
3881 theNodes.push_back( nStart );
3884 // several continuations found
3885 list< const SMDS_MeshElement* >::iterator curElemIt;
3886 list< const SMDS_MeshNode* >::iterator nStartIt;
3887 // check if one of them reached the last node
3888 if ( needTheLast ) {
3889 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3890 curElemIt!= curElemList.end();
3891 curElemIt++, nStartIt++ )
3892 if ( *nStartIt == theLastNode ) {
3893 theFaces.push_back( *curElemIt );
3894 theNodes.push_back( *nStartIt );
3898 // find the best free border by the continuations
3899 list<const SMDS_MeshNode*> contNodes[ 2 ], *cNL;
3900 list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3901 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3902 curElemIt!= curElemList.end();
3903 curElemIt++, nStartIt++ )
3905 cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3906 cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3907 // find one more free border
3908 if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3912 else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3913 // choice: clear a worse one
3914 int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3915 int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3916 contNodes[ iWorse ].clear();
3917 contFaces[ iWorse ].clear();
3920 if ( contNodes[0].empty() && contNodes[1].empty() )
3923 // append the best free border
3924 cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3925 cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3926 theNodes.pop_back(); // remove nIgnore
3927 theNodes.pop_back(); // remove nStart
3928 theFaces.pop_back(); // remove curElem
3929 list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3930 list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3931 for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3932 for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3935 } // several continuations found
3936 } // while ( nStart != theLastNode )
3941 //=======================================================================
3942 //function : CheckFreeBorderNodes
3943 //purpose : Return true if the tree nodes are on a free border
3944 //=======================================================================
3946 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3947 const SMDS_MeshNode* theNode2,
3948 const SMDS_MeshNode* theNode3)
3950 list< const SMDS_MeshNode* > nodes;
3951 list< const SMDS_MeshElement* > faces;
3952 return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3955 //=======================================================================
3956 //function : SewFreeBorder
3958 //=======================================================================
3960 SMESH_MeshEditor::Sew_Error
3961 SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3962 const SMDS_MeshNode* theBordSecondNode,
3963 const SMDS_MeshNode* theBordLastNode,
3964 const SMDS_MeshNode* theSideFirstNode,
3965 const SMDS_MeshNode* theSideSecondNode,
3966 const SMDS_MeshNode* theSideThirdNode,
3967 const bool theSideIsFreeBorder,
3968 const bool toCreatePolygons,
3969 const bool toCreatePolyedrs)
3971 MESSAGE("::SewFreeBorder()");
3972 Sew_Error aResult = SEW_OK;
3974 // ====================================
3975 // find side nodes and elements
3976 // ====================================
3978 list< const SMDS_MeshNode* > nSide[ 2 ];
3979 list< const SMDS_MeshElement* > eSide[ 2 ];
3980 list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3981 list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3985 if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3986 nSide[0], eSide[0])) {
3987 MESSAGE(" Free Border 1 not found " );
3988 aResult = SEW_BORDER1_NOT_FOUND;
3990 if (theSideIsFreeBorder)
3994 if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3995 nSide[1], eSide[1])) {
3996 MESSAGE(" Free Border 2 not found " );
3997 aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
4000 if ( aResult != SEW_OK )
4003 if (!theSideIsFreeBorder)
4008 // -------------------------------------------------------------------------
4010 // 1. If nodes to merge are not coincident, move nodes of the free border
4011 // from the coord sys defined by the direction from the first to last
4012 // nodes of the border to the correspondent sys of the side 2
4013 // 2. On the side 2, find the links most co-directed with the correspondent
4014 // links of the free border
4015 // -------------------------------------------------------------------------
4017 // 1. Since sewing may brake if there are volumes to split on the side 2,
4018 // we wont move nodes but just compute new coordinates for them
4019 typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
4020 TNodeXYZMap nBordXYZ;
4021 list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
4022 list< const SMDS_MeshNode* >::iterator nBordIt;
4024 gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
4025 gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
4026 gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
4027 gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
4028 double tol2 = 1.e-8;
4029 gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
4030 if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
4032 // Need node movement.
4034 // find X and Z axes to create trsf
4035 gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
4037 if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
4039 X = gp_Ax2( gp::Origin(), Zb ).XDirection();
4042 gp_Ax3 toBordAx( Pb1, Zb, X );
4043 gp_Ax3 fromSideAx( Ps1, Zs, X );
4044 gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
4046 gp_Trsf toBordSys, fromSide2Sys;
4047 toBordSys.SetTransformation( toBordAx );
4048 fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
4049 fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
4052 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
4053 const SMDS_MeshNode* n = *nBordIt;
4054 gp_XYZ xyz( n->X(),n->Y(),n->Z() );
4055 toBordSys.Transforms( xyz );
4056 fromSide2Sys.Transforms( xyz );
4057 nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
4062 // just insert nodes XYZ in the nBordXYZ map
4063 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
4064 const SMDS_MeshNode* n = *nBordIt;
4065 nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
4069 // 2. On the side 2, find the links most co-directed with the correspondent
4070 // links of the free border
4072 list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
4073 list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
4074 sideNodes.push_back( theSideFirstNode );
4076 bool hasVolumes = false;
4077 LinkID_Gen aLinkID_Gen( GetMeshDS() );
4078 set<long> foundSideLinkIDs, checkedLinkIDs;
4079 SMDS_VolumeTool volume;
4080 //const SMDS_MeshNode* faceNodes[ 4 ];
4082 const SMDS_MeshNode* sideNode;
4083 const SMDS_MeshElement* sideElem;
4084 const SMDS_MeshNode* prevSideNode = theSideFirstNode;
4085 const SMDS_MeshNode* prevBordNode = theBordFirstNode;
4086 nBordIt = bordNodes.begin();
4088 // border node position and border link direction to compare with
4089 gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
4090 gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
4091 // choose next side node by link direction or by closeness to
4092 // the current border node:
4093 bool searchByDir = ( *nBordIt != theBordLastNode );
4095 // find the next node on the Side 2
4097 double maxDot = -DBL_MAX, minDist = DBL_MAX;
4099 checkedLinkIDs.clear();
4100 gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
4102 SMDS_ElemIteratorPtr invElemIt
4103 = prevSideNode->GetInverseElementIterator();
4104 while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
4105 const SMDS_MeshElement* elem = invElemIt->next();
4106 // prepare data for a loop on links, of a face or a volume
4107 int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
4108 const SMDS_MeshNode* faceNodes[ nbNodes ];
4109 bool isVolume = volume.Set( elem );
4110 const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
4111 if ( isVolume ) // --volume
4113 else if ( nbNodes > 2 ) { // --face
4114 // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
4115 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
4116 while ( nIt->more() ) {
4117 nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
4118 if ( nodes[ iNode++ ] == prevSideNode )
4119 iPrevNode = iNode - 1;
4121 // there are 2 links to check
4126 // loop on links, to be precise, on the second node of links
4127 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
4128 const SMDS_MeshNode* n = nodes[ iNode ];
4130 if ( !volume.IsLinked( n, prevSideNode ))
4133 if ( iNode ) // a node before prevSideNode
4134 n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
4135 else // a node after prevSideNode
4136 n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
4138 // check if this link was already used
4139 long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
4140 bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
4141 if (!isJustChecked &&
4142 foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
4143 // test a link geometrically
4144 gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
4145 bool linkIsBetter = false;
4147 if ( searchByDir ) { // choose most co-directed link
4148 dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
4149 linkIsBetter = ( dot > maxDot );
4151 else { // choose link with the node closest to bordPos
4152 dist = ( nextXYZ - bordPos ).SquareModulus();
4153 linkIsBetter = ( dist < minDist );
4155 if ( linkIsBetter ) {
4164 } // loop on inverse elements of prevSideNode
4167 MESSAGE(" Cant find path by links of the Side 2 ");
4168 return SEW_BAD_SIDE_NODES;
4170 sideNodes.push_back( sideNode );
4171 sideElems.push_back( sideElem );
4172 foundSideLinkIDs.insert ( linkID );
4173 prevSideNode = sideNode;
4175 if ( *nBordIt == theBordLastNode )
4176 searchByDir = false;
4178 // find the next border link to compare with
4179 gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
4180 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4181 while ( *nBordIt != theBordLastNode && !searchByDir ) {
4182 prevBordNode = *nBordIt;
4184 bordPos = nBordXYZ[ *nBordIt ];
4185 bordDir = bordPos - nBordXYZ[ prevBordNode ];
4186 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4190 while ( sideNode != theSideSecondNode );
4192 if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
4193 MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
4194 return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
4196 } // end nodes search on the side 2
4198 // ============================
4199 // sew the border to the side 2
4200 // ============================
4202 int nbNodes[] = { nSide[0].size(), nSide[1].size() };
4203 int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
4205 TListOfListOfNodes nodeGroupsToMerge;
4206 if ( nbNodes[0] == nbNodes[1] ||
4207 ( theSideIsFreeBorder && !theSideThirdNode)) {
4209 // all nodes are to be merged
4211 for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
4212 nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
4213 nIt[0]++, nIt[1]++ )
4215 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4216 nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
4217 nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
4222 // insert new nodes into the border and the side to get equal nb of segments
4224 // get normalized parameters of nodes on the borders
4225 double param[ 2 ][ maxNbNodes ];
4227 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4228 list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
4229 list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
4230 const SMDS_MeshNode* nPrev = *nIt;
4231 double bordLength = 0;
4232 for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
4233 const SMDS_MeshNode* nCur = *nIt;
4234 gp_XYZ segment (nCur->X() - nPrev->X(),
4235 nCur->Y() - nPrev->Y(),
4236 nCur->Z() - nPrev->Z());
4237 double segmentLen = segment.Modulus();
4238 bordLength += segmentLen;
4239 param[ iBord ][ iNode ] = bordLength;
4242 // normalize within [0,1]
4243 for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
4244 param[ iBord ][ iNode ] /= bordLength;
4248 // loop on border segments
4249 const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
4250 int i[ 2 ] = { 0, 0 };
4251 nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
4252 nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
4254 TElemOfNodeListMap insertMap;
4255 TElemOfNodeListMap::iterator insertMapIt;
4257 // key: elem to insert nodes into
4258 // value: 2 nodes to insert between + nodes to be inserted
4260 bool next[ 2 ] = { false, false };
4262 // find min adjacent segment length after sewing
4263 double nextParam = 10., prevParam = 0;
4264 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4265 if ( i[ iBord ] + 1 < nbNodes[ iBord ])
4266 nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
4267 if ( i[ iBord ] > 0 )
4268 prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
4270 double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4271 double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4272 double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
4274 // choose to insert or to merge nodes
4275 double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
4276 if ( Abs( du ) <= minSegLen * 0.2 ) {
4279 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4280 const SMDS_MeshNode* n0 = *nIt[0];
4281 const SMDS_MeshNode* n1 = *nIt[1];
4282 nodeGroupsToMerge.back().push_back( n1 );
4283 nodeGroupsToMerge.back().push_back( n0 );
4284 // position of node of the border changes due to merge
4285 param[ 0 ][ i[0] ] += du;
4286 // move n1 for the sake of elem shape evaluation during insertion.
4287 // n1 will be removed by MergeNodes() anyway
4288 const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
4289 next[0] = next[1] = true;
4294 int intoBord = ( du < 0 ) ? 0 : 1;
4295 const SMDS_MeshElement* elem = *eIt[ intoBord ];
4296 const SMDS_MeshNode* n1 = nPrev[ intoBord ];
4297 const SMDS_MeshNode* n2 = *nIt[ intoBord ];
4298 const SMDS_MeshNode* nIns = *nIt[ 1 - intoBord ];
4299 if ( intoBord == 1 ) {
4300 // move node of the border to be on a link of elem of the side
4301 gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
4302 gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
4303 double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
4304 gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
4305 GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
4307 insertMapIt = insertMap.find( elem );
4308 bool notFound = ( insertMapIt == insertMap.end() );
4309 bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
4311 // insert into another link of the same element:
4312 // 1. perform insertion into the other link of the elem
4313 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4314 const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
4315 const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
4316 InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
4317 // 2. perform insertion into the link of adjacent faces
4319 const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
4321 InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
4325 if (toCreatePolyedrs) {
4326 // perform insertion into the links of adjacent volumes
4327 UpdateVolumes(n12, n22, nodeList);
4329 // 3. find an element appeared on n1 and n2 after the insertion
4330 insertMap.erase( elem );
4331 elem = findAdjacentFace( n1, n2, 0 );
4333 if ( notFound || otherLink ) {
4334 // add element and nodes of the side into the insertMap
4335 insertMapIt = insertMap.insert
4336 ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
4337 (*insertMapIt).second.push_back( n1 );
4338 (*insertMapIt).second.push_back( n2 );
4340 // add node to be inserted into elem
4341 (*insertMapIt).second.push_back( nIns );
4342 next[ 1 - intoBord ] = true;
4345 // go to the next segment
4346 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4347 if ( next[ iBord ] ) {
4348 if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
4350 nPrev[ iBord ] = *nIt[ iBord ];
4351 nIt[ iBord ]++; i[ iBord ]++;
4355 while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
4357 // perform insertion of nodes into elements
4359 for (insertMapIt = insertMap.begin();
4360 insertMapIt != insertMap.end();
4363 const SMDS_MeshElement* elem = (*insertMapIt).first;
4364 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4365 const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
4366 const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
4368 InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
4370 if ( !theSideIsFreeBorder ) {
4371 // look for and insert nodes into the faces adjacent to elem
4373 const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
4375 InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
4380 if (toCreatePolyedrs) {
4381 // perform insertion into the links of adjacent volumes
4382 UpdateVolumes(n1, n2, nodeList);
4386 } // end: insert new nodes
4388 MergeNodes ( nodeGroupsToMerge );
4393 //=======================================================================
4394 //function : InsertNodesIntoLink
4395 //purpose : insert theNodesToInsert into theFace between theBetweenNode1
4396 // and theBetweenNode2 and split theElement
4397 //=======================================================================
4399 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement* theFace,
4400 const SMDS_MeshNode* theBetweenNode1,
4401 const SMDS_MeshNode* theBetweenNode2,
4402 list<const SMDS_MeshNode*>& theNodesToInsert,
4403 const bool toCreatePoly)
4405 if ( theFace->GetType() != SMDSAbs_Face ) return;
4407 // find indices of 2 link nodes and of the rest nodes
4408 int iNode = 0, il1, il2, i3, i4;
4409 il1 = il2 = i3 = i4 = -1;
4410 const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
4411 SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
4412 while ( nodeIt->more() ) {
4413 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4414 if ( n == theBetweenNode1 )
4416 else if ( n == theBetweenNode2 )
4422 nodes[ iNode++ ] = n;
4424 if ( il1 < 0 || il2 < 0 || i3 < 0 )
4427 // arrange link nodes to go one after another regarding the face orientation
4428 bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
4429 list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
4434 aNodesToInsert.reverse();
4436 // check that not link nodes of a quadrangles are in good order
4437 int nbFaceNodes = theFace->NbNodes();
4438 if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
4444 if (toCreatePoly || theFace->IsPoly()) {
4447 vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
4449 // add nodes of face up to first node of link
4451 nodeIt = theFace->nodesIterator();
4452 while ( nodeIt->more() && !isFLN ) {
4453 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4454 poly_nodes[iNode++] = n;
4455 if (n == nodes[il1]) {
4460 // add nodes to insert
4461 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4462 for (; nIt != aNodesToInsert.end(); nIt++) {
4463 poly_nodes[iNode++] = *nIt;
4466 // add nodes of face starting from last node of link
4467 while ( nodeIt->more() ) {
4468 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4469 poly_nodes[iNode++] = n;
4472 // edit or replace the face
4473 SMESHDS_Mesh *aMesh = GetMeshDS();
4475 if (theFace->IsPoly()) {
4476 aMesh->ChangePolygonNodes(theFace, poly_nodes);
4479 int aShapeId = FindShape( theFace );
4481 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4482 if ( aShapeId && newElem )
4483 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4485 aMesh->RemoveElement(theFace);
4490 // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
4491 int nbLinkNodes = 2 + aNodesToInsert.size();
4492 const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
4493 linkNodes[ 0 ] = nodes[ il1 ];
4494 linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
4495 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4496 for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
4497 linkNodes[ iNode++ ] = *nIt;
4499 // decide how to split a quadrangle: compare possible variants
4500 // and choose which of splits to be a quadrangle
4501 int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
4502 if ( nbFaceNodes == 3 )
4504 iBestQuad = nbSplits;
4507 else if ( nbFaceNodes == 4 )
4509 SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
4510 double aBestRate = DBL_MAX;
4511 for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
4513 double aBadRate = 0;
4514 // evaluate elements quality
4515 for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
4516 if ( iSplit == iQuad ) {
4517 SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
4521 aBadRate += getBadRate( &quad, aCrit );
4524 SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
4526 nodes[ iSplit < iQuad ? i4 : i3 ]);
4527 aBadRate += getBadRate( &tria, aCrit );
4531 if ( aBadRate < aBestRate ) {
4533 aBestRate = aBadRate;
4538 // create new elements
4539 SMESHDS_Mesh *aMesh = GetMeshDS();
4540 int aShapeId = FindShape( theFace );
4543 for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
4544 SMDS_MeshElement* newElem = 0;
4545 if ( iSplit == iBestQuad )
4546 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4551 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4553 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
4554 if ( aShapeId && newElem )
4555 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4558 // change nodes of theFace
4559 const SMDS_MeshNode* newNodes[ 4 ];
4560 newNodes[ 0 ] = linkNodes[ i1 ];
4561 newNodes[ 1 ] = linkNodes[ i2 ];
4562 newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
4563 newNodes[ 3 ] = nodes[ i4 ];
4564 aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
4567 //=======================================================================
4568 //function : UpdateVolumes
4570 //=======================================================================
4571 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode* theBetweenNode1,
4572 const SMDS_MeshNode* theBetweenNode2,
4573 list<const SMDS_MeshNode*>& theNodesToInsert)
4575 SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
4576 while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
4577 const SMDS_MeshElement* elem = invElemIt->next();
4578 if (elem->GetType() != SMDSAbs_Volume)
4581 // check, if current volume has link theBetweenNode1 - theBetweenNode2
4582 SMDS_VolumeTool aVolume (elem);
4583 if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
4586 // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
4587 int iface, nbFaces = aVolume.NbFaces();
4588 vector<const SMDS_MeshNode *> poly_nodes;
4589 vector<int> quantities (nbFaces);
4591 for (iface = 0; iface < nbFaces; iface++) {
4592 int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
4593 // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
4594 const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
4596 for (int inode = 0; inode < nbFaceNodes; inode++) {
4597 poly_nodes.push_back(faceNodes[inode]);
4599 if (nbInserted == 0) {
4600 if (faceNodes[inode] == theBetweenNode1) {
4601 if (faceNodes[inode + 1] == theBetweenNode2) {
4602 nbInserted = theNodesToInsert.size();
4604 // add nodes to insert
4605 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
4606 for (; nIt != theNodesToInsert.end(); nIt++) {
4607 poly_nodes.push_back(*nIt);
4610 } else if (faceNodes[inode] == theBetweenNode2) {
4611 if (faceNodes[inode + 1] == theBetweenNode1) {
4612 nbInserted = theNodesToInsert.size();
4614 // add nodes to insert in reversed order
4615 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
4617 for (; nIt != theNodesToInsert.begin(); nIt--) {
4618 poly_nodes.push_back(*nIt);
4620 poly_nodes.push_back(*nIt);
4626 quantities[iface] = nbFaceNodes + nbInserted;
4629 // Replace or update the volume
4630 SMESHDS_Mesh *aMesh = GetMeshDS();
4632 if (elem->IsPoly()) {
4633 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4636 int aShapeId = FindShape( elem );
4638 SMDS_MeshElement* newElem =
4639 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
4640 if (aShapeId && newElem)
4641 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4643 aMesh->RemoveElement(elem);
4648 //=======================================================================
4649 //function : SewSideElements
4651 //=======================================================================
4653 SMESH_MeshEditor::Sew_Error
4654 SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
4655 set<const SMDS_MeshElement*>& theSide2,
4656 const SMDS_MeshNode* theFirstNode1,
4657 const SMDS_MeshNode* theFirstNode2,
4658 const SMDS_MeshNode* theSecondNode1,
4659 const SMDS_MeshNode* theSecondNode2)
4661 MESSAGE ("::::SewSideElements()");
4662 if ( theSide1.size() != theSide2.size() )
4663 return SEW_DIFF_NB_OF_ELEMENTS;
4665 Sew_Error aResult = SEW_OK;
4667 // 1. Build set of faces representing each side
4668 // 2. Find which nodes of the side 1 to merge with ones on the side 2
4669 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4671 // =======================================================================
4672 // 1. Build set of faces representing each side:
4673 // =======================================================================
4674 // a. build set of nodes belonging to faces
4675 // b. complete set of faces: find missing fices whose nodes are in set of nodes
4676 // c. create temporary faces representing side of volumes if correspondent
4677 // face does not exist
4679 SMESHDS_Mesh* aMesh = GetMeshDS();
4680 SMDS_Mesh aTmpFacesMesh;
4681 set<const SMDS_MeshElement*> faceSet1, faceSet2;
4682 set<const SMDS_MeshElement*> volSet1, volSet2;
4683 set<const SMDS_MeshNode*> nodeSet1, nodeSet2;
4684 set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
4685 set<const SMDS_MeshElement*> * volSetPtr[] = { &volSet1, &volSet2 };
4686 set<const SMDS_MeshNode*> * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
4687 set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
4688 int iSide, iFace, iNode;
4690 for ( iSide = 0; iSide < 2; iSide++ ) {
4691 set<const SMDS_MeshNode*> * nodeSet = nodeSetPtr[ iSide ];
4692 set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
4693 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4694 set<const SMDS_MeshElement*> * volSet = volSetPtr [ iSide ];
4695 set<const SMDS_MeshElement*>::iterator vIt, eIt;
4696 set<const SMDS_MeshNode*>::iterator nIt;
4698 // -----------------------------------------------------------
4699 // 1a. Collect nodes of existing faces
4700 // and build set of face nodes in order to detect missing
4701 // faces corresponing to sides of volumes
4702 // -----------------------------------------------------------
4704 set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
4706 // loop on the given element of a side
4707 for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
4708 const SMDS_MeshElement* elem = *eIt;
4709 if ( elem->GetType() == SMDSAbs_Face ) {
4710 faceSet->insert( elem );
4711 set <const SMDS_MeshNode*> faceNodeSet;
4712 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
4713 while ( nodeIt->more() ) {
4714 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4715 nodeSet->insert( n );
4716 faceNodeSet.insert( n );
4718 setOfFaceNodeSet.insert( faceNodeSet );
4720 else if ( elem->GetType() == SMDSAbs_Volume )
4721 volSet->insert( elem );
4723 // ------------------------------------------------------------------------------
4724 // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
4725 // ------------------------------------------------------------------------------
4727 for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4728 SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4729 while ( fIt->more() ) { // loop on faces sharing a node
4730 const SMDS_MeshElement* f = fIt->next();
4731 if ( faceSet->find( f ) == faceSet->end() ) {
4732 // check if all nodes are in nodeSet and
4733 // complete setOfFaceNodeSet if they are
4734 set <const SMDS_MeshNode*> faceNodeSet;
4735 SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4736 bool allInSet = true;
4737 while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4738 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4739 if ( nodeSet->find( n ) == nodeSet->end() )
4742 faceNodeSet.insert( n );
4745 faceSet->insert( f );
4746 setOfFaceNodeSet.insert( faceNodeSet );
4752 // -------------------------------------------------------------------------
4753 // 1c. Create temporary faces representing sides of volumes if correspondent
4754 // face does not exist
4755 // -------------------------------------------------------------------------
4757 if ( !volSet->empty() )
4759 //int nodeSetSize = nodeSet->size();
4761 // loop on given volumes
4762 for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
4763 SMDS_VolumeTool vol (*vIt);
4764 // loop on volume faces: find free faces
4765 // --------------------------------------
4766 list<const SMDS_MeshElement* > freeFaceList;
4767 for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
4768 if ( !vol.IsFreeFace( iFace ))
4770 // check if there is already a face with same nodes in a face set
4771 const SMDS_MeshElement* aFreeFace = 0;
4772 const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
4773 int nbNodes = vol.NbFaceNodes( iFace );
4774 set <const SMDS_MeshNode*> faceNodeSet;
4775 vol.GetFaceNodes( iFace, faceNodeSet );
4776 bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
4778 // no such a face is given but it still can exist, check it
4779 if ( nbNodes == 3 ) {
4780 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
4781 } else if ( nbNodes == 4 ) {
4782 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4784 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4785 for (int inode = 0; inode < nbNodes; inode++) {
4786 poly_nodes[inode] = fNodes[inode];
4788 aFreeFace = aMesh->FindFace(poly_nodes);
4792 // create a temporary face
4793 if ( nbNodes == 3 ) {
4794 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
4795 } else if ( nbNodes == 4 ) {
4796 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4798 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4799 for (int inode = 0; inode < nbNodes; inode++) {
4800 poly_nodes[inode] = fNodes[inode];
4802 aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
4806 freeFaceList.push_back( aFreeFace );
4808 } // loop on faces of a volume
4810 // choose one of several free faces
4811 // --------------------------------------
4812 if ( freeFaceList.size() > 1 ) {
4813 // choose a face having max nb of nodes shared by other elems of a side
4814 int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
4815 list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
4816 while ( fIt != freeFaceList.end() ) { // loop on free faces
4817 int nbSharedNodes = 0;
4818 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4819 while ( nodeIt->more() ) { // loop on free face nodes
4820 const SMDS_MeshNode* n =
4821 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4822 SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
4823 while ( invElemIt->more() ) {
4824 const SMDS_MeshElement* e = invElemIt->next();
4825 if ( faceSet->find( e ) != faceSet->end() )
4827 if ( elemSet->find( e ) != elemSet->end() )
4831 if ( nbSharedNodes >= maxNbNodes ) {
4832 maxNbNodes = nbSharedNodes;
4836 freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
4838 if ( freeFaceList.size() > 1 )
4840 // could not choose one face, use another way
4841 // choose a face most close to the bary center of the opposite side
4842 gp_XYZ aBC( 0., 0., 0. );
4843 set <const SMDS_MeshNode*> addedNodes;
4844 set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
4845 eIt = elemSet2->begin();
4846 for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
4847 SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
4848 while ( nodeIt->more() ) { // loop on free face nodes
4849 const SMDS_MeshNode* n =
4850 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4851 if ( addedNodes.insert( n ).second )
4852 aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
4855 aBC /= addedNodes.size();
4856 double minDist = DBL_MAX;
4857 fIt = freeFaceList.begin();
4858 while ( fIt != freeFaceList.end() ) { // loop on free faces
4860 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4861 while ( nodeIt->more() ) { // loop on free face nodes
4862 const SMDS_MeshNode* n =
4863 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4864 gp_XYZ p( n->X(),n->Y(),n->Z() );
4865 dist += ( aBC - p ).SquareModulus();
4867 if ( dist < minDist ) {
4869 freeFaceList.erase( freeFaceList.begin(), fIt++ );
4872 fIt = freeFaceList.erase( fIt++ );
4875 } // choose one of several free faces of a volume
4877 if ( freeFaceList.size() == 1 ) {
4878 const SMDS_MeshElement* aFreeFace = freeFaceList.front();
4879 faceSet->insert( aFreeFace );
4880 // complete a node set with nodes of a found free face
4881 // for ( iNode = 0; iNode < ; iNode++ )
4882 // nodeSet->insert( fNodes[ iNode ] );
4885 } // loop on volumes of a side
4887 // // complete a set of faces if new nodes in a nodeSet appeared
4888 // // ----------------------------------------------------------
4889 // if ( nodeSetSize != nodeSet->size() ) {
4890 // for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4891 // SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4892 // while ( fIt->more() ) { // loop on faces sharing a node
4893 // const SMDS_MeshElement* f = fIt->next();
4894 // if ( faceSet->find( f ) == faceSet->end() ) {
4895 // // check if all nodes are in nodeSet and
4896 // // complete setOfFaceNodeSet if they are
4897 // set <const SMDS_MeshNode*> faceNodeSet;
4898 // SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4899 // bool allInSet = true;
4900 // while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4901 // const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4902 // if ( nodeSet->find( n ) == nodeSet->end() )
4903 // allInSet = false;
4905 // faceNodeSet.insert( n );
4907 // if ( allInSet ) {
4908 // faceSet->insert( f );
4909 // setOfFaceNodeSet.insert( faceNodeSet );
4915 } // Create temporary faces, if there are volumes given
4918 if ( faceSet1.size() != faceSet2.size() ) {
4919 // delete temporary faces: they are in reverseElements of actual nodes
4920 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4921 while ( tmpFaceIt->more() )
4922 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4923 MESSAGE("Diff nb of faces");
4924 return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4927 // ============================================================
4928 // 2. Find nodes to merge:
4929 // bind a node to remove to a node to put instead
4930 // ============================================================
4932 TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
4933 if ( theFirstNode1 != theFirstNode2 )
4934 nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
4935 if ( theSecondNode1 != theSecondNode2 )
4936 nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
4938 LinkID_Gen aLinkID_Gen( GetMeshDS() );
4939 set< long > linkIdSet; // links to process
4940 linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
4942 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
4943 list< TPairOfNodes > linkList[2];
4944 linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
4945 linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
4946 // loop on links in linkList; find faces by links and append links
4947 // of the found faces to linkList
4948 list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
4949 for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
4951 TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
4952 long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
4953 if ( linkIdSet.find( linkID ) == linkIdSet.end() )
4956 // by links, find faces in the face sets,
4957 // and find indices of link nodes in the found faces;
4958 // in a face set, there is only one or no face sharing a link
4959 // ---------------------------------------------------------------
4961 const SMDS_MeshElement* face[] = { 0, 0 };
4962 const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
4963 const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
4964 int iLinkNode[2][2];
4965 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4966 const SMDS_MeshNode* n1 = link[iSide].first;
4967 const SMDS_MeshNode* n2 = link[iSide].second;
4968 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4969 set< const SMDS_MeshElement* > fMap;
4970 for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
4971 const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
4972 SMDS_ElemIteratorPtr fIt = n->facesIterator();
4973 while ( fIt->more() ) { // loop on faces sharing a node
4974 const SMDS_MeshElement* f = fIt->next();
4975 if (faceSet->find( f ) != faceSet->end() && // f is in face set
4976 ! fMap.insert( f ).second ) // f encounters twice
4978 if ( face[ iSide ] ) {
4979 MESSAGE( "2 faces per link " );
4980 aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
4984 faceSet->erase( f );
4985 // get face nodes and find ones of a link
4987 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
4988 while ( nIt->more() ) {
4989 const SMDS_MeshNode* n =
4990 static_cast<const SMDS_MeshNode*>( nIt->next() );
4992 iLinkNode[ iSide ][ 0 ] = iNode;
4994 iLinkNode[ iSide ][ 1 ] = iNode;
4995 else if ( notLinkNodes[ iSide ][ 0 ] )
4996 notLinkNodes[ iSide ][ 1 ] = n;
4998 notLinkNodes[ iSide ][ 0 ] = n;
4999 faceNodes[ iSide ][ iNode++ ] = n;
5001 faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
5006 // check similarity of elements of the sides
5007 if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
5008 MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
5009 if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
5010 aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
5012 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
5013 break; // do not return because it s necessary to remove tmp faces
5016 // set nodes to merge
5017 // -------------------
5019 if ( face[0] && face[1] )
5021 int nbNodes = face[0]->NbNodes();
5022 if ( nbNodes != face[1]->NbNodes() ) {
5023 MESSAGE("Diff nb of face nodes");
5024 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
5025 break; // do not return because it s necessary to remove tmp faces
5027 bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
5029 nReplaceMap.insert( TNodeNodeMap::value_type
5030 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
5032 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
5033 // analyse link orientation in faces
5034 int i1 = iLinkNode[ iSide ][ 0 ];
5035 int i2 = iLinkNode[ iSide ][ 1 ];
5036 reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
5037 // if notLinkNodes are the first and the last ones, then
5038 // their order does not correspond to the link orientation
5039 if (( i1 == 1 && i2 == 2 ) ||
5040 ( i1 == 2 && i2 == 1 ))
5041 reverse[ iSide ] = !reverse[ iSide ];
5043 if ( reverse[0] == reverse[1] ) {
5044 nReplaceMap.insert( TNodeNodeMap::value_type
5045 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
5046 nReplaceMap.insert( TNodeNodeMap::value_type
5047 ( notLinkNodes[0][1], notLinkNodes[1][1] ));
5050 nReplaceMap.insert( TNodeNodeMap::value_type
5051 ( notLinkNodes[0][0], notLinkNodes[1][1] ));
5052 nReplaceMap.insert( TNodeNodeMap::value_type
5053 ( notLinkNodes[0][1], notLinkNodes[1][0] ));
5057 // add other links of the faces to linkList
5058 // -----------------------------------------
5060 const SMDS_MeshNode** nodes = faceNodes[ 0 ];
5061 for ( iNode = 0; iNode < nbNodes; iNode++ )
5063 linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
5064 pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
5065 if ( !iter_isnew.second ) { // already in a set: no need to process
5066 linkIdSet.erase( iter_isnew.first );
5068 else // new in set == encountered for the first time: add
5070 const SMDS_MeshNode* n1 = nodes[ iNode ];
5071 const SMDS_MeshNode* n2 = nodes[ iNode + 1];
5072 linkList[0].push_back ( TPairOfNodes( n1, n2 ));
5073 linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
5077 } // loop on link lists
5079 if ( aResult == SEW_OK &&
5080 ( linkIt[0] != linkList[0].end() ||
5081 !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
5082 MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
5083 " " << (faceSetPtr[1]->empty()));
5084 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
5087 // ====================================================================
5088 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
5089 // ====================================================================
5091 // delete temporary faces: they are in reverseElements of actual nodes
5092 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
5093 while ( tmpFaceIt->more() )
5094 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
5096 if ( aResult != SEW_OK)
5099 list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
5100 // loop on nodes replacement map
5101 TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
5102 for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
5103 if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
5105 const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
5106 nodeIDsToRemove.push_back( nToRemove->GetID() );
5107 // loop on elements sharing nToRemove
5108 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
5109 while ( invElemIt->more() ) {
5110 const SMDS_MeshElement* e = invElemIt->next();
5111 // get a new suite of nodes: make replacement
5112 int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
5113 const SMDS_MeshNode* nodes[ 8 ];
5114 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5115 while ( nIt->more() ) {
5116 const SMDS_MeshNode* n =
5117 static_cast<const SMDS_MeshNode*>( nIt->next() );
5118 nnIt = nReplaceMap.find( n );
5119 if ( nnIt != nReplaceMap.end() ) {
5125 // if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
5126 // elemIDsToRemove.push_back( e->GetID() );
5129 aMesh->ChangeElementNodes( e, nodes, nbNodes );
5133 Remove( nodeIDsToRemove, true );