1 // SMESH SMESH : idl implementation based on 'SMESH' unit's classes
3 // Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
24 // File : SMESH_MeshEditor.cxx
25 // Created : Mon Apr 12 16:10:22 2004
26 // Author : Edward AGAPOV (eap)
29 #include "SMESH_MeshEditor.hxx"
31 #include "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
35 #include "SMDS_FacePosition.hxx"
36 #include "SMDS_SpacePosition.hxx"
38 #include "SMESHDS_Group.hxx"
39 #include "SMESHDS_Mesh.hxx"
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_ControlsDef.hxx"
44 #include "utilities.h"
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopTools_ListOfShape.hxx>
52 #include <gp_Trsf.hxx>
58 #include <BRep_Tool.hxx>
59 #include <Geom_Curve.hxx>
60 #include <Geom_Surface.hxx>
61 #include <Geom2d_Curve.hxx>
62 #include <Extrema_GenExtPS.hxx>
63 #include <Extrema_POnSurf.hxx>
64 #include <GeomAdaptor_Surface.hxx>
66 #include <TColStd_ListOfInteger.hxx>
71 using namespace SMESH::Controls;
73 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*> TNodeNodeMap;
74 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> > TElemOfNodeListMap;
75 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
76 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
77 typedef TNodeOfNodeListMap::iterator TNodeOfNodeListMapItr;
78 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
80 //=======================================================================
81 //function : SMESH_MeshEditor
83 //=======================================================================
85 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
90 //=======================================================================
92 //purpose : Remove a node or an element.
93 // Modify a compute state of sub-meshes which become empty
94 //=======================================================================
96 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
100 SMESHDS_Mesh* aMesh = GetMeshDS();
101 set< SMESH_subMesh *> smmap;
103 list<int>::const_iterator it = theIDs.begin();
104 for ( ; it != theIDs.end(); it++ )
106 const SMDS_MeshElement * elem;
108 elem = aMesh->FindNode( *it );
110 elem = aMesh->FindElement( *it );
114 // Find sub-meshes to notify about modification
115 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
116 while ( nodeIt->more() )
118 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
119 const SMDS_PositionPtr& aPosition = node->GetPosition();
120 if ( aPosition.get() ) {
121 int aShapeID = aPosition->GetShapeId();
123 TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
124 SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
133 aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
135 aMesh->RemoveElement( elem );
138 // Notify sub-meshes about modification
139 if ( !smmap.empty() ) {
140 set< SMESH_subMesh *>::iterator smIt;
141 for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
142 (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
147 //=======================================================================
148 //function : FindShape
149 //purpose : Return an index of the shape theElem is on
150 // or zero if a shape not found
151 //=======================================================================
153 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
155 SMESHDS_Mesh * aMesh = GetMeshDS();
156 if ( aMesh->ShapeToMesh().IsNull() )
159 if ( theElem->GetType() == SMDSAbs_Node )
161 const SMDS_PositionPtr& aPosition =
162 static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
163 if ( aPosition.get() )
164 return aPosition->GetShapeId();
169 TopoDS_Shape aShape; // the shape a node is on
170 SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
171 while ( nodeIt->more() )
173 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
174 const SMDS_PositionPtr& aPosition = node->GetPosition();
175 if ( aPosition.get() ) {
176 int aShapeID = aPosition->GetShapeId();
177 SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
180 if ( sm->Contains( theElem ))
182 if ( aShape.IsNull() )
183 aShape = aMesh->IndexToShape( aShapeID );
187 //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
192 // None of nodes is on a proper shape,
193 // find the shape among ancestors of aShape on which a node is
194 if ( aShape.IsNull() ) {
195 //MESSAGE ("::FindShape() - NONE node is on shape")
198 TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
199 for ( ; ancIt.More(); ancIt.Next() )
201 SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
202 if ( sm && sm->Contains( theElem ))
203 return aMesh->ShapeToIndex( ancIt.Value() );
206 //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
210 //=======================================================================
211 //function : InverseDiag
212 //purpose : Replace two neighbour triangles with ones built on the same 4 nodes
213 // but having other common link.
214 // Return False if args are improper
215 //=======================================================================
217 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
218 const SMDS_MeshElement * theTria2 )
220 if (!theTria1 || !theTria2)
222 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
223 if (!F1) return false;
224 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
225 if (!F2) return false;
227 // 1 +--+ A theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
228 // | /| theTria2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
232 // put nodes in array and find out indices of the same ones
233 const SMDS_MeshNode* aNodes [6];
234 int sameInd [] = { 0, 0, 0, 0, 0, 0 };
236 SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
239 aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
241 if ( i > 2 ) // theTria2
242 // find same node of theTria1
243 for ( int j = 0; j < 3; j++ )
244 if ( aNodes[ i ] == aNodes[ j ]) {
253 return false; // theTria1 is not a triangle
254 it = theTria2->nodesIterator();
256 if ( i == 6 && it->more() )
257 return false; // theTria2 is not a triangle
260 // find indices of 1,2 and of A,B in theTria1
261 int iA = 0, iB = 0, i1 = 0, i2 = 0;
262 for ( i = 0; i < 6; i++ )
264 if ( sameInd [ i ] == 0 )
271 // nodes 1 and 2 should not be the same
272 if ( aNodes[ i1 ] == aNodes[ i2 ] )
277 aNodes[ iA ] = aNodes[ i2 ];
279 aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
281 //MESSAGE( theTria1 << theTria2 );
283 GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
284 GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
286 //MESSAGE( theTria1 << theTria2 );
291 //=======================================================================
292 //function : findTriangles
293 //purpose : find triangles sharing theNode1-theNode2 link
294 //=======================================================================
296 static bool findTriangles(const SMDS_MeshNode * theNode1,
297 const SMDS_MeshNode * theNode2,
298 const SMDS_MeshElement*& theTria1,
299 const SMDS_MeshElement*& theTria2)
301 if ( !theNode1 || !theNode2 ) return false;
303 theTria1 = theTria2 = 0;
305 set< const SMDS_MeshElement* > emap;
306 SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
308 const SMDS_MeshElement* elem = it->next();
309 if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
312 it = theNode2->GetInverseElementIterator();
314 const SMDS_MeshElement* elem = it->next();
315 if ( elem->GetType() == SMDSAbs_Face &&
316 emap.find( elem ) != emap.end() )
324 return ( theTria1 && theTria2 );
327 //=======================================================================
328 //function : InverseDiag
329 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
330 // with ones built on the same 4 nodes but having other common link.
331 // Return false if proper faces not found
332 //=======================================================================
334 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
335 const SMDS_MeshNode * theNode2)
337 MESSAGE( "::InverseDiag()" );
339 const SMDS_MeshElement *tr1, *tr2;
340 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
343 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
344 if (!F1) return false;
345 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
346 if (!F2) return false;
348 // 1 +--+ A tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
349 // | /| tr2: ( B A 2 ) B->1 ( 1 A 2 ) |\ |
353 // put nodes in array
354 // and find indices of 1,2 and of A in tr1 and of B in tr2
355 int i, iA1 = 0, i1 = 0;
356 const SMDS_MeshNode* aNodes1 [3];
357 SMDS_ElemIteratorPtr it;
358 for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
359 aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
360 if ( aNodes1[ i ] == theNode1 )
361 iA1 = i; // node A in tr1
362 else if ( aNodes1[ i ] != theNode2 )
366 const SMDS_MeshNode* aNodes2 [3];
367 for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
368 aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
369 if ( aNodes2[ i ] == theNode2 )
370 iB2 = i; // node B in tr2
371 else if ( aNodes2[ i ] != theNode1 )
375 // nodes 1 and 2 should not be the same
376 if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
380 aNodes1[ iA1 ] = aNodes2[ i2 ];
382 aNodes2[ iB2 ] = aNodes1[ i1 ];
384 //MESSAGE( tr1 << tr2 );
386 GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
387 GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
389 //MESSAGE( tr1 << tr2 );
395 //=======================================================================
396 //function : getQuadrangleNodes
397 //purpose : fill theQuadNodes - nodes of a quadrangle resulting from
398 // fusion of triangles tr1 and tr2 having shared link on
399 // theNode1 and theNode2
400 //=======================================================================
402 bool getQuadrangleNodes(const SMDS_MeshNode * theQuadNodes [],
403 const SMDS_MeshNode * theNode1,
404 const SMDS_MeshNode * theNode2,
405 const SMDS_MeshElement * tr1,
406 const SMDS_MeshElement * tr2 )
408 // find the 4-th node to insert into tr1
409 const SMDS_MeshNode* n4 = 0;
410 SMDS_ElemIteratorPtr it = tr2->nodesIterator();
411 while ( !n4 && it->more() )
413 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
414 bool isDiag = ( n == theNode1 || n == theNode2 );
418 // Make an array of nodes to be in a quadrangle
419 int iNode = 0, iFirstDiag = -1;
420 it = tr1->nodesIterator();
423 const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
424 bool isDiag = ( n == theNode1 || n == theNode2 );
427 if ( iFirstDiag < 0 )
429 else if ( iNode - iFirstDiag == 1 )
430 theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
434 return false; // tr1 and tr2 should not have all the same nodes
436 theQuadNodes[ iNode++ ] = n;
438 if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
439 theQuadNodes[ iNode ] = n4;
444 //=======================================================================
445 //function : DeleteDiag
446 //purpose : Replace two neighbour triangles sharing theNode1-theNode2 link
447 // with a quadrangle built on the same 4 nodes.
448 // Return false if proper faces not found
449 //=======================================================================
451 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
452 const SMDS_MeshNode * theNode2)
454 MESSAGE( "::DeleteDiag()" );
456 const SMDS_MeshElement *tr1, *tr2;
457 if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
460 const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
461 if (!F1) return false;
462 const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
463 if (!F2) return false;
465 const SMDS_MeshNode* aNodes [ 4 ];
466 if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
469 //MESSAGE( endl << tr1 << tr2 );
471 GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
472 GetMeshDS()->RemoveElement( tr2 );
474 //MESSAGE( endl << tr1 );
479 //=======================================================================
480 //function : Reorient
481 //purpose : Reverse theElement orientation
482 //=======================================================================
484 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
488 SMDS_ElemIteratorPtr it = theElem->nodesIterator();
489 if ( !it || !it->more() )
492 switch ( theElem->GetType() ) {
497 int i = theElem->NbNodes();
498 vector<const SMDS_MeshNode*> aNodes( i );
500 aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
501 return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
505 if (theElem->IsPoly()) {
506 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
507 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
509 MESSAGE("Warning: bad volumic element");
513 int nbFaces = aPolyedre->NbFaces();
514 vector<const SMDS_MeshNode *> poly_nodes;
515 vector<int> quantities (nbFaces);
517 // reverse each face of the polyedre
518 for (int iface = 1; iface <= nbFaces; iface++) {
519 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
520 quantities[iface - 1] = nbFaceNodes;
522 for (inode = nbFaceNodes; inode >= 1; inode--) {
523 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
524 poly_nodes.push_back(curNode);
528 return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
531 SMDS_VolumeTool vTool;
532 if ( !vTool.Set( theElem ))
535 return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
544 //=======================================================================
545 //function : getBadRate
547 //=======================================================================
549 static double getBadRate (const SMDS_MeshElement* theElem,
550 SMESH::Controls::NumericalFunctorPtr& theCrit)
552 SMESH::Controls::TSequenceOfXYZ P;
553 if ( !theElem || !theCrit->GetPoints( theElem, P ))
555 return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
556 //return theCrit->GetBadRate( theCrit->GetValue( theElem->GetID() ), theElem->NbNodes() );
559 //=======================================================================
560 //function : QuadToTri
561 //purpose : Cut quadrangles into triangles.
562 // theCrit is used to select a diagonal to cut
563 //=======================================================================
565 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> & theElems,
566 SMESH::Controls::NumericalFunctorPtr theCrit)
568 MESSAGE( "::QuadToTri()" );
570 if ( !theCrit.get() )
573 SMESHDS_Mesh * aMesh = GetMeshDS();
575 set< const SMDS_MeshElement * >::iterator itElem;
576 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
578 const SMDS_MeshElement* elem = (*itElem);
579 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
582 // retrieve element nodes
583 const SMDS_MeshNode* aNodes [4];
584 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
586 while ( itN->more() )
587 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
589 // compare two sets of possible triangles
590 double aBadRate1, aBadRate2; // to what extent a set is bad
591 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
592 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
593 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
595 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
596 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
597 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
599 int aShapeId = FindShape( elem );
600 //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
601 // << " ShapeID = " << aShapeId << endl << elem );
603 if ( aBadRate1 <= aBadRate2 ) {
604 // tr1 + tr2 is better
605 aMesh->ChangeElementNodes( elem, aNodes, 3 );
606 //MESSAGE( endl << elem );
608 elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
611 // tr3 + tr4 is better
612 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
613 //MESSAGE( endl << elem );
615 elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
617 //MESSAGE( endl << elem );
619 // put a new triangle on the same shape
621 aMesh->SetMeshElementOnShape( elem, aShapeId );
627 //=======================================================================
628 //function : BestSplit
629 //purpose : Find better diagonal for cutting.
630 //=======================================================================
631 int SMESH_MeshEditor::BestSplit (const SMDS_MeshElement* theQuad,
632 SMESH::Controls::NumericalFunctorPtr theCrit)
637 if (!theQuad || theQuad->GetType() != SMDSAbs_Face || theQuad->NbNodes() != 4)
640 // retrieve element nodes
641 const SMDS_MeshNode* aNodes [4];
642 SMDS_ElemIteratorPtr itN = theQuad->nodesIterator();
645 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
647 // compare two sets of possible triangles
648 double aBadRate1, aBadRate2; // to what extent a set is bad
649 SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
650 SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
651 aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
653 SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
654 SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
655 aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
657 if (aBadRate1 <= aBadRate2) // tr1 + tr2 is better
658 return 1; // diagonal 1-3
660 return 2; // diagonal 2-4
663 //=======================================================================
664 //function : AddToSameGroups
665 //purpose : add elemToAdd to the groups the elemInGroups belongs to
666 //=======================================================================
668 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
669 const SMDS_MeshElement* elemInGroups,
670 SMESHDS_Mesh * aMesh)
672 const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
673 set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
674 for ( ; grIt != groups.end(); grIt++ ) {
675 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
676 if ( group && group->SMDSGroup().Contains( elemInGroups ))
677 group->SMDSGroup().Add( elemToAdd );
681 //=======================================================================
682 //function : QuadToTri
683 //purpose : Cut quadrangles into triangles.
684 // theCrit is used to select a diagonal to cut
685 //=======================================================================
687 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
688 const bool the13Diag)
690 MESSAGE( "::QuadToTri()" );
692 SMESHDS_Mesh * aMesh = GetMeshDS();
694 set< const SMDS_MeshElement * >::iterator itElem;
695 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
697 const SMDS_MeshElement* elem = (*itElem);
698 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
701 // retrieve element nodes
702 const SMDS_MeshNode* aNodes [4];
703 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
705 while ( itN->more() )
706 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
708 int aShapeId = FindShape( elem );
709 const SMDS_MeshElement* newElem = 0;
712 aMesh->ChangeElementNodes( elem, aNodes, 3 );
713 newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
717 aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
718 newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
721 // put a new triangle on the same shape and add to the same groups
724 aMesh->SetMeshElementOnShape( newElem, aShapeId );
726 AddToSameGroups( newElem, elem, aMesh );
732 //=======================================================================
733 //function : getAngle
735 //=======================================================================
737 double getAngle(const SMDS_MeshElement * tr1,
738 const SMDS_MeshElement * tr2,
739 const SMDS_MeshNode * n1,
740 const SMDS_MeshNode * n2)
742 double angle = 2*PI; // bad angle
745 SMESH::Controls::TSequenceOfXYZ P1, P2;
746 if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
747 !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
749 gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
750 if ( N1.SquareMagnitude() <= gp::Resolution() )
752 gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
753 if ( N2.SquareMagnitude() <= gp::Resolution() )
756 // find the first diagonal node n1 in the triangles:
757 // take in account a diagonal link orientation
758 const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
759 for ( int t = 0; t < 2; t++ )
761 SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
762 int i = 0, iDiag = -1;
763 while ( it->more()) {
764 const SMDS_MeshElement *n = it->next();
765 if ( n == n1 || n == n2 )
769 if ( i - iDiag == 1 )
770 nFirst[ t ] = ( n == n1 ? n2 : n1 );
778 if ( nFirst[ 0 ] == nFirst[ 1 ] )
781 angle = N1.Angle( N2 );
786 // =================================================
787 // class generating a unique ID for a pair of nodes
788 // and able to return nodes by that ID
789 // =================================================
794 LinkID_Gen( const SMESHDS_Mesh* theMesh )
795 :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
798 long GetLinkID (const SMDS_MeshNode * n1,
799 const SMDS_MeshNode * n2) const
801 return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
804 bool GetNodes (const long theLinkID,
805 const SMDS_MeshNode* & theNode1,
806 const SMDS_MeshNode* & theNode2) const
808 theNode1 = myMesh->FindNode( theLinkID / myMaxID );
809 if ( !theNode1 ) return false;
810 theNode2 = myMesh->FindNode( theLinkID % myMaxID );
811 if ( !theNode2 ) return false;
817 const SMESHDS_Mesh* myMesh;
821 //=======================================================================
822 //function : TriToQuad
823 //purpose : Fuse neighbour triangles into quadrangles.
824 // theCrit is used to select a neighbour to fuse with.
825 // theMaxAngle is a max angle between element normals at which
826 // fusion is still performed.
827 //=======================================================================
829 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> & theElems,
830 SMESH::Controls::NumericalFunctorPtr theCrit,
831 const double theMaxAngle)
833 MESSAGE( "::TriToQuad()" );
835 if ( !theCrit.get() )
838 SMESHDS_Mesh * aMesh = GetMeshDS();
839 LinkID_Gen aLinkID_Gen( aMesh );
842 // Prepare data for algo: build
843 // 1. map of elements with their linkIDs
844 // 2. map of linkIDs with their elements
846 map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
847 map< long, list< const SMDS_MeshElement* > >::iterator itLE;
848 map< const SMDS_MeshElement*, set< long > > mapEl_setLi;
849 map< const SMDS_MeshElement*, set< long > >::iterator itEL;
851 set<const SMDS_MeshElement*>::iterator itElem;
852 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
854 const SMDS_MeshElement* elem = (*itElem);
855 if ( !elem || elem->NbNodes() != 3 )
858 // retrieve element nodes
859 const SMDS_MeshNode* aNodes [4];
860 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
862 while ( itN->more() )
863 aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
865 aNodes[ 3 ] = aNodes[ 0 ];
868 for ( i = 0; i < 3; i++ )
870 long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
871 // check if elements sharing a link can be fused
872 itLE = mapLi_listEl.find( linkID );
873 if ( itLE != mapLi_listEl.end() )
875 if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
877 const SMDS_MeshElement* elem2 = (*itLE).second.front();
878 // if ( FindShape( elem ) != FindShape( elem2 ))
879 // continue; // do not fuse triangles laying on different shapes
880 if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
881 continue; // avoid making badly shaped quads
882 (*itLE).second.push_back( elem );
885 mapLi_listEl[ linkID ].push_back( elem );
886 mapEl_setLi [ elem ].insert( linkID );
889 // Clean the maps from the links shared by a sole element, ie
890 // links to which only one element is bound in mapLi_listEl
892 for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
894 int nbElems = (*itLE).second.size();
896 const SMDS_MeshElement* elem = (*itLE).second.front();
897 long link = (*itLE).first;
898 mapEl_setLi[ elem ].erase( link );
899 if ( mapEl_setLi[ elem ].empty() )
900 mapEl_setLi.erase( elem );
904 // Algo: fuse triangles into quadrangles
906 while ( ! mapEl_setLi.empty() )
908 // Look for the start element:
909 // the element having the least nb of shared links
911 const SMDS_MeshElement* startElem = 0;
913 for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
915 int nbLinks = (*itEL).second.size();
916 if ( nbLinks < minNbLinks )
918 startElem = (*itEL).first;
919 minNbLinks = nbLinks;
920 if ( minNbLinks == 1 )
925 // search elements to fuse starting from startElem or links of elements
926 // fused earlyer - startLinks
927 list< long > startLinks;
928 while ( startElem || !startLinks.empty() )
930 while ( !startElem && !startLinks.empty() )
932 // Get an element to start, by a link
933 long linkId = startLinks.front();
934 startLinks.pop_front();
935 itLE = mapLi_listEl.find( linkId );
936 if ( itLE != mapLi_listEl.end() )
938 list< const SMDS_MeshElement* > & listElem = (*itLE).second;
939 list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
940 for ( ; itE != listElem.end() ; itE++ )
941 if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
943 mapLi_listEl.erase( itLE );
949 // Get candidates to be fused
951 const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
954 ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
955 set< long >& setLi = mapEl_setLi[ tr1 ];
956 ASSERT( !setLi.empty() );
957 set< long >::iterator itLi;
958 for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
960 long linkID = (*itLi);
961 itLE = mapLi_listEl.find( linkID );
962 if ( itLE == mapLi_listEl.end() )
964 const SMDS_MeshElement* elem = (*itLE).second.front();
966 elem = (*itLE).second.back();
967 mapLi_listEl.erase( itLE );
968 if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
981 // add other links of elem to list of links to re-start from
982 set< long >& links = mapEl_setLi[ elem ];
983 set< long >::iterator it;
984 for ( it = links.begin(); it != links.end(); it++ )
986 long linkID2 = (*it);
987 if ( linkID2 != linkID )
988 startLinks.push_back( linkID2 );
992 // Get nodes of possible quadrangles
994 const SMDS_MeshNode *n12 [4], *n13 [4];
995 bool Ok12 = false, Ok13 = false;
996 const SMDS_MeshNode *linkNode1, *linkNode2;
998 aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
999 getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
1002 aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
1003 getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
1006 // Choose a pair to fuse
1010 SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
1011 SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
1012 double aBadRate12 = getBadRate( &quad12, theCrit );
1013 double aBadRate13 = getBadRate( &quad13, theCrit );
1014 if ( aBadRate13 < aBadRate12 )
1022 // and remove fused elems and removed links from the maps
1024 mapEl_setLi.erase( tr1 );
1027 mapEl_setLi.erase( tr2 );
1028 mapLi_listEl.erase( link12 );
1029 aMesh->ChangeElementNodes( tr1, n12, 4 );
1030 aMesh->RemoveElement( tr2 );
1034 mapEl_setLi.erase( tr3 );
1035 mapLi_listEl.erase( link13 );
1036 aMesh->ChangeElementNodes( tr1, n13, 4 );
1037 aMesh->RemoveElement( tr3 );
1040 // Next element to fuse: the rejected one
1042 startElem = Ok12 ? tr3 : tr2;
1044 } // if ( startElem )
1045 } // while ( startElem || !startLinks.empty() )
1046 } // while ( ! mapEl_setLi.empty() )
1052 /*#define DUMPSO(txt) \
1053 // cout << txt << endl;
1054 //=============================================================================
1058 //=============================================================================
1059 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1063 int tmp = idNodes[ i1 ];
1064 idNodes[ i1 ] = idNodes[ i2 ];
1065 idNodes[ i2 ] = tmp;
1066 gp_Pnt Ptmp = P[ i1 ];
1069 DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1072 //=======================================================================
1073 //function : SortQuadNodes
1074 //purpose : Set 4 nodes of a quadrangle face in a good order.
1075 // Swap 1<->2 or 2<->3 nodes and correspondingly return
1077 //=======================================================================
1079 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1084 for ( i = 0; i < 4; i++ ) {
1085 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1087 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1090 gp_Vec V1(P[0], P[1]);
1091 gp_Vec V2(P[0], P[2]);
1092 gp_Vec V3(P[0], P[3]);
1094 gp_Vec Cross1 = V1 ^ V2;
1095 gp_Vec Cross2 = V2 ^ V3;
1098 if (Cross1.Dot(Cross2) < 0)
1103 if (Cross1.Dot(Cross2) < 0)
1107 swap ( i, i + 1, idNodes, P );
1109 // for ( int ii = 0; ii < 4; ii++ ) {
1110 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1111 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1117 //=======================================================================
1118 //function : SortHexaNodes
1119 //purpose : Set 8 nodes of a hexahedron in a good order.
1120 // Return success status
1121 //=======================================================================
1123 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1128 DUMPSO( "INPUT: ========================================");
1129 for ( i = 0; i < 8; i++ ) {
1130 const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1131 if ( !n ) return false;
1132 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1133 DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1135 DUMPSO( "========================================");
1138 set<int> faceNodes; // ids of bottom face nodes, to be found
1139 set<int> checkedId1; // ids of tried 2-nd nodes
1140 Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1141 const Standard_Real tol = 1.e-6; // tolerance to find nodes in plane
1142 int iMin, iLoop1 = 0;
1144 // Loop to try the 2-nd nodes
1146 while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1148 // Find not checked 2-nd node
1149 for ( i = 1; i < 8; i++ )
1150 if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1151 int id1 = idNodes[i];
1152 swap ( 1, i, idNodes, P );
1153 checkedId1.insert ( id1 );
1157 // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1158 // ie that all but meybe one (id3 which is on the same face) nodes
1159 // lay on the same side from the triangle plane.
1161 bool manyInPlane = false; // more than 4 nodes lay in plane
1163 while ( ++iLoop2 < 6 ) {
1165 // get 1-2-3 plane coeffs
1166 Standard_Real A, B, C, D;
1167 gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1168 if ( N.SquareMagnitude() > gp::Resolution() )
1170 gp_Pln pln ( P[0], N );
1171 pln.Coefficients( A, B, C, D );
1173 // find the node (iMin) closest to pln
1174 Standard_Real dist[ 8 ], minDist = DBL_MAX;
1176 for ( i = 3; i < 8; i++ ) {
1177 dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1178 if ( fabs( dist[i] ) < minDist ) {
1179 minDist = fabs( dist[i] );
1182 if ( fabs( dist[i] ) <= tol )
1183 idInPln.insert( idNodes[i] );
1186 // there should not be more than 4 nodes in bottom plane
1187 if ( idInPln.size() > 1 )
1189 DUMPSO( "### idInPln.size() = " << idInPln.size());
1190 // idInPlane does not contain the first 3 nodes
1191 if ( manyInPlane || idInPln.size() == 5)
1192 return false; // all nodes in one plane
1195 // set the 1-st node to be not in plane
1196 for ( i = 3; i < 8; i++ ) {
1197 if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1198 DUMPSO( "### Reset 0-th node");
1199 swap( 0, i, idNodes, P );
1204 // reset to re-check second nodes
1205 leastDist = DBL_MAX;
1209 break; // from iLoop2;
1212 // check that the other 4 nodes are on the same side
1213 bool sameSide = true;
1214 bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1215 for ( i = 3; sameSide && i < 8; i++ ) {
1217 sameSide = ( isNeg == dist[i] <= 0.);
1220 // keep best solution
1221 if ( sameSide && minDist < leastDist ) {
1222 leastDist = minDist;
1224 faceNodes.insert( idNodes[ 1 ] );
1225 faceNodes.insert( idNodes[ 2 ] );
1226 faceNodes.insert( idNodes[ iMin ] );
1227 DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1228 << " leastDist = " << leastDist);
1229 if ( leastDist <= DBL_MIN )
1234 // set next 3-d node to check
1235 int iNext = 2 + iLoop2;
1237 DUMPSO( "Try 2-nd");
1238 swap ( 2, iNext, idNodes, P );
1240 } // while ( iLoop2 < 6 )
1243 if ( faceNodes.empty() ) return false;
1245 // Put the faceNodes in proper places
1246 for ( i = 4; i < 8; i++ ) {
1247 if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1248 // find a place to put
1250 while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1252 DUMPSO( "Set faceNodes");
1253 swap ( iTo, i, idNodes, P );
1258 // Set nodes of the found bottom face in good order
1259 DUMPSO( " Found bottom face: ");
1260 i = SortQuadNodes( theMesh, idNodes );
1262 gp_Pnt Ptmp = P[ i ];
1267 // for ( int ii = 0; ii < 4; ii++ ) {
1268 // const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1269 // DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1272 // Gravity center of the top and bottom faces
1273 gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1274 gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1276 // Get direction from the bottom to the top face
1277 gp_Vec upDir ( aGCb, aGCt );
1278 Standard_Real upDirSize = upDir.Magnitude();
1279 if ( upDirSize <= gp::Resolution() ) return false;
1282 // Assure that the bottom face normal points up
1283 gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1284 Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1285 if ( Nb.Dot( upDir ) < 0 ) {
1286 DUMPSO( "Reverse bottom face");
1287 swap( 1, 3, idNodes, P );
1290 // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1291 Standard_Real minDist = DBL_MAX;
1292 for ( i = 4; i < 8; i++ ) {
1293 // projection of P[i] to the plane defined by P[0] and upDir
1294 gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1295 Standard_Real sqDist = P[0].SquareDistance( Pp );
1296 if ( sqDist < minDist ) {
1301 DUMPSO( "Set 4-th");
1302 swap ( 4, iMin, idNodes, P );
1304 // Set nodes of the top face in good order
1305 DUMPSO( "Sort top face");
1306 i = SortQuadNodes( theMesh, &idNodes[4] );
1309 gp_Pnt Ptmp = P[ i ];
1314 // Assure that direction of the top face normal is from the bottom face
1315 gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1316 Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1317 if ( Nt.Dot( upDir ) < 0 ) {
1318 DUMPSO( "Reverse top face");
1319 swap( 5, 7, idNodes, P );
1322 // DUMPSO( "OUTPUT: ========================================");
1323 // for ( i = 0; i < 8; i++ ) {
1324 // float *p = ugrid->GetPoint(idNodes[i]);
1325 // DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1331 //=======================================================================
1332 //function : laplacianSmooth
1333 //purpose : pulls theNode toward the center of surrounding nodes directly
1334 // connected to that node along an element edge
1335 //=======================================================================
1337 void laplacianSmooth(const SMDS_MeshNode* theNode,
1338 const Handle(Geom_Surface)& theSurface,
1339 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1341 // find surrounding nodes
1343 set< const SMDS_MeshNode* > nodeSet;
1344 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1345 while ( elemIt->more() )
1347 const SMDS_MeshElement* elem = elemIt->next();
1348 if ( elem->GetType() != SMDSAbs_Face )
1351 // put all nodes in array
1352 int nbNodes = 0, iNode = 0;
1353 vector< const SMDS_MeshNode*> aNodes( elem->NbNodes() );
1354 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1355 while ( itN->more() )
1357 aNodes[ nbNodes ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1358 if ( aNodes[ nbNodes ] == theNode )
1359 iNode = nbNodes; // index of theNode within aNodes
1363 int iAfter = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1364 nodeSet.insert( aNodes[ iAfter ]);
1365 int iBefore = ( iNode == 0 ) ? nbNodes - 1 : iNode - 1;
1366 nodeSet.insert( aNodes[ iBefore ]);
1369 // compute new coodrs
1371 double coord[] = { 0., 0., 0. };
1372 set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1373 for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1374 const SMDS_MeshNode* node = (*nodeSetIt);
1375 if ( theSurface.IsNull() ) { // smooth in 3D
1376 coord[0] += node->X();
1377 coord[1] += node->Y();
1378 coord[2] += node->Z();
1380 else { // smooth in 2D
1381 ASSERT( theUVMap.find( node ) != theUVMap.end() );
1382 gp_XY* uv = theUVMap[ node ];
1383 coord[0] += uv->X();
1384 coord[1] += uv->Y();
1387 int nbNodes = nodeSet.size();
1390 coord[0] /= nbNodes;
1391 coord[1] /= nbNodes;
1393 if ( !theSurface.IsNull() ) {
1394 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1395 theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
1396 gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
1402 coord[2] /= nbNodes;
1406 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
1409 //=======================================================================
1410 //function : centroidalSmooth
1411 //purpose : pulls theNode toward the element-area-weighted centroid of the
1412 // surrounding elements
1413 //=======================================================================
1415 void centroidalSmooth(const SMDS_MeshNode* theNode,
1416 const Handle(Geom_Surface)& theSurface,
1417 map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1419 gp_XYZ aNewXYZ(0.,0.,0.);
1420 SMESH::Controls::Area anAreaFunc;
1421 double totalArea = 0.;
1426 SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1427 while ( elemIt->more() )
1429 const SMDS_MeshElement* elem = elemIt->next();
1430 if ( elem->GetType() != SMDSAbs_Face )
1434 gp_XYZ elemCenter(0.,0.,0.);
1435 SMESH::Controls::TSequenceOfXYZ aNodePoints;
1436 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1437 while ( itN->more() )
1439 const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1440 gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1441 aNodePoints.push_back( aP );
1442 if ( !theSurface.IsNull() ) { // smooth in 2D
1443 ASSERT( theUVMap.find( aNode ) != theUVMap.end() );
1444 gp_XY* uv = theUVMap[ aNode ];
1445 aP.SetCoord( uv->X(), uv->Y(), 0. );
1449 double elemArea = anAreaFunc.GetValue( aNodePoints );
1450 totalArea += elemArea;
1451 elemCenter /= elem->NbNodes();
1452 aNewXYZ += elemCenter * elemArea;
1454 aNewXYZ /= totalArea;
1455 if ( !theSurface.IsNull() ) {
1456 ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1457 theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
1458 aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
1463 const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
1466 //=======================================================================
1467 //function : getClosestUV
1468 //purpose : return UV of closest projection
1469 //=======================================================================
1471 static bool getClosestUV (Extrema_GenExtPS& projector,
1472 const gp_Pnt& point,
1475 projector.Perform( point );
1476 if ( projector.IsDone() ) {
1477 double u, v, minVal = DBL_MAX;
1478 for ( int i = projector.NbExt(); i > 0; i-- )
1479 if ( projector.Value( i ) < minVal ) {
1480 minVal = projector.Value( i );
1481 projector.Point( i ).Parameter( u, v );
1483 result.SetCoord( u, v );
1489 //=======================================================================
1491 //purpose : Smooth theElements during theNbIterations or until a worst
1492 // element has aspect ratio <= theTgtAspectRatio.
1493 // Aspect Ratio varies in range [1.0, inf].
1494 // If theElements is empty, the whole mesh is smoothed.
1495 // theFixedNodes contains additionally fixed nodes. Nodes built
1496 // on edges and boundary nodes are always fixed.
1497 //=======================================================================
1499 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1500 set<const SMDS_MeshNode*> & theFixedNodes,
1501 const SmoothMethod theSmoothMethod,
1502 const int theNbIterations,
1503 double theTgtAspectRatio,
1506 MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1508 if ( theTgtAspectRatio < 1.0 )
1509 theTgtAspectRatio = 1.0;
1511 SMESH::Controls::AspectRatio aQualityFunc;
1513 SMESHDS_Mesh* aMesh = GetMeshDS();
1515 if ( theElems.empty() ) {
1516 // add all faces to theElems
1517 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1518 while ( fIt->more() )
1519 theElems.insert( fIt->next() );
1521 // get all face ids theElems are on
1522 set< int > faceIdSet;
1523 set< const SMDS_MeshElement* >::iterator itElem;
1525 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1526 int fId = FindShape( *itElem );
1527 // check that corresponding submesh exists and a shape is face
1529 faceIdSet.find( fId ) == faceIdSet.end() &&
1530 aMesh->MeshElements( fId )) {
1531 TopoDS_Shape F = aMesh->IndexToShape( fId );
1532 if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
1533 faceIdSet.insert( fId );
1536 faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
1538 // ===============================================
1539 // smooth elements on each TopoDS_Face separately
1540 // ===============================================
1542 set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
1543 for ( ; fId != faceIdSet.rend(); ++fId )
1545 // get face surface and submesh
1546 Handle(Geom_Surface) surface;
1547 SMESHDS_SubMesh* faceSubMesh = 0;
1549 double fToler2 = 0, vPeriod = 0., uPeriod = 0., f,l;
1550 double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
1551 bool isUPeriodic = false, isVPeriodic = false;
1553 face = TopoDS::Face( aMesh->IndexToShape( *fId ));
1554 surface = BRep_Tool::Surface( face );
1555 faceSubMesh = aMesh->MeshElements( *fId );
1556 fToler2 = BRep_Tool::Tolerance( face );
1557 fToler2 *= fToler2 * 10.;
1558 isUPeriodic = surface->IsUPeriodic();
1560 vPeriod = surface->UPeriod();
1561 isVPeriodic = surface->IsVPeriodic();
1563 uPeriod = surface->VPeriod();
1564 surface->Bounds( u1, u2, v1, v2 );
1566 // ---------------------------------------------------------
1567 // for elements on a face, find movable and fixed nodes and
1568 // compute UV for them
1569 // ---------------------------------------------------------
1570 bool checkBoundaryNodes = false;
1571 set<const SMDS_MeshNode*> setMovableNodes;
1572 map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
1573 list< gp_XY > listUV; // uvs the 2 uvMaps refer to
1574 list< const SMDS_MeshElement* > elemsOnFace;
1576 Extrema_GenExtPS projector;
1577 GeomAdaptor_Surface surfAdaptor;
1578 if ( !surface.IsNull() ) {
1579 surfAdaptor.Load( surface );
1580 projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
1582 int nbElemOnFace = 0;
1583 itElem = theElems.begin();
1584 // loop on not yet smoothed elements: look for elems on a face
1585 while ( itElem != theElems.end() )
1587 if ( faceSubMesh && nbElemOnFace == faceSubMesh->NbElements() )
1588 break; // all elements found
1590 const SMDS_MeshElement* elem = (*itElem);
1591 if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
1592 ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
1596 elemsOnFace.push_back( elem );
1597 theElems.erase( itElem++ );
1600 // get movable nodes of elem
1601 const SMDS_MeshNode* node;
1602 SMDS_TypeOfPosition posType;
1603 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1604 while ( itN->more() ) {
1605 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1606 const SMDS_PositionPtr& pos = node->GetPosition();
1607 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1608 if (posType != SMDS_TOP_EDGE &&
1609 posType != SMDS_TOP_VERTEX &&
1610 theFixedNodes.find( node ) == theFixedNodes.end())
1612 // check if all faces around the node are on faceSubMesh
1613 // because a node on edge may be bound to face
1614 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1616 if ( faceSubMesh ) {
1617 while ( eIt->more() && all ) {
1618 const SMDS_MeshElement* e = eIt->next();
1619 if ( e->GetType() == SMDSAbs_Face )
1620 all = faceSubMesh->Contains( e );
1624 setMovableNodes.insert( node );
1626 checkBoundaryNodes = true;
1628 if ( posType == SMDS_TOP_3DSPACE )
1629 checkBoundaryNodes = true;
1632 if ( surface.IsNull() )
1635 // get nodes to check UV
1636 list< const SMDS_MeshNode* > uvCheckNodes;
1637 itN = elem->nodesIterator();
1638 while ( itN->more() ) {
1639 node = static_cast<const SMDS_MeshNode*>( itN->next() );
1640 if ( uvMap.find( node ) == uvMap.end() )
1641 uvCheckNodes.push_back( node );
1642 // add nodes of elems sharing node
1643 // SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1644 // while ( eIt->more() ) {
1645 // const SMDS_MeshElement* e = eIt->next();
1646 // if ( e != elem && e->GetType() == SMDSAbs_Face ) {
1647 // SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1648 // while ( nIt->more() ) {
1649 // const SMDS_MeshNode* n =
1650 // static_cast<const SMDS_MeshNode*>( nIt->next() );
1651 // if ( uvMap.find( n ) == uvMap.end() )
1652 // uvCheckNodes.push_back( n );
1658 list< const SMDS_MeshNode* >::iterator n = uvCheckNodes.begin();
1659 for ( ; n != uvCheckNodes.end(); ++n )
1663 const SMDS_PositionPtr& pos = node->GetPosition();
1664 posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1666 switch ( posType ) {
1667 case SMDS_TOP_FACE: {
1668 SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
1669 uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
1672 case SMDS_TOP_EDGE: {
1673 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1674 Handle(Geom2d_Curve) pcurve;
1675 if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
1676 pcurve = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), face, f,l );
1677 if ( !pcurve.IsNull() ) {
1678 double u = (( SMDS_EdgePosition* ) pos.get() )->GetUParameter();
1679 uv = pcurve->Value( u ).XY();
1683 case SMDS_TOP_VERTEX: {
1684 TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1685 if ( !S.IsNull() && S.ShapeType() == TopAbs_VERTEX )
1686 uv = BRep_Tool::Parameters( TopoDS::Vertex( S ), face ).XY();
1691 // check existing UV
1692 bool project = true;
1693 gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
1694 double dist1 = DBL_MAX, dist2 = 0;
1695 if ( posType != SMDS_TOP_3DSPACE ) {
1696 dist1 = pNode.SquareDistance( surface->Value( uv.X(), uv.Y() ));
1697 project = dist1 > fToler2;
1699 if ( project ) { // compute new UV
1701 if ( !getClosestUV( projector, pNode, newUV )) {
1702 MESSAGE("Node Projection Failed " << node);
1706 newUV.SetX( ElCLib::InPeriod( newUV.X(), u1, u2 ));
1708 newUV.SetY( ElCLib::InPeriod( newUV.Y(), v1, v2 ));
1710 if ( posType != SMDS_TOP_3DSPACE )
1711 dist2 = pNode.SquareDistance( surface->Value( newUV.X(), newUV.Y() ));
1712 if ( dist2 < dist1 )
1716 // store UV in the map
1717 listUV.push_back( uv );
1718 uvMap.insert( make_pair( node, &listUV.back() ));
1720 } // loop on not yet smoothed elements
1722 if ( !faceSubMesh || nbElemOnFace != faceSubMesh->NbElements() )
1723 checkBoundaryNodes = true;
1725 // fix nodes on mesh boundary
1727 if ( checkBoundaryNodes )
1729 typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
1730 map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
1731 map< TLink, int >::iterator link_nb;
1732 // put all elements links to linkNbMap
1733 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1734 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1736 // put elem nodes in array
1737 vector< const SMDS_MeshNode* > nodes;
1738 nodes.reserve( (*elemIt)->NbNodes() + 1 );
1739 SMDS_ElemIteratorPtr itN = (*elemIt)->nodesIterator();
1740 while ( itN->more() )
1741 nodes.push_back( static_cast<const SMDS_MeshNode*>( itN->next() ));
1742 nodes.push_back( nodes.front() );
1743 // loop on elem links: insert them in linkNbMap
1744 for ( int iN = 1; iN < nodes.size(); ++iN ) {
1746 if ( nodes[ iN-1 ]->GetID() < nodes[ iN ]->GetID() )
1747 link = make_pair( nodes[ iN-1 ], nodes[ iN ] );
1749 link = make_pair( nodes[ iN ], nodes[ iN-1 ] );
1750 link_nb = linkNbMap.find( link );
1751 if ( link_nb == linkNbMap.end() )
1752 linkNbMap.insert( make_pair ( link, 1 ));
1757 // remove nodes that are in links encountered only once from setMovableNodes
1758 for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
1759 if ( link_nb->second == 1 ) {
1760 setMovableNodes.erase( link_nb->first.first );
1761 setMovableNodes.erase( link_nb->first.second );
1766 // -----------------------------------------------------
1767 // for nodes on seam edge, compute one more UV ( uvMap2 );
1768 // find movable nodes linked to nodes on seam and which
1769 // are to be smoothed using the second UV ( uvMap2 )
1770 // -----------------------------------------------------
1772 set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
1773 if ( !surface.IsNull() )
1775 TopExp_Explorer eExp( face, TopAbs_EDGE );
1776 for ( ; eExp.More(); eExp.Next() )
1778 TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
1779 if ( !BRep_Tool::IsClosed( edge, face ))
1781 SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
1782 if ( !sm ) continue;
1783 // find out which parameter varies for a node on seam
1786 Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1787 if ( pcurve.IsNull() ) continue;
1788 uv1 = pcurve->Value( f );
1790 pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1791 if ( pcurve.IsNull() ) continue;
1792 uv2 = pcurve->Value( f );
1793 int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
1795 if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
1796 gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
1798 // get nodes on seam and its vertices
1799 list< const SMDS_MeshNode* > seamNodes;
1800 SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
1801 while ( nSeamIt->more() )
1802 seamNodes.push_back( nSeamIt->next() );
1803 TopExp_Explorer vExp( edge, TopAbs_VERTEX );
1804 for ( ; vExp.More(); vExp.Next() ) {
1805 sm = aMesh->MeshElements( vExp.Current() );
1807 nSeamIt = sm->GetNodes();
1808 while ( nSeamIt->more() )
1809 seamNodes.push_back( nSeamIt->next() );
1812 // loop on nodes on seam
1813 list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
1814 for ( ; noSeIt != seamNodes.end(); ++noSeIt )
1816 const SMDS_MeshNode* nSeam = *noSeIt;
1817 map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
1818 if ( n_uv == uvMap.end() )
1821 n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
1822 // set the second UV
1823 listUV.push_back( *n_uv->second );
1824 listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
1825 if ( uvMap2.empty() )
1826 uvMap2 = uvMap; // copy the uvMap contents
1827 uvMap2[ nSeam ] = &listUV.back();
1829 // collect movable nodes linked to ones on seam in nodesNearSeam
1830 SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator();
1831 while ( eIt->more() )
1833 const SMDS_MeshElement* e = eIt->next();
1834 if ( e->GetType() != SMDSAbs_Face )
1836 int nbUseMap1 = 0, nbUseMap2 = 0;
1837 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1838 while ( nIt->more() )
1840 const SMDS_MeshNode* n =
1841 static_cast<const SMDS_MeshNode*>( nIt->next() );
1843 setMovableNodes.find( n ) == setMovableNodes.end() )
1845 // add only nodes being closer to uv2 than to uv1
1846 gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
1847 0.5 * ( n->Y() + nSeam->Y() ),
1848 0.5 * ( n->Z() + nSeam->Z() ));
1850 getClosestUV( projector, pMid, uv );
1851 if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
1852 nodesNearSeam.insert( n );
1858 // for centroidalSmooth all element nodes must
1859 // be on one side of a seam
1860 if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 )
1862 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1863 while ( nIt->more() ) {
1864 const SMDS_MeshNode* n =
1865 static_cast<const SMDS_MeshNode*>( nIt->next() );
1866 setMovableNodes.erase( n );
1870 } // loop on nodes on seam
1871 } // loop on edge of a face
1872 } // if ( !face.IsNull() )
1874 if ( setMovableNodes.empty() ) {
1875 MESSAGE( "Face id : " << *fId << " - NO SMOOTHING: no nodes to move!!!");
1876 continue; // goto next face
1884 double maxRatio = -1., maxDisplacement = -1.;
1885 set<const SMDS_MeshNode*>::iterator nodeToMove;
1886 for ( it = 0; it < theNbIterations; it++ )
1888 maxDisplacement = 0.;
1889 nodeToMove = setMovableNodes.begin();
1890 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1892 const SMDS_MeshNode* node = (*nodeToMove);
1893 gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1896 bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
1897 if ( theSmoothMethod == LAPLACIAN )
1898 laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
1900 centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
1902 // node displacement
1903 gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1904 Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1905 if ( aDispl > maxDisplacement )
1906 maxDisplacement = aDispl;
1908 // no node movement => exit
1909 if ( maxDisplacement < 1.e-16 ) {
1910 MESSAGE("-- no node movement --");
1914 // check elements quality
1916 list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1917 for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1919 const SMDS_MeshElement* elem = (*elemIt);
1920 if ( !elem || elem->GetType() != SMDSAbs_Face )
1922 SMESH::Controls::TSequenceOfXYZ aPoints;
1923 if ( aQualityFunc.GetPoints( elem, aPoints )) {
1924 double aValue = aQualityFunc.GetValue( aPoints );
1925 if ( aValue > maxRatio )
1929 if ( maxRatio <= theTgtAspectRatio ) {
1930 MESSAGE("-- quality achived --");
1933 if (it+1 == theNbIterations) {
1934 MESSAGE("-- Iteration limit exceeded --");
1936 } // smoothing iterations
1938 MESSAGE(" Face id: " << *fId <<
1939 " Nb iterstions: " << it <<
1940 " Displacement: " << maxDisplacement <<
1941 " Aspect Ratio " << maxRatio);
1943 // ---------------------------------------
1944 // new nodes positions are computed,
1945 // record movement in DS and set new UV
1946 // ---------------------------------------
1948 nodeToMove = setMovableNodes.begin();
1949 for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1951 SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
1952 aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
1953 map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
1954 if ( node_uv != uvMap.end() ) {
1955 gp_XY* uv = node_uv->second;
1957 ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
1961 } // loop on face ids
1964 //=======================================================================
1965 //function : isReverse
1966 //purpose : Return true if normal of prevNodes is not co-directied with
1967 // gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1968 // iNotSame is where prevNodes and nextNodes are different
1969 //=======================================================================
1971 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1972 const SMDS_MeshNode* nextNodes[],
1976 int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1977 int iAfterNotSame = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1979 const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1980 const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1981 const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1982 const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1984 gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1985 gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1986 gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1987 gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1989 gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1991 return (vA ^ vB) * vN < 0.0;
1994 //=======================================================================
1995 //function : sweepElement
1997 //=======================================================================
1999 static void sweepElement(SMESHDS_Mesh* aMesh,
2000 const SMDS_MeshElement* elem,
2001 const vector<TNodeOfNodeListMapItr> & newNodesItVec,
2002 list<const SMDS_MeshElement*>& newElems)
2004 // Loop on elem nodes:
2005 // find new nodes and detect same nodes indices
2006 int nbNodes = elem->NbNodes();
2007 list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
2008 const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
2009 int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
2011 for ( iNode = 0; iNode < nbNodes; iNode++ )
2013 TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
2014 const SMDS_MeshNode* node = nnIt->first;
2015 const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
2016 if ( listNewNodes.empty() )
2019 itNN[ iNode ] = listNewNodes.begin();
2020 prevNod[ iNode ] = node;
2021 nextNod[ iNode ] = listNewNodes.front();
2022 if ( prevNod[ iNode ] != nextNod [ iNode ])
2023 iNotSameNode = iNode;
2029 if ( nbSame == nbNodes || nbSame > 2) {
2030 MESSAGE( " Too many same nodes of element " << elem->GetID() );
2034 int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
2036 iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
2037 iAfterSame = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
2038 iOpposSame = ( iSameNode - 2 < 0 ? iSameNode + 2 : iSameNode - 2 );
2041 // check element orientation
2043 if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
2044 //MESSAGE("Reversed elem " << elem );
2048 int iAB = iAfterSame + iBeforeSame;
2049 iBeforeSame = iAB - iBeforeSame;
2050 iAfterSame = iAB - iAfterSame;
2054 // make new elements
2055 int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
2056 for (iStep = 0; iStep < nbSteps; iStep++ )
2059 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2060 nextNod[ iNode ] = *itNN[ iNode ];
2063 SMDS_MeshElement* aNewElem = 0;
2070 aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
2076 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2077 nextNod[ 1 ], nextNod[ 0 ] );
2079 aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2080 nextNod[ iNotSameNode ] );
2083 case 3: { // TRIANGLE
2085 if ( nbSame == 0 ) // --- pentahedron
2086 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2087 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
2089 else if ( nbSame == 1 ) // --- pyramid
2090 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2091 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2092 nextNod[ iSameNode ]);
2094 else // 2 same nodes: --- tetrahedron
2095 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2096 nextNod[ iNotSameNode ]);
2099 case 4: { // QUADRANGLE
2101 if ( nbSame == 0 ) // --- hexahedron
2102 aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
2103 nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
2105 else if ( nbSame == 1 ) // --- pyramid + pentahedron
2107 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iAfterSame ],
2108 nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2109 nextNod[ iSameNode ]);
2110 newElems.push_back( aNewElem );
2111 aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iOpposSame ],
2112 prevNod[ iBeforeSame ], nextNod[ iAfterSame ],
2113 nextNod[ iOpposSame ], nextNod[ iBeforeSame ] );
2115 else if ( nbSame == 2 ) // pentahedron
2117 if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
2118 // iBeforeSame is same too
2119 aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
2120 nextNod[ iOpposSame ], prevNod[ iSameNode ],
2121 prevNod[ iAfterSame ], nextNod[ iAfterSame ]);
2123 // iAfterSame is same too
2124 aNewElem = aMesh->AddVolume (prevNod[ iSameNode ], prevNod[ iBeforeSame ],
2125 nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
2126 prevNod[ iOpposSame ], nextNod[ iOpposSame ]);
2131 // realized for extrusion only
2132 vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2133 vector<int> quantities (nbNodes + 2);
2135 quantities[0] = nbNodes; // bottom of prism
2136 for (int inode = 0; inode < nbNodes; inode++) {
2137 polyedre_nodes[inode] = prevNod[inode];
2140 quantities[1] = nbNodes; // top of prism
2141 for (int inode = 0; inode < nbNodes; inode++) {
2142 polyedre_nodes[nbNodes + inode] = nextNod[inode];
2145 for (int iface = 0; iface < nbNodes; iface++) {
2146 quantities[iface + 2] = 4;
2147 int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2148 polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2149 polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2150 polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2151 polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2153 aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2157 newElems.push_back( aNewElem );
2159 // set new prev nodes
2160 for ( iNode = 0; iNode < nbNodes; iNode++ )
2161 prevNod[ iNode ] = nextNod[ iNode ];
2166 //=======================================================================
2167 //function : makeWalls
2168 //purpose : create 1D and 2D elements around swept elements
2169 //=======================================================================
2171 static void makeWalls (SMESHDS_Mesh* aMesh,
2172 TNodeOfNodeListMap & mapNewNodes,
2173 TElemOfElemListMap & newElemsMap,
2174 TElemOfVecOfNnlmiMap & elemNewNodesMap,
2175 set<const SMDS_MeshElement*>& elemSet)
2177 ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
2179 // Find nodes belonging to only one initial element - sweep them to get edges.
2181 TNodeOfNodeListMapItr nList = mapNewNodes.begin();
2182 for ( ; nList != mapNewNodes.end(); nList++ )
2184 const SMDS_MeshNode* node =
2185 static_cast<const SMDS_MeshNode*>( nList->first );
2186 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2187 int nbInitElems = 0;
2188 while ( eIt->more() && nbInitElems < 2 )
2189 if ( elemSet.find( eIt->next() ) != elemSet.end() )
2191 if ( nbInitElems < 2 ) {
2192 vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2193 list<const SMDS_MeshElement*> newEdges;
2194 sweepElement( aMesh, node, newNodesItVec, newEdges );
2198 // Make a ceiling for each element ie an equal element of last new nodes.
2199 // Find free links of faces - make edges and sweep them into faces.
2201 TElemOfElemListMap::iterator itElem = newElemsMap.begin();
2202 TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2203 for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
2205 const SMDS_MeshElement* elem = itElem->first;
2206 vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2208 if ( elem->GetType() == SMDSAbs_Edge )
2210 // create a ceiling edge
2211 aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2212 vecNewNodes[ 1 ]->second.back() );
2214 if ( elem->GetType() != SMDSAbs_Face )
2217 bool hasFreeLinks = false;
2219 set<const SMDS_MeshElement*> avoidSet;
2220 avoidSet.insert( elem );
2222 // loop on a face nodes
2223 set<const SMDS_MeshNode*> aFaceLastNodes;
2224 int iNode, nbNodes = vecNewNodes.size();
2225 for ( iNode = 0; iNode < nbNodes; iNode++ )
2227 aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
2228 // look for free links of a face
2229 int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
2230 const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
2231 const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
2232 // check if a link is free
2233 if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
2235 hasFreeLinks = true;
2236 // make an edge and a ceiling for a new edge
2237 if ( !aMesh->FindEdge( n1, n2 ))
2238 aMesh->AddEdge( n1, n2 );
2239 n1 = vecNewNodes[ iNode ]->second.back();
2240 n2 = vecNewNodes[ iNext ]->second.back();
2241 if ( !aMesh->FindEdge( n1, n2 ))
2242 aMesh->AddEdge( n1, n2 );
2245 // sweep free links into faces
2249 list<const SMDS_MeshElement*> & newVolumes = itElem->second;
2250 int iStep, nbSteps = vecNewNodes[0]->second.size();
2251 int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
2253 set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
2254 for ( iNode = 0; iNode < nbNodes; iNode++ )
2255 initNodeSet.insert( vecNewNodes[ iNode ]->first );
2257 for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
2259 list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
2261 while ( iVol++ < volNb ) v++;
2262 // find indices of free faces of a volume
2264 SMDS_VolumeTool vTool( *v );
2265 int iF, nbF = vTool.NbFaces();
2266 for ( iF = 0; iF < nbF; iF ++ )
2267 if (vTool.IsFreeFace( iF ) &&
2268 vTool.GetFaceNodes( iF, faceNodeSet ) &&
2269 initNodeSet != faceNodeSet) // except an initial face
2270 fInd.push_back( iF );
2274 // create faces for all steps
2275 for ( iStep = 0; iStep < nbSteps; iStep++ )
2278 vTool.SetExternalNormal();
2279 list< int >::iterator ind = fInd.begin();
2280 for ( ; ind != fInd.end(); ind++ )
2282 const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
2283 switch ( vTool.NbFaceNodes( *ind ) ) {
2285 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
2287 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
2290 int nbPolygonNodes = vTool.NbFaceNodes( *ind );
2291 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2292 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2293 polygon_nodes[inode] = nodes[inode];
2295 aMesh->AddPolygonalFace(polygon_nodes);
2300 // go to the next volume
2302 while ( iVol++ < nbVolumesByStep ) v++;
2305 } // sweep free links into faces
2307 // make a ceiling face with a normal external to a volume
2309 SMDS_VolumeTool lastVol( itElem->second.back() );
2310 int iF = lastVol.GetFaceIndex( aFaceLastNodes );
2313 lastVol.SetExternalNormal();
2314 const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
2315 switch ( lastVol.NbFaceNodes( iF ) ) {
2317 if (!hasFreeLinks ||
2318 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
2319 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2322 if (!hasFreeLinks ||
2323 !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
2324 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] );
2328 int nbPolygonNodes = lastVol.NbFaceNodes( iF );
2329 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2330 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2331 polygon_nodes[inode] = nodes[inode];
2333 if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
2334 aMesh->AddPolygonalFace(polygon_nodes);
2340 } // loop on swept elements
2343 //=======================================================================
2344 //function : RotationSweep
2346 //=======================================================================
2348 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
2349 const gp_Ax1& theAxis,
2350 const double theAngle,
2351 const int theNbSteps,
2352 const double theTol)
2354 MESSAGE( "RotationSweep()");
2356 aTrsf.SetRotation( theAxis, theAngle );
2358 gp_Lin aLine( theAxis );
2359 double aSqTol = theTol * theTol;
2361 SMESHDS_Mesh* aMesh = GetMeshDS();
2363 TNodeOfNodeListMap mapNewNodes;
2364 TElemOfVecOfNnlmiMap mapElemNewNodes;
2365 TElemOfElemListMap newElemsMap;
2368 set< const SMDS_MeshElement* >::iterator itElem;
2369 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2371 const SMDS_MeshElement* elem = (*itElem);
2374 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2375 newNodesItVec.reserve( elem->NbNodes() );
2377 // loop on elem nodes
2378 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2379 while ( itN->more() ) {
2381 // check if a node has been already sweeped
2382 const SMDS_MeshNode* node =
2383 static_cast<const SMDS_MeshNode*>( itN->next() );
2384 TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
2385 if ( nIt == mapNewNodes.end() )
2387 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2388 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2391 gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
2393 aXYZ.Coord( coord[0], coord[1], coord[2] );
2394 bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
2395 const SMDS_MeshNode * newNode = node;
2396 for ( int i = 0; i < theNbSteps; i++ ) {
2398 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2399 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2401 listNewNodes.push_back( newNode );
2404 newNodesItVec.push_back( nIt );
2406 // make new elements
2407 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2410 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2413 //=======================================================================
2414 //function : ExtrusionSweep
2416 //=======================================================================
2418 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
2419 const gp_Vec& theStep,
2420 const int theNbSteps)
2423 aTrsf.SetTranslation( theStep );
2425 SMESHDS_Mesh* aMesh = GetMeshDS();
2427 TNodeOfNodeListMap mapNewNodes;
2428 TElemOfVecOfNnlmiMap mapElemNewNodes;
2429 TElemOfElemListMap newElemsMap;
2432 set< const SMDS_MeshElement* >::iterator itElem;
2433 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2435 // check element type
2436 const SMDS_MeshElement* elem = (*itElem);
2440 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2441 newNodesItVec.reserve( elem->NbNodes() );
2443 // loop on elem nodes
2444 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2445 while ( itN->more() ) {
2447 // check if a node has been already sweeped
2448 const SMDS_MeshNode* node =
2449 static_cast<const SMDS_MeshNode*>( itN->next() );
2450 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2451 if ( nIt == mapNewNodes.end() )
2453 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2454 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2457 double coord[] = { node->X(), node->Y(), node->Z() };
2458 for ( int i = 0; i < theNbSteps; i++ ) {
2459 aTrsf.Transforms( coord[0], coord[1], coord[2] );
2460 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2461 listNewNodes.push_back( newNode );
2464 newNodesItVec.push_back( nIt );
2466 // make new elements
2467 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2470 SMESH_SequenceOfElemPtr SeqNewME;
2471 list<const SMDS_MeshElement*> tmpList = newElemsMap[elem];
2472 for(list<const SMDS_MeshElement*>::iterator ite = tmpList.begin();
2473 ite!=tmpList.end(); ite++) {
2474 SeqNewME.Append(*ite);
2476 myExtrusionHistory.Bind(elem,SeqNewME);
2480 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2483 //=======================================================================
2484 //class : SMESH_MeshEditor_PathPoint
2485 //purpose : auxiliary class
2486 //=======================================================================
2487 class SMESH_MeshEditor_PathPoint {
2489 SMESH_MeshEditor_PathPoint() {
2490 myPnt.SetCoord(99., 99., 99.);
2491 myTgt.SetCoord(1.,0.,0.);
2495 void SetPnt(const gp_Pnt& aP3D){
2498 void SetTangent(const gp_Dir& aTgt){
2501 void SetAngle(const double& aBeta){
2504 void SetParameter(const double& aPrm){
2507 const gp_Pnt& Pnt()const{
2510 const gp_Dir& Tangent()const{
2513 double Angle()const{
2516 double Parameter()const{
2527 //=======================================================================
2528 //function : ExtrusionAlongTrack
2530 //=======================================================================
2531 SMESH_MeshEditor::Extrusion_Error
2532 SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2533 SMESH_subMesh* theTrack,
2534 const SMDS_MeshNode* theN1,
2535 const bool theHasAngles,
2536 std::list<double>& theAngles,
2537 const bool theHasRefPoint,
2538 const gp_Pnt& theRefPoint)
2540 MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2541 int j, aNbTP, aNbE, aNb;
2542 double aT1, aT2, aT, aAngle, aX, aY, aZ;
2543 std::list<double> aPrms;
2544 std::list<double>::iterator aItD;
2545 std::set< const SMDS_MeshElement* >::iterator itElem;
2547 Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2551 Handle(Geom_Curve) aC3D;
2552 TopoDS_Edge aTrackEdge;
2553 TopoDS_Vertex aV1, aV2;
2555 SMDS_ElemIteratorPtr aItE;
2556 SMDS_NodeIteratorPtr aItN;
2557 SMDSAbs_ElementType aTypeE;
2559 TNodeOfNodeListMap mapNewNodes;
2560 TElemOfVecOfNnlmiMap mapElemNewNodes;
2561 TElemOfElemListMap newElemsMap;
2564 aTolVec2=aTolVec*aTolVec;
2567 aNbE = theElements.size();
2570 return EXTR_NO_ELEMENTS;
2572 // 1.1 Track Pattern
2575 SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2577 aItE = pSubMeshDS->GetElements();
2578 while ( aItE->more() ) {
2579 const SMDS_MeshElement* pE = aItE->next();
2580 aTypeE = pE->GetType();
2581 // Pattern must contain links only
2582 if ( aTypeE != SMDSAbs_Edge )
2583 return EXTR_PATH_NOT_EDGE;
2586 const TopoDS_Shape& aS = theTrack->GetSubShape();
2587 // Sub shape for the Pattern must be an Edge
2588 if ( aS.ShapeType() != TopAbs_EDGE )
2589 return EXTR_BAD_PATH_SHAPE;
2591 aTrackEdge = TopoDS::Edge( aS );
2592 // the Edge must not be degenerated
2593 if ( BRep_Tool::Degenerated( aTrackEdge ) )
2594 return EXTR_BAD_PATH_SHAPE;
2596 TopExp::Vertices( aTrackEdge, aV1, aV2 );
2597 aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2598 aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2600 aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2601 const SMDS_MeshNode* aN1 = aItN->next();
2603 aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2604 const SMDS_MeshNode* aN2 = aItN->next();
2606 // starting node must be aN1 or aN2
2607 if ( !( aN1 == theN1 || aN2 == theN1 ) )
2608 return EXTR_BAD_STARTING_NODE;
2610 aNbTP = pSubMeshDS->NbNodes() + 2;
2613 vector<double> aAngles( aNbTP );
2615 for ( j=0; j < aNbTP; ++j ) {
2619 if ( theHasAngles ) {
2620 aItD = theAngles.begin();
2621 for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2623 aAngles[j] = aAngle;
2627 // 2. Collect parameters on the track edge
2628 aPrms.push_back( aT1 );
2629 aPrms.push_back( aT2 );
2631 aItN = pSubMeshDS->GetNodes();
2632 while ( aItN->more() ) {
2633 const SMDS_MeshNode* pNode = aItN->next();
2634 const SMDS_EdgePosition* pEPos =
2635 static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2636 aT = pEPos->GetUParameter();
2637 aPrms.push_back( aT );
2642 if ( aN1 == theN1 ) {
2654 SMESH_MeshEditor_PathPoint aPP;
2655 vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2657 aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2659 aItD = aPrms.begin();
2660 for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2662 aC3D->D1( aT, aP3D, aVec );
2663 aL2 = aVec.SquareMagnitude();
2664 if ( aL2 < aTolVec2 )
2665 return EXTR_CANT_GET_TANGENT;
2667 gp_Dir aTgt( aVec );
2668 aAngle = aAngles[j];
2671 aPP.SetTangent( aTgt );
2672 aPP.SetAngle( aAngle );
2673 aPP.SetParameter( aT );
2677 // 3. Center of rotation aV0
2679 if ( !theHasRefPoint ) {
2681 aGC.SetCoord( 0.,0.,0. );
2683 itElem = theElements.begin();
2684 for ( ; itElem != theElements.end(); itElem++ ) {
2685 const SMDS_MeshElement* elem = (*itElem);
2687 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2688 while ( itN->more() ) {
2689 const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2694 if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2695 list<const SMDS_MeshNode*> aLNx;
2696 mapNewNodes[node] = aLNx;
2698 gp_XYZ aXYZ( aX, aY, aZ );
2706 } // if (!theHasRefPoint) {
2707 mapNewNodes.clear();
2709 // 4. Processing the elements
2710 SMESHDS_Mesh* aMesh = GetMeshDS();
2712 for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2713 // check element type
2714 const SMDS_MeshElement* elem = (*itElem);
2715 aTypeE = elem->GetType();
2716 if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2719 vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2720 newNodesItVec.reserve( elem->NbNodes() );
2722 // loop on elem nodes
2723 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2724 while ( itN->more() ) {
2726 // check if a node has been already processed
2727 const SMDS_MeshNode* node =
2728 static_cast<const SMDS_MeshNode*>( itN->next() );
2729 TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2730 if ( nIt == mapNewNodes.end() ) {
2731 nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2732 list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2735 aX = node->X(); aY = node->Y(); aZ = node->Z();
2737 Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2738 gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2739 gp_Ax1 anAx1, anAxT1T0;
2740 gp_Dir aDT1x, aDT0x, aDT1T0;
2745 aPN0.SetCoord(aX, aY, aZ);
2747 const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2749 aDT0x= aPP0.Tangent();
2751 for ( j = 1; j < aNbTP; ++j ) {
2752 const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2754 aDT1x = aPP1.Tangent();
2755 aAngle1x = aPP1.Angle();
2757 gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
2759 gp_Vec aV01x( aP0x, aP1x );
2760 aTrsf.SetTranslation( aV01x );
2763 aV1x = aV0x.Transformed( aTrsf );
2764 aPN1 = aPN0.Transformed( aTrsf );
2766 // rotation 1 [ T1,T0 ]
2767 aAngleT1T0=-aDT1x.Angle( aDT0x );
2768 if (fabs(aAngleT1T0) > aTolAng) {
2770 anAxT1T0.SetLocation( aV1x );
2771 anAxT1T0.SetDirection( aDT1T0 );
2772 aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2774 aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2778 if ( theHasAngles ) {
2779 anAx1.SetLocation( aV1x );
2780 anAx1.SetDirection( aDT1x );
2781 aTrsfRot.SetRotation( anAx1, aAngle1x );
2783 aPN1 = aPN1.Transformed( aTrsfRot );
2790 const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2791 listNewNodes.push_back( newNode );
2799 newNodesItVec.push_back( nIt );
2801 // make new elements
2802 sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2805 makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2810 //=======================================================================
2811 //function : Transform
2813 //=======================================================================
2815 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2816 const gp_Trsf& theTrsf,
2820 switch ( theTrsf.Form() ) {
2826 needReverse = false;
2829 SMESHDS_Mesh* aMesh = GetMeshDS();
2831 // map old node to new one
2832 TNodeNodeMap nodeMap;
2834 // elements sharing moved nodes; those of them which have all
2835 // nodes mirrored but are not in theElems are to be reversed
2836 set<const SMDS_MeshElement*> inverseElemSet;
2839 set< const SMDS_MeshElement* >::iterator itElem;
2840 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2842 const SMDS_MeshElement* elem = (*itElem);
2846 // loop on elem nodes
2847 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2848 while ( itN->more() ) {
2850 // check if a node has been already transformed
2851 const SMDS_MeshNode* node =
2852 static_cast<const SMDS_MeshNode*>( itN->next() );
2853 if (nodeMap.find( node ) != nodeMap.end() )
2857 coord[0] = node->X();
2858 coord[1] = node->Y();
2859 coord[2] = node->Z();
2860 theTrsf.Transforms( coord[0], coord[1], coord[2] );
2861 const SMDS_MeshNode * newNode = node;
2863 newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2865 aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2866 // node position on shape becomes invalid
2867 const_cast< SMDS_MeshNode* > ( node )->SetPosition
2868 ( SMDS_SpacePosition::originSpacePosition() );
2870 nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2872 // keep inverse elements
2873 if ( !theCopy && needReverse ) {
2874 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2875 while ( invElemIt->more() )
2876 inverseElemSet.insert( invElemIt->next() );
2881 // either new elements are to be created
2882 // or a mirrored element are to be reversed
2883 if ( !theCopy && !needReverse)
2886 if ( !inverseElemSet.empty()) {
2887 set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2888 for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2889 theElems.insert( *invElemIt );
2892 // replicate or reverse elements
2895 REV_TETRA = 0, // = nbNodes - 4
2896 REV_PYRAMID = 1, // = nbNodes - 4
2897 REV_PENTA = 2, // = nbNodes - 4
2899 REV_HEXA = 4, // = nbNodes - 4
2903 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_TETRA
2904 { 2, 1, 0, 3, 4, 0, 0, 0 }, // REV_PYRAMID
2905 { 2, 1, 0, 5, 4, 3, 0, 0 }, // REV_PENTA
2906 { 2, 1, 0, 3, 0, 0, 0, 0 }, // REV_FACE
2907 { 2, 1, 0, 3, 6, 5, 4, 7 }, // REV_HEXA
2908 { 0, 1, 2, 3, 4, 5, 6, 7 } // FORWARD
2911 for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2913 const SMDS_MeshElement* elem = (*itElem);
2914 if ( !elem || elem->GetType() == SMDSAbs_Node )
2917 int nbNodes = elem->NbNodes();
2918 int elemType = elem->GetType();
2920 if (elem->IsPoly()) {
2921 // Polygon or Polyhedral Volume
2922 switch ( elemType ) {
2925 vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
2927 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2928 while (itN->more()) {
2929 const SMDS_MeshNode* node =
2930 static_cast<const SMDS_MeshNode*>(itN->next());
2931 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2932 if (nodeMapIt == nodeMap.end())
2933 break; // not all nodes transformed
2935 // reverse mirrored faces and volumes
2936 poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
2938 poly_nodes[iNode] = (*nodeMapIt).second;
2942 if ( iNode != nbNodes )
2943 continue; // not all nodes transformed
2946 aMesh->AddPolygonalFace(poly_nodes);
2948 aMesh->ChangePolygonNodes(elem, poly_nodes);
2952 case SMDSAbs_Volume:
2954 // ATTENTION: Reversing is not yet done!!!
2955 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
2956 (const SMDS_PolyhedralVolumeOfNodes*) elem;
2958 MESSAGE("Warning: bad volumic element");
2962 vector<const SMDS_MeshNode*> poly_nodes;
2963 vector<int> quantities;
2965 bool allTransformed = true;
2966 int nbFaces = aPolyedre->NbFaces();
2967 for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
2968 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
2969 for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
2970 const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
2971 TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2972 if (nodeMapIt == nodeMap.end()) {
2973 allTransformed = false; // not all nodes transformed
2975 poly_nodes.push_back((*nodeMapIt).second);
2978 quantities.push_back(nbFaceNodes);
2980 if ( !allTransformed )
2981 continue; // not all nodes transformed
2984 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
2986 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
2996 int* i = index[ FORWARD ];
2997 if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
2998 if ( elemType == SMDSAbs_Face )
2999 i = index[ REV_FACE ];
3001 i = index[ nbNodes - 4 ];
3003 // find transformed nodes
3004 const SMDS_MeshNode* nodes[8];
3006 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3007 while ( itN->more() )
3009 const SMDS_MeshNode* node =
3010 static_cast<const SMDS_MeshNode*>( itN->next() );
3011 TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
3012 if ( nodeMapIt == nodeMap.end() )
3013 break; // not all nodes transformed
3014 nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
3016 if ( iNode != nbNodes )
3017 continue; // not all nodes transformed
3021 // add a new element
3022 switch ( elemType ) {
3024 aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
3028 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
3030 aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
3032 case SMDSAbs_Volume:
3034 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
3035 else if ( nbNodes == 8 )
3036 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3037 nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
3038 else if ( nbNodes == 6 )
3039 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3040 nodes[ 4 ], nodes[ 5 ]);
3041 else if ( nbNodes == 5 )
3042 aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3050 // reverse element as it was reversed by transformation
3052 aMesh->ChangeElementNodes( elem, nodes, nbNodes );
3057 //=======================================================================
3058 //function : FindCoincidentNodes
3059 //purpose : Return list of group of nodes close to each other within theTolerance
3060 // Search among theNodes or in the whole mesh if theNodes is empty.
3061 //=======================================================================
3063 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
3064 const double theTolerance,
3065 TListOfListOfNodes & theGroupsOfNodes)
3067 double tol2 = theTolerance * theTolerance;
3069 list<const SMDS_MeshNode*> nodes;
3070 if ( theNodes.empty() )
3071 { // get all nodes in the mesh
3072 SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
3073 while ( nIt->more() )
3074 nodes.push_back( nIt->next() );
3078 nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
3081 list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
3082 for ( ; it1 != nodes.end(); it1++ )
3084 const SMDS_MeshNode* n1 = *it1;
3085 gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
3087 list<const SMDS_MeshNode*> * groupPtr = 0;
3089 for ( it2++; it2 != nodes.end(); it2++ )
3091 const SMDS_MeshNode* n2 = *it2;
3092 gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
3093 if ( p1.SquareDistance( p2 ) <= tol2 )
3096 theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
3097 groupPtr = & theGroupsOfNodes.back();
3098 groupPtr->push_back( n1 );
3100 groupPtr->push_back( n2 );
3101 it2 = nodes.erase( it2 );
3108 //=======================================================================
3109 //function : SimplifyFace
3111 //=======================================================================
3112 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
3113 vector<const SMDS_MeshNode *>& poly_nodes,
3114 vector<int>& quantities) const
3116 int nbNodes = faceNodes.size();
3121 set<const SMDS_MeshNode*> nodeSet;
3123 // get simple seq of nodes
3124 const SMDS_MeshNode* simpleNodes[ nbNodes ];
3125 int iSimple = 0, nbUnique = 0;
3127 simpleNodes[iSimple++] = faceNodes[0];
3129 for (int iCur = 1; iCur < nbNodes; iCur++) {
3130 if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
3131 simpleNodes[iSimple++] = faceNodes[iCur];
3132 if (nodeSet.insert( faceNodes[iCur] ).second)
3136 int nbSimple = iSimple;
3137 if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
3147 bool foundLoop = (nbSimple > nbUnique);
3150 set<const SMDS_MeshNode*> loopSet;
3151 for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
3152 const SMDS_MeshNode* n = simpleNodes[iSimple];
3153 if (!loopSet.insert( n ).second) {
3157 int iC = 0, curLast = iSimple;
3158 for (; iC < curLast; iC++) {
3159 if (simpleNodes[iC] == n) break;
3161 int loopLen = curLast - iC;
3163 // create sub-element
3165 quantities.push_back(loopLen);
3166 for (; iC < curLast; iC++) {
3167 poly_nodes.push_back(simpleNodes[iC]);
3170 // shift the rest nodes (place from the first loop position)
3171 for (iC = curLast + 1; iC < nbSimple; iC++) {
3172 simpleNodes[iC - loopLen] = simpleNodes[iC];
3174 nbSimple -= loopLen;
3177 } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
3178 } // while (foundLoop)
3182 quantities.push_back(iSimple);
3183 for (int i = 0; i < iSimple; i++)
3184 poly_nodes.push_back(simpleNodes[i]);
3190 //=======================================================================
3191 //function : MergeNodes
3192 //purpose : In each group, the cdr of nodes are substituted by the first one
3194 //=======================================================================
3196 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
3198 SMESHDS_Mesh* aMesh = GetMeshDS();
3200 TNodeNodeMap nodeNodeMap; // node to replace - new node
3201 set<const SMDS_MeshElement*> elems; // all elements with changed nodes
3202 list< int > rmElemIds, rmNodeIds;
3204 // Fill nodeNodeMap and elems
3206 TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
3207 for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
3209 list<const SMDS_MeshNode*>& nodes = *grIt;
3210 list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
3211 const SMDS_MeshNode* nToKeep = *nIt;
3212 for ( ; nIt != nodes.end(); nIt++ )
3214 const SMDS_MeshNode* nToRemove = *nIt;
3215 nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
3216 if ( nToRemove != nToKeep ) {
3217 rmNodeIds.push_back( nToRemove->GetID() );
3218 AddToSameGroups( nToKeep, nToRemove, aMesh );
3221 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3222 while ( invElemIt->more() )
3223 elems.insert( invElemIt->next() );
3226 // Change element nodes or remove an element
3228 set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
3229 for ( ; eIt != elems.end(); eIt++ )
3231 const SMDS_MeshElement* elem = *eIt;
3232 int nbNodes = elem->NbNodes();
3233 int aShapeId = FindShape( elem );
3235 set<const SMDS_MeshNode*> nodeSet;
3236 const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
3237 int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
3239 // get new seq of nodes
3240 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3241 while ( itN->more() )
3243 const SMDS_MeshNode* n =
3244 static_cast<const SMDS_MeshNode*>( itN->next() );
3246 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
3247 if ( nnIt != nodeNodeMap.end() ) { // n sticks
3249 iRepl[ nbRepl++ ] = iCur;
3251 curNodes[ iCur ] = n;
3252 bool isUnique = nodeSet.insert( n ).second;
3254 uniqueNodes[ iUnique++ ] = n;
3258 // Analyse element topology after replacement
3261 int nbUniqueNodes = nodeSet.size();
3262 if ( nbNodes != nbUniqueNodes ) // some nodes stick
3264 // Polygons and Polyhedral volumes
3265 if (elem->IsPoly()) {
3267 if (elem->GetType() == SMDSAbs_Face) {
3269 vector<const SMDS_MeshNode *> face_nodes (nbNodes);
3271 for (; inode < nbNodes; inode++) {
3272 face_nodes[inode] = curNodes[inode];
3275 vector<const SMDS_MeshNode *> polygons_nodes;
3276 vector<int> quantities;
3277 int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
3281 for (int iface = 0; iface < nbNew - 1; iface++) {
3282 int nbNodes = quantities[iface];
3283 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
3284 for (int ii = 0; ii < nbNodes; ii++, inode++) {
3285 poly_nodes[ii] = polygons_nodes[inode];
3287 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
3289 aMesh->SetMeshElementOnShape(newElem, aShapeId);
3291 aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
3293 rmElemIds.push_back(elem->GetID());
3296 } else if (elem->GetType() == SMDSAbs_Volume) {
3297 // Polyhedral volume
3298 if (nbUniqueNodes < 4) {
3299 rmElemIds.push_back(elem->GetID());
3301 // each face has to be analized in order to check volume validity
3302 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3303 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3305 int nbFaces = aPolyedre->NbFaces();
3307 vector<const SMDS_MeshNode *> poly_nodes;
3308 vector<int> quantities;
3310 for (int iface = 1; iface <= nbFaces; iface++) {
3311 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3312 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
3314 for (int inode = 1; inode <= nbFaceNodes; inode++) {
3315 const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
3316 TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
3317 if (nnIt != nodeNodeMap.end()) { // faceNode sticks
3318 faceNode = (*nnIt).second;
3320 faceNodes[inode - 1] = faceNode;
3323 SimplifyFace(faceNodes, poly_nodes, quantities);
3326 if (quantities.size() > 3) {
3327 // to be done: remove coincident faces
3330 if (quantities.size() > 3)
3331 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3333 rmElemIds.push_back(elem->GetID());
3336 rmElemIds.push_back(elem->GetID());
3346 switch ( nbNodes ) {
3347 case 2: ///////////////////////////////////// EDGE
3348 isOk = false; break;
3349 case 3: ///////////////////////////////////// TRIANGLE
3350 isOk = false; break;
3352 if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
3354 else { //////////////////////////////////// QUADRANGLE
3355 if ( nbUniqueNodes < 3 )
3357 else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
3358 isOk = false; // opposite nodes stick
3361 case 6: ///////////////////////////////////// PENTAHEDRON
3362 if ( nbUniqueNodes == 4 ) {
3363 // ---------------------------------> tetrahedron
3365 iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
3366 // all top nodes stick: reverse a bottom
3367 uniqueNodes[ 0 ] = curNodes [ 1 ];
3368 uniqueNodes[ 1 ] = curNodes [ 0 ];
3370 else if (nbRepl == 3 &&
3371 iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
3372 // all bottom nodes stick: set a top before
3373 uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
3374 uniqueNodes[ 0 ] = curNodes [ 3 ];
3375 uniqueNodes[ 1 ] = curNodes [ 4 ];
3376 uniqueNodes[ 2 ] = curNodes [ 5 ];
3378 else if (nbRepl == 4 &&
3379 iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
3380 // a lateral face turns into a line: reverse a bottom
3381 uniqueNodes[ 0 ] = curNodes [ 1 ];
3382 uniqueNodes[ 1 ] = curNodes [ 0 ];
3387 else if ( nbUniqueNodes == 5 ) {
3388 // PENTAHEDRON --------------------> 2 tetrahedrons
3389 if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
3390 // a bottom node sticks with a linked top one
3392 SMDS_MeshElement* newElem =
3393 aMesh->AddVolume(curNodes[ 3 ],
3396 curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
3398 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3399 // 2. : reverse a bottom
3400 uniqueNodes[ 0 ] = curNodes [ 1 ];
3401 uniqueNodes[ 1 ] = curNodes [ 0 ];
3410 case 8: { //////////////////////////////////// HEXAHEDRON
3412 SMDS_VolumeTool hexa (elem);
3413 hexa.SetExternalNormal();
3414 if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
3415 //////////////////////// ---> tetrahedron
3416 for ( int iFace = 0; iFace < 6; iFace++ ) {
3417 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3418 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3419 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3420 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3421 // one face turns into a point ...
3422 int iOppFace = hexa.GetOppFaceIndex( iFace );
3423 ind = hexa.GetFaceNodesIndices( iOppFace );
3425 iUnique = 2; // reverse a tetrahedron bottom
3426 for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
3427 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3429 else if ( iUnique >= 0 )
3430 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3432 if ( nbStick == 1 ) {
3433 // ... and the opposite one - into a triangle.
3435 ind = hexa.GetFaceNodesIndices( iFace );
3436 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
3443 else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
3444 //////////////////// HEXAHEDRON ---> 2 tetrahedrons
3445 for ( int iFace = 0; iFace < 6; iFace++ ) {
3446 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3447 if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3448 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3449 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3450 // one face turns into a point ...
3451 int iOppFace = hexa.GetOppFaceIndex( iFace );
3452 ind = hexa.GetFaceNodesIndices( iOppFace );
3454 iUnique = 2; // reverse a tetrahedron 1 bottom
3455 for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
3456 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3458 else if ( iUnique >= 0 )
3459 uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3461 if ( nbStick == 0 ) {
3462 // ... and the opposite one is a quadrangle
3464 const int* indTop = hexa.GetFaceNodesIndices( iFace );
3465 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
3468 SMDS_MeshElement* newElem =
3469 aMesh->AddVolume(curNodes[ind[ 0 ]],
3472 curNodes[indTop[ 0 ]]);
3474 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3481 else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
3482 ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
3483 // find indices of quad and tri faces
3484 int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
3485 for ( iFace = 0; iFace < 6; iFace++ ) {
3486 const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3488 for ( iCur = 0; iCur < 4; iCur++ )
3489 nodeSet.insert( curNodes[ind[ iCur ]] );
3490 nbUniqueNodes = nodeSet.size();
3491 if ( nbUniqueNodes == 3 )
3492 iTriFace[ nbTri++ ] = iFace;
3493 else if ( nbUniqueNodes == 4 )
3494 iQuadFace[ nbQuad++ ] = iFace;
3496 if (nbQuad == 2 && nbTri == 4 &&
3497 hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
3498 // 2 opposite quadrangles stuck with a diagonal;
3499 // sample groups of merged indices: (0-4)(2-6)
3500 // --------------------------------------------> 2 tetrahedrons
3501 const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
3502 const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
3503 int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
3504 if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
3505 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
3506 // stuck with 0-2 diagonal
3514 else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
3515 curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
3516 // stuck with 1-3 diagonal
3528 uniqueNodes[ 0 ] = curNodes [ i0 ];
3529 uniqueNodes[ 1 ] = curNodes [ i1d ];
3530 uniqueNodes[ 2 ] = curNodes [ i3d ];
3531 uniqueNodes[ 3 ] = curNodes [ i0t ];
3534 SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
3539 aMesh->SetMeshElementOnShape( newElem, aShapeId );
3542 else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
3543 ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
3544 // --------------------------------------------> prism
3545 // find 2 opposite triangles
3547 for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
3548 if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
3549 // find indices of kept and replaced nodes
3550 // and fill unique nodes of 2 opposite triangles
3551 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
3552 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
3553 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
3554 // fill unique nodes
3557 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
3558 const SMDS_MeshNode* n = curNodes[ind1[ iCur ]];
3559 const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
3561 // iCur of a linked node of the opposite face (make normals co-directed):
3562 int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
3563 // check that correspondent corners of triangles are linked
3564 if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
3567 uniqueNodes[ iUnique ] = n;
3568 uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
3577 } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
3583 } // switch ( nbNodes )
3585 } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
3588 if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
3589 // Change nodes of polyedre
3590 const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3591 static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3593 int nbFaces = aPolyedre->NbFaces();
3595 vector<const SMDS_MeshNode *> poly_nodes;
3596 vector<int> quantities (nbFaces);
3598 for (int iface = 1; iface <= nbFaces; iface++) {
3599 int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3600 quantities[iface - 1] = nbFaceNodes;
3602 for (inode = 1; inode <= nbFaceNodes; inode++) {
3603 const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
3605 TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
3606 if (nnIt != nodeNodeMap.end()) { // curNode sticks
3607 curNode = (*nnIt).second;
3609 poly_nodes.push_back(curNode);
3612 aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
3615 // Change regular element or polygon
3616 aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
3619 // Remove invalid regular element or invalid polygon
3620 rmElemIds.push_back( elem->GetID() );
3623 } // loop on elements
3625 // Remove equal nodes and bad elements
3627 Remove( rmNodeIds, true );
3628 Remove( rmElemIds, false );
3632 //=======================================================================
3633 //function : MergeEqualElements
3634 //purpose : Remove all but one of elements built on the same nodes.
3635 //=======================================================================
3637 void SMESH_MeshEditor::MergeEqualElements()
3639 SMESHDS_Mesh* aMesh = GetMeshDS();
3641 SMDS_EdgeIteratorPtr eIt = aMesh->edgesIterator();
3642 SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
3643 SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
3645 list< int > rmElemIds; // IDs of elems to remove
3647 for ( int iDim = 1; iDim <= 3; iDim++ ) {
3649 set< set <const SMDS_MeshElement*> > setOfNodeSet;
3653 const SMDS_MeshElement* elem = 0;
3655 if ( eIt->more() ) elem = eIt->next();
3656 } else if ( iDim == 2 ) {
3657 if ( fIt->more() ) elem = fIt->next();
3659 if ( vIt->more() ) elem = vIt->next();
3664 set <const SMDS_MeshElement*> nodeSet;
3665 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3666 while ( nodeIt->more() )
3667 nodeSet.insert( nodeIt->next() );
3670 bool isUnique = setOfNodeSet.insert( nodeSet ).second;
3672 rmElemIds.push_back( elem->GetID() );
3676 Remove( rmElemIds, false );
3679 //=======================================================================
3680 //function : FindFaceInSet
3681 //purpose : Return a face having linked nodes n1 and n2 and which is
3682 // - not in avoidSet,
3683 // - in elemSet provided that !elemSet.empty()
3684 //=======================================================================
3686 const SMDS_MeshElement*
3687 SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode* n1,
3688 const SMDS_MeshNode* n2,
3689 const set<const SMDS_MeshElement*>& elemSet,
3690 const set<const SMDS_MeshElement*>& avoidSet)
3693 SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
3694 while ( invElemIt->more() ) { // loop on inverse elements of n1
3695 const SMDS_MeshElement* elem = invElemIt->next();
3696 if (elem->GetType() != SMDSAbs_Face ||
3697 avoidSet.find( elem ) != avoidSet.end() )
3699 if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
3701 // get face nodes and find index of n1
3702 int i1, nbN = elem->NbNodes(), iNode = 0;
3703 const SMDS_MeshNode* faceNodes[ nbN ], *n;
3704 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3705 while ( nIt->more() ) {
3706 faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3707 if ( faceNodes[ iNode++ ] == n1 )
3710 // find a n2 linked to n1
3711 for ( iNode = 0; iNode < 2; iNode++ ) {
3712 if ( iNode ) // node before n1
3713 n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
3714 else // node after n1
3715 n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
3723 //=======================================================================
3724 //function : findAdjacentFace
3726 //=======================================================================
3728 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
3729 const SMDS_MeshNode* n2,
3730 const SMDS_MeshElement* elem)
3732 set<const SMDS_MeshElement*> elemSet, avoidSet;
3734 avoidSet.insert ( elem );
3735 return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3738 //=======================================================================
3739 //function : findFreeBorder
3741 //=======================================================================
3743 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
3745 static bool findFreeBorder (const SMDS_MeshNode* theFirstNode,
3746 const SMDS_MeshNode* theSecondNode,
3747 const SMDS_MeshNode* theLastNode,
3748 list< const SMDS_MeshNode* > & theNodes,
3749 list< const SMDS_MeshElement* > & theFaces)
3751 if ( !theFirstNode || !theSecondNode )
3753 // find border face between theFirstNode and theSecondNode
3754 const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
3758 theFaces.push_back( curElem );
3759 theNodes.push_back( theFirstNode );
3760 theNodes.push_back( theSecondNode );
3762 const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
3763 set < const SMDS_MeshElement* > foundElems;
3764 bool needTheLast = ( theLastNode != 0 );
3766 while ( nStart != theLastNode )
3768 if ( nStart == theFirstNode )
3769 return !needTheLast;
3771 // find all free border faces sharing form nStart
3773 list< const SMDS_MeshElement* > curElemList;
3774 list< const SMDS_MeshNode* > nStartList;
3775 SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
3776 while ( invElemIt->more() ) {
3777 const SMDS_MeshElement* e = invElemIt->next();
3778 if ( e == curElem || foundElems.insert( e ).second )
3781 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3782 int iNode = 0, nbNodes = e->NbNodes();
3783 while ( nIt->more() )
3784 nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3785 nodes[ iNode ] = nodes[ 0 ];
3787 for ( iNode = 0; iNode < nbNodes; iNode++ )
3788 if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
3789 (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
3790 ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
3792 nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
3793 curElemList.push_back( e );
3797 // analyse the found
3799 int nbNewBorders = curElemList.size();
3800 if ( nbNewBorders == 0 ) {
3801 // no free border furthermore
3802 return !needTheLast;
3804 else if ( nbNewBorders == 1 ) {
3805 // one more element found
3807 nStart = nStartList.front();
3808 curElem = curElemList.front();
3809 theFaces.push_back( curElem );
3810 theNodes.push_back( nStart );
3813 // several continuations found
3814 list< const SMDS_MeshElement* >::iterator curElemIt;
3815 list< const SMDS_MeshNode* >::iterator nStartIt;
3816 // check if one of them reached the last node
3817 if ( needTheLast ) {
3818 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3819 curElemIt!= curElemList.end();
3820 curElemIt++, nStartIt++ )
3821 if ( *nStartIt == theLastNode ) {
3822 theFaces.push_back( *curElemIt );
3823 theNodes.push_back( *nStartIt );
3827 // find the best free border by the continuations
3828 list<const SMDS_MeshNode*> contNodes[ 2 ], *cNL;
3829 list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3830 for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3831 curElemIt!= curElemList.end();
3832 curElemIt++, nStartIt++ )
3834 cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3835 cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3836 // find one more free border
3837 if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3841 else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3842 // choice: clear a worse one
3843 int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3844 int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3845 contNodes[ iWorse ].clear();
3846 contFaces[ iWorse ].clear();
3849 if ( contNodes[0].empty() && contNodes[1].empty() )
3852 // append the best free border
3853 cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3854 cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3855 theNodes.pop_back(); // remove nIgnore
3856 theNodes.pop_back(); // remove nStart
3857 theFaces.pop_back(); // remove curElem
3858 list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3859 list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3860 for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3861 for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3864 } // several continuations found
3865 } // while ( nStart != theLastNode )
3870 //=======================================================================
3871 //function : CheckFreeBorderNodes
3872 //purpose : Return true if the tree nodes are on a free border
3873 //=======================================================================
3875 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3876 const SMDS_MeshNode* theNode2,
3877 const SMDS_MeshNode* theNode3)
3879 list< const SMDS_MeshNode* > nodes;
3880 list< const SMDS_MeshElement* > faces;
3881 return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3884 //=======================================================================
3885 //function : SewFreeBorder
3887 //=======================================================================
3889 SMESH_MeshEditor::Sew_Error
3890 SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3891 const SMDS_MeshNode* theBordSecondNode,
3892 const SMDS_MeshNode* theBordLastNode,
3893 const SMDS_MeshNode* theSideFirstNode,
3894 const SMDS_MeshNode* theSideSecondNode,
3895 const SMDS_MeshNode* theSideThirdNode,
3896 const bool theSideIsFreeBorder,
3897 const bool toCreatePolygons,
3898 const bool toCreatePolyedrs)
3900 MESSAGE("::SewFreeBorder()");
3901 Sew_Error aResult = SEW_OK;
3903 // ====================================
3904 // find side nodes and elements
3905 // ====================================
3907 list< const SMDS_MeshNode* > nSide[ 2 ];
3908 list< const SMDS_MeshElement* > eSide[ 2 ];
3909 list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3910 list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3914 if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3915 nSide[0], eSide[0])) {
3916 MESSAGE(" Free Border 1 not found " );
3917 aResult = SEW_BORDER1_NOT_FOUND;
3919 if (theSideIsFreeBorder)
3923 if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3924 nSide[1], eSide[1])) {
3925 MESSAGE(" Free Border 2 not found " );
3926 aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
3929 if ( aResult != SEW_OK )
3932 if (!theSideIsFreeBorder)
3937 // -------------------------------------------------------------------------
3939 // 1. If nodes to merge are not coincident, move nodes of the free border
3940 // from the coord sys defined by the direction from the first to last
3941 // nodes of the border to the correspondent sys of the side 2
3942 // 2. On the side 2, find the links most co-directed with the correspondent
3943 // links of the free border
3944 // -------------------------------------------------------------------------
3946 // 1. Since sewing may brake if there are volumes to split on the side 2,
3947 // we wont move nodes but just compute new coordinates for them
3948 typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
3949 TNodeXYZMap nBordXYZ;
3950 list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
3951 list< const SMDS_MeshNode* >::iterator nBordIt;
3953 gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
3954 gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
3955 gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
3956 gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
3957 double tol2 = 1.e-8;
3958 gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
3959 if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
3961 // Need node movement.
3963 // find X and Z axes to create trsf
3964 gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
3966 if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
3968 X = gp_Ax2( gp::Origin(), Zb ).XDirection();
3971 gp_Ax3 toBordAx( Pb1, Zb, X );
3972 gp_Ax3 fromSideAx( Ps1, Zs, X );
3973 gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
3975 gp_Trsf toBordSys, fromSide2Sys;
3976 toBordSys.SetTransformation( toBordAx );
3977 fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
3978 fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
3981 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3982 const SMDS_MeshNode* n = *nBordIt;
3983 gp_XYZ xyz( n->X(),n->Y(),n->Z() );
3984 toBordSys.Transforms( xyz );
3985 fromSide2Sys.Transforms( xyz );
3986 nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
3991 // just insert nodes XYZ in the nBordXYZ map
3992 for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3993 const SMDS_MeshNode* n = *nBordIt;
3994 nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
3998 // 2. On the side 2, find the links most co-directed with the correspondent
3999 // links of the free border
4001 list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
4002 list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
4003 sideNodes.push_back( theSideFirstNode );
4005 bool hasVolumes = false;
4006 LinkID_Gen aLinkID_Gen( GetMeshDS() );
4007 set<long> foundSideLinkIDs, checkedLinkIDs;
4008 SMDS_VolumeTool volume;
4009 //const SMDS_MeshNode* faceNodes[ 4 ];
4011 const SMDS_MeshNode* sideNode;
4012 const SMDS_MeshElement* sideElem;
4013 const SMDS_MeshNode* prevSideNode = theSideFirstNode;
4014 const SMDS_MeshNode* prevBordNode = theBordFirstNode;
4015 nBordIt = bordNodes.begin();
4017 // border node position and border link direction to compare with
4018 gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
4019 gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
4020 // choose next side node by link direction or by closeness to
4021 // the current border node:
4022 bool searchByDir = ( *nBordIt != theBordLastNode );
4024 // find the next node on the Side 2
4026 double maxDot = -DBL_MAX, minDist = DBL_MAX;
4028 checkedLinkIDs.clear();
4029 gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
4031 SMDS_ElemIteratorPtr invElemIt
4032 = prevSideNode->GetInverseElementIterator();
4033 while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
4034 const SMDS_MeshElement* elem = invElemIt->next();
4035 // prepare data for a loop on links, of a face or a volume
4036 int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
4037 const SMDS_MeshNode* faceNodes[ nbNodes ];
4038 bool isVolume = volume.Set( elem );
4039 const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
4040 if ( isVolume ) // --volume
4042 else if ( nbNodes > 2 ) { // --face
4043 // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
4044 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
4045 while ( nIt->more() ) {
4046 nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
4047 if ( nodes[ iNode++ ] == prevSideNode )
4048 iPrevNode = iNode - 1;
4050 // there are 2 links to check
4055 // loop on links, to be precise, on the second node of links
4056 for ( iNode = 0; iNode < nbNodes; iNode++ ) {
4057 const SMDS_MeshNode* n = nodes[ iNode ];
4059 if ( !volume.IsLinked( n, prevSideNode ))
4062 if ( iNode ) // a node before prevSideNode
4063 n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
4064 else // a node after prevSideNode
4065 n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
4067 // check if this link was already used
4068 long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
4069 bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
4070 if (!isJustChecked &&
4071 foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
4072 // test a link geometrically
4073 gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
4074 bool linkIsBetter = false;
4076 if ( searchByDir ) { // choose most co-directed link
4077 dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
4078 linkIsBetter = ( dot > maxDot );
4080 else { // choose link with the node closest to bordPos
4081 dist = ( nextXYZ - bordPos ).SquareModulus();
4082 linkIsBetter = ( dist < minDist );
4084 if ( linkIsBetter ) {
4093 } // loop on inverse elements of prevSideNode
4096 MESSAGE(" Cant find path by links of the Side 2 ");
4097 return SEW_BAD_SIDE_NODES;
4099 sideNodes.push_back( sideNode );
4100 sideElems.push_back( sideElem );
4101 foundSideLinkIDs.insert ( linkID );
4102 prevSideNode = sideNode;
4104 if ( *nBordIt == theBordLastNode )
4105 searchByDir = false;
4107 // find the next border link to compare with
4108 gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
4109 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4110 while ( *nBordIt != theBordLastNode && !searchByDir ) {
4111 prevBordNode = *nBordIt;
4113 bordPos = nBordXYZ[ *nBordIt ];
4114 bordDir = bordPos - nBordXYZ[ prevBordNode ];
4115 searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4119 while ( sideNode != theSideSecondNode );
4121 if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
4122 MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
4123 return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
4125 } // end nodes search on the side 2
4127 // ============================
4128 // sew the border to the side 2
4129 // ============================
4131 int nbNodes[] = { nSide[0].size(), nSide[1].size() };
4132 int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
4134 TListOfListOfNodes nodeGroupsToMerge;
4135 if ( nbNodes[0] == nbNodes[1] ||
4136 ( theSideIsFreeBorder && !theSideThirdNode)) {
4138 // all nodes are to be merged
4140 for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
4141 nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
4142 nIt[0]++, nIt[1]++ )
4144 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4145 nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
4146 nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
4151 // insert new nodes into the border and the side to get equal nb of segments
4153 // get normalized parameters of nodes on the borders
4154 double param[ 2 ][ maxNbNodes ];
4156 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4157 list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
4158 list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
4159 const SMDS_MeshNode* nPrev = *nIt;
4160 double bordLength = 0;
4161 for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
4162 const SMDS_MeshNode* nCur = *nIt;
4163 gp_XYZ segment (nCur->X() - nPrev->X(),
4164 nCur->Y() - nPrev->Y(),
4165 nCur->Z() - nPrev->Z());
4166 double segmentLen = segment.Modulus();
4167 bordLength += segmentLen;
4168 param[ iBord ][ iNode ] = bordLength;
4171 // normalize within [0,1]
4172 for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
4173 param[ iBord ][ iNode ] /= bordLength;
4177 // loop on border segments
4178 const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
4179 int i[ 2 ] = { 0, 0 };
4180 nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
4181 nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
4183 TElemOfNodeListMap insertMap;
4184 TElemOfNodeListMap::iterator insertMapIt;
4186 // key: elem to insert nodes into
4187 // value: 2 nodes to insert between + nodes to be inserted
4189 bool next[ 2 ] = { false, false };
4191 // find min adjacent segment length after sewing
4192 double nextParam = 10., prevParam = 0;
4193 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4194 if ( i[ iBord ] + 1 < nbNodes[ iBord ])
4195 nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
4196 if ( i[ iBord ] > 0 )
4197 prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
4199 double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4200 double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4201 double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
4203 // choose to insert or to merge nodes
4204 double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
4205 if ( Abs( du ) <= minSegLen * 0.2 ) {
4208 nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4209 const SMDS_MeshNode* n0 = *nIt[0];
4210 const SMDS_MeshNode* n1 = *nIt[1];
4211 nodeGroupsToMerge.back().push_back( n1 );
4212 nodeGroupsToMerge.back().push_back( n0 );
4213 // position of node of the border changes due to merge
4214 param[ 0 ][ i[0] ] += du;
4215 // move n1 for the sake of elem shape evaluation during insertion.
4216 // n1 will be removed by MergeNodes() anyway
4217 const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
4218 next[0] = next[1] = true;
4223 int intoBord = ( du < 0 ) ? 0 : 1;
4224 const SMDS_MeshElement* elem = *eIt[ intoBord ];
4225 const SMDS_MeshNode* n1 = nPrev[ intoBord ];
4226 const SMDS_MeshNode* n2 = *nIt[ intoBord ];
4227 const SMDS_MeshNode* nIns = *nIt[ 1 - intoBord ];
4228 if ( intoBord == 1 ) {
4229 // move node of the border to be on a link of elem of the side
4230 gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
4231 gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
4232 double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
4233 gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
4234 GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
4236 insertMapIt = insertMap.find( elem );
4237 bool notFound = ( insertMapIt == insertMap.end() );
4238 bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
4240 // insert into another link of the same element:
4241 // 1. perform insertion into the other link of the elem
4242 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4243 const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
4244 const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
4245 InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
4246 // 2. perform insertion into the link of adjacent faces
4248 const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
4250 InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
4254 if (toCreatePolyedrs) {
4255 // perform insertion into the links of adjacent volumes
4256 UpdateVolumes(n12, n22, nodeList);
4258 // 3. find an element appeared on n1 and n2 after the insertion
4259 insertMap.erase( elem );
4260 elem = findAdjacentFace( n1, n2, 0 );
4262 if ( notFound || otherLink ) {
4263 // add element and nodes of the side into the insertMap
4264 insertMapIt = insertMap.insert
4265 ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
4266 (*insertMapIt).second.push_back( n1 );
4267 (*insertMapIt).second.push_back( n2 );
4269 // add node to be inserted into elem
4270 (*insertMapIt).second.push_back( nIns );
4271 next[ 1 - intoBord ] = true;
4274 // go to the next segment
4275 for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4276 if ( next[ iBord ] ) {
4277 if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
4279 nPrev[ iBord ] = *nIt[ iBord ];
4280 nIt[ iBord ]++; i[ iBord ]++;
4284 while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
4286 // perform insertion of nodes into elements
4288 for (insertMapIt = insertMap.begin();
4289 insertMapIt != insertMap.end();
4292 const SMDS_MeshElement* elem = (*insertMapIt).first;
4293 list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4294 const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
4295 const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
4297 InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
4299 if ( !theSideIsFreeBorder ) {
4300 // look for and insert nodes into the faces adjacent to elem
4302 const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
4304 InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
4309 if (toCreatePolyedrs) {
4310 // perform insertion into the links of adjacent volumes
4311 UpdateVolumes(n1, n2, nodeList);
4315 } // end: insert new nodes
4317 MergeNodes ( nodeGroupsToMerge );
4322 //=======================================================================
4323 //function : InsertNodesIntoLink
4324 //purpose : insert theNodesToInsert into theFace between theBetweenNode1
4325 // and theBetweenNode2 and split theElement
4326 //=======================================================================
4328 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement* theFace,
4329 const SMDS_MeshNode* theBetweenNode1,
4330 const SMDS_MeshNode* theBetweenNode2,
4331 list<const SMDS_MeshNode*>& theNodesToInsert,
4332 const bool toCreatePoly)
4334 if ( theFace->GetType() != SMDSAbs_Face ) return;
4336 // find indices of 2 link nodes and of the rest nodes
4337 int iNode = 0, il1, il2, i3, i4;
4338 il1 = il2 = i3 = i4 = -1;
4339 const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
4340 SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
4341 while ( nodeIt->more() ) {
4342 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4343 if ( n == theBetweenNode1 )
4345 else if ( n == theBetweenNode2 )
4351 nodes[ iNode++ ] = n;
4353 if ( il1 < 0 || il2 < 0 || i3 < 0 )
4356 // arrange link nodes to go one after another regarding the face orientation
4357 bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
4358 list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
4363 aNodesToInsert.reverse();
4365 // check that not link nodes of a quadrangles are in good order
4366 int nbFaceNodes = theFace->NbNodes();
4367 if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
4373 if (toCreatePoly || theFace->IsPoly()) {
4376 vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
4378 // add nodes of face up to first node of link
4380 nodeIt = theFace->nodesIterator();
4381 while ( nodeIt->more() && !isFLN ) {
4382 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4383 poly_nodes[iNode++] = n;
4384 if (n == nodes[il1]) {
4389 // add nodes to insert
4390 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4391 for (; nIt != aNodesToInsert.end(); nIt++) {
4392 poly_nodes[iNode++] = *nIt;
4395 // add nodes of face starting from last node of link
4396 while ( nodeIt->more() ) {
4397 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4398 poly_nodes[iNode++] = n;
4401 // edit or replace the face
4402 SMESHDS_Mesh *aMesh = GetMeshDS();
4404 if (theFace->IsPoly()) {
4405 aMesh->ChangePolygonNodes(theFace, poly_nodes);
4408 int aShapeId = FindShape( theFace );
4410 SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4411 if ( aShapeId && newElem )
4412 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4414 aMesh->RemoveElement(theFace);
4419 // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
4420 int nbLinkNodes = 2 + aNodesToInsert.size();
4421 const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
4422 linkNodes[ 0 ] = nodes[ il1 ];
4423 linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
4424 list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4425 for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
4426 linkNodes[ iNode++ ] = *nIt;
4428 // decide how to split a quadrangle: compare possible variants
4429 // and choose which of splits to be a quadrangle
4430 int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
4431 if ( nbFaceNodes == 3 )
4433 iBestQuad = nbSplits;
4436 else if ( nbFaceNodes == 4 )
4438 SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
4439 double aBestRate = DBL_MAX;
4440 for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
4442 double aBadRate = 0;
4443 // evaluate elements quality
4444 for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
4445 if ( iSplit == iQuad ) {
4446 SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
4450 aBadRate += getBadRate( &quad, aCrit );
4453 SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
4455 nodes[ iSplit < iQuad ? i4 : i3 ]);
4456 aBadRate += getBadRate( &tria, aCrit );
4460 if ( aBadRate < aBestRate ) {
4462 aBestRate = aBadRate;
4467 // create new elements
4468 SMESHDS_Mesh *aMesh = GetMeshDS();
4469 int aShapeId = FindShape( theFace );
4472 for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
4473 SMDS_MeshElement* newElem = 0;
4474 if ( iSplit == iBestQuad )
4475 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4480 newElem = aMesh->AddFace (linkNodes[ i1++ ],
4482 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
4483 if ( aShapeId && newElem )
4484 aMesh->SetMeshElementOnShape( newElem, aShapeId );
4487 // change nodes of theFace
4488 const SMDS_MeshNode* newNodes[ 4 ];
4489 newNodes[ 0 ] = linkNodes[ i1 ];
4490 newNodes[ 1 ] = linkNodes[ i2 ];
4491 newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
4492 newNodes[ 3 ] = nodes[ i4 ];
4493 aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
4496 //=======================================================================
4497 //function : UpdateVolumes
4499 //=======================================================================
4500 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode* theBetweenNode1,
4501 const SMDS_MeshNode* theBetweenNode2,
4502 list<const SMDS_MeshNode*>& theNodesToInsert)
4504 SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
4505 while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
4506 const SMDS_MeshElement* elem = invElemIt->next();
4507 if (elem->GetType() != SMDSAbs_Volume)
4510 // check, if current volume has link theBetweenNode1 - theBetweenNode2
4511 SMDS_VolumeTool aVolume (elem);
4512 if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
4515 // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
4516 int iface, nbFaces = aVolume.NbFaces();
4517 vector<const SMDS_MeshNode *> poly_nodes;
4518 vector<int> quantities (nbFaces);
4520 for (iface = 0; iface < nbFaces; iface++) {
4521 int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
4522 // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
4523 const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
4525 for (int inode = 0; inode < nbFaceNodes; inode++) {
4526 poly_nodes.push_back(faceNodes[inode]);
4528 if (nbInserted == 0) {
4529 if (faceNodes[inode] == theBetweenNode1) {
4530 if (faceNodes[inode + 1] == theBetweenNode2) {
4531 nbInserted = theNodesToInsert.size();
4533 // add nodes to insert
4534 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
4535 for (; nIt != theNodesToInsert.end(); nIt++) {
4536 poly_nodes.push_back(*nIt);
4539 } else if (faceNodes[inode] == theBetweenNode2) {
4540 if (faceNodes[inode + 1] == theBetweenNode1) {
4541 nbInserted = theNodesToInsert.size();
4543 // add nodes to insert in reversed order
4544 list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
4546 for (; nIt != theNodesToInsert.begin(); nIt--) {
4547 poly_nodes.push_back(*nIt);
4549 poly_nodes.push_back(*nIt);
4555 quantities[iface] = nbFaceNodes + nbInserted;
4558 // Replace or update the volume
4559 SMESHDS_Mesh *aMesh = GetMeshDS();
4561 if (elem->IsPoly()) {
4562 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4565 int aShapeId = FindShape( elem );
4567 SMDS_MeshElement* newElem =
4568 aMesh->AddPolyhedralVolume(poly_nodes, quantities);
4569 if (aShapeId && newElem)
4570 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4572 aMesh->RemoveElement(elem);
4577 //=======================================================================
4578 //function : SewSideElements
4580 //=======================================================================
4582 SMESH_MeshEditor::Sew_Error
4583 SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
4584 set<const SMDS_MeshElement*>& theSide2,
4585 const SMDS_MeshNode* theFirstNode1,
4586 const SMDS_MeshNode* theFirstNode2,
4587 const SMDS_MeshNode* theSecondNode1,
4588 const SMDS_MeshNode* theSecondNode2)
4590 MESSAGE ("::::SewSideElements()");
4591 if ( theSide1.size() != theSide2.size() )
4592 return SEW_DIFF_NB_OF_ELEMENTS;
4594 Sew_Error aResult = SEW_OK;
4596 // 1. Build set of faces representing each side
4597 // 2. Find which nodes of the side 1 to merge with ones on the side 2
4598 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4600 // =======================================================================
4601 // 1. Build set of faces representing each side:
4602 // =======================================================================
4603 // a. build set of nodes belonging to faces
4604 // b. complete set of faces: find missing fices whose nodes are in set of nodes
4605 // c. create temporary faces representing side of volumes if correspondent
4606 // face does not exist
4608 SMESHDS_Mesh* aMesh = GetMeshDS();
4609 SMDS_Mesh aTmpFacesMesh;
4610 set<const SMDS_MeshElement*> faceSet1, faceSet2;
4611 set<const SMDS_MeshElement*> volSet1, volSet2;
4612 set<const SMDS_MeshNode*> nodeSet1, nodeSet2;
4613 set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
4614 set<const SMDS_MeshElement*> * volSetPtr[] = { &volSet1, &volSet2 };
4615 set<const SMDS_MeshNode*> * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
4616 set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
4617 int iSide, iFace, iNode;
4619 for ( iSide = 0; iSide < 2; iSide++ ) {
4620 set<const SMDS_MeshNode*> * nodeSet = nodeSetPtr[ iSide ];
4621 set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
4622 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4623 set<const SMDS_MeshElement*> * volSet = volSetPtr [ iSide ];
4624 set<const SMDS_MeshElement*>::iterator vIt, eIt;
4625 set<const SMDS_MeshNode*>::iterator nIt;
4627 // -----------------------------------------------------------
4628 // 1a. Collect nodes of existing faces
4629 // and build set of face nodes in order to detect missing
4630 // faces corresponing to sides of volumes
4631 // -----------------------------------------------------------
4633 set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
4635 // loop on the given element of a side
4636 for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
4637 const SMDS_MeshElement* elem = *eIt;
4638 if ( elem->GetType() == SMDSAbs_Face ) {
4639 faceSet->insert( elem );
4640 set <const SMDS_MeshNode*> faceNodeSet;
4641 SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
4642 while ( nodeIt->more() ) {
4643 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4644 nodeSet->insert( n );
4645 faceNodeSet.insert( n );
4647 setOfFaceNodeSet.insert( faceNodeSet );
4649 else if ( elem->GetType() == SMDSAbs_Volume )
4650 volSet->insert( elem );
4652 // ------------------------------------------------------------------------------
4653 // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
4654 // ------------------------------------------------------------------------------
4656 for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4657 SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4658 while ( fIt->more() ) { // loop on faces sharing a node
4659 const SMDS_MeshElement* f = fIt->next();
4660 if ( faceSet->find( f ) == faceSet->end() ) {
4661 // check if all nodes are in nodeSet and
4662 // complete setOfFaceNodeSet if they are
4663 set <const SMDS_MeshNode*> faceNodeSet;
4664 SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4665 bool allInSet = true;
4666 while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4667 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4668 if ( nodeSet->find( n ) == nodeSet->end() )
4671 faceNodeSet.insert( n );
4674 faceSet->insert( f );
4675 setOfFaceNodeSet.insert( faceNodeSet );
4681 // -------------------------------------------------------------------------
4682 // 1c. Create temporary faces representing sides of volumes if correspondent
4683 // face does not exist
4684 // -------------------------------------------------------------------------
4686 if ( !volSet->empty() )
4688 //int nodeSetSize = nodeSet->size();
4690 // loop on given volumes
4691 for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
4692 SMDS_VolumeTool vol (*vIt);
4693 // loop on volume faces: find free faces
4694 // --------------------------------------
4695 list<const SMDS_MeshElement* > freeFaceList;
4696 for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
4697 if ( !vol.IsFreeFace( iFace ))
4699 // check if there is already a face with same nodes in a face set
4700 const SMDS_MeshElement* aFreeFace = 0;
4701 const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
4702 int nbNodes = vol.NbFaceNodes( iFace );
4703 set <const SMDS_MeshNode*> faceNodeSet;
4704 vol.GetFaceNodes( iFace, faceNodeSet );
4705 bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
4707 // no such a face is given but it still can exist, check it
4708 if ( nbNodes == 3 ) {
4709 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
4710 } else if ( nbNodes == 4 ) {
4711 aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4713 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4714 for (int inode = 0; inode < nbNodes; inode++) {
4715 poly_nodes[inode] = fNodes[inode];
4717 aFreeFace = aMesh->FindFace(poly_nodes);
4721 // create a temporary face
4722 if ( nbNodes == 3 ) {
4723 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
4724 } else if ( nbNodes == 4 ) {
4725 aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4727 vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4728 for (int inode = 0; inode < nbNodes; inode++) {
4729 poly_nodes[inode] = fNodes[inode];
4731 aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
4735 freeFaceList.push_back( aFreeFace );
4737 } // loop on faces of a volume
4739 // choose one of several free faces
4740 // --------------------------------------
4741 if ( freeFaceList.size() > 1 ) {
4742 // choose a face having max nb of nodes shared by other elems of a side
4743 int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
4744 list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
4745 while ( fIt != freeFaceList.end() ) { // loop on free faces
4746 int nbSharedNodes = 0;
4747 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4748 while ( nodeIt->more() ) { // loop on free face nodes
4749 const SMDS_MeshNode* n =
4750 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4751 SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
4752 while ( invElemIt->more() ) {
4753 const SMDS_MeshElement* e = invElemIt->next();
4754 if ( faceSet->find( e ) != faceSet->end() )
4756 if ( elemSet->find( e ) != elemSet->end() )
4760 if ( nbSharedNodes >= maxNbNodes ) {
4761 maxNbNodes = nbSharedNodes;
4765 freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
4767 if ( freeFaceList.size() > 1 )
4769 // could not choose one face, use another way
4770 // choose a face most close to the bary center of the opposite side
4771 gp_XYZ aBC( 0., 0., 0. );
4772 set <const SMDS_MeshNode*> addedNodes;
4773 set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
4774 eIt = elemSet2->begin();
4775 for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
4776 SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
4777 while ( nodeIt->more() ) { // loop on free face nodes
4778 const SMDS_MeshNode* n =
4779 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4780 if ( addedNodes.insert( n ).second )
4781 aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
4784 aBC /= addedNodes.size();
4785 double minDist = DBL_MAX;
4786 fIt = freeFaceList.begin();
4787 while ( fIt != freeFaceList.end() ) { // loop on free faces
4789 SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4790 while ( nodeIt->more() ) { // loop on free face nodes
4791 const SMDS_MeshNode* n =
4792 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4793 gp_XYZ p( n->X(),n->Y(),n->Z() );
4794 dist += ( aBC - p ).SquareModulus();
4796 if ( dist < minDist ) {
4798 freeFaceList.erase( freeFaceList.begin(), fIt++ );
4801 fIt = freeFaceList.erase( fIt++ );
4804 } // choose one of several free faces of a volume
4806 if ( freeFaceList.size() == 1 ) {
4807 const SMDS_MeshElement* aFreeFace = freeFaceList.front();
4808 faceSet->insert( aFreeFace );
4809 // complete a node set with nodes of a found free face
4810 // for ( iNode = 0; iNode < ; iNode++ )
4811 // nodeSet->insert( fNodes[ iNode ] );
4814 } // loop on volumes of a side
4816 // // complete a set of faces if new nodes in a nodeSet appeared
4817 // // ----------------------------------------------------------
4818 // if ( nodeSetSize != nodeSet->size() ) {
4819 // for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4820 // SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4821 // while ( fIt->more() ) { // loop on faces sharing a node
4822 // const SMDS_MeshElement* f = fIt->next();
4823 // if ( faceSet->find( f ) == faceSet->end() ) {
4824 // // check if all nodes are in nodeSet and
4825 // // complete setOfFaceNodeSet if they are
4826 // set <const SMDS_MeshNode*> faceNodeSet;
4827 // SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4828 // bool allInSet = true;
4829 // while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4830 // const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4831 // if ( nodeSet->find( n ) == nodeSet->end() )
4832 // allInSet = false;
4834 // faceNodeSet.insert( n );
4836 // if ( allInSet ) {
4837 // faceSet->insert( f );
4838 // setOfFaceNodeSet.insert( faceNodeSet );
4844 } // Create temporary faces, if there are volumes given
4847 if ( faceSet1.size() != faceSet2.size() ) {
4848 // delete temporary faces: they are in reverseElements of actual nodes
4849 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4850 while ( tmpFaceIt->more() )
4851 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4852 MESSAGE("Diff nb of faces");
4853 return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4856 // ============================================================
4857 // 2. Find nodes to merge:
4858 // bind a node to remove to a node to put instead
4859 // ============================================================
4861 TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
4862 if ( theFirstNode1 != theFirstNode2 )
4863 nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
4864 if ( theSecondNode1 != theSecondNode2 )
4865 nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
4867 LinkID_Gen aLinkID_Gen( GetMeshDS() );
4868 set< long > linkIdSet; // links to process
4869 linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
4871 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
4872 list< TPairOfNodes > linkList[2];
4873 linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
4874 linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
4875 // loop on links in linkList; find faces by links and append links
4876 // of the found faces to linkList
4877 list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
4878 for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
4880 TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
4881 long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
4882 if ( linkIdSet.find( linkID ) == linkIdSet.end() )
4885 // by links, find faces in the face sets,
4886 // and find indices of link nodes in the found faces;
4887 // in a face set, there is only one or no face sharing a link
4888 // ---------------------------------------------------------------
4890 const SMDS_MeshElement* face[] = { 0, 0 };
4891 const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
4892 const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
4893 int iLinkNode[2][2];
4894 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4895 const SMDS_MeshNode* n1 = link[iSide].first;
4896 const SMDS_MeshNode* n2 = link[iSide].second;
4897 set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4898 set< const SMDS_MeshElement* > fMap;
4899 for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
4900 const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
4901 SMDS_ElemIteratorPtr fIt = n->facesIterator();
4902 while ( fIt->more() ) { // loop on faces sharing a node
4903 const SMDS_MeshElement* f = fIt->next();
4904 if (faceSet->find( f ) != faceSet->end() && // f is in face set
4905 ! fMap.insert( f ).second ) // f encounters twice
4907 if ( face[ iSide ] ) {
4908 MESSAGE( "2 faces per link " );
4909 aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
4913 faceSet->erase( f );
4914 // get face nodes and find ones of a link
4916 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
4917 while ( nIt->more() ) {
4918 const SMDS_MeshNode* n =
4919 static_cast<const SMDS_MeshNode*>( nIt->next() );
4921 iLinkNode[ iSide ][ 0 ] = iNode;
4923 iLinkNode[ iSide ][ 1 ] = iNode;
4924 else if ( notLinkNodes[ iSide ][ 0 ] )
4925 notLinkNodes[ iSide ][ 1 ] = n;
4927 notLinkNodes[ iSide ][ 0 ] = n;
4928 faceNodes[ iSide ][ iNode++ ] = n;
4930 faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
4935 // check similarity of elements of the sides
4936 if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
4937 MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
4938 if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
4939 aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
4941 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4942 break; // do not return because it s necessary to remove tmp faces
4945 // set nodes to merge
4946 // -------------------
4948 if ( face[0] && face[1] )
4950 int nbNodes = face[0]->NbNodes();
4951 if ( nbNodes != face[1]->NbNodes() ) {
4952 MESSAGE("Diff nb of face nodes");
4953 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4954 break; // do not return because it s necessary to remove tmp faces
4956 bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
4958 nReplaceMap.insert( TNodeNodeMap::value_type
4959 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4961 for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4962 // analyse link orientation in faces
4963 int i1 = iLinkNode[ iSide ][ 0 ];
4964 int i2 = iLinkNode[ iSide ][ 1 ];
4965 reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
4966 // if notLinkNodes are the first and the last ones, then
4967 // their order does not correspond to the link orientation
4968 if (( i1 == 1 && i2 == 2 ) ||
4969 ( i1 == 2 && i2 == 1 ))
4970 reverse[ iSide ] = !reverse[ iSide ];
4972 if ( reverse[0] == reverse[1] ) {
4973 nReplaceMap.insert( TNodeNodeMap::value_type
4974 ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4975 nReplaceMap.insert( TNodeNodeMap::value_type
4976 ( notLinkNodes[0][1], notLinkNodes[1][1] ));
4979 nReplaceMap.insert( TNodeNodeMap::value_type
4980 ( notLinkNodes[0][0], notLinkNodes[1][1] ));
4981 nReplaceMap.insert( TNodeNodeMap::value_type
4982 ( notLinkNodes[0][1], notLinkNodes[1][0] ));
4986 // add other links of the faces to linkList
4987 // -----------------------------------------
4989 const SMDS_MeshNode** nodes = faceNodes[ 0 ];
4990 for ( iNode = 0; iNode < nbNodes; iNode++ )
4992 linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
4993 pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
4994 if ( !iter_isnew.second ) { // already in a set: no need to process
4995 linkIdSet.erase( iter_isnew.first );
4997 else // new in set == encountered for the first time: add
4999 const SMDS_MeshNode* n1 = nodes[ iNode ];
5000 const SMDS_MeshNode* n2 = nodes[ iNode + 1];
5001 linkList[0].push_back ( TPairOfNodes( n1, n2 ));
5002 linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
5006 } // loop on link lists
5008 if ( aResult == SEW_OK &&
5009 ( linkIt[0] != linkList[0].end() ||
5010 !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
5011 MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
5012 " " << (faceSetPtr[1]->empty()));
5013 aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
5016 // ====================================================================
5017 // 3. Replace nodes in elements of the side 1 and remove replaced nodes
5018 // ====================================================================
5020 // delete temporary faces: they are in reverseElements of actual nodes
5021 SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
5022 while ( tmpFaceIt->more() )
5023 aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
5025 if ( aResult != SEW_OK)
5028 list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
5029 // loop on nodes replacement map
5030 TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
5031 for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
5032 if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
5034 const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
5035 nodeIDsToRemove.push_back( nToRemove->GetID() );
5036 // loop on elements sharing nToRemove
5037 SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
5038 while ( invElemIt->more() ) {
5039 const SMDS_MeshElement* e = invElemIt->next();
5040 // get a new suite of nodes: make replacement
5041 int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
5042 const SMDS_MeshNode* nodes[ 8 ];
5043 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5044 while ( nIt->more() ) {
5045 const SMDS_MeshNode* n =
5046 static_cast<const SMDS_MeshNode*>( nIt->next() );
5047 nnIt = nReplaceMap.find( n );
5048 if ( nnIt != nReplaceMap.end() ) {
5054 // if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
5055 // elemIDsToRemove.push_back( e->GetID() );
5058 aMesh->ChangeElementNodes( e, nodes, nbNodes );
5062 Remove( nodeIDsToRemove, true );