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>
70 using namespace SMESH::Controls;
72 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*> TNodeNodeMap;
73 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> > TElemOfNodeListMap;
74 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
75 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
76 typedef TNodeOfNodeListMap::iterator TNodeOfNodeListMapItr;
77 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
79 //=======================================================================
80 //function : SMESH_MeshEditor
82 //=======================================================================
84 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
89 //=======================================================================
91 //purpose : Remove a node or an element.
92 // Modify a compute state of sub-meshes which become empty
93 //=======================================================================
95 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
99 SMESHDS_Mesh* aMesh = GetMeshDS();
100 set< SMESH_subMesh *> smmap;
102 list<int>::const_iterator it = theIDs.begin();
103 for ( ; it != theIDs.end(); it++ )
105 const SMDS_MeshElement * elem;
107 elem = aMesh->FindNode( *it );
109 elem = aMesh->FindElement( *it );
113 // Find sub-meshes to notify about modification
114 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
115 while ( nodeIt->more() )
117 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
118 const SMDS_PositionPtr& aPosition = node->GetPosition();
119 if ( aPosition.get() ) {
120 int aShapeID = aPosition->GetShapeId();
122 TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
123 SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
132 aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
134 aMesh->RemoveElement( elem );
137 // Notify sub-meshes about modification
138 if ( !smmap.empty() ) {
139 set< SMESH_subMesh *>::iterator smIt;
140 for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
141 (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
146 //=======================================================================
147 //function : FindShape
148 //purpose : Return an index of the shape theElem is on
149 // or zero if a shape not found
150 //=======================================================================
152 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
154 SMESHDS_Mesh * aMesh = GetMeshDS();
155 if ( aMesh->ShapeToMesh().IsNull() )
158 if ( theElem->GetType() == SMDSAbs_Node )
160 const SMDS_PositionPtr& aPosition =
161 static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
162 if ( aPosition.get() )
163 return aPosition->GetShapeId();
168 TopoDS_Shape aShape; // the shape a node is on
169 SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
170 while ( nodeIt->more() )
172 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
173 const SMDS_PositionPtr& aPosition = node->GetPosition();
174 if ( aPosition.get() ) {
175 int aShapeID = aPosition->GetShapeId();
176 SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
179 if ( sm->Contains( theElem ))
181 if ( aShape.IsNull() )
182 aShape = aMesh->IndexToShape( aShapeID );
186 //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
191 // None of nodes is on a proper shape,
192 // find the shape among ancestors of aShape on which a node is
193 if ( aShape.IsNull() ) {
194 //MESSAGE ("::FindShape() - NONE node is on shape")
197 TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
198 for ( ; ancIt.More(); ancIt.Next() )
200 SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
201 if ( sm && sm->Contains( theElem ))
202 return aMesh->ShapeToIndex( ancIt.Value() );
205 //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
209 //=======================================================================
210 //function : InverseDiag
211 //purpose : Replace two neighbour triangles with ones built on the same 4 nodes
212 // but having other common link.
213 // Return False if args are improper
214 //=======================================================================
216 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
217 const SMDS_MeshElement * theTria2 )
219 if (!theTria1 || !theTria2)
221 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
222 if (!F1) return false;
223 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
224 if (!F2) return false;
226 // 1 +--+ A theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
227 // | /| theTria2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
231 // put nodes in array and find out indices of the same ones
232 const SMDS_MeshNode* aNodes [6];
233 int sameInd [] = { 0, 0, 0, 0, 0, 0 };
235 SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
238 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
240 if ( i > 2 ) // theTria2
241 // find same node of theTria1
242 for ( int j = 0; j < 3; j++ )
243 if ( aNodes[ i ] == aNodes[ j ]) {
252 return false; // theTria1 is not a triangle
253 it = theTria2->nodesIterator();
255 if ( i == 6 && it->more() )
256 return false; // theTria2 is not a triangle
259 // find indices of 1,2 and of A,B in theTria1
260 int iA = 0, iB = 0, i1 = 0, i2 = 0;
261 for ( i = 0; i < 6; i++ )
263 if ( sameInd [ i ] == 0 )
270 // nodes 1 and 2 should not be the same
271 if ( aNodes[ i1 ] == aNodes[ i2 ] )
276 aNodes[ iA ] = aNodes[ i2 ];
278 aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
280 //MESSAGE( theTria1 << theTria2 );
282 GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
283 GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
285 //MESSAGE( theTria1 << theTria2 );
290 //=======================================================================
291 //function : findTriangles
292 //purpose : find triangles sharing theNode1-theNode2 link
293 //=======================================================================
295 static bool findTriangles(const SMDS_MeshNode * theNode1,
296 const SMDS_MeshNode * theNode2,
297 const SMDS_MeshElement*& theTria1,
298 const SMDS_MeshElement*& theTria2)
300 if ( !theNode1 || !theNode2 ) return false;
302 theTria1 = theTria2 = 0;
304 set< const SMDS_MeshElement* > emap;
305 SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
307 const SMDS_MeshElement* elem = it->next();
308 if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
311 it = theNode2->GetInverseElementIterator();
313 const SMDS_MeshElement* elem = it->next();
314 if ( elem->GetType() == SMDSAbs_Face &&
315 emap.find( elem ) != emap.end() )
323 return ( theTria1 && theTria2 );
326 //=======================================================================
327 //function : InverseDiag
328 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
329 // with ones built on the same 4 nodes but having other common link.
330 // Return false if proper faces not found
331 //=======================================================================
333 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
334 const SMDS_MeshNode * theNode2)
336 MESSAGE( "::InverseDiag()" );
338 const SMDS_MeshElement *tr1, *tr2;
339 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
342 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
343 if (!F1) return false;
344 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
345 if (!F2) return false;
347 // 1 +--+ A tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
348 // | /| tr2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
352 // put nodes in array
353 // and find indices of 1,2 and of A in tr1 and of B in tr2
354 int i, iA1 = 0, i1 = 0;
355 const SMDS_MeshNode* aNodes1 [3];
356 SMDS_ElemIteratorPtr it;
357 for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
358 aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
359 if ( aNodes1[ i ] == theNode1 )
360 iA1 = i; // node A in tr1
361 else if ( aNodes1[ i ] != theNode2 )
365 const SMDS_MeshNode* aNodes2 [3];
366 for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
367 aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
368 if ( aNodes2[ i ] == theNode2 )
369 iB2 = i; // node B in tr2
370 else if ( aNodes2[ i ] != theNode1 )
374 // nodes 1 and 2 should not be the same
375 if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
379 aNodes1[ iA1 ] = aNodes2[ i2 ];
381 aNodes2[ iB2 ] = aNodes1[ i1 ];
383 //MESSAGE( tr1 << tr2 );
385 GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
386 GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
388 //MESSAGE( tr1 << tr2 );
394 //=======================================================================
395 //function : getQuadrangleNodes
396 //purpose : fill theQuadNodes - nodes of a quadrangle resulting from
397 // fusion of triangles tr1 and tr2 having shared link on
398 // theNode1 and theNode2
399 //=======================================================================
401 bool getQuadrangleNodes(const SMDS_MeshNode * theQuadNodes [],
402 const SMDS_MeshNode * theNode1,
403 const SMDS_MeshNode * theNode2,
404 const SMDS_MeshElement * tr1,
405 const SMDS_MeshElement * tr2 )
407 // find the 4-th node to insert into tr1
408 const SMDS_MeshNode* n4 = 0;
409 SMDS_ElemIteratorPtr it = tr2->nodesIterator();
410 while ( !n4 && it->more() )
412 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
413 bool isDiag = ( n == theNode1 || n == theNode2 );
417 // Make an array of nodes to be in a quadrangle
418 int iNode = 0, iFirstDiag = -1;
419 it = tr1->nodesIterator();
422 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
423 bool isDiag = ( n == theNode1 || n == theNode2 );
426 if ( iFirstDiag < 0 )
428 else if ( iNode - iFirstDiag == 1 )
429 theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
433 return false; // tr1 and tr2 should not have all the same nodes
435 theQuadNodes[ iNode++ ] = n;
437 if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
438 theQuadNodes[ iNode ] = n4;
443 //=======================================================================
444 //function : DeleteDiag
445 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
446 // with a quadrangle built on the same 4 nodes.
447 // Return false if proper faces not found
448 //=======================================================================
450 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
451 const SMDS_MeshNode * theNode2)
453 MESSAGE( "::DeleteDiag()" );
455 const SMDS_MeshElement *tr1, *tr2;
456 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
459 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
460 if (!F1) return false;
461 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
462 if (!F2) return false;
464 const SMDS_MeshNode* aNodes [ 4 ];
465 if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
468 //MESSAGE( endl << tr1 << tr2 );
470 GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
471 GetMeshDS()->RemoveElement( tr2 );
473 //MESSAGE( endl << tr1 );
478 //=======================================================================
479 //function : Reorient
480 //purpose : Reverse theElement orientation
481 //=======================================================================
483 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
487 SMDS_ElemIteratorPtr it = theElem->nodesIterator();
488 if ( !it || !it->more() )
491 switch ( theElem->GetType() ) {
496 int i = theElem->NbNodes();
497 vector<const SMDS_MeshNode*> aNodes( i );
499 aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
500 return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
504 if (theElem->IsPoly()) {
505 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
506 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
508 MESSAGE("Warning: bad volumic element");
512 int nbFaces = aPolyedre->NbFaces();
513 vector<const SMDS_MeshNode *> poly_nodes;
514 vector<int> quantities (nbFaces);
516 // reverse each face of the polyedre
517 for (int iface = 1; iface <= nbFaces; iface++) {
518 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
519 quantities[iface - 1] = nbFaceNodes;
521 for (inode = nbFaceNodes; inode >= 1; inode--) {
522 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
523 poly_nodes.push_back(curNode);
527 return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
530 SMDS_VolumeTool vTool;
531 if ( !vTool.Set( theElem ))
534 return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
543 //=======================================================================
544 //function : getBadRate
546 //=======================================================================
548 static double getBadRate (const SMDS_MeshElement* theElem,
549 SMESH::Controls::NumericalFunctorPtr& theCrit)
551 SMESH::Controls::TSequenceOfXYZ P;
552 if ( !theElem || !theCrit->GetPoints( theElem, P ))
554 return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
555 //return theCrit->GetBadRate( theCrit->GetValue( theElem->GetID() ), theElem->NbNodes() );
558 //=======================================================================
559 //function : QuadToTri
560 //purpose : Cut quadrangles into triangles.
561 // theCrit is used to select a diagonal to cut
562 //=======================================================================
564 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> & theElems,
565 SMESH::Controls::NumericalFunctorPtr theCrit)
567 MESSAGE( "::QuadToTri()" );
569 if ( !theCrit.get() )
572 SMESHDS_Mesh * aMesh = GetMeshDS();
574 set< const SMDS_MeshElement * >::iterator itElem;
575 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
577 const SMDS_MeshElement* elem = (*itElem);
578 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
581 // retrieve element nodes
582 const SMDS_MeshNode* aNodes [4];
583 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
585 while ( itN->more() )
586 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
588 // compare two sets of possible triangles
589 double aBadRate1, aBadRate2; // to what extent a set is bad
590 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
591 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
592 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
594 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
595 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
596 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
598 int aShapeId = FindShape( elem );
599 //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
600 // << " ShapeID = " << aShapeId << endl << elem );
602 if ( aBadRate1 <= aBadRate2 ) {
603 // tr1 + tr2 is better
604 aMesh->ChangeElementNodes( elem, aNodes, 3 );
605 //MESSAGE( endl << elem );
607 elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
610 // tr3 + tr4 is better
611 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
612 //MESSAGE( endl << elem );
614 elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
616 //MESSAGE( endl << elem );
618 // put a new triangle on the same shape
620 aMesh->SetMeshElementOnShape( elem, aShapeId );
626 //=======================================================================
627 //function : BestSplit
628 //purpose : Find better diagonal for cutting.
629 //=======================================================================
630 int SMESH_MeshEditor::BestSplit (const SMDS_MeshElement* theQuad,
631 SMESH::Controls::NumericalFunctorPtr theCrit)
636 if (!theQuad || theQuad->GetType() != SMDSAbs_Face || theQuad->NbNodes() != 4)
639 // retrieve element nodes
640 const SMDS_MeshNode* aNodes [4];
641 SMDS_ElemIteratorPtr itN = theQuad->nodesIterator();
644 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
646 // compare two sets of possible triangles
647 double aBadRate1, aBadRate2; // to what extent a set is bad
648 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
649 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
650 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
652 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
653 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
654 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
656 if (aBadRate1 <= aBadRate2) // tr1 + tr2 is better
657 return 1; // diagonal 1-3
659 return 2; // diagonal 2-4
662 //=======================================================================
663 //function : AddToSameGroups
664 //purpose : add elemToAdd to the groups the elemInGroups belongs to
665 //=======================================================================
667 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
668 const SMDS_MeshElement* elemInGroups,
669 SMESHDS_Mesh * aMesh)
671 const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
672 set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
673 for ( ; grIt != groups.end(); grIt++ ) {
674 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
675 if ( group && group->SMDSGroup().Contains( elemInGroups ))
676 group->SMDSGroup().Add( elemToAdd );
680 //=======================================================================
681 //function : QuadToTri
682 //purpose : Cut quadrangles into triangles.
683 // theCrit is used to select a diagonal to cut
684 //=======================================================================
686 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
687 const bool the13Diag)
689 MESSAGE( "::QuadToTri()" );
691 SMESHDS_Mesh * aMesh = GetMeshDS();
693 set< const SMDS_MeshElement * >::iterator itElem;
694 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
696 const SMDS_MeshElement* elem = (*itElem);
697 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
700 // retrieve element nodes
701 const SMDS_MeshNode* aNodes [4];
702 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
704 while ( itN->more() )
705 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
707 int aShapeId = FindShape( elem );
708 const SMDS_MeshElement* newElem = 0;
711 aMesh->ChangeElementNodes( elem, aNodes, 3 );
712 newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
716 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
717 newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
720 // put a new triangle on the same shape and add to the same groups
723 aMesh->SetMeshElementOnShape( newElem, aShapeId );
725 AddToSameGroups( newElem, elem, aMesh );
731 //=======================================================================
732 //function : getAngle
734 //=======================================================================
736 double getAngle(const SMDS_MeshElement * tr1,
737 const SMDS_MeshElement * tr2,
738 const SMDS_MeshNode * n1,
739 const SMDS_MeshNode * n2)
741 double angle = 2*PI; // bad angle
744 SMESH::Controls::TSequenceOfXYZ P1, P2;
745 if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
746 !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
748 gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
749 if ( N1.SquareMagnitude() <= gp::Resolution() )
751 gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
752 if ( N2.SquareMagnitude() <= gp::Resolution() )
755 // find the first diagonal node n1 in the triangles:
756 // take in account a diagonal link orientation
757 const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
758 for ( int t = 0; t < 2; t++ )
760 SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
761 int i = 0, iDiag = -1;
762 while ( it->more()) {
763 const SMDS_MeshElement *n = it->next();
764 if ( n == n1 || n == n2 )
768 if ( i - iDiag == 1 )
769 nFirst[ t ] = ( n == n1 ? n2 : n1 );
777 if ( nFirst[ 0 ] == nFirst[ 1 ] )
780 angle = N1.Angle( N2 );
785 // =================================================
786 // class generating a unique ID for a pair of nodes
787 // and able to return nodes by that ID
788 // =================================================
793 LinkID_Gen( const SMESHDS_Mesh* theMesh )
794 :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
797 long GetLinkID (const SMDS_MeshNode * n1,
798 const SMDS_MeshNode * n2) const
800 return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
803 bool GetNodes (const long theLinkID,
804 const SMDS_MeshNode* & theNode1,
805 const SMDS_MeshNode* & theNode2) const
807 theNode1 = myMesh->FindNode( theLinkID / myMaxID );
808 if ( !theNode1 ) return false;
809 theNode2 = myMesh->FindNode( theLinkID % myMaxID );
810 if ( !theNode2 ) return false;
816 const SMESHDS_Mesh* myMesh;
820 //=======================================================================
821 //function : TriToQuad
822 //purpose : Fuse neighbour triangles into quadrangles.
823 // theCrit is used to select a neighbour to fuse with.
824 // theMaxAngle is a max angle between element normals at which
825 // fusion is still performed.
826 //=======================================================================
828 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> & theElems,
829 SMESH::Controls::NumericalFunctorPtr theCrit,
830 const double theMaxAngle)
832 MESSAGE( "::TriToQuad()" );
834 if ( !theCrit.get() )
837 SMESHDS_Mesh * aMesh = GetMeshDS();
838 LinkID_Gen aLinkID_Gen( aMesh );
841 // Prepare data for algo: build
842 // 1. map of elements with their linkIDs
843 // 2. map of linkIDs with their elements
845 map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
846 map< long, list< const SMDS_MeshElement* > >::iterator itLE;
847 map< const SMDS_MeshElement*, set< long > > mapEl_setLi;
848 map< const SMDS_MeshElement*, set< long > >::iterator itEL;
850 set<const SMDS_MeshElement*>::iterator itElem;
851 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
853 const SMDS_MeshElement* elem = (*itElem);
854 if ( !elem || elem->NbNodes() != 3 )
857 // retrieve element nodes
858 const SMDS_MeshNode* aNodes [4];
859 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
861 while ( itN->more() )
862 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
864 aNodes[ 3 ] = aNodes[ 0 ];
867 for ( i = 0; i < 3; i++ )
869 long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
870 // check if elements sharing a link can be fused
871 itLE = mapLi_listEl.find( linkID );
872 if ( itLE != mapLi_listEl.end() )
874 if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
876 const SMDS_MeshElement* elem2 = (*itLE).second.front();
877 // if ( FindShape( elem ) != FindShape( elem2 ))
878 // continue; // do not fuse triangles laying on different shapes
879 if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
880 continue; // avoid making badly shaped quads
881 (*itLE).second.push_back( elem );
884 mapLi_listEl[ linkID ].push_back( elem );
885 mapEl_setLi [ elem ].insert( linkID );
888 // Clean the maps from the links shared by a sole element, ie
889 // links to which only one element is bound in mapLi_listEl
891 for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
893 int nbElems = (*itLE).second.size();
895 const SMDS_MeshElement* elem = (*itLE).second.front();
896 long link = (*itLE).first;
897 mapEl_setLi[ elem ].erase( link );
898 if ( mapEl_setLi[ elem ].empty() )
899 mapEl_setLi.erase( elem );
903 // Algo: fuse triangles into quadrangles
905 while ( ! mapEl_setLi.empty() )
907 // Look for the start element:
908 // the element having the least nb of shared links
910 const SMDS_MeshElement* startElem = 0;
912 for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
914 int nbLinks = (*itEL).second.size();
915 if ( nbLinks < minNbLinks )
917 startElem = (*itEL).first;
918 minNbLinks = nbLinks;
919 if ( minNbLinks == 1 )
924 // search elements to fuse starting from startElem or links of elements
925 // fused earlyer - startLinks
926 list< long > startLinks;
927 while ( startElem || !startLinks.empty() )
929 while ( !startElem && !startLinks.empty() )
931 // Get an element to start, by a link
932 long linkId = startLinks.front();
933 startLinks.pop_front();
934 itLE = mapLi_listEl.find( linkId );
935 if ( itLE != mapLi_listEl.end() )
937 list< const SMDS_MeshElement* > & listElem = (*itLE).second;
938 list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
939 for ( ; itE != listElem.end() ; itE++ )
940 if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
942 mapLi_listEl.erase( itLE );
948 // Get candidates to be fused
950 const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
953 ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
954 set< long >& setLi = mapEl_setLi[ tr1 ];
955 ASSERT( !setLi.empty() );
956 set< long >::iterator itLi;
957 for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
959 long linkID = (*itLi);
960 itLE = mapLi_listEl.find( linkID );
961 if ( itLE == mapLi_listEl.end() )
963 const SMDS_MeshElement* elem = (*itLE).second.front();
965 elem = (*itLE).second.back();
966 mapLi_listEl.erase( itLE );
967 if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
980 // add other links of elem to list of links to re-start from
981 set< long >& links = mapEl_setLi[ elem ];
982 set< long >::iterator it;
983 for ( it = links.begin(); it != links.end(); it++ )
985 long linkID2 = (*it);
986 if ( linkID2 != linkID )
987 startLinks.push_back( linkID2 );
991 // Get nodes of possible quadrangles
993 const SMDS_MeshNode *n12 [4], *n13 [4];
994 bool Ok12 = false, Ok13 = false;
995 const SMDS_MeshNode *linkNode1, *linkNode2;
997 aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
998 getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
1001 aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
1002 getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
1005 // Choose a pair to fuse
1009 SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
1010 SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
1011 double aBadRate12 = getBadRate( &quad12, theCrit );
1012 double aBadRate13 = getBadRate( &quad13, theCrit );
1013 if ( aBadRate13 < aBadRate12 )
1021 // and remove fused elems and removed links from the maps
1023 mapEl_setLi.erase( tr1 );
1026 mapEl_setLi.erase( tr2 );
1027 mapLi_listEl.erase( link12 );
1028 aMesh->ChangeElementNodes( tr1, n12, 4 );
1029 aMesh->RemoveElement( tr2 );
1033 mapEl_setLi.erase( tr3 );
1034 mapLi_listEl.erase( link13 );
1035 aMesh->ChangeElementNodes( tr1, n13, 4 );
1036 aMesh->RemoveElement( tr3 );
1039 // Next element to fuse: the rejected one
1041 startElem = Ok12 ? tr3 : tr2;
1043 } // if ( startElem )
1044 } // while ( startElem || !startLinks.empty() )
1045 } // while ( ! mapEl_setLi.empty() )
1051 /*#define DUMPSO(txt) \
1052 // cout << txt << endl;
1053 //=============================================================================
1057 //=============================================================================
1058 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1062 int tmp = idNodes[ i1 ];
1063 idNodes[ i1 ] = idNodes[ i2 ];
1064 idNodes[ i2 ] = tmp;
1065 gp_Pnt Ptmp = P[ i1 ];
1068 DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1071 //=======================================================================
1072 //function : SortQuadNodes
1073 //purpose : Set 4 nodes of a quadrangle face in a good order.
1074 // Swap 1<->2 or 2<->3 nodes and correspondingly return
1076 //=======================================================================
1078 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1083 for ( i = 0; i < 4; i++ ) {
1084 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1086 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1089 gp_Vec V1(P[0], P[1]);
1090 gp_Vec V2(P[0], P[2]);
1091 gp_Vec V3(P[0], P[3]);
1093 gp_Vec Cross1 = V1 ^ V2;
1094 gp_Vec Cross2 = V2 ^ V3;
1097 if (Cross1.Dot(Cross2) < 0)
1102 if (Cross1.Dot(Cross2) < 0)
1106 swap ( i, i + 1, idNodes, P );
1108 // for ( int ii = 0; ii < 4; ii++ ) {
1109 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1110 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1116 //=======================================================================
1117 //function : SortHexaNodes
1118 //purpose : Set 8 nodes of a hexahedron in a good order.
1119 // Return success status
1120 //=======================================================================
1122 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1127 DUMPSO( "INPUT: ========================================");
1128 for ( i = 0; i < 8; i++ ) {
1129 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1130 if ( !n ) return false;
1131 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1132 DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1134 DUMPSO( "========================================");
1137 set<int> faceNodes; // ids of bottom face nodes, to be found
1138 set<int> checkedId1; // ids of tried 2-nd nodes
1139 Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1140 const Standard_Real tol = 1.e-6; // tolerance to find nodes in plane
1141 int iMin, iLoop1 = 0;
1143 // Loop to try the 2-nd nodes
1145 while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1147 // Find not checked 2-nd node
1148 for ( i = 1; i < 8; i++ )
1149 if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1150 int id1 = idNodes[i];
1151 swap ( 1, i, idNodes, P );
1152 checkedId1.insert ( id1 );
1156 // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1157 // ie that all but meybe one (id3 which is on the same face) nodes
1158 // lay on the same side from the triangle plane.
1160 bool manyInPlane = false; // more than 4 nodes lay in plane
1162 while ( ++iLoop2 < 6 ) {
1164 // get 1-2-3 plane coeffs
1165 Standard_Real A, B, C, D;
1166 gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1167 if ( N.SquareMagnitude() > gp::Resolution() )
1169 gp_Pln pln ( P[0], N );
1170 pln.Coefficients( A, B, C, D );
1172 // find the node (iMin) closest to pln
1173 Standard_Real dist[ 8 ], minDist = DBL_MAX;
1175 for ( i = 3; i < 8; i++ ) {
1176 dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1177 if ( fabs( dist[i] ) < minDist ) {
1178 minDist = fabs( dist[i] );
1181 if ( fabs( dist[i] ) <= tol )
1182 idInPln.insert( idNodes[i] );
1185 // there should not be more than 4 nodes in bottom plane
1186 if ( idInPln.size() > 1 )
1188 DUMPSO( "### idInPln.size() = " << idInPln.size());
1189 // idInPlane does not contain the first 3 nodes
1190 if ( manyInPlane || idInPln.size() == 5)
1191 return false; // all nodes in one plane
1194 // set the 1-st node to be not in plane
1195 for ( i = 3; i < 8; i++ ) {
1196 if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1197 DUMPSO( "### Reset 0-th node");
1198 swap( 0, i, idNodes, P );
1203 // reset to re-check second nodes
1204 leastDist = DBL_MAX;
1208 break; // from iLoop2;
1211 // check that the other 4 nodes are on the same side
1212 bool sameSide = true;
1213 bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1214 for ( i = 3; sameSide && i < 8; i++ ) {
1216 sameSide = ( isNeg == dist[i] <= 0.);
1219 // keep best solution
1220 if ( sameSide && minDist < leastDist ) {
1221 leastDist = minDist;
1223 faceNodes.insert( idNodes[ 1 ] );
1224 faceNodes.insert( idNodes[ 2 ] );
1225 faceNodes.insert( idNodes[ iMin ] );
1226 DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1227 << " leastDist = " << leastDist);
1228 if ( leastDist <= DBL_MIN )
1233 // set next 3-d node to check
1234 int iNext = 2 + iLoop2;
1236 DUMPSO( "Try 2-nd");
1237 swap ( 2, iNext, idNodes, P );
1239 } // while ( iLoop2 < 6 )
1242 if ( faceNodes.empty() ) return false;
1244 // Put the faceNodes in proper places
1245 for ( i = 4; i < 8; i++ ) {
1246 if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1247 // find a place to put
1249 while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1251 DUMPSO( "Set faceNodes");
1252 swap ( iTo, i, idNodes, P );
1257 // Set nodes of the found bottom face in good order
1258 DUMPSO( " Found bottom face: ");
1259 i = SortQuadNodes( theMesh, idNodes );
1261 gp_Pnt Ptmp = P[ i ];
1266 // for ( int ii = 0; ii < 4; ii++ ) {
1267 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1268 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1271 // Gravity center of the top and bottom faces
1272 gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1273 gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1275 // Get direction from the bottom to the top face
1276 gp_Vec upDir ( aGCb, aGCt );
1277 Standard_Real upDirSize = upDir.Magnitude();
1278 if ( upDirSize <= gp::Resolution() ) return false;
1281 // Assure that the bottom face normal points up
1282 gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1283 Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1284 if ( Nb.Dot( upDir ) < 0 ) {
1285 DUMPSO( "Reverse bottom face");
1286 swap( 1, 3, idNodes, P );
1289 // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1290 Standard_Real minDist = DBL_MAX;
1291 for ( i = 4; i < 8; i++ ) {
1292 // projection of P[i] to the plane defined by P[0] and upDir
1293 gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1294 Standard_Real sqDist = P[0].SquareDistance( Pp );
1295 if ( sqDist < minDist ) {
1300 DUMPSO( "Set 4-th");
1301 swap ( 4, iMin, idNodes, P );
1303 // Set nodes of the top face in good order
1304 DUMPSO( "Sort top face");
1305 i = SortQuadNodes( theMesh, &idNodes[4] );
1308 gp_Pnt Ptmp = P[ i ];
1313 // Assure that direction of the top face normal is from the bottom face
1314 gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1315 Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1316 if ( Nt.Dot( upDir ) < 0 ) {
1317 DUMPSO( "Reverse top face");
1318 swap( 5, 7, idNodes, P );
1321 // DUMPSO( "OUTPUT: ========================================");
1322 // for ( i = 0; i < 8; i++ ) {
1323 // float *p = ugrid->GetPoint(idNodes[i]);
1324 // DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1330 //=======================================================================
1331 //function : laplacianSmooth
1332 //purpose : pulls theNode toward the center of surrounding nodes directly
1333 // connected to that node along an element edge
1334 //=======================================================================
1336 void laplacianSmooth(const SMDS_MeshNode* theNode,
1337 const Handle(Geom_Surface)& theSurface,
1338 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1340 // find surrounding nodes
1342 set< const SMDS_MeshNode* > nodeSet;
1343 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1344 while ( elemIt->more() )
1346 const SMDS_MeshElement* elem = elemIt->next();
1347 if ( elem->GetType() != SMDSAbs_Face )
1350 // put all nodes in array
1351 int nbNodes = 0, iNode = 0;
1352 vector< const SMDS_MeshNode*> aNodes( elem->NbNodes() );
1353 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1354 while ( itN->more() )
1356 aNodes[ nbNodes ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1357 if ( aNodes[ nbNodes ] == theNode )
1358 iNode = nbNodes; // index of theNode within aNodes
1362 int iAfter = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1363 nodeSet.insert( aNodes[ iAfter ]);
1364 int iBefore = ( iNode == 0 ) ? nbNodes - 1 : iNode - 1;
1365 nodeSet.insert( aNodes[ iBefore ]);
1368 // compute new coodrs
1370 double coord[] = { 0., 0., 0. };
1371 set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1372 for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1373 const SMDS_MeshNode* node = (*nodeSetIt);
1374 if ( theSurface.IsNull() ) { // smooth in 3D
1375 coord[0] += node->X();
1376 coord[1] += node->Y();
1377 coord[2] += node->Z();
1379 else { // smooth in 2D
1380 ASSERT( theUVMap.find( node ) != theUVMap.end() );
1381 gp_XY* uv = theUVMap[ node ];
1382 coord[0] += uv->X();
1383 coord[1] += uv->Y();
1386 int nbNodes = nodeSet.size();
1389 coord[0] /= nbNodes;
1390 coord[1] /= nbNodes;
1392 if ( !theSurface.IsNull() ) {
1393 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1394 theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
1395 gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
1401 coord[2] /= nbNodes;
1405 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
1408 //=======================================================================
1409 //function : centroidalSmooth
1410 //purpose : pulls theNode toward the element-area-weighted centroid of the
1411 // surrounding elements
1412 //=======================================================================
1414 void centroidalSmooth(const SMDS_MeshNode* theNode,
1415 const Handle(Geom_Surface)& theSurface,
1416 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1418 gp_XYZ aNewXYZ(0.,0.,0.);
1419 SMESH::Controls::Area anAreaFunc;
1420 double totalArea = 0.;
1425 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1426 while ( elemIt->more() )
1428 const SMDS_MeshElement* elem = elemIt->next();
1429 if ( elem->GetType() != SMDSAbs_Face )
1433 gp_XYZ elemCenter(0.,0.,0.);
1434 SMESH::Controls::TSequenceOfXYZ aNodePoints;
1435 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1436 while ( itN->more() )
1438 const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1439 gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1440 aNodePoints.push_back( aP );
1441 if ( !theSurface.IsNull() ) { // smooth in 2D
1442 ASSERT( theUVMap.find( aNode ) != theUVMap.end() );
1443 gp_XY* uv = theUVMap[ aNode ];
1444 aP.SetCoord( uv->X(), uv->Y(), 0. );
1448 double elemArea = anAreaFunc.GetValue( aNodePoints );
1449 totalArea += elemArea;
1450 elemCenter /= elem->NbNodes();
1451 aNewXYZ += elemCenter * elemArea;
1453 aNewXYZ /= totalArea;
1454 if ( !theSurface.IsNull() ) {
1455 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1456 theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
1457 aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
1462 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
1465 //=======================================================================
1466 //function : getClosestUV
1467 //purpose : return UV of closest projection
1468 //=======================================================================
1470 static bool getClosestUV (Extrema_GenExtPS& projector,
1471 const gp_Pnt& point,
1474 projector.Perform( point );
1475 if ( projector.IsDone() ) {
1476 double u, v, minVal = DBL_MAX;
1477 for ( int i = projector.NbExt(); i > 0; i-- )
1478 if ( projector.Value( i ) < minVal ) {
1479 minVal = projector.Value( i );
1480 projector.Point( i ).Parameter( u, v );
1482 result.SetCoord( u, v );
1488 //=======================================================================
1490 //purpose : Smooth theElements during theNbIterations or until a worst
1491 // element has aspect ratio <= theTgtAspectRatio.
1492 // Aspect Ratio varies in range [1.0, inf].
1493 // If theElements is empty, the whole mesh is smoothed.
1494 // theFixedNodes contains additionally fixed nodes. Nodes built
1495 // on edges and boundary nodes are always fixed.
1496 //=======================================================================
1498 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1499 set<const SMDS_MeshNode*> & theFixedNodes,
1500 const SmoothMethod theSmoothMethod,
1501 const int theNbIterations,
1502 double theTgtAspectRatio,
1505 MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1507 if ( theTgtAspectRatio < 1.0 )
1508 theTgtAspectRatio = 1.0;
1510 SMESH::Controls::AspectRatio aQualityFunc;
1512 SMESHDS_Mesh* aMesh = GetMeshDS();
1514 if ( theElems.empty() ) {
1515 // add all faces to theElems
1516 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1517 while ( fIt->more() )
1518 theElems.insert( fIt->next() );
1520 // get all face ids theElems are on
1521 set< int > faceIdSet;
1522 set< const SMDS_MeshElement* >::iterator itElem;
1524 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1525 int fId = FindShape( *itElem );
1526 // check that corresponding submesh exists and a shape is face
1528 faceIdSet.find( fId ) == faceIdSet.end() &&
1529 aMesh->MeshElements( fId )) {
1530 TopoDS_Shape F = aMesh->IndexToShape( fId );
1531 if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
1532 faceIdSet.insert( fId );
1535 faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
1537 // ===============================================
1538 // smooth elements on each TopoDS_Face separately
1539 // ===============================================
1541 set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
1542 for ( ; fId != faceIdSet.rend(); ++fId )
1544 // get face surface and submesh
1545 Handle(Geom_Surface) surface;
1546 SMESHDS_SubMesh* faceSubMesh = 0;
1548 double fToler2 = 0, vPeriod = 0., uPeriod = 0., f,l;
1549 double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
1550 bool isUPeriodic = false, isVPeriodic = false;
1552 face = TopoDS::Face( aMesh->IndexToShape( *fId ));
1553 surface = BRep_Tool::Surface( face );
1554 faceSubMesh = aMesh->MeshElements( *fId );
1555 fToler2 = BRep_Tool::Tolerance( face );
1556 fToler2 *= fToler2 * 10.;
1557 isUPeriodic = surface->IsUPeriodic();
1559 vPeriod = surface->UPeriod();
1560 isVPeriodic = surface->IsVPeriodic();
1562 uPeriod = surface->VPeriod();
1563 surface->Bounds( u1, u2, v1, v2 );
1565 // ---------------------------------------------------------
1566 // for elements on a face, find movable and fixed nodes and
1567 // compute UV for them
1568 // ---------------------------------------------------------
1569 bool checkBoundaryNodes = false;
1570 set<const SMDS_MeshNode*> setMovableNodes;
1571 map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
1572 list< gp_XY > listUV; // uvs the 2 uvMaps refer to
1573 list< const SMDS_MeshElement* > elemsOnFace;
1575 Extrema_GenExtPS projector;
1576 GeomAdaptor_Surface surfAdaptor;
1577 if ( !surface.IsNull() ) {
1578 surfAdaptor.Load( surface );
1579 projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
1581 int nbElemOnFace = 0;
1582 itElem = theElems.begin();
1583 // loop on not yet smoothed elements: look for elems on a face
1584 while ( itElem != theElems.end() )
1586 if ( faceSubMesh && nbElemOnFace == faceSubMesh->NbElements() )
1587 break; // all elements found
1589 const SMDS_MeshElement* elem = (*itElem);
1590 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
1591 ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
1595 elemsOnFace.push_back( elem );
1596 theElems.erase( itElem++ );
1599 // get movable nodes of elem
1600 const SMDS_MeshNode* node;
1601 SMDS_TypeOfPosition posType;
1602 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1603 while ( itN->more() ) {
1604 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1605 const SMDS_PositionPtr& pos = node->GetPosition();
1606 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1607 if (posType != SMDS_TOP_EDGE &&
1608 posType != SMDS_TOP_VERTEX &&
1609 theFixedNodes.find( node ) == theFixedNodes.end())
1611 // check if all faces around the node are on faceSubMesh
1612 // because a node on edge may be bound to face
1613 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1615 if ( faceSubMesh ) {
1616 while ( eIt->more() && all ) {
1617 const SMDS_MeshElement* e = eIt->next();
1618 if ( e->GetType() == SMDSAbs_Face )
1619 all = faceSubMesh->Contains( e );
1623 setMovableNodes.insert( node );
1625 checkBoundaryNodes = true;
1627 if ( posType == SMDS_TOP_3DSPACE )
1628 checkBoundaryNodes = true;
1631 if ( surface.IsNull() )
1634 // get nodes to check UV
1635 list< const SMDS_MeshNode* > uvCheckNodes;
1636 itN = elem->nodesIterator();
1637 while ( itN->more() ) {
1638 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1639 if ( uvMap.find( node ) == uvMap.end() )
1640 uvCheckNodes.push_back( node );
1641 // add nodes of elems sharing node
1642 // SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1643 // while ( eIt->more() ) {
1644 // const SMDS_MeshElement* e = eIt->next();
1645 // if ( e != elem && e->GetType() == SMDSAbs_Face ) {
1646 // SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1647 // while ( nIt->more() ) {
1648 // const SMDS_MeshNode* n =
1649 // static_cast<const SMDS_MeshNode*>( nIt->next() );
1650 // if ( uvMap.find( n ) == uvMap.end() )
1651 // uvCheckNodes.push_back( n );
1657 list< const SMDS_MeshNode* >::iterator n = uvCheckNodes.begin();
1658 for ( ; n != uvCheckNodes.end(); ++n )
1662 const SMDS_PositionPtr& pos = node->GetPosition();
1663 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1665 switch ( posType ) {
1666 case SMDS_TOP_FACE: {
1667 SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
1668 uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
1671 case SMDS_TOP_EDGE: {
1672 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1673 Handle(Geom2d_Curve) pcurve;
1674 if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
1675 pcurve = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), face, f,l );
1676 if ( !pcurve.IsNull() ) {
1677 double u = (( SMDS_EdgePosition* ) pos.get() )->GetUParameter();
1678 uv = pcurve->Value( u ).XY();
1682 case SMDS_TOP_VERTEX: {
1683 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1684 if ( !S.IsNull() && S.ShapeType() == TopAbs_VERTEX )
1685 uv = BRep_Tool::Parameters( TopoDS::Vertex( S ), face ).XY();
1690 // check existing UV
1691 bool project = true;
1692 gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
1693 double dist1 = DBL_MAX, dist2 = 0;
1694 if ( posType != SMDS_TOP_3DSPACE ) {
1695 dist1 = pNode.SquareDistance( surface->Value( uv.X(), uv.Y() ));
1696 project = dist1 > fToler2;
1698 if ( project ) { // compute new UV
1700 if ( !getClosestUV( projector, pNode, newUV )) {
1701 MESSAGE("Node Projection Failed " << node);
1705 newUV.SetX( ElCLib::InPeriod( newUV.X(), u1, u2 ));
1707 newUV.SetY( ElCLib::InPeriod( newUV.Y(), v1, v2 ));
1709 if ( posType != SMDS_TOP_3DSPACE )
1710 dist2 = pNode.SquareDistance( surface->Value( newUV.X(), newUV.Y() ));
1711 if ( dist2 < dist1 )
1715 // store UV in the map
1716 listUV.push_back( uv );
1717 uvMap.insert( make_pair( node, &listUV.back() ));
1719 } // loop on not yet smoothed elements
1721 if ( !faceSubMesh || nbElemOnFace != faceSubMesh->NbElements() )
1722 checkBoundaryNodes = true;
1724 // fix nodes on mesh boundary
1726 if ( checkBoundaryNodes )
1728 typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
1729 map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
1730 map< TLink, int >::iterator link_nb;
1731 // put all elements links to linkNbMap
1732 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1733 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1735 // put elem nodes in array
1736 vector< const SMDS_MeshNode* > nodes;
1737 nodes.reserve( (*elemIt)->NbNodes() + 1 );
1738 SMDS_ElemIteratorPtr itN = (*elemIt)->nodesIterator();
1739 while ( itN->more() )
1740 nodes.push_back( static_cast<const SMDS_MeshNode*>( itN->next() ));
1741 nodes.push_back( nodes.front() );
1742 // loop on elem links: insert them in linkNbMap
1743 for ( int iN = 1; iN < nodes.size(); ++iN ) {
1745 if ( nodes[ iN-1 ]->GetID() < nodes[ iN ]->GetID() )
1746 link = make_pair( nodes[ iN-1 ], nodes[ iN ] );
1748 link = make_pair( nodes[ iN ], nodes[ iN-1 ] );
1749 link_nb = linkNbMap.find( link );
1750 if ( link_nb == linkNbMap.end() )
1751 linkNbMap.insert( make_pair ( link, 1 ));
1756 // remove nodes that are in links encountered only once from setMovableNodes
1757 for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
1758 if ( link_nb->second == 1 ) {
1759 setMovableNodes.erase( link_nb->first.first );
1760 setMovableNodes.erase( link_nb->first.second );
1765 // -----------------------------------------------------
1766 // for nodes on seam edge, compute one more UV ( uvMap2 );
1767 // find movable nodes linked to nodes on seam and which
1768 // are to be smoothed using the second UV ( uvMap2 )
1769 // -----------------------------------------------------
1771 set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
1772 if ( !surface.IsNull() )
1774 TopExp_Explorer eExp( face, TopAbs_EDGE );
1775 for ( ; eExp.More(); eExp.Next() )
1777 TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
1778 if ( !BRep_Tool::IsClosed( edge, face ))
1780 SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
1781 if ( !sm ) continue;
1782 // find out which parameter varies for a node on seam
1785 Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1786 if ( pcurve.IsNull() ) continue;
1787 uv1 = pcurve->Value( f );
1789 pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1790 if ( pcurve.IsNull() ) continue;
1791 uv2 = pcurve->Value( f );
1792 int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
1794 if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
1795 gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
1797 // get nodes on seam and its vertices
1798 list< const SMDS_MeshNode* > seamNodes;
1799 SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
1800 while ( nSeamIt->more() )
1801 seamNodes.push_back( nSeamIt->next() );
1802 TopExp_Explorer vExp( edge, TopAbs_VERTEX );
1803 for ( ; vExp.More(); vExp.Next() ) {
1804 sm = aMesh->MeshElements( vExp.Current() );
1806 nSeamIt = sm->GetNodes();
1807 while ( nSeamIt->more() )
1808 seamNodes.push_back( nSeamIt->next() );
1811 // loop on nodes on seam
1812 list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
1813 for ( ; noSeIt != seamNodes.end(); ++noSeIt )
1815 const SMDS_MeshNode* nSeam = *noSeIt;
1816 map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
1817 if ( n_uv == uvMap.end() )
1820 n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
1821 // set the second UV
1822 listUV.push_back( *n_uv->second );
1823 listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
1824 if ( uvMap2.empty() )
1825 uvMap2 = uvMap; // copy the uvMap contents
1826 uvMap2[ nSeam ] = &listUV.back();
1828 // collect movable nodes linked to ones on seam in nodesNearSeam
1829 SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator();
1830 while ( eIt->more() )
1832 const SMDS_MeshElement* e = eIt->next();
1833 if ( e->GetType() != SMDSAbs_Face )
1835 int nbUseMap1 = 0, nbUseMap2 = 0;
1836 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1837 while ( nIt->more() )
1839 const SMDS_MeshNode* n =
1840 static_cast<const SMDS_MeshNode*>( nIt->next() );
1842 setMovableNodes.find( n ) == setMovableNodes.end() )
1844 // add only nodes being closer to uv2 than to uv1
1845 gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
1846 0.5 * ( n->Y() + nSeam->Y() ),
1847 0.5 * ( n->Z() + nSeam->Z() ));
1849 getClosestUV( projector, pMid, uv );
1850 if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
1851 nodesNearSeam.insert( n );
1857 // for centroidalSmooth all element nodes must
1858 // be on one side of a seam
1859 if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 )
1861 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1862 while ( nIt->more() ) {
1863 const SMDS_MeshNode* n =
1864 static_cast<const SMDS_MeshNode*>( nIt->next() );
1865 setMovableNodes.erase( n );
1869 } // loop on nodes on seam
1870 } // loop on edge of a face
1871 } // if ( !face.IsNull() )
1873 if ( setMovableNodes.empty() ) {
1874 MESSAGE( "Face id : " << *fId << " - NO SMOOTHING: no nodes to move!!!");
1875 continue; // goto next face
1883 double maxRatio = -1., maxDisplacement = -1.;
1884 set<const SMDS_MeshNode*>::iterator nodeToMove;
1885 for ( it = 0; it < theNbIterations; it++ )
1887 maxDisplacement = 0.;
1888 nodeToMove = setMovableNodes.begin();
1889 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1891 const SMDS_MeshNode* node = (*nodeToMove);
1892 gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1895 bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
1896 if ( theSmoothMethod == LAPLACIAN )
1897 laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
1899 centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
1901 // node displacement
1902 gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1903 Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1904 if ( aDispl > maxDisplacement )
1905 maxDisplacement = aDispl;
1907 // no node movement => exit
1908 if ( maxDisplacement < 1.e-16 ) {
1909 MESSAGE("-- no node movement --");
1913 // check elements quality
1915 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1916 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1918 const SMDS_MeshElement* elem = (*elemIt);
1919 if ( !elem || elem->GetType() != SMDSAbs_Face )
1921 SMESH::Controls::TSequenceOfXYZ aPoints;
1922 if ( aQualityFunc.GetPoints( elem, aPoints )) {
1923 double aValue = aQualityFunc.GetValue( aPoints );
1924 if ( aValue > maxRatio )
1928 if ( maxRatio <= theTgtAspectRatio ) {
1929 MESSAGE("-- quality achived --");
1932 if (it+1 == theNbIterations) {
1933 MESSAGE("-- Iteration limit exceeded --");
1935 } // smoothing iterations
1937 MESSAGE(" Face id: " << *fId <<
1938 " Nb iterstions: " << it <<
1939 " Displacement: " << maxDisplacement <<
1940 " Aspect Ratio " << maxRatio);
1942 // ---------------------------------------
1943 // new nodes positions are computed,
1944 // record movement in DS and set new UV
1945 // ---------------------------------------
1947 nodeToMove = setMovableNodes.begin();
1948 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1950 SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
1951 aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
1952 map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
1953 if ( node_uv != uvMap.end() ) {
1954 gp_XY* uv = node_uv->second;
1956 ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
1960 } // loop on face ids
1963 //=======================================================================
1964 //function : isReverse
1965 //purpose : Return true if normal of prevNodes is not co-directied with
1966 // gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1967 // iNotSame is where prevNodes and nextNodes are different
1968 //=======================================================================
1970 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1971 const SMDS_MeshNode* nextNodes[],
1975 int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1976 int iAfterNotSame = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1978 const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1979 const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1980 const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1981 const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1983 gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1984 gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1985 gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1986 gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1988 gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1990 return (vA ^ vB) * vN < 0.0;
1993 //=======================================================================
1994 //function : sweepElement
1996 //=======================================================================
1998 static void sweepElement(SMESHDS_Mesh* aMesh,
1999 const SMDS_MeshElement* elem,
2000 const vector<TNodeOfNodeListMapItr> & newNodesItVec,
2001 list<const SMDS_MeshElement*>& newElems)
2003 // Loop on elem nodes:
2004 // find new nodes and detect same nodes indices
2005 int nbNodes = elem->NbNodes();
2006 list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
2007 const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
2008 int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
2010 for ( iNode = 0; iNode < nbNodes; iNode++ )
2012 TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
2013 const SMDS_MeshNode* node = nnIt->first;
2014 const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
2015 if ( listNewNodes.empty() )
2018 itNN[ iNode ] = listNewNodes.begin();
2019 prevNod[ iNode ] = node;
2020 nextNod[ iNode ] = listNewNodes.front();
2021 if ( prevNod[ iNode ] != nextNod [ iNode ])
2022 iNotSameNode = iNode;
2028 if ( nbSame == nbNodes || nbSame > 2) {
2029 MESSAGE( " Too many same nodes of element " << elem->GetID() );
2033 int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
2035 iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
2036 iAfterSame = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
2037 iOpposSame = ( iSameNode - 2 < 0 ? iSameNode + 2 : iSameNode - 2 );
2040 // check element orientation
2042 if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
2043 //MESSAGE("Reversed elem " << elem );
2047 int iAB = iAfterSame + iBeforeSame;
2048 iBeforeSame = iAB - iBeforeSame;
2049 iAfterSame = iAB - iAfterSame;
2053 // make new elements
2054 int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
2055 for (iStep = 0; iStep < nbSteps; iStep++ )
2058 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2059 nextNod[ iNode ] = *itNN[ iNode ];
2062 SMDS_MeshElement* aNewElem = 0;
2069 aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
2075 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2076 nextNod[ 1 ], nextNod[ 0 ] );
2078 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2079 nextNod[ iNotSameNode ] );
2082 case 3: { // TRIANGLE
2084 if ( nbSame == 0 ) // --- pentahedron
2085 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2086 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
2088 else if ( nbSame == 1 ) // --- pyramid
2089 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2090 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2091 nextNod[ iSameNode ]);
2093 else // 2 same nodes: --- tetrahedron
2094 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2095 nextNod[ iNotSameNode ]);
2098 case 4: { // QUADRANGLE
2100 if ( nbSame == 0 ) // --- hexahedron
2101 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
2102 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
2104 else if ( nbSame == 1 ) // --- pyramid + pentahedron
2106 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2107 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2108 nextNod[ iSameNode ]);
2109 newElems.push_back( aNewElem );
2110 aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iOpposSame ],
2111 prevNod[ iBeforeSame ], nextNod[ iAfterSame ],
2112 nextNod[ iOpposSame ], nextNod[ iBeforeSame ] );
2114 else if ( nbSame == 2 ) // pentahedron
2116 if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
2117 // iBeforeSame is same too
2118 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
2119 nextNod[ iOpposSame ], prevNod[ iSameNode ],
2120 prevNod[ iAfterSame ], nextNod[ iAfterSame ]);
2122 // iAfterSame is same too
2123 aNewElem = aMesh->AddVolume (prevNod[ iSameNode ], prevNod[ iBeforeSame ],
2124 nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
2125 prevNod[ iOpposSame ], nextNod[ iOpposSame ]);
2130 // realized for extrusion only
2131 vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2132 vector<int> quantities (nbNodes + 2);
2134 quantities[0] = nbNodes; // bottom of prism
2135 for (int inode = 0; inode < nbNodes; inode++) {
2136 polyedre_nodes[inode] = prevNod[inode];
2139 quantities[1] = nbNodes; // top of prism
2140 for (int inode = 0; inode < nbNodes; inode++) {
2141 polyedre_nodes[nbNodes + inode] = nextNod[inode];
2144 for (int iface = 0; iface < nbNodes; iface++) {
2145 quantities[iface + 2] = 4;
2146 int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2147 polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2148 polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2149 polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2150 polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2152 aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2156 newElems.push_back( aNewElem );
2158 // set new prev nodes
2159 for ( iNode = 0; iNode < nbNodes; iNode++ )
2160 prevNod[ iNode ] = nextNod[ iNode ];
2165 //=======================================================================
2166 //function : makeWalls
2167 //purpose : create 1D and 2D elements around swept elements
2168 //=======================================================================
2170 static void makeWalls (SMESHDS_Mesh* aMesh,
2171 TNodeOfNodeListMap & mapNewNodes,
2172 TElemOfElemListMap & newElemsMap,
2173 TElemOfVecOfNnlmiMap & elemNewNodesMap,
2174 set<const SMDS_MeshElement*>& elemSet)
2176 ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
2178 // Find nodes belonging to only one initial element - sweep them to get edges.
2180 TNodeOfNodeListMapItr nList = mapNewNodes.begin();
2181 for ( ; nList != mapNewNodes.end(); nList++ )
2183 const SMDS_MeshNode* node =
2184 static_cast<const SMDS_MeshNode*>( nList->first );
2185 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2186 int nbInitElems = 0;
2187 while ( eIt->more() && nbInitElems < 2 )
2188 if ( elemSet.find( eIt->next() ) != elemSet.end() )
2190 if ( nbInitElems < 2 ) {
2191 vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2192 list<const SMDS_MeshElement*> newEdges;
2193 sweepElement( aMesh, node, newNodesItVec, newEdges );
2197 // Make a ceiling for each element ie an equal element of last new nodes.
2198 // Find free links of faces - make edges and sweep them into faces.
2200 TElemOfElemListMap::iterator itElem = newElemsMap.begin();
2201 TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2202 for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
2204 const SMDS_MeshElement* elem = itElem->first;
2205 vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2207 if ( elem->GetType() == SMDSAbs_Edge )
2209 // create a ceiling edge
2210 aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2211 vecNewNodes[ 1 ]->second.back() );
2213 if ( elem->GetType() != SMDSAbs_Face )
2216 bool hasFreeLinks = false;
2218 set<const SMDS_MeshElement*> avoidSet;
2219 avoidSet.insert( elem );
2221 // loop on a face nodes
2222 set<const SMDS_MeshNode*> aFaceLastNodes;
2223 int iNode, nbNodes = vecNewNodes.size();
2224 for ( iNode = 0; iNode < nbNodes; iNode++ )
2226 aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
2227 // look for free links of a face
2228 int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
2229 const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
2230 const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
2231 // check if a link is free
2232 if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
2234 hasFreeLinks = true;
2235 // make an edge and a ceiling for a new edge
2236 if ( !aMesh->FindEdge( n1, n2 ))
2237 aMesh->AddEdge( n1, n2 );
2238 n1 = vecNewNodes[ iNode ]->second.back();
2239 n2 = vecNewNodes[ iNext ]->second.back();
2240 if ( !aMesh->FindEdge( n1, n2 ))
2241 aMesh->AddEdge( n1, n2 );
2244 // sweep free links into faces
2248 list<const SMDS_MeshElement*> & newVolumes = itElem->second;
2249 int iStep, nbSteps = vecNewNodes[0]->second.size();
2250 int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
2252 set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
2253 for ( iNode = 0; iNode < nbNodes; iNode++ )
2254 initNodeSet.insert( vecNewNodes[ iNode ]->first );
2256 for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
2258 list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
2260 while ( iVol++ < volNb ) v++;
2261 // find indices of free faces of a volume
2263 SMDS_VolumeTool vTool( *v );
2264 int iF, nbF = vTool.NbFaces();
2265 for ( iF = 0; iF < nbF; iF ++ )
2266 if (vTool.IsFreeFace( iF ) &&
2267 vTool.GetFaceNodes( iF, faceNodeSet ) &&
2268 initNodeSet != faceNodeSet) // except an initial face
2269 fInd.push_back( iF );
2273 // create faces for all steps
2274 for ( iStep = 0; iStep < nbSteps; iStep++ )
2277 vTool.SetExternalNormal();
2278 list< int >::iterator ind = fInd.begin();
2279 for ( ; ind != fInd.end(); ind++ )
2281 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
2282 switch ( vTool.NbFaceNodes( *ind ) ) {
2284 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
2286 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
2289 int nbPolygonNodes = vTool.NbFaceNodes( *ind );
2290 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2291 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2292 polygon_nodes[inode] = nodes[inode];
2294 aMesh->AddPolygonalFace(polygon_nodes);
2299 // go to the next volume
2301 while ( iVol++ < nbVolumesByStep ) v++;
2304 } // sweep free links into faces
2306 // make a ceiling face with a normal external to a volume
2308 SMDS_VolumeTool lastVol( itElem->second.back() );
2309 int iF = lastVol.GetFaceIndex( aFaceLastNodes );
2312 lastVol.SetExternalNormal();
2313 const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
2314 switch ( lastVol.NbFaceNodes( iF ) ) {
2316 if (!hasFreeLinks ||
2317 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
2318 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2321 if (!hasFreeLinks ||
2322 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
2323 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] );
2327 int nbPolygonNodes = lastVol.NbFaceNodes( iF );
2328 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2329 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2330 polygon_nodes[inode] = nodes[inode];
2332 if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
2333 aMesh->AddPolygonalFace(polygon_nodes);
2339 } // loop on swept elements
2342 //=======================================================================
2343 //function : RotationSweep
2345 //=======================================================================
2347 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
2348 const gp_Ax1& theAxis,
2349 const double theAngle,
2350 const int theNbSteps,
2351 const double theTol)
2353 MESSAGE( "RotationSweep()");
2355 aTrsf.SetRotation( theAxis, theAngle );
2357 gp_Lin aLine( theAxis );
2358 double aSqTol = theTol * theTol;
2360 SMESHDS_Mesh* aMesh = GetMeshDS();
2362 TNodeOfNodeListMap mapNewNodes;
2363 TElemOfVecOfNnlmiMap mapElemNewNodes;
2364 TElemOfElemListMap newElemsMap;
2367 set< const SMDS_MeshElement* >::iterator itElem;
2368 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2370 const SMDS_MeshElement* elem = (*itElem);
2373 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2374 newNodesItVec.reserve( elem->NbNodes() );
2376 // loop on elem nodes
2377 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2378 while ( itN->more() ) {
2380 // check if a node has been already sweeped
2381 const SMDS_MeshNode* node =
2382 static_cast<const SMDS_MeshNode*>( itN->next() );
2383 TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
2384 if ( nIt == mapNewNodes.end() )
2386 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2387 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2390 gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
2392 aXYZ.Coord( coord[0], coord[1], coord[2] );
2393 bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
2394 const SMDS_MeshNode * newNode = node;
2395 for ( int i = 0; i < theNbSteps; i++ ) {
2397 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2398 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2400 listNewNodes.push_back( newNode );
2403 newNodesItVec.push_back( nIt );
2405 // make new elements
2406 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2409 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2412 //=======================================================================
2413 //function : ExtrusionSweep
2415 //=======================================================================
2417 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
2418 const gp_Vec& theStep,
2419 const int theNbSteps)
2422 aTrsf.SetTranslation( theStep );
2424 SMESHDS_Mesh* aMesh = GetMeshDS();
2426 TNodeOfNodeListMap mapNewNodes;
2427 TElemOfVecOfNnlmiMap mapElemNewNodes;
2428 TElemOfElemListMap newElemsMap;
2431 set< const SMDS_MeshElement* >::iterator itElem;
2432 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2434 // check element type
2435 const SMDS_MeshElement* elem = (*itElem);
2439 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2440 newNodesItVec.reserve( elem->NbNodes() );
2442 // loop on elem nodes
2443 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2444 while ( itN->more() ) {
2446 // check if a node has been already sweeped
2447 const SMDS_MeshNode* node =
2448 static_cast<const SMDS_MeshNode*>( itN->next() );
2449 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2450 if ( nIt == mapNewNodes.end() )
2452 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2453 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2456 double coord[] = { node->X(), node->Y(), node->Z() };
2457 for ( int i = 0; i < theNbSteps; i++ ) {
2458 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2459 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2460 listNewNodes.push_back( newNode );
2463 newNodesItVec.push_back( nIt );
2465 // make new elements
2466 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2468 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2471 //=======================================================================
2472 //class : SMESH_MeshEditor_PathPoint
2473 //purpose : auxiliary class
2474 //=======================================================================
2475 class SMESH_MeshEditor_PathPoint {
2477 SMESH_MeshEditor_PathPoint() {
2478 myPnt.SetCoord(99., 99., 99.);
2479 myTgt.SetCoord(1.,0.,0.);
2483 void SetPnt(const gp_Pnt& aP3D){
2486 void SetTangent(const gp_Dir& aTgt){
2489 void SetAngle(const double& aBeta){
2492 void SetParameter(const double& aPrm){
2495 const gp_Pnt& Pnt()const{
2498 const gp_Dir& Tangent()const{
2501 double Angle()const{
2504 double Parameter()const{
2515 //=======================================================================
2516 //function : ExtrusionAlongTrack
2518 //=======================================================================
2519 SMESH_MeshEditor::Extrusion_Error
2520 SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2521 SMESH_subMesh* theTrack,
2522 const SMDS_MeshNode* theN1,
2523 const bool theHasAngles,
2524 std::list<double>& theAngles,
2525 const bool theHasRefPoint,
2526 const gp_Pnt& theRefPoint)
2528 MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2529 int j, aNbTP, aNbE, aNb;
2530 double aT1, aT2, aT, aAngle, aX, aY, aZ;
2531 std::list<double> aPrms;
2532 std::list<double>::iterator aItD;
2533 std::set< const SMDS_MeshElement* >::iterator itElem;
2535 Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2539 Handle(Geom_Curve) aC3D;
2540 TopoDS_Edge aTrackEdge;
2541 TopoDS_Vertex aV1, aV2;
2543 SMDS_ElemIteratorPtr aItE;
2544 SMDS_NodeIteratorPtr aItN;
2545 SMDSAbs_ElementType aTypeE;
2547 TNodeOfNodeListMap mapNewNodes;
2548 TElemOfVecOfNnlmiMap mapElemNewNodes;
2549 TElemOfElemListMap newElemsMap;
2552 aTolVec2=aTolVec*aTolVec;
2555 aNbE = theElements.size();
2558 return EXTR_NO_ELEMENTS;
2560 // 1.1 Track Pattern
2563 SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2565 aItE = pSubMeshDS->GetElements();
2566 while ( aItE->more() ) {
2567 const SMDS_MeshElement* pE = aItE->next();
2568 aTypeE = pE->GetType();
2569 // Pattern must contain links only
2570 if ( aTypeE != SMDSAbs_Edge )
2571 return EXTR_PATH_NOT_EDGE;
2574 const TopoDS_Shape& aS = theTrack->GetSubShape();
2575 // Sub shape for the Pattern must be an Edge
2576 if ( aS.ShapeType() != TopAbs_EDGE )
2577 return EXTR_BAD_PATH_SHAPE;
2579 aTrackEdge = TopoDS::Edge( aS );
2580 // the Edge must not be degenerated
2581 if ( BRep_Tool::Degenerated( aTrackEdge ) )
2582 return EXTR_BAD_PATH_SHAPE;
2584 TopExp::Vertices( aTrackEdge, aV1, aV2 );
2585 aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2586 aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2588 aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2589 const SMDS_MeshNode* aN1 = aItN->next();
2591 aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2592 const SMDS_MeshNode* aN2 = aItN->next();
2594 // starting node must be aN1 or aN2
2595 if ( !( aN1 == theN1 || aN2 == theN1 ) )
2596 return EXTR_BAD_STARTING_NODE;
2598 aNbTP = pSubMeshDS->NbNodes() + 2;
2601 vector<double> aAngles( aNbTP );
2603 for ( j=0; j < aNbTP; ++j ) {
2607 if ( theHasAngles ) {
2608 aItD = theAngles.begin();
2609 for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2611 aAngles[j] = aAngle;
2615 // 2. Collect parameters on the track edge
2616 aPrms.push_back( aT1 );
2617 aPrms.push_back( aT2 );
2619 aItN = pSubMeshDS->GetNodes();
2620 while ( aItN->more() ) {
2621 const SMDS_MeshNode* pNode = aItN->next();
2622 const SMDS_EdgePosition* pEPos =
2623 static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2624 aT = pEPos->GetUParameter();
2625 aPrms.push_back( aT );
2630 if ( aN1 == theN1 ) {
2642 SMESH_MeshEditor_PathPoint aPP;
2643 vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2645 aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2647 aItD = aPrms.begin();
2648 for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2650 aC3D->D1( aT, aP3D, aVec );
2651 aL2 = aVec.SquareMagnitude();
2652 if ( aL2 < aTolVec2 )
2653 return EXTR_CANT_GET_TANGENT;
2655 gp_Dir aTgt( aVec );
2656 aAngle = aAngles[j];
2659 aPP.SetTangent( aTgt );
2660 aPP.SetAngle( aAngle );
2661 aPP.SetParameter( aT );
2665 // 3. Center of rotation aV0
2667 if ( !theHasRefPoint ) {
2669 aGC.SetCoord( 0.,0.,0. );
2671 itElem = theElements.begin();
2672 for ( ; itElem != theElements.end(); itElem++ ) {
2673 const SMDS_MeshElement* elem = (*itElem);
2675 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2676 while ( itN->more() ) {
2677 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2682 if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2683 list<const SMDS_MeshNode*> aLNx;
2684 mapNewNodes[node] = aLNx;
2686 gp_XYZ aXYZ( aX, aY, aZ );
2694 } // if (!theHasRefPoint) {
2695 mapNewNodes.clear();
2697 // 4. Processing the elements
2698 SMESHDS_Mesh* aMesh = GetMeshDS();
2700 for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2701 // check element type
2702 const SMDS_MeshElement* elem = (*itElem);
2703 aTypeE = elem->GetType();
2704 if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2707 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2708 newNodesItVec.reserve( elem->NbNodes() );
2710 // loop on elem nodes
2711 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2712 while ( itN->more() ) {
2714 // check if a node has been already processed
2715 const SMDS_MeshNode* node =
2716 static_cast<const SMDS_MeshNode*>( itN->next() );
2717 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2718 if ( nIt == mapNewNodes.end() ) {
2719 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2720 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2723 aX = node->X(); aY = node->Y(); aZ = node->Z();
2725 Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2726 gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2727 gp_Ax1 anAx1, anAxT1T0;
2728 gp_Dir aDT1x, aDT0x, aDT1T0;
2733 aPN0.SetCoord(aX, aY, aZ);
2735 const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2737 aDT0x= aPP0.Tangent();
2739 for ( j = 1; j < aNbTP; ++j ) {
2740 const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2742 aDT1x = aPP1.Tangent();
2743 aAngle1x = aPP1.Angle();
2745 gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
2747 gp_Vec aV01x( aP0x, aP1x );
2748 aTrsf.SetTranslation( aV01x );
2751 aV1x = aV0x.Transformed( aTrsf );
2752 aPN1 = aPN0.Transformed( aTrsf );
2754 // rotation 1 [ T1,T0 ]
2755 aAngleT1T0=-aDT1x.Angle( aDT0x );
2756 if (fabs(aAngleT1T0) > aTolAng) {
2758 anAxT1T0.SetLocation( aV1x );
2759 anAxT1T0.SetDirection( aDT1T0 );
2760 aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2762 aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2766 if ( theHasAngles ) {
2767 anAx1.SetLocation( aV1x );
2768 anAx1.SetDirection( aDT1x );
2769 aTrsfRot.SetRotation( anAx1, aAngle1x );
2771 aPN1 = aPN1.Transformed( aTrsfRot );
2778 const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2779 listNewNodes.push_back( newNode );
2787 newNodesItVec.push_back( nIt );
2789 // make new elements
2790 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2793 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2798 //=======================================================================
2799 //function : Transform
2801 //=======================================================================
2803 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2804 const gp_Trsf& theTrsf,
2808 switch ( theTrsf.Form() ) {
2814 needReverse = false;
2817 SMESHDS_Mesh* aMesh = GetMeshDS();
2819 // map old node to new one
2820 TNodeNodeMap nodeMap;
2822 // elements sharing moved nodes; those of them which have all
2823 // nodes mirrored but are not in theElems are to be reversed
2824 set<const SMDS_MeshElement*> inverseElemSet;
2827 set< const SMDS_MeshElement* >::iterator itElem;
2828 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2830 const SMDS_MeshElement* elem = (*itElem);
2834 // loop on elem nodes
2835 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2836 while ( itN->more() ) {
2838 // check if a node has been already transformed
2839 const SMDS_MeshNode* node =
2840 static_cast<const SMDS_MeshNode*>( itN->next() );
2841 if (nodeMap.find( node ) != nodeMap.end() )
2845 coord[0] = node->X();
2846 coord[1] = node->Y();
2847 coord[2] = node->Z();
2848 theTrsf.Transforms( coord[0], coord[1], coord[2] );
2849 const SMDS_MeshNode * newNode = node;
2851 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2853 aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2854 // node position on shape becomes invalid
2855 const_cast< SMDS_MeshNode* > ( node )->SetPosition
2856 ( SMDS_SpacePosition::originSpacePosition() );
2858 nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2860 // keep inverse elements
2861 if ( !theCopy && needReverse ) {
2862 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2863 while ( invElemIt->more() )
2864 inverseElemSet.insert( invElemIt->next() );
2869 // either new elements are to be created
2870 // or a mirrored element are to be reversed
2871 if ( !theCopy && !needReverse)
2874 if ( !inverseElemSet.empty()) {
2875 set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2876 for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2877 theElems.insert( *invElemIt );
2880 // replicate or reverse elements
2883 REV_TETRA = 0, // = nbNodes - 4
2884 REV_PYRAMID = 1, // = nbNodes - 4
2885 REV_PENTA = 2, // = nbNodes - 4
2887 REV_HEXA = 4, // = nbNodes - 4
2891 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_TETRA
2892 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_PYRAMID
2893 { 2, 1, 0, 5, 4, 3, 0, 0 }, // REV_PENTA
2894 { 2, 1, 0, 3, 0, 0, 0, 0 }, // REV_FACE
2895 { 2, 1, 0, 3, 6, 5, 4, 7 }, // REV_HEXA
2896 { 0, 1, 2, 3, 4, 5, 6, 7 } // FORWARD
2899 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2901 const SMDS_MeshElement* elem = (*itElem);
2902 if ( !elem || elem->GetType() == SMDSAbs_Node )
2905 int nbNodes = elem->NbNodes();
2906 int elemType = elem->GetType();
2908 if (elem->IsPoly()) {
2909 // Polygon or Polyhedral Volume
2910 switch ( elemType ) {
2913 vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
2915 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2916 while (itN->more()) {
2917 const SMDS_MeshNode* node =
2918 static_cast<const SMDS_MeshNode*>(itN->next());
2919 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2920 if (nodeMapIt == nodeMap.end())
2921 break; // not all nodes transformed
2923 // reverse mirrored faces and volumes
2924 poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
2926 poly_nodes[iNode] = (*nodeMapIt).second;
2930 if ( iNode != nbNodes )
2931 continue; // not all nodes transformed
2934 aMesh->AddPolygonalFace(poly_nodes);
2936 aMesh->ChangePolygonNodes(elem, poly_nodes);
2940 case SMDSAbs_Volume:
2942 // ATTENTION: Reversing is not yet done!!!
2943 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
2944 (const SMDS_PolyhedralVolumeOfNodes*) elem;
2946 MESSAGE("Warning: bad volumic element");
2950 vector<const SMDS_MeshNode*> poly_nodes;
2951 vector<int> quantities;
2953 bool allTransformed = true;
2954 int nbFaces = aPolyedre->NbFaces();
2955 for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
2956 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
2957 for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
2958 const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
2959 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2960 if (nodeMapIt == nodeMap.end()) {
2961 allTransformed = false; // not all nodes transformed
2963 poly_nodes.push_back((*nodeMapIt).second);
2966 quantities.push_back(nbFaceNodes);
2968 if ( !allTransformed )
2969 continue; // not all nodes transformed
2972 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
2974 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
2984 int* i = index[ FORWARD ];
2985 if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
2986 if ( elemType == SMDSAbs_Face )
2987 i = index[ REV_FACE ];
2989 i = index[ nbNodes - 4 ];
2991 // find transformed nodes
2992 const SMDS_MeshNode* nodes[8];
2994 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2995 while ( itN->more() )
2997 const SMDS_MeshNode* node =
2998 static_cast<const SMDS_MeshNode*>( itN->next() );
2999 TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
3000 if ( nodeMapIt == nodeMap.end() )
3001 break; // not all nodes transformed
3002 nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
3004 if ( iNode != nbNodes )
3005 continue; // not all nodes transformed
3009 // add a new element
3010 switch ( elemType ) {
3012 aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
3016 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
3018 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
3020 case SMDSAbs_Volume:
3022 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
3023 else if ( nbNodes == 8 )
3024 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3025 nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
3026 else if ( nbNodes == 6 )
3027 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3028 nodes[ 4 ], nodes[ 5 ]);
3029 else if ( nbNodes == 5 )
3030 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3038 // reverse element as it was reversed by transformation
3040 aMesh->ChangeElementNodes( elem, nodes, nbNodes );
3045 //=======================================================================
3046 //function : FindCoincidentNodes
3047 //purpose : Return list of group of nodes close to each other within theTolerance
3048 // Search among theNodes or in the whole mesh if theNodes is empty.
3049 //=======================================================================
3051 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
3052 const double theTolerance,
3053 TListOfListOfNodes & theGroupsOfNodes)
3055 double tol2 = theTolerance * theTolerance;
3057 list<const SMDS_MeshNode*> nodes;
3058 if ( theNodes.empty() )
3059 { // get all nodes in the mesh
3060 SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
3061 while ( nIt->more() )
3062 nodes.push_back( nIt->next() );
3066 nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
3069 list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
3070 for ( ; it1 != nodes.end(); it1++ )
3072 const SMDS_MeshNode* n1 = *it1;
3073 gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
3075 list<const SMDS_MeshNode*> * groupPtr = 0;
3077 for ( it2++; it2 != nodes.end(); it2++ )
3079 const SMDS_MeshNode* n2 = *it2;
3080 gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
3081 if ( p1.SquareDistance( p2 ) <= tol2 )
3084 theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
3085 groupPtr = & theGroupsOfNodes.back();
3086 groupPtr->push_back( n1 );
3088 groupPtr->push_back( n2 );
3089 it2 = nodes.erase( it2 );
3096 //=======================================================================
3097 //function : SimplifyFace
3099 //=======================================================================
3100 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
3101 vector<const SMDS_MeshNode *>& poly_nodes,
3102 vector<int>& quantities) const
3104 int nbNodes = faceNodes.size();
3109 set<const SMDS_MeshNode*> nodeSet;
3111 // get simple seq of nodes
3112 const SMDS_MeshNode* simpleNodes[ nbNodes ];
3113 int iSimple = 0, nbUnique = 0;
3115 simpleNodes[iSimple++] = faceNodes[0];
3117 for (int iCur = 1; iCur < nbNodes; iCur++) {
3118 if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
3119 simpleNodes[iSimple++] = faceNodes[iCur];
3120 if (nodeSet.insert( faceNodes[iCur] ).second)
3124 int nbSimple = iSimple;
3125 if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
3135 bool foundLoop = (nbSimple > nbUnique);
3138 set<const SMDS_MeshNode*> loopSet;
3139 for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
3140 const SMDS_MeshNode* n = simpleNodes[iSimple];
3141 if (!loopSet.insert( n ).second) {
3145 int iC = 0, curLast = iSimple;
3146 for (; iC < curLast; iC++) {
3147 if (simpleNodes[iC] == n) break;
3149 int loopLen = curLast - iC;
3151 // create sub-element
3153 quantities.push_back(loopLen);
3154 for (; iC < curLast; iC++) {
3155 poly_nodes.push_back(simpleNodes[iC]);
3158 // shift the rest nodes (place from the first loop position)
3159 for (iC = curLast + 1; iC < nbSimple; iC++) {
3160 simpleNodes[iC - loopLen] = simpleNodes[iC];
3162 nbSimple -= loopLen;
3165 } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
3166 } // while (foundLoop)
3170 quantities.push_back(iSimple);
3171 for (int i = 0; i < iSimple; i++)
3172 poly_nodes.push_back(simpleNodes[i]);
3178 //=======================================================================
3179 //function : MergeNodes
3180 //purpose : In each group, the cdr of nodes are substituted by the first one
3182 //=======================================================================
3184 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
3186 SMESHDS_Mesh* aMesh = GetMeshDS();
3188 TNodeNodeMap nodeNodeMap; // node to replace - new node
3189 set<const SMDS_MeshElement*> elems; // all elements with changed nodes
3190 list< int > rmElemIds, rmNodeIds;
3192 // Fill nodeNodeMap and elems
3194 TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
3195 for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
3197 list<const SMDS_MeshNode*>& nodes = *grIt;
3198 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
3199 const SMDS_MeshNode* nToKeep = *nIt;
3200 for ( ; nIt != nodes.end(); nIt++ )
3202 const SMDS_MeshNode* nToRemove = *nIt;
3203 nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
3204 if ( nToRemove != nToKeep ) {
3205 rmNodeIds.push_back( nToRemove->GetID() );
3206 AddToSameGroups( nToKeep, nToRemove, aMesh );
3209 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3210 while ( invElemIt->more() )
3211 elems.insert( invElemIt->next() );
3214 // Change element nodes or remove an element
3216 set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
3217 for ( ; eIt != elems.end(); eIt++ )
3219 const SMDS_MeshElement* elem = *eIt;
3220 int nbNodes = elem->NbNodes();
3221 int aShapeId = FindShape( elem );
3223 set<const SMDS_MeshNode*> nodeSet;
3224 const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
3225 int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
3227 // get new seq of nodes
3228 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3229 while ( itN->more() )
3231 const SMDS_MeshNode* n =
3232 static_cast<const SMDS_MeshNode*>( itN->next() );
3234 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
3235 if ( nnIt != nodeNodeMap.end() ) { // n sticks
3237 iRepl[ nbRepl++ ] = iCur;
3239 curNodes[ iCur ] = n;
3240 bool isUnique = nodeSet.insert( n ).second;
3242 uniqueNodes[ iUnique++ ] = n;
3246 // Analyse element topology after replacement
3249 int nbUniqueNodes = nodeSet.size();
3250 if ( nbNodes != nbUniqueNodes ) // some nodes stick
3252 // Polygons and Polyhedral volumes
3253 if (elem->IsPoly()) {
3255 if (elem->GetType() == SMDSAbs_Face) {
3257 vector<const SMDS_MeshNode *> face_nodes (nbNodes);
3259 for (; inode < nbNodes; inode++) {
3260 face_nodes[inode] = curNodes[inode];
3263 vector<const SMDS_MeshNode *> polygons_nodes;
3264 vector<int> quantities;
3265 int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
3269 for (int iface = 0; iface < nbNew - 1; iface++) {
3270 int nbNodes = quantities[iface];
3271 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
3272 for (int ii = 0; ii < nbNodes; ii++, inode++) {
3273 poly_nodes[ii] = polygons_nodes[inode];
3275 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
3277 aMesh->SetMeshElementOnShape(newElem, aShapeId);
3279 aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
3281 rmElemIds.push_back(elem->GetID());
3284 } else if (elem->GetType() == SMDSAbs_Volume) {
3285 // Polyhedral volume
3286 if (nbUniqueNodes < 4) {
3287 rmElemIds.push_back(elem->GetID());
3289 // each face has to be analized in order to check volume validity
3290 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3291 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3293 int nbFaces = aPolyedre->NbFaces();
3295 vector<const SMDS_MeshNode *> poly_nodes;
3296 vector<int> quantities;
3298 for (int iface = 1; iface <= nbFaces; iface++) {
3299 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3300 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
3302 for (int inode = 1; inode <= nbFaceNodes; inode++) {
3303 const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
3304 TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
3305 if (nnIt != nodeNodeMap.end()) { // faceNode sticks
3306 faceNode = (*nnIt).second;
3308 faceNodes[inode - 1] = faceNode;
3311 SimplifyFace(faceNodes, poly_nodes, quantities);
3314 if (quantities.size() > 3) {
3315 // to be done: remove coincident faces
3318 if (quantities.size() > 3)
3319 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3321 rmElemIds.push_back(elem->GetID());
3324 rmElemIds.push_back(elem->GetID());
3334 switch ( nbNodes ) {
3335 case 2: ///////////////////////////////////// EDGE
3336 isOk = false; break;
3337 case 3: ///////////////////////////////////// TRIANGLE
3338 isOk = false; break;
3340 if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
3342 else { //////////////////////////////////// QUADRANGLE
3343 if ( nbUniqueNodes < 3 )
3345 else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
3346 isOk = false; // opposite nodes stick
3349 case 6: ///////////////////////////////////// PENTAHEDRON
3350 if ( nbUniqueNodes == 4 ) {
3351 // ---------------------------------> tetrahedron
3353 iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
3354 // all top nodes stick: reverse a bottom
3355 uniqueNodes[ 0 ] = curNodes [ 1 ];
3356 uniqueNodes[ 1 ] = curNodes [ 0 ];
3358 else if (nbRepl == 3 &&
3359 iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
3360 // all bottom nodes stick: set a top before
3361 uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
3362 uniqueNodes[ 0 ] = curNodes [ 3 ];
3363 uniqueNodes[ 1 ] = curNodes [ 4 ];
3364 uniqueNodes[ 2 ] = curNodes [ 5 ];
3366 else if (nbRepl == 4 &&
3367 iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
3368 // a lateral face turns into a line: reverse a bottom
3369 uniqueNodes[ 0 ] = curNodes [ 1 ];
3370 uniqueNodes[ 1 ] = curNodes [ 0 ];
3375 else if ( nbUniqueNodes == 5 ) {
3376 // PENTAHEDRON --------------------> 2 tetrahedrons
3377 if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
3378 // a bottom node sticks with a linked top one
3380 SMDS_MeshElement* newElem =
3381 aMesh->AddVolume(curNodes[ 3 ],
3384 curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
3386 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3387 // 2. : reverse a bottom
3388 uniqueNodes[ 0 ] = curNodes [ 1 ];
3389 uniqueNodes[ 1 ] = curNodes [ 0 ];
3398 case 8: { //////////////////////////////////// HEXAHEDRON
3400 SMDS_VolumeTool hexa (elem);
3401 hexa.SetExternalNormal();
3402 if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
3403 //////////////////////// ---> tetrahedron
3404 for ( int iFace = 0; iFace < 6; iFace++ ) {
3405 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3406 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3407 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3408 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3409 // one face turns into a point ...
3410 int iOppFace = hexa.GetOppFaceIndex( iFace );
3411 ind = hexa.GetFaceNodesIndices( iOppFace );
3413 iUnique = 2; // reverse a tetrahedron bottom
3414 for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
3415 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3417 else if ( iUnique >= 0 )
3418 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3420 if ( nbStick == 1 ) {
3421 // ... and the opposite one - into a triangle.
3423 ind = hexa.GetFaceNodesIndices( iFace );
3424 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
3431 else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
3432 //////////////////// HEXAHEDRON ---> 2 tetrahedrons
3433 for ( int iFace = 0; iFace < 6; iFace++ ) {
3434 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3435 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3436 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3437 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3438 // one face turns into a point ...
3439 int iOppFace = hexa.GetOppFaceIndex( iFace );
3440 ind = hexa.GetFaceNodesIndices( iOppFace );
3442 iUnique = 2; // reverse a tetrahedron 1 bottom
3443 for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
3444 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3446 else if ( iUnique >= 0 )
3447 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3449 if ( nbStick == 0 ) {
3450 // ... and the opposite one is a quadrangle
3452 const int* indTop = hexa.GetFaceNodesIndices( iFace );
3453 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
3456 SMDS_MeshElement* newElem =
3457 aMesh->AddVolume(curNodes[ind[ 0 ]],
3460 curNodes[indTop[ 0 ]]);
3462 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3469 else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
3470 ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
3471 // find indices of quad and tri faces
3472 int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
3473 for ( iFace = 0; iFace < 6; iFace++ ) {
3474 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3476 for ( iCur = 0; iCur < 4; iCur++ )
3477 nodeSet.insert( curNodes[ind[ iCur ]] );
3478 nbUniqueNodes = nodeSet.size();
3479 if ( nbUniqueNodes == 3 )
3480 iTriFace[ nbTri++ ] = iFace;
3481 else if ( nbUniqueNodes == 4 )
3482 iQuadFace[ nbQuad++ ] = iFace;
3484 if (nbQuad == 2 && nbTri == 4 &&
3485 hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
3486 // 2 opposite quadrangles stuck with a diagonal;
3487 // sample groups of merged indices: (0-4)(2-6)
3488 // --------------------------------------------> 2 tetrahedrons
3489 const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
3490 const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
3491 int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
3492 if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
3493 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
3494 // stuck with 0-2 diagonal
3502 else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
3503 curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
3504 // stuck with 1-3 diagonal
3516 uniqueNodes[ 0 ] = curNodes [ i0 ];
3517 uniqueNodes[ 1 ] = curNodes [ i1d ];
3518 uniqueNodes[ 2 ] = curNodes [ i3d ];
3519 uniqueNodes[ 3 ] = curNodes [ i0t ];
3522 SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
3527 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3530 else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
3531 ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
3532 // --------------------------------------------> prism
3533 // find 2 opposite triangles
3535 for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
3536 if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
3537 // find indices of kept and replaced nodes
3538 // and fill unique nodes of 2 opposite triangles
3539 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
3540 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
3541 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
3542 // fill unique nodes
3545 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
3546 const SMDS_MeshNode* n = curNodes[ind1[ iCur ]];
3547 const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
3549 // iCur of a linked node of the opposite face (make normals co-directed):
3550 int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
3551 // check that correspondent corners of triangles are linked
3552 if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
3555 uniqueNodes[ iUnique ] = n;
3556 uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
3565 } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
3571 } // switch ( nbNodes )
3573 } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
3576 if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
3577 // Change nodes of polyedre
3578 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3579 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3581 int nbFaces = aPolyedre->NbFaces();
3583 vector<const SMDS_MeshNode *> poly_nodes;
3584 vector<int> quantities (nbFaces);
3586 for (int iface = 1; iface <= nbFaces; iface++) {
3587 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3588 quantities[iface - 1] = nbFaceNodes;
3590 for (inode = 1; inode <= nbFaceNodes; inode++) {
3591 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
3593 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
3594 if (nnIt != nodeNodeMap.end()) { // curNode sticks
3595 curNode = (*nnIt).second;
3597 poly_nodes.push_back(curNode);
3600 aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
3603 // Change regular element or polygon
3604 aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
3607 // Remove invalid regular element or invalid polygon
3608 rmElemIds.push_back( elem->GetID() );
3611 } // loop on elements
3613 // Remove equal nodes and bad elements
3615 Remove( rmNodeIds, true );
3616 Remove( rmElemIds, false );
3620 //=======================================================================
3621 //function : MergeEqualElements
3622 //purpose : Remove all but one of elements built on the same nodes.
3623 //=======================================================================
3625 void SMESH_MeshEditor::MergeEqualElements()
3627 SMESHDS_Mesh* aMesh = GetMeshDS();
3629 SMDS_EdgeIteratorPtr eIt = aMesh->edgesIterator();
3630 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
3631 SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
3633 list< int > rmElemIds; // IDs of elems to remove
3635 for ( int iDim = 1; iDim <= 3; iDim++ ) {
3637 set< set <const SMDS_MeshElement*> > setOfNodeSet;
3641 const SMDS_MeshElement* elem = 0;
3643 if ( eIt->more() ) elem = eIt->next();
3644 } else if ( iDim == 2 ) {
3645 if ( fIt->more() ) elem = fIt->next();
3647 if ( vIt->more() ) elem = vIt->next();
3652 set <const SMDS_MeshElement*> nodeSet;
3653 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3654 while ( nodeIt->more() )
3655 nodeSet.insert( nodeIt->next() );
3658 bool isUnique = setOfNodeSet.insert( nodeSet ).second;
3660 rmElemIds.push_back( elem->GetID() );
3664 Remove( rmElemIds, false );
3667 //=======================================================================
3668 //function : FindFaceInSet
3669 //purpose : Return a face having linked nodes n1 and n2 and which is
3670 // - not in avoidSet,
3671 // - in elemSet provided that !elemSet.empty()
3672 //=======================================================================
3674 const SMDS_MeshElement*
3675 SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode* n1,
3676 const SMDS_MeshNode* n2,
3677 const set<const SMDS_MeshElement*>& elemSet,
3678 const set<const SMDS_MeshElement*>& avoidSet)
3681 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
3682 while ( invElemIt->more() ) { // loop on inverse elements of n1
3683 const SMDS_MeshElement* elem = invElemIt->next();
3684 if (elem->GetType() != SMDSAbs_Face ||
3685 avoidSet.find( elem ) != avoidSet.end() )
3687 if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
3689 // get face nodes and find index of n1
3690 int i1, nbN = elem->NbNodes(), iNode = 0;
3691 const SMDS_MeshNode* faceNodes[ nbN ], *n;
3692 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3693 while ( nIt->more() ) {
3694 faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3695 if ( faceNodes[ iNode++ ] == n1 )
3698 // find a n2 linked to n1
3699 for ( iNode = 0; iNode < 2; iNode++ ) {
3700 if ( iNode ) // node before n1
3701 n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
3702 else // node after n1
3703 n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
3711 //=======================================================================
3712 //function : findAdjacentFace
3714 //=======================================================================
3716 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
3717 const SMDS_MeshNode* n2,
3718 const SMDS_MeshElement* elem)
3720 set<const SMDS_MeshElement*> elemSet, avoidSet;
3722 avoidSet.insert ( elem );
3723 return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3726 //=======================================================================
3727 //function : findFreeBorder
3729 //=======================================================================
3731 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
3733 static bool findFreeBorder (const SMDS_MeshNode* theFirstNode,
3734 const SMDS_MeshNode* theSecondNode,
3735 const SMDS_MeshNode* theLastNode,
3736 list< const SMDS_MeshNode* > & theNodes,
3737 list< const SMDS_MeshElement* > & theFaces)
3739 if ( !theFirstNode || !theSecondNode )
3741 // find border face between theFirstNode and theSecondNode
3742 const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
3746 theFaces.push_back( curElem );
3747 theNodes.push_back( theFirstNode );
3748 theNodes.push_back( theSecondNode );
3750 const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
3751 set < const SMDS_MeshElement* > foundElems;
3752 bool needTheLast = ( theLastNode != 0 );
3754 while ( nStart != theLastNode )
3756 if ( nStart == theFirstNode )
3757 return !needTheLast;
3759 // find all free border faces sharing form nStart
3761 list< const SMDS_MeshElement* > curElemList;
3762 list< const SMDS_MeshNode* > nStartList;
3763 SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
3764 while ( invElemIt->more() ) {
3765 const SMDS_MeshElement* e = invElemIt->next();
3766 if ( e == curElem || foundElems.insert( e ).second )
3769 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3770 int iNode = 0, nbNodes = e->NbNodes();
3771 while ( nIt->more() )
3772 nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3773 nodes[ iNode ] = nodes[ 0 ];
3775 for ( iNode = 0; iNode < nbNodes; iNode++ )
3776 if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
3777 (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
3778 ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
3780 nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
3781 curElemList.push_back( e );
3785 // analyse the found
3787 int nbNewBorders = curElemList.size();
3788 if ( nbNewBorders == 0 ) {
3789 // no free border furthermore
3790 return !needTheLast;
3792 else if ( nbNewBorders == 1 ) {
3793 // one more element found
3795 nStart = nStartList.front();
3796 curElem = curElemList.front();
3797 theFaces.push_back( curElem );
3798 theNodes.push_back( nStart );
3801 // several continuations found
3802 list< const SMDS_MeshElement* >::iterator curElemIt;
3803 list< const SMDS_MeshNode* >::iterator nStartIt;
3804 // check if one of them reached the last node
3805 if ( needTheLast ) {
3806 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3807 curElemIt!= curElemList.end();
3808 curElemIt++, nStartIt++ )
3809 if ( *nStartIt == theLastNode ) {
3810 theFaces.push_back( *curElemIt );
3811 theNodes.push_back( *nStartIt );
3815 // find the best free border by the continuations
3816 list<const SMDS_MeshNode*> contNodes[ 2 ], *cNL;
3817 list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3818 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3819 curElemIt!= curElemList.end();
3820 curElemIt++, nStartIt++ )
3822 cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3823 cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3824 // find one more free border
3825 if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3829 else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3830 // choice: clear a worse one
3831 int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3832 int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3833 contNodes[ iWorse ].clear();
3834 contFaces[ iWorse ].clear();
3837 if ( contNodes[0].empty() && contNodes[1].empty() )
3840 // append the best free border
3841 cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3842 cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3843 theNodes.pop_back(); // remove nIgnore
3844 theNodes.pop_back(); // remove nStart
3845 theFaces.pop_back(); // remove curElem
3846 list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3847 list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3848 for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3849 for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3852 } // several continuations found
3853 } // while ( nStart != theLastNode )
3858 //=======================================================================
3859 //function : CheckFreeBorderNodes
3860 //purpose : Return true if the tree nodes are on a free border
3861 //=======================================================================
3863 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3864 const SMDS_MeshNode* theNode2,
3865 const SMDS_MeshNode* theNode3)
3867 list< const SMDS_MeshNode* > nodes;
3868 list< const SMDS_MeshElement* > faces;
3869 return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3872 //=======================================================================
3873 //function : SewFreeBorder
3875 //=======================================================================
3877 SMESH_MeshEditor::Sew_Error
3878 SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3879 const SMDS_MeshNode* theBordSecondNode,
3880 const SMDS_MeshNode* theBordLastNode,
3881 const SMDS_MeshNode* theSideFirstNode,
3882 const SMDS_MeshNode* theSideSecondNode,
3883 const SMDS_MeshNode* theSideThirdNode,
3884 const bool theSideIsFreeBorder,
3885 const bool toCreatePolygons,
3886 const bool toCreatePolyedrs)
3888 MESSAGE("::SewFreeBorder()");
3889 Sew_Error aResult = SEW_OK;
3891 // ====================================
3892 // find side nodes and elements
3893 // ====================================
3895 list< const SMDS_MeshNode* > nSide[ 2 ];
3896 list< const SMDS_MeshElement* > eSide[ 2 ];
3897 list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3898 list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3902 if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3903 nSide[0], eSide[0])) {
3904 MESSAGE(" Free Border 1 not found " );
3905 aResult = SEW_BORDER1_NOT_FOUND;
3907 if (theSideIsFreeBorder)
3911 if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3912 nSide[1], eSide[1])) {
3913 MESSAGE(" Free Border 2 not found " );
3914 aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
3917 if ( aResult != SEW_OK )
3920 if (!theSideIsFreeBorder)
3925 // -------------------------------------------------------------------------
3927 // 1. If nodes to merge are not coincident, move nodes of the free border
3928 // from the coord sys defined by the direction from the first to last
3929 // nodes of the border to the correspondent sys of the side 2
3930 // 2. On the side 2, find the links most co-directed with the correspondent
3931 // links of the free border
3932 // -------------------------------------------------------------------------
3934 // 1. Since sewing may brake if there are volumes to split on the side 2,
3935 // we wont move nodes but just compute new coordinates for them
3936 typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
3937 TNodeXYZMap nBordXYZ;
3938 list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
3939 list< const SMDS_MeshNode* >::iterator nBordIt;
3941 gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
3942 gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
3943 gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
3944 gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
3945 double tol2 = 1.e-8;
3946 gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
3947 if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
3949 // Need node movement.
3951 // find X and Z axes to create trsf
3952 gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
3954 if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
3956 X = gp_Ax2( gp::Origin(), Zb ).XDirection();
3959 gp_Ax3 toBordAx( Pb1, Zb, X );
3960 gp_Ax3 fromSideAx( Ps1, Zs, X );
3961 gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
3963 gp_Trsf toBordSys, fromSide2Sys;
3964 toBordSys.SetTransformation( toBordAx );
3965 fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
3966 fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
3969 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3970 const SMDS_MeshNode* n = *nBordIt;
3971 gp_XYZ xyz( n->X(),n->Y(),n->Z() );
3972 toBordSys.Transforms( xyz );
3973 fromSide2Sys.Transforms( xyz );
3974 nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
3979 // just insert nodes XYZ in the nBordXYZ map
3980 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3981 const SMDS_MeshNode* n = *nBordIt;
3982 nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
3986 // 2. On the side 2, find the links most co-directed with the correspondent
3987 // links of the free border
3989 list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
3990 list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
3991 sideNodes.push_back( theSideFirstNode );
3993 bool hasVolumes = false;
3994 LinkID_Gen aLinkID_Gen( GetMeshDS() );
3995 set<long> foundSideLinkIDs, checkedLinkIDs;
3996 SMDS_VolumeTool volume;
3997 //const SMDS_MeshNode* faceNodes[ 4 ];
3999 const SMDS_MeshNode* sideNode;
4000 const SMDS_MeshElement* sideElem;
4001 const SMDS_MeshNode* prevSideNode = theSideFirstNode;
4002 const SMDS_MeshNode* prevBordNode = theBordFirstNode;
4003 nBordIt = bordNodes.begin();
4005 // border node position and border link direction to compare with
4006 gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
4007 gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
4008 // choose next side node by link direction or by closeness to
4009 // the current border node:
4010 bool searchByDir = ( *nBordIt != theBordLastNode );
4012 // find the next node on the Side 2
4014 double maxDot = -DBL_MAX, minDist = DBL_MAX;
4016 checkedLinkIDs.clear();
4017 gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
4019 SMDS_ElemIteratorPtr invElemIt
4020 = prevSideNode->GetInverseElementIterator();
4021 while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
4022 const SMDS_MeshElement* elem = invElemIt->next();
4023 // prepare data for a loop on links, of a face or a volume
4024 int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
4025 const SMDS_MeshNode* faceNodes[ nbNodes ];
4026 bool isVolume = volume.Set( elem );
4027 const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
4028 if ( isVolume ) // --volume
4030 else if ( nbNodes > 2 ) { // --face
4031 // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
4032 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
4033 while ( nIt->more() ) {
4034 nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
4035 if ( nodes[ iNode++ ] == prevSideNode )
4036 iPrevNode = iNode - 1;
4038 // there are 2 links to check
4043 // loop on links, to be precise, on the second node of links
4044 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
4045 const SMDS_MeshNode* n = nodes[ iNode ];
4047 if ( !volume.IsLinked( n, prevSideNode ))
4050 if ( iNode ) // a node before prevSideNode
4051 n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
4052 else // a node after prevSideNode
4053 n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
4055 // check if this link was already used
4056 long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
4057 bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
4058 if (!isJustChecked &&
4059 foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
4060 // test a link geometrically
4061 gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
4062 bool linkIsBetter = false;
4064 if ( searchByDir ) { // choose most co-directed link
4065 dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
4066 linkIsBetter = ( dot > maxDot );
4068 else { // choose link with the node closest to bordPos
4069 dist = ( nextXYZ - bordPos ).SquareModulus();
4070 linkIsBetter = ( dist < minDist );
4072 if ( linkIsBetter ) {
4081 } // loop on inverse elements of prevSideNode
4084 MESSAGE(" Cant find path by links of the Side 2 ");
4085 return SEW_BAD_SIDE_NODES;
4087 sideNodes.push_back( sideNode );
4088 sideElems.push_back( sideElem );
4089 foundSideLinkIDs.insert ( linkID );
4090 prevSideNode = sideNode;
4092 if ( *nBordIt == theBordLastNode )
4093 searchByDir = false;
4095 // find the next border link to compare with
4096 gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
4097 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4098 while ( *nBordIt != theBordLastNode && !searchByDir ) {
4099 prevBordNode = *nBordIt;
4101 bordPos = nBordXYZ[ *nBordIt ];
4102 bordDir = bordPos - nBordXYZ[ prevBordNode ];
4103 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4107 while ( sideNode != theSideSecondNode );
4109 if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
4110 MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
4111 return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
4113 } // end nodes search on the side 2
4115 // ============================
4116 // sew the border to the side 2
4117 // ============================
4119 int nbNodes[] = { nSide[0].size(), nSide[1].size() };
4120 int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
4122 TListOfListOfNodes nodeGroupsToMerge;
4123 if ( nbNodes[0] == nbNodes[1] ||
4124 ( theSideIsFreeBorder && !theSideThirdNode)) {
4126 // all nodes are to be merged
4128 for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
4129 nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
4130 nIt[0]++, nIt[1]++ )
4132 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4133 nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
4134 nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
4139 // insert new nodes into the border and the side to get equal nb of segments
4141 // get normalized parameters of nodes on the borders
4142 double param[ 2 ][ maxNbNodes ];
4144 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4145 list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
4146 list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
4147 const SMDS_MeshNode* nPrev = *nIt;
4148 double bordLength = 0;
4149 for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
4150 const SMDS_MeshNode* nCur = *nIt;
4151 gp_XYZ segment (nCur->X() - nPrev->X(),
4152 nCur->Y() - nPrev->Y(),
4153 nCur->Z() - nPrev->Z());
4154 double segmentLen = segment.Modulus();
4155 bordLength += segmentLen;
4156 param[ iBord ][ iNode ] = bordLength;
4159 // normalize within [0,1]
4160 for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
4161 param[ iBord ][ iNode ] /= bordLength;
4165 // loop on border segments
4166 const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
4167 int i[ 2 ] = { 0, 0 };
4168 nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
4169 nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
4171 TElemOfNodeListMap insertMap;
4172 TElemOfNodeListMap::iterator insertMapIt;
4174 // key: elem to insert nodes into
4175 // value: 2 nodes to insert between + nodes to be inserted
4177 bool next[ 2 ] = { false, false };
4179 // find min adjacent segment length after sewing
4180 double nextParam = 10., prevParam = 0;
4181 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4182 if ( i[ iBord ] + 1 < nbNodes[ iBord ])
4183 nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
4184 if ( i[ iBord ] > 0 )
4185 prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
4187 double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4188 double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4189 double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
4191 // choose to insert or to merge nodes
4192 double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
4193 if ( Abs( du ) <= minSegLen * 0.2 ) {
4196 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4197 const SMDS_MeshNode* n0 = *nIt[0];
4198 const SMDS_MeshNode* n1 = *nIt[1];
4199 nodeGroupsToMerge.back().push_back( n1 );
4200 nodeGroupsToMerge.back().push_back( n0 );
4201 // position of node of the border changes due to merge
4202 param[ 0 ][ i[0] ] += du;
4203 // move n1 for the sake of elem shape evaluation during insertion.
4204 // n1 will be removed by MergeNodes() anyway
4205 const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
4206 next[0] = next[1] = true;
4211 int intoBord = ( du < 0 ) ? 0 : 1;
4212 const SMDS_MeshElement* elem = *eIt[ intoBord ];
4213 const SMDS_MeshNode* n1 = nPrev[ intoBord ];
4214 const SMDS_MeshNode* n2 = *nIt[ intoBord ];
4215 const SMDS_MeshNode* nIns = *nIt[ 1 - intoBord ];
4216 if ( intoBord == 1 ) {
4217 // move node of the border to be on a link of elem of the side
4218 gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
4219 gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
4220 double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
4221 gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
4222 GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
4224 insertMapIt = insertMap.find( elem );
4225 bool notFound = ( insertMapIt == insertMap.end() );
4226 bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
4228 // insert into another link of the same element:
4229 // 1. perform insertion into the other link of the elem
4230 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4231 const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
4232 const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
4233 InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
4234 // 2. perform insertion into the link of adjacent faces
4236 const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
4238 InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
4242 if (toCreatePolyedrs) {
4243 // perform insertion into the links of adjacent volumes
4244 UpdateVolumes(n12, n22, nodeList);
4246 // 3. find an element appeared on n1 and n2 after the insertion
4247 insertMap.erase( elem );
4248 elem = findAdjacentFace( n1, n2, 0 );
4250 if ( notFound || otherLink ) {
4251 // add element and nodes of the side into the insertMap
4252 insertMapIt = insertMap.insert
4253 ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
4254 (*insertMapIt).second.push_back( n1 );
4255 (*insertMapIt).second.push_back( n2 );
4257 // add node to be inserted into elem
4258 (*insertMapIt).second.push_back( nIns );
4259 next[ 1 - intoBord ] = true;
4262 // go to the next segment
4263 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4264 if ( next[ iBord ] ) {
4265 if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
4267 nPrev[ iBord ] = *nIt[ iBord ];
4268 nIt[ iBord ]++; i[ iBord ]++;
4272 while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
4274 // perform insertion of nodes into elements
4276 for (insertMapIt = insertMap.begin();
4277 insertMapIt != insertMap.end();
4280 const SMDS_MeshElement* elem = (*insertMapIt).first;
4281 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4282 const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
4283 const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
4285 InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
4287 if ( !theSideIsFreeBorder ) {
4288 // look for and insert nodes into the faces adjacent to elem
4290 const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
4292 InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
4297 if (toCreatePolyedrs) {
4298 // perform insertion into the links of adjacent volumes
4299 UpdateVolumes(n1, n2, nodeList);
4303 } // end: insert new nodes
4305 MergeNodes ( nodeGroupsToMerge );
4310 //=======================================================================
4311 //function : InsertNodesIntoLink
4312 //purpose : insert theNodesToInsert into theFace between theBetweenNode1
4313 // and theBetweenNode2 and split theElement
4314 //=======================================================================
4316 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement* theFace,
4317 const SMDS_MeshNode* theBetweenNode1,
4318 const SMDS_MeshNode* theBetweenNode2,
4319 list<const SMDS_MeshNode*>& theNodesToInsert,
4320 const bool toCreatePoly)
4322 if ( theFace->GetType() != SMDSAbs_Face ) return;
4324 // find indices of 2 link nodes and of the rest nodes
4325 int iNode = 0, il1, il2, i3, i4;
4326 il1 = il2 = i3 = i4 = -1;
4327 const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
4328 SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
4329 while ( nodeIt->more() ) {
4330 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4331 if ( n == theBetweenNode1 )
4333 else if ( n == theBetweenNode2 )
4339 nodes[ iNode++ ] = n;
4341 if ( il1 < 0 || il2 < 0 || i3 < 0 )
4344 // arrange link nodes to go one after another regarding the face orientation
4345 bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
4346 list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
4351 aNodesToInsert.reverse();
4353 // check that not link nodes of a quadrangles are in good order
4354 int nbFaceNodes = theFace->NbNodes();
4355 if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
4361 if (toCreatePoly || theFace->IsPoly()) {
4364 vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
4366 // add nodes of face up to first node of link
4368 nodeIt = theFace->nodesIterator();
4369 while ( nodeIt->more() && !isFLN ) {
4370 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4371 poly_nodes[iNode++] = n;
4372 if (n == nodes[il1]) {
4377 // add nodes to insert
4378 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4379 for (; nIt != aNodesToInsert.end(); nIt++) {
4380 poly_nodes[iNode++] = *nIt;
4383 // add nodes of face starting from last node of link
4384 while ( nodeIt->more() ) {
4385 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4386 poly_nodes[iNode++] = n;
4389 // edit or replace the face
4390 SMESHDS_Mesh *aMesh = GetMeshDS();
4392 if (theFace->IsPoly()) {
4393 aMesh->ChangePolygonNodes(theFace, poly_nodes);
4396 int aShapeId = FindShape( theFace );
4398 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4399 if ( aShapeId && newElem )
4400 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4402 aMesh->RemoveElement(theFace);
4407 // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
4408 int nbLinkNodes = 2 + aNodesToInsert.size();
4409 const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
4410 linkNodes[ 0 ] = nodes[ il1 ];
4411 linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
4412 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4413 for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
4414 linkNodes[ iNode++ ] = *nIt;
4416 // decide how to split a quadrangle: compare possible variants
4417 // and choose which of splits to be a quadrangle
4418 int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
4419 if ( nbFaceNodes == 3 )
4421 iBestQuad = nbSplits;
4424 else if ( nbFaceNodes == 4 )
4426 SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
4427 double aBestRate = DBL_MAX;
4428 for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
4430 double aBadRate = 0;
4431 // evaluate elements quality
4432 for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
4433 if ( iSplit == iQuad ) {
4434 SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
4438 aBadRate += getBadRate( &quad, aCrit );
4441 SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
4443 nodes[ iSplit < iQuad ? i4 : i3 ]);
4444 aBadRate += getBadRate( &tria, aCrit );
4448 if ( aBadRate < aBestRate ) {
4450 aBestRate = aBadRate;
4455 // create new elements
4456 SMESHDS_Mesh *aMesh = GetMeshDS();
4457 int aShapeId = FindShape( theFace );
4460 for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
4461 SMDS_MeshElement* newElem = 0;
4462 if ( iSplit == iBestQuad )
4463 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4468 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4470 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
4471 if ( aShapeId && newElem )
4472 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4475 // change nodes of theFace
4476 const SMDS_MeshNode* newNodes[ 4 ];
4477 newNodes[ 0 ] = linkNodes[ i1 ];
4478 newNodes[ 1 ] = linkNodes[ i2 ];
4479 newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
4480 newNodes[ 3 ] = nodes[ i4 ];
4481 aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
4484 //=======================================================================
4485 //function : UpdateVolumes
4487 //=======================================================================
4488 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode* theBetweenNode1,
4489 const SMDS_MeshNode* theBetweenNode2,
4490 list<const SMDS_MeshNode*>& theNodesToInsert)
4492 SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
4493 while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
4494 const SMDS_MeshElement* elem = invElemIt->next();
4495 if (elem->GetType() != SMDSAbs_Volume)
4498 // check, if current volume has link theBetweenNode1 - theBetweenNode2
4499 SMDS_VolumeTool aVolume (elem);
4500 if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
4503 // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
4504 int iface, nbFaces = aVolume.NbFaces();
4505 vector<const SMDS_MeshNode *> poly_nodes;
4506 vector<int> quantities (nbFaces);
4508 for (iface = 0; iface < nbFaces; iface++) {
4509 int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
4510 // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
4511 const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
4513 for (int inode = 0; inode < nbFaceNodes; inode++) {
4514 poly_nodes.push_back(faceNodes[inode]);
4516 if (nbInserted == 0) {
4517 if (faceNodes[inode] == theBetweenNode1) {
4518 if (faceNodes[inode + 1] == theBetweenNode2) {
4519 nbInserted = theNodesToInsert.size();
4521 // add nodes to insert
4522 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
4523 for (; nIt != theNodesToInsert.end(); nIt++) {
4524 poly_nodes.push_back(*nIt);
4527 } else if (faceNodes[inode] == theBetweenNode2) {
4528 if (faceNodes[inode + 1] == theBetweenNode1) {
4529 nbInserted = theNodesToInsert.size();
4531 // add nodes to insert in reversed order
4532 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
4534 for (; nIt != theNodesToInsert.begin(); nIt--) {
4535 poly_nodes.push_back(*nIt);
4537 poly_nodes.push_back(*nIt);
4543 quantities[iface] = nbFaceNodes + nbInserted;
4546 // Replace or update the volume
4547 SMESHDS_Mesh *aMesh = GetMeshDS();
4549 if (elem->IsPoly()) {
4550 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4553 int aShapeId = FindShape( elem );
4555 SMDS_MeshElement* newElem =
4556 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
4557 if (aShapeId && newElem)
4558 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4560 aMesh->RemoveElement(elem);
4565 //=======================================================================
4566 //function : SewSideElements
4568 //=======================================================================
4570 SMESH_MeshEditor::Sew_Error
4571 SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
4572 set<const SMDS_MeshElement*>& theSide2,
4573 const SMDS_MeshNode* theFirstNode1,
4574 const SMDS_MeshNode* theFirstNode2,
4575 const SMDS_MeshNode* theSecondNode1,
4576 const SMDS_MeshNode* theSecondNode2)
4578 MESSAGE ("::::SewSideElements()");
4579 if ( theSide1.size() != theSide2.size() )
4580 return SEW_DIFF_NB_OF_ELEMENTS;
4582 Sew_Error aResult = SEW_OK;
4584 // 1. Build set of faces representing each side
4585 // 2. Find which nodes of the side 1 to merge with ones on the side 2
4586 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4588 // =======================================================================
4589 // 1. Build set of faces representing each side:
4590 // =======================================================================
4591 // a. build set of nodes belonging to faces
4592 // b. complete set of faces: find missing fices whose nodes are in set of nodes
4593 // c. create temporary faces representing side of volumes if correspondent
4594 // face does not exist
4596 SMESHDS_Mesh* aMesh = GetMeshDS();
4597 SMDS_Mesh aTmpFacesMesh;
4598 set<const SMDS_MeshElement*> faceSet1, faceSet2;
4599 set<const SMDS_MeshElement*> volSet1, volSet2;
4600 set<const SMDS_MeshNode*> nodeSet1, nodeSet2;
4601 set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
4602 set<const SMDS_MeshElement*> * volSetPtr[] = { &volSet1, &volSet2 };
4603 set<const SMDS_MeshNode*> * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
4604 set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
4605 int iSide, iFace, iNode;
4607 for ( iSide = 0; iSide < 2; iSide++ ) {
4608 set<const SMDS_MeshNode*> * nodeSet = nodeSetPtr[ iSide ];
4609 set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
4610 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4611 set<const SMDS_MeshElement*> * volSet = volSetPtr [ iSide ];
4612 set<const SMDS_MeshElement*>::iterator vIt, eIt;
4613 set<const SMDS_MeshNode*>::iterator nIt;
4615 // -----------------------------------------------------------
4616 // 1a. Collect nodes of existing faces
4617 // and build set of face nodes in order to detect missing
4618 // faces corresponing to sides of volumes
4619 // -----------------------------------------------------------
4621 set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
4623 // loop on the given element of a side
4624 for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
4625 const SMDS_MeshElement* elem = *eIt;
4626 if ( elem->GetType() == SMDSAbs_Face ) {
4627 faceSet->insert( elem );
4628 set <const SMDS_MeshNode*> faceNodeSet;
4629 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
4630 while ( nodeIt->more() ) {
4631 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4632 nodeSet->insert( n );
4633 faceNodeSet.insert( n );
4635 setOfFaceNodeSet.insert( faceNodeSet );
4637 else if ( elem->GetType() == SMDSAbs_Volume )
4638 volSet->insert( elem );
4640 // ------------------------------------------------------------------------------
4641 // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
4642 // ------------------------------------------------------------------------------
4644 for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4645 SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4646 while ( fIt->more() ) { // loop on faces sharing a node
4647 const SMDS_MeshElement* f = fIt->next();
4648 if ( faceSet->find( f ) == faceSet->end() ) {
4649 // check if all nodes are in nodeSet and
4650 // complete setOfFaceNodeSet if they are
4651 set <const SMDS_MeshNode*> faceNodeSet;
4652 SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4653 bool allInSet = true;
4654 while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4655 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4656 if ( nodeSet->find( n ) == nodeSet->end() )
4659 faceNodeSet.insert( n );
4662 faceSet->insert( f );
4663 setOfFaceNodeSet.insert( faceNodeSet );
4669 // -------------------------------------------------------------------------
4670 // 1c. Create temporary faces representing sides of volumes if correspondent
4671 // face does not exist
4672 // -------------------------------------------------------------------------
4674 if ( !volSet->empty() )
4676 //int nodeSetSize = nodeSet->size();
4678 // loop on given volumes
4679 for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
4680 SMDS_VolumeTool vol (*vIt);
4681 // loop on volume faces: find free faces
4682 // --------------------------------------
4683 list<const SMDS_MeshElement* > freeFaceList;
4684 for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
4685 if ( !vol.IsFreeFace( iFace ))
4687 // check if there is already a face with same nodes in a face set
4688 const SMDS_MeshElement* aFreeFace = 0;
4689 const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
4690 int nbNodes = vol.NbFaceNodes( iFace );
4691 set <const SMDS_MeshNode*> faceNodeSet;
4692 vol.GetFaceNodes( iFace, faceNodeSet );
4693 bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
4695 // no such a face is given but it still can exist, check it
4696 if ( nbNodes == 3 ) {
4697 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
4698 } else if ( nbNodes == 4 ) {
4699 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4701 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4702 for (int inode = 0; inode < nbNodes; inode++) {
4703 poly_nodes[inode] = fNodes[inode];
4705 aFreeFace = aMesh->FindFace(poly_nodes);
4709 // create a temporary face
4710 if ( nbNodes == 3 ) {
4711 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
4712 } else if ( nbNodes == 4 ) {
4713 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4715 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4716 for (int inode = 0; inode < nbNodes; inode++) {
4717 poly_nodes[inode] = fNodes[inode];
4719 aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
4723 freeFaceList.push_back( aFreeFace );
4725 } // loop on faces of a volume
4727 // choose one of several free faces
4728 // --------------------------------------
4729 if ( freeFaceList.size() > 1 ) {
4730 // choose a face having max nb of nodes shared by other elems of a side
4731 int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
4732 list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
4733 while ( fIt != freeFaceList.end() ) { // loop on free faces
4734 int nbSharedNodes = 0;
4735 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4736 while ( nodeIt->more() ) { // loop on free face nodes
4737 const SMDS_MeshNode* n =
4738 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4739 SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
4740 while ( invElemIt->more() ) {
4741 const SMDS_MeshElement* e = invElemIt->next();
4742 if ( faceSet->find( e ) != faceSet->end() )
4744 if ( elemSet->find( e ) != elemSet->end() )
4748 if ( nbSharedNodes >= maxNbNodes ) {
4749 maxNbNodes = nbSharedNodes;
4753 freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
4755 if ( freeFaceList.size() > 1 )
4757 // could not choose one face, use another way
4758 // choose a face most close to the bary center of the opposite side
4759 gp_XYZ aBC( 0., 0., 0. );
4760 set <const SMDS_MeshNode*> addedNodes;
4761 set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
4762 eIt = elemSet2->begin();
4763 for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
4764 SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
4765 while ( nodeIt->more() ) { // loop on free face nodes
4766 const SMDS_MeshNode* n =
4767 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4768 if ( addedNodes.insert( n ).second )
4769 aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
4772 aBC /= addedNodes.size();
4773 double minDist = DBL_MAX;
4774 fIt = freeFaceList.begin();
4775 while ( fIt != freeFaceList.end() ) { // loop on free faces
4777 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4778 while ( nodeIt->more() ) { // loop on free face nodes
4779 const SMDS_MeshNode* n =
4780 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4781 gp_XYZ p( n->X(),n->Y(),n->Z() );
4782 dist += ( aBC - p ).SquareModulus();
4784 if ( dist < minDist ) {
4786 freeFaceList.erase( freeFaceList.begin(), fIt++ );
4789 fIt = freeFaceList.erase( fIt++ );
4792 } // choose one of several free faces of a volume
4794 if ( freeFaceList.size() == 1 ) {
4795 const SMDS_MeshElement* aFreeFace = freeFaceList.front();
4796 faceSet->insert( aFreeFace );
4797 // complete a node set with nodes of a found free face
4798 // for ( iNode = 0; iNode < ; iNode++ )
4799 // nodeSet->insert( fNodes[ iNode ] );
4802 } // loop on volumes of a side
4804 // // complete a set of faces if new nodes in a nodeSet appeared
4805 // // ----------------------------------------------------------
4806 // if ( nodeSetSize != nodeSet->size() ) {
4807 // for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4808 // SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4809 // while ( fIt->more() ) { // loop on faces sharing a node
4810 // const SMDS_MeshElement* f = fIt->next();
4811 // if ( faceSet->find( f ) == faceSet->end() ) {
4812 // // check if all nodes are in nodeSet and
4813 // // complete setOfFaceNodeSet if they are
4814 // set <const SMDS_MeshNode*> faceNodeSet;
4815 // SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4816 // bool allInSet = true;
4817 // while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4818 // const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4819 // if ( nodeSet->find( n ) == nodeSet->end() )
4820 // allInSet = false;
4822 // faceNodeSet.insert( n );
4824 // if ( allInSet ) {
4825 // faceSet->insert( f );
4826 // setOfFaceNodeSet.insert( faceNodeSet );
4832 } // Create temporary faces, if there are volumes given
4835 if ( faceSet1.size() != faceSet2.size() ) {
4836 // delete temporary faces: they are in reverseElements of actual nodes
4837 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4838 while ( tmpFaceIt->more() )
4839 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4840 MESSAGE("Diff nb of faces");
4841 return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4844 // ============================================================
4845 // 2. Find nodes to merge:
4846 // bind a node to remove to a node to put instead
4847 // ============================================================
4849 TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
4850 if ( theFirstNode1 != theFirstNode2 )
4851 nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
4852 if ( theSecondNode1 != theSecondNode2 )
4853 nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
4855 LinkID_Gen aLinkID_Gen( GetMeshDS() );
4856 set< long > linkIdSet; // links to process
4857 linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
4859 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
4860 list< TPairOfNodes > linkList[2];
4861 linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
4862 linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
4863 // loop on links in linkList; find faces by links and append links
4864 // of the found faces to linkList
4865 list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
4866 for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
4868 TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
4869 long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
4870 if ( linkIdSet.find( linkID ) == linkIdSet.end() )
4873 // by links, find faces in the face sets,
4874 // and find indices of link nodes in the found faces;
4875 // in a face set, there is only one or no face sharing a link
4876 // ---------------------------------------------------------------
4878 const SMDS_MeshElement* face[] = { 0, 0 };
4879 const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
4880 const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
4881 int iLinkNode[2][2];
4882 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4883 const SMDS_MeshNode* n1 = link[iSide].first;
4884 const SMDS_MeshNode* n2 = link[iSide].second;
4885 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4886 set< const SMDS_MeshElement* > fMap;
4887 for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
4888 const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
4889 SMDS_ElemIteratorPtr fIt = n->facesIterator();
4890 while ( fIt->more() ) { // loop on faces sharing a node
4891 const SMDS_MeshElement* f = fIt->next();
4892 if (faceSet->find( f ) != faceSet->end() && // f is in face set
4893 ! fMap.insert( f ).second ) // f encounters twice
4895 if ( face[ iSide ] ) {
4896 MESSAGE( "2 faces per link " );
4897 aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
4901 faceSet->erase( f );
4902 // get face nodes and find ones of a link
4904 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
4905 while ( nIt->more() ) {
4906 const SMDS_MeshNode* n =
4907 static_cast<const SMDS_MeshNode*>( nIt->next() );
4909 iLinkNode[ iSide ][ 0 ] = iNode;
4911 iLinkNode[ iSide ][ 1 ] = iNode;
4912 else if ( notLinkNodes[ iSide ][ 0 ] )
4913 notLinkNodes[ iSide ][ 1 ] = n;
4915 notLinkNodes[ iSide ][ 0 ] = n;
4916 faceNodes[ iSide ][ iNode++ ] = n;
4918 faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
4923 // check similarity of elements of the sides
4924 if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
4925 MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
4926 if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
4927 aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
4929 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4930 break; // do not return because it s necessary to remove tmp faces
4933 // set nodes to merge
4934 // -------------------
4936 if ( face[0] && face[1] )
4938 int nbNodes = face[0]->NbNodes();
4939 if ( nbNodes != face[1]->NbNodes() ) {
4940 MESSAGE("Diff nb of face nodes");
4941 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4942 break; // do not return because it s necessary to remove tmp faces
4944 bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
4946 nReplaceMap.insert( TNodeNodeMap::value_type
4947 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4949 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4950 // analyse link orientation in faces
4951 int i1 = iLinkNode[ iSide ][ 0 ];
4952 int i2 = iLinkNode[ iSide ][ 1 ];
4953 reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
4954 // if notLinkNodes are the first and the last ones, then
4955 // their order does not correspond to the link orientation
4956 if (( i1 == 1 && i2 == 2 ) ||
4957 ( i1 == 2 && i2 == 1 ))
4958 reverse[ iSide ] = !reverse[ iSide ];
4960 if ( reverse[0] == reverse[1] ) {
4961 nReplaceMap.insert( TNodeNodeMap::value_type
4962 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4963 nReplaceMap.insert( TNodeNodeMap::value_type
4964 ( notLinkNodes[0][1], notLinkNodes[1][1] ));
4967 nReplaceMap.insert( TNodeNodeMap::value_type
4968 ( notLinkNodes[0][0], notLinkNodes[1][1] ));
4969 nReplaceMap.insert( TNodeNodeMap::value_type
4970 ( notLinkNodes[0][1], notLinkNodes[1][0] ));
4974 // add other links of the faces to linkList
4975 // -----------------------------------------
4977 const SMDS_MeshNode** nodes = faceNodes[ 0 ];
4978 for ( iNode = 0; iNode < nbNodes; iNode++ )
4980 linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
4981 pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
4982 if ( !iter_isnew.second ) { // already in a set: no need to process
4983 linkIdSet.erase( iter_isnew.first );
4985 else // new in set == encountered for the first time: add
4987 const SMDS_MeshNode* n1 = nodes[ iNode ];
4988 const SMDS_MeshNode* n2 = nodes[ iNode + 1];
4989 linkList[0].push_back ( TPairOfNodes( n1, n2 ));
4990 linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
4994 } // loop on link lists
4996 if ( aResult == SEW_OK &&
4997 ( linkIt[0] != linkList[0].end() ||
4998 !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
4999 MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
5000 " " << (faceSetPtr[1]->empty()));
5001 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
5004 // ====================================================================
5005 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
5006 // ====================================================================
5008 // delete temporary faces: they are in reverseElements of actual nodes
5009 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
5010 while ( tmpFaceIt->more() )
5011 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
5013 if ( aResult != SEW_OK)
5016 list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
5017 // loop on nodes replacement map
5018 TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
5019 for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
5020 if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
5022 const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
5023 nodeIDsToRemove.push_back( nToRemove->GetID() );
5024 // loop on elements sharing nToRemove
5025 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
5026 while ( invElemIt->more() ) {
5027 const SMDS_MeshElement* e = invElemIt->next();
5028 // get a new suite of nodes: make replacement
5029 int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
5030 const SMDS_MeshNode* nodes[ 8 ];
5031 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5032 while ( nIt->more() ) {
5033 const SMDS_MeshNode* n =
5034 static_cast<const SMDS_MeshNode*>( nIt->next() );
5035 nnIt = nReplaceMap.find( n );
5036 if ( nnIt != nReplaceMap.end() ) {
5042 // if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
5043 // elemIDsToRemove.push_back( e->GetID() );
5046 aMesh->ChangeElementNodes( e, nodes, nbNodes );
5050 Remove( nodeIDsToRemove, true );