Salome HOME
Fix on - Bug PAL7220: DEVELOPMENT : 3D Aspect Ratio
[modules/smesh.git] / src / SMESH / SMESH_MeshEditor.cxx
1 //  SMESH SMESH : idl implementation based on 'SMESH' unit's classes
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
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. 
10 // 
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. 
15 // 
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 
19 // 
20 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
21 //
22 //
23 //
24 // File      : SMESH_MeshEditor.cxx
25 // Created   : Mon Apr 12 16:10:22 2004
26 // Author    : Edward AGAPOV (eap)
27
28
29 #include "SMESH_MeshEditor.hxx"
30
31 #include "SMESH_ControlsDef.hxx"
32
33 #include "SMDS_FaceOfNodes.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Group.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "SMESH_subMesh.hxx"
38
39 #include <TopTools_ListIteratorOfListOfShape.hxx>
40 #include <TopTools_ListOfShape.hxx>
41 #include <gp_Vec.hxx>
42 #include <gp_Ax1.hxx>
43 #include <gp_Trsf.hxx>
44 #include <gp_Lin.hxx>
45 #include <gp.hxx>
46 #include <gp_Pln.hxx>
47
48 #include <map>
49
50 #include "utilities.h"
51
52 using namespace std;
53 using namespace SMESH::Controls;
54
55 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*>           TNodeNodeMap;
56 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> >    TNodeOfNodeListMap;
57 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> > TElemOfNodeListMap;
58
59 //=======================================================================
60 //function : SMESH_MeshEditor
61 //purpose  : 
62 //=======================================================================
63
64 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
65 myMesh( theMesh )
66 {
67 }
68
69 //=======================================================================
70 //function : Remove
71 //purpose  : Remove a node or an element.
72 //           Modify a compute state of sub-meshes which become empty
73 //=======================================================================
74
75 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
76                                const bool         isNodes )
77 {
78
79   SMESHDS_Mesh* aMesh = GetMeshDS();
80   set< SMESH_subMesh *> smmap;
81   
82   list<int>::const_iterator it = theIDs.begin();
83   for ( ; it != theIDs.end(); it++ )
84   {
85     const SMDS_MeshElement * elem;
86     if ( isNodes )
87       elem = aMesh->FindNode( *it );
88     else
89       elem = aMesh->FindElement( *it );
90     if ( !elem )
91       continue;
92
93     // Find sub-meshes to notify about modification
94     SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
95     while ( nodeIt->more() )
96     {
97       const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
98       const SMDS_PositionPtr& aPosition = node->GetPosition();
99       if ( aPosition.get() ) {
100         int aShapeID = aPosition->GetShapeId();
101         if ( aShapeID ) {
102           TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
103           SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
104           if ( sm )
105             smmap.insert( sm );
106         }
107       }
108     }
109
110     // Do remove
111     if ( isNodes )
112       aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
113     else
114       aMesh->RemoveElement( elem );
115   }
116
117   // Notify sub-meshes about modification
118   if ( !smmap.empty() ) {
119     set< SMESH_subMesh *>::iterator smIt;
120     for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
121       (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
122   }
123   return true;
124 }
125
126 //=======================================================================
127 //function : FindShape
128 //purpose  : Return an index of the shape theElem is on
129 //           or zero if a shape not found
130 //=======================================================================
131
132 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
133 {
134   SMESHDS_Mesh * aMesh = GetMeshDS();
135   if ( aMesh->ShapeToMesh().IsNull() )
136     return 0;
137
138   if ( theElem->GetType() == SMDSAbs_Node )
139   {
140     const SMDS_PositionPtr& aPosition =
141       static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
142     if ( aPosition.get() )
143       return aPosition->GetShapeId();
144     else
145       return 0;
146   }
147
148   TopoDS_Shape aShape; // the shape a node is on
149   SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
150   while ( nodeIt->more() )
151   {
152     const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
153     const SMDS_PositionPtr& aPosition = node->GetPosition();
154     if ( aPosition.get() ) {
155         int aShapeID = aPosition->GetShapeId();
156         SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
157         if ( sm )
158         {
159           if ( sm->Contains( theElem ))
160             return aShapeID;
161           if ( aShape.IsNull() )
162             aShape = aMesh->IndexToShape( aShapeID );
163         }
164         else
165         {
166           //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
167         }
168       }
169   }
170
171   // None of nodes is on a proper shape,
172   // find the shape among ancestors of aShape on which a node is
173   if ( aShape.IsNull() ) {
174     //MESSAGE ("::FindShape() - NONE node is on shape")
175     return 0;
176   }
177   TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
178   for ( ; ancIt.More(); ancIt.Next() )
179   {
180       SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
181       if ( sm && sm->Contains( theElem ))
182         return aMesh->ShapeToIndex( ancIt.Value() );
183   }
184
185   //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
186   return 0;
187 }
188
189 //=======================================================================
190 //function : InverseDiag
191 //purpose  : Replace two neighbour triangles with ones built on the same 4 nodes
192 //           but having other common link.
193 //           Return False if args are improper
194 //=======================================================================
195
196 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
197                                     const SMDS_MeshElement * theTria2 )
198 {
199   if (!theTria1 || !theTria2)
200     return false;
201   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
202   if (!F1) return false;
203   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
204   if (!F2) return false;
205
206   //  1 +--+ A  theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
207   //    | /|    theTria2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |  
208   //    |/ |                                         | \|  
209   //  B +--+ 2                                     B +--+ 2
210
211   // put nodes in array and find out indices of the same ones
212   const SMDS_MeshNode* aNodes [6];
213   int sameInd [] = { 0, 0, 0, 0, 0, 0 };
214   int i = 0;
215   SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
216   while ( it->more() )
217   {
218     aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
219
220     if ( i > 2 ) // theTria2
221       // find same node of theTria1
222       for ( int j = 0; j < 3; j++ )
223         if ( aNodes[ i ] == aNodes[ j ]) {
224           sameInd[ j ] = i;
225           sameInd[ i ] = j;
226           break;
227         }
228     // next
229     i++;
230     if ( i == 3 ) {
231       if ( it->more() )
232         return false; // theTria1 is not a triangle
233       it = theTria2->nodesIterator();
234     }
235     if ( i == 6 && it->more() )
236       return false; // theTria2 is not a triangle
237   }
238
239   // find indices of 1,2 and of A,B in theTria1
240   int iA = 0, iB = 0, i1 = 0, i2 = 0;
241   for ( i = 0; i < 6; i++ )
242   {
243     if ( sameInd [ i ] == 0 )
244       if ( i < 3 ) i1 = i;
245       else         i2 = i;
246     else if (i < 3)
247       if ( iA ) iB = i;
248       else      iA = i;
249   }
250   // nodes 1 and 2 should not be the same
251   if ( aNodes[ i1 ] == aNodes[ i2 ] )
252     return false;
253
254
255   // theTria1: A->2
256   aNodes[ iA ] = aNodes[ i2 ];
257   // theTria2: B->1
258   aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
259
260   //MESSAGE( theTria1 << theTria2 );
261
262   GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
263   GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
264
265   //MESSAGE( theTria1 << theTria2 );
266
267   return true;
268 }
269
270 //=======================================================================
271 //function : findTriangles
272 //purpose  : find triangles sharing theNode1-theNode2 link
273 //=======================================================================
274
275 static bool findTriangles(const SMDS_MeshNode *    theNode1,
276                           const SMDS_MeshNode *    theNode2,
277                           const SMDS_MeshElement*& theTria1,
278                           const SMDS_MeshElement*& theTria2)
279 {
280   if ( !theNode1 || !theNode2 ) return false;
281
282   theTria1 = theTria2 = 0;
283
284   set< const SMDS_MeshElement* > emap;
285   SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
286   while (it->more()) {
287     const SMDS_MeshElement* elem = it->next();
288     if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
289       emap.insert( elem );
290   }
291   it = theNode2->GetInverseElementIterator();
292   while (it->more()) {
293     const SMDS_MeshElement* elem = it->next();
294     if ( elem->GetType() == SMDSAbs_Face &&
295          emap.find( elem ) != emap.end() )
296       if ( theTria1 ) {
297         theTria2 = elem;
298         break;
299       } else {
300         theTria1 = elem;
301       }
302   }
303   return ( theTria1 && theTria2 );
304 }
305
306 //=======================================================================
307 //function : InverseDiag
308 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
309 //           with ones built on the same 4 nodes but having other common link.
310 //           Return false if proper faces not found
311 //=======================================================================
312
313 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
314                                     const SMDS_MeshNode * theNode2)
315 {
316   MESSAGE( "::InverseDiag()" );
317
318   const SMDS_MeshElement *tr1, *tr2;
319   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
320     return false;
321
322   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
323   if (!F1) return false;
324   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
325   if (!F2) return false;
326
327   //  1 +--+ A  tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
328   //    | /|    tr2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |  
329   //    |/ |                                    | \|  
330   //  B +--+ 2                                B +--+ 2
331
332   // put nodes in array
333   // and find indices of 1,2 and of A in tr1 and of B in tr2
334   int i, iA1 = 0, i1 = 0;
335   const SMDS_MeshNode* aNodes1 [3];
336   SMDS_ElemIteratorPtr it;
337   for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
338     aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
339     if ( aNodes1[ i ] == theNode1 )
340       iA1 = i; // node A in tr1
341     else if ( aNodes1[ i ] != theNode2 )
342       i1 = i;  // node 1
343   }
344   int iB2 = 0, i2 = 0;
345   const SMDS_MeshNode* aNodes2 [3];
346   for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
347     aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
348     if ( aNodes2[ i ] == theNode2 )
349       iB2 = i; // node B in tr2
350     else if ( aNodes2[ i ] != theNode1 )
351       i2 = i;  // node 2
352   }
353
354   // nodes 1 and 2 should not be the same
355   if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
356     return false;
357
358   // tr1: A->2
359   aNodes1[ iA1 ] = aNodes2[ i2 ];
360   // tr2: B->1
361   aNodes2[ iB2 ] = aNodes1[ i1 ];
362
363   //MESSAGE( tr1 << tr2 );
364
365   GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
366   GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
367
368   //MESSAGE( tr1 << tr2 );
369
370   return true;
371   
372 }
373
374 //=======================================================================
375 //function : getQuadrangleNodes
376 //purpose  : fill theQuadNodes - nodes of a quadrangle resulting from
377 //           fusion of triangles tr1 and tr2 having shared link on
378 //           theNode1 and theNode2
379 //=======================================================================
380
381 bool getQuadrangleNodes(const SMDS_MeshNode *    theQuadNodes [],
382                         const SMDS_MeshNode *    theNode1,
383                         const SMDS_MeshNode *    theNode2,
384                         const SMDS_MeshElement * tr1,
385                         const SMDS_MeshElement * tr2 )
386 {
387   // find the 4-th node to insert into tr1
388   const SMDS_MeshNode* n4 = 0;
389   SMDS_ElemIteratorPtr it = tr2->nodesIterator();
390   while ( !n4 && it->more() )
391   {
392     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
393     bool isDiag = ( n == theNode1 || n == theNode2 );
394     if ( !isDiag )
395       n4 = n;
396   }
397   // Make an array of nodes to be in a quadrangle
398   int iNode = 0, iFirstDiag = -1;
399   it = tr1->nodesIterator();
400   while ( it->more() )
401   {
402     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
403     bool isDiag = ( n == theNode1 || n == theNode2 );
404     if ( isDiag )
405     {
406       if ( iFirstDiag < 0 )
407         iFirstDiag = iNode;
408       else if ( iNode - iFirstDiag == 1 )
409         theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
410     }
411     else if ( n == n4 )
412     {
413       return false; // tr1 and tr2 should not have all the same nodes
414     }
415     theQuadNodes[ iNode++ ] = n;
416   }
417   if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
418     theQuadNodes[ iNode ] = n4;
419
420   return true;
421 }
422
423 //=======================================================================
424 //function : DeleteDiag
425 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
426 //           with a quadrangle built on the same 4 nodes.
427 //           Return false if proper faces not found
428 //=======================================================================
429
430 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
431                                    const SMDS_MeshNode * theNode2)
432 {
433   MESSAGE( "::DeleteDiag()" );
434
435   const SMDS_MeshElement *tr1, *tr2;
436   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
437     return false;
438
439   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
440   if (!F1) return false;
441   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
442   if (!F2) return false;
443
444   const SMDS_MeshNode* aNodes [ 4 ];
445   if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
446     return false;
447
448   //MESSAGE( endl << tr1 << tr2 );
449
450   GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
451   GetMeshDS()->RemoveElement( tr2 );
452
453   //MESSAGE( endl << tr1 );
454
455   return true;
456 }
457
458 //=======================================================================
459 //function : Reorient
460 //purpose  : Reverse the normal of theFace
461 //           Return false if theFace is null
462 //=======================================================================
463
464 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theFace)
465 {
466   if (!theFace) return false;
467   const SMDS_FaceOfNodes* F = dynamic_cast<const SMDS_FaceOfNodes*>( theFace );
468   if (!F) return false;
469
470   const SMDS_MeshNode* aNodes [4], *tmpNode;
471   int i = 0;
472   SMDS_ElemIteratorPtr it = theFace->nodesIterator();
473   while ( it->more() )
474     aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( it->next() );
475
476   // exchange nodes with indeces 0 and 2
477   tmpNode = aNodes[ 0 ];
478   aNodes[ 0 ] = aNodes[ 2 ];
479   aNodes[ 2 ] = tmpNode;
480
481   //MESSAGE( theFace );
482
483   GetMeshDS()->ChangeElementNodes( theFace, aNodes, theFace->NbNodes() );
484
485   //MESSAGE( theFace );
486
487   return true;
488 }
489
490 //=======================================================================
491 //function : getBadRate
492 //purpose  : 
493 //=======================================================================
494
495 static double getBadRate (const SMDS_MeshElement*               theElem,
496                           SMESH::Controls::NumericalFunctorPtr& theCrit)
497 {
498   TSequenceOfXYZ P;
499   if ( !theElem || !theCrit->GetPoints( theElem, P ))
500     return 1e100;
501   return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
502 }
503   
504 //=======================================================================
505 //function : QuadToTri
506 //purpose  : Cut quadrangles into triangles.
507 //           theCrit is used to select a diagonal to cut
508 //=======================================================================
509
510 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> &       theElems,
511                                   SMESH::Controls::NumericalFunctorPtr theCrit)
512 {
513   MESSAGE( "::QuadToTri()" );
514
515   if ( !theCrit.get() )
516     return false;
517
518   SMESHDS_Mesh * aMesh = GetMeshDS();
519
520   set< const SMDS_MeshElement * >::iterator itElem;
521   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
522   {
523     const SMDS_MeshElement* elem = (*itElem);
524     if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
525       continue;
526
527     // retrieve element nodes
528     const SMDS_MeshNode* aNodes [4];
529     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
530     int i = 0;
531     while ( itN->more() )
532       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
533
534     // compare two sets of possible triangles
535     double aBadRate1, aBadRate2; // to what extent a set is bad
536     SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
537     SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
538     aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
539       
540     SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
541     SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
542     aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
543
544     int aShapeId = FindShape( elem );
545     //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
546       //      << " ShapeID = " << aShapeId << endl << elem );
547     
548     if ( aBadRate1 <= aBadRate2 ) {
549       // tr1 + tr2 is better
550       aMesh->ChangeElementNodes( elem, aNodes, 3 );
551       //MESSAGE( endl << elem );
552
553       elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
554     }
555     else {
556       // tr3 + tr4 is better
557       aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
558       //MESSAGE( endl << elem );
559
560       elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
561     }
562     //MESSAGE( endl << elem );
563
564     // put a new triangle on the same shape
565     if ( aShapeId )
566       aMesh->SetMeshElementOnShape( elem, aShapeId );
567   }
568
569   return true;
570 }
571
572 //=======================================================================
573 //function : addToSameGroups
574 //purpose  : add elemToAdd to the groups the elemInGroups belongs to
575 //=======================================================================
576
577 static void addToSameGroups (const SMDS_MeshElement* elemToAdd,
578                              const SMDS_MeshElement* elemInGroups,
579                              SMESHDS_Mesh *          aMesh)
580 {
581   const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
582   set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
583   for ( ; grIt != groups.end(); grIt++ ) {
584     SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
585     if ( group && group->SMDSGroup().Contains( elemInGroups ))
586       group->SMDSGroup().Add( elemToAdd );
587   }
588 }
589
590 //=======================================================================
591 //function : QuadToTri
592 //purpose  : Cut quadrangles into triangles.
593 //           theCrit is used to select a diagonal to cut
594 //=======================================================================
595
596 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
597                                   const bool                          the13Diag)
598 {
599   MESSAGE( "::QuadToTri()" );
600
601   SMESHDS_Mesh * aMesh = GetMeshDS();
602
603   set< const SMDS_MeshElement * >::iterator itElem;
604   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
605   {
606     const SMDS_MeshElement* elem = (*itElem);
607     if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
608       continue;
609
610     // retrieve element nodes
611     const SMDS_MeshNode* aNodes [4];
612     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
613     int i = 0;
614     while ( itN->more() )
615       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
616
617     int aShapeId = FindShape( elem );
618     const SMDS_MeshElement* newElem = 0;
619     if ( the13Diag )
620     {
621       aMesh->ChangeElementNodes( elem, aNodes, 3 );
622       newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
623     }
624     else
625     {
626       aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
627       newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
628     }
629
630     // put a new triangle on the same shape and add to the same groups
631
632     if ( aShapeId )
633       aMesh->SetMeshElementOnShape( newElem, aShapeId );
634
635     addToSameGroups( newElem, elem, aMesh );
636   }
637
638   return true;
639 }
640
641 //=======================================================================
642 //function : getAngle
643 //purpose  : 
644 //=======================================================================
645
646 double getAngle(const SMDS_MeshElement * tr1,
647                 const SMDS_MeshElement * tr2,
648                 const SMDS_MeshNode *    n1,
649                 const SMDS_MeshNode *    n2)
650 {
651   double angle = 2*PI; // bad angle
652
653   // get normals
654   TSequenceOfXYZ P1, P2;
655   if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
656        !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
657     return angle;
658   gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
659   if ( N1.SquareMagnitude() <= gp::Resolution() )
660     return angle;
661   gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
662   if ( N2.SquareMagnitude() <= gp::Resolution() )
663     return angle;
664   
665   // find the first diagonal node n1 in the triangles:
666   // take in account a diagonal link orientation
667   const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
668   for ( int t = 0; t < 2; t++ )
669   {
670     SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
671     int i = 0, iDiag = -1;
672     while ( it->more()) {
673       const SMDS_MeshElement *n = it->next();
674       if ( n == n1 || n == n2 )
675         if ( iDiag < 0)
676           iDiag = i;
677         else {
678           if ( i - iDiag == 1 )
679             nFirst[ t ] = ( n == n1 ? n2 : n1 );
680           else
681             nFirst[ t ] = n;
682           break;
683         }
684       i++;
685     }
686   }
687   if ( nFirst[ 0 ] == nFirst[ 1 ] )
688     N2.Reverse();
689
690   angle = N1.Angle( N2 );
691   //SCRUTE( angle );
692   return angle;
693 }
694
695 // =================================================
696 // class generating a unique ID for a pair of nodes
697 // and able to return nodes by that ID
698 // =================================================
699
700 class LinkID_Gen {
701  public:
702
703   LinkID_Gen( const SMESHDS_Mesh* theMesh )
704     :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
705   {}
706
707   long GetLinkID (const SMDS_MeshNode * n1,
708                   const SMDS_MeshNode * n2) const
709   {
710     return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
711   }
712
713   bool GetNodes (const long             theLinkID,
714                  const SMDS_MeshNode* & theNode1,
715                  const SMDS_MeshNode* & theNode2) const
716   {
717     theNode1 = myMesh->FindNode( theLinkID / myMaxID );
718     if ( !theNode1 ) return false;
719     theNode2 = myMesh->FindNode( theLinkID % myMaxID );
720     if ( !theNode2 ) return false;
721     return true;
722   }
723
724  private:
725   LinkID_Gen();
726   const SMESHDS_Mesh* myMesh;
727   long                myMaxID;
728 };
729
730 //=======================================================================
731 //function : TriToQuad
732 //purpose  : Fuse neighbour triangles into quadrangles.
733 //           theCrit is used to select a neighbour to fuse with.
734 //           theMaxAngle is a max angle between element normals at which
735 //           fusion is still performed.
736 //=======================================================================
737
738 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> &       theElems,
739                                   SMESH::Controls::NumericalFunctorPtr theCrit,
740                                   const double                         theMaxAngle)
741 {
742   MESSAGE( "::TriToQuad()" );
743
744   if ( !theCrit.get() )
745     return false;
746
747   SMESHDS_Mesh * aMesh = GetMeshDS();
748   LinkID_Gen aLinkID_Gen( aMesh );
749
750
751   // Prepare data for algo: build
752   // 1. map of elements with their linkIDs
753   // 2. map of linkIDs with their elements
754
755   map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
756   map< long, list< const SMDS_MeshElement* > >::iterator itLE;
757   map< const SMDS_MeshElement*, set< long > >  mapEl_setLi;
758   map< const SMDS_MeshElement*, set< long > >::iterator itEL;
759
760   set<const SMDS_MeshElement*>::iterator itElem;
761   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
762   {
763     const SMDS_MeshElement* elem = (*itElem);
764     if ( !elem || elem->NbNodes() != 3 )
765       continue;
766
767     // retrieve element nodes
768     const SMDS_MeshNode* aNodes [4];
769     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
770     int i = 0;
771     while ( itN->more() )
772       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
773     ASSERT( i == 3 );
774     aNodes[ 3 ] = aNodes[ 0 ];
775
776     // fill maps
777     for ( i = 0; i < 3; i++ )
778     {
779       long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
780       // check if elements sharing a link can be fused
781       itLE = mapLi_listEl.find( linkID );
782       if ( itLE != mapLi_listEl.end() )
783       {
784         if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link 
785           continue;
786         const SMDS_MeshElement* elem2 = (*itLE).second.front();
787 //         if ( FindShape( elem ) != FindShape( elem2 ))
788 //           continue; // do not fuse triangles laying on different shapes
789         if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
790           continue; // avoid making badly shaped quads
791         (*itLE).second.push_back( elem );
792       }
793       else
794         mapLi_listEl[ linkID ].push_back( elem );
795       mapEl_setLi [ elem ].insert( linkID );
796     }
797   }
798   // Clean the maps from the links shared by a sole element, ie
799   // links to which only one element is bound in mapLi_listEl
800
801   for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
802   {
803     int nbElems = (*itLE).second.size();
804     if ( nbElems < 2  ) {
805       const SMDS_MeshElement* elem = (*itLE).second.front();
806       long link = (*itLE).first;
807       mapEl_setLi[ elem ].erase( link );
808       if ( mapEl_setLi[ elem ].empty() )
809         mapEl_setLi.erase( elem );
810     }
811   }
812
813   // Algo: fuse triangles into quadrangles
814   
815   while ( ! mapEl_setLi.empty() )
816   {
817     // Look for the start element:
818     // the element having the least nb of shared links
819
820     const SMDS_MeshElement* startElem = 0;
821     int minNbLinks = 4;
822     for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
823     {
824       int nbLinks = (*itEL).second.size();
825       if ( nbLinks < minNbLinks )
826       {
827         startElem = (*itEL).first;
828         minNbLinks = nbLinks;
829         if ( minNbLinks == 1 )
830           break;
831       }
832     }
833
834     // search elements to fuse starting from startElem or links of elements
835     // fused earlyer - startLinks
836     list< long > startLinks;
837     while ( startElem || !startLinks.empty() )
838     {
839       while ( !startElem && !startLinks.empty() )
840       {
841         // Get an element to start, by a link
842         long linkId = startLinks.front();
843         startLinks.pop_front();
844         itLE = mapLi_listEl.find( linkId );
845         if ( itLE != mapLi_listEl.end() )
846         {
847           list< const SMDS_MeshElement* > & listElem = (*itLE).second;
848           list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
849           for ( ; itE != listElem.end() ; itE++ )
850             if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
851               startElem = (*itE);
852           mapLi_listEl.erase( itLE );
853         }
854       }
855
856       if ( startElem )
857       {
858         // Get candidates to be fused
859
860         const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
861         long link12, link13;
862         startElem = 0;
863         ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
864         set< long >& setLi = mapEl_setLi[ tr1 ];
865         ASSERT( !setLi.empty() );
866         set< long >::iterator itLi;
867         for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
868         {
869           long linkID = (*itLi);
870           itLE = mapLi_listEl.find( linkID );
871           if ( itLE == mapLi_listEl.end() )
872             continue;
873           const SMDS_MeshElement* elem = (*itLE).second.front();
874           if ( elem == tr1 )
875             elem = (*itLE).second.back();
876           mapLi_listEl.erase( itLE );
877           if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
878             continue;
879           if ( tr2 )
880           {
881             tr3 = elem;
882             link13 = linkID;
883           }
884           else
885           {
886             tr2 = elem;
887             link12 = linkID;
888           }
889
890           // add other links of elem to list of links to re-start from
891           set< long >& links = mapEl_setLi[ elem ];
892           set< long >::iterator it;
893           for ( it = links.begin(); it != links.end(); it++ )
894           {
895             long linkID2 = (*it);
896             if ( linkID2 != linkID )
897               startLinks.push_back( linkID2 );
898           }
899         }
900
901         // Get nodes of possible quadrangles
902
903         const SMDS_MeshNode *n12 [4], *n13 [4];
904         bool Ok12 = false, Ok13 = false;
905         const SMDS_MeshNode *linkNode1, *linkNode2;
906         if ( tr2 &&
907              aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
908              getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
909           Ok12 = true;
910         if ( tr3 &&
911              aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
912              getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
913           Ok13 = true;
914
915         // Choose a pair to fuse
916
917         if ( Ok12 && Ok13 )
918         {
919           SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
920           SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
921           double aBadRate12 = getBadRate( &quad12, theCrit );
922           double aBadRate13 = getBadRate( &quad13, theCrit );
923           if (  aBadRate13 < aBadRate12 )
924             Ok12 = false;
925           else
926             Ok13 = false;
927         }
928
929
930         // Make quadrangles
931         // and remove fused elems and removed links from the maps
932
933         mapEl_setLi.erase( tr1 );
934         if ( Ok12 )
935         {
936           mapEl_setLi.erase( tr2 );
937           mapLi_listEl.erase( link12 );
938           aMesh->ChangeElementNodes( tr1, n12, 4 );
939           aMesh->RemoveElement( tr2 );
940         }
941         else if ( Ok13 )
942         {
943           mapEl_setLi.erase( tr3 );
944           mapLi_listEl.erase( link13 );
945           aMesh->ChangeElementNodes( tr1, n13, 4 );
946           aMesh->RemoveElement( tr3 );
947         }
948
949         // Next element to fuse: the rejected one
950         if ( tr3 )
951           startElem = Ok12 ? tr3 : tr2;
952
953       } // if ( startElem )
954     } // while ( startElem || !startLinks.empty() )
955   } // while ( ! mapEl_setLi.empty() )
956     
957   return true;
958 }
959
960
961 #define DUMPSO(txt) \
962 //  cout << txt << endl;
963 //=============================================================================
964 /*!
965  *
966  */
967 //=============================================================================
968 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
969 {
970   if ( i1 == i2 )
971     return;
972   int tmp = idNodes[ i1 ];
973   idNodes[ i1 ] = idNodes[ i2 ];
974   idNodes[ i2 ] = tmp;
975   gp_Pnt Ptmp = P[ i1 ];
976   P[ i1 ] = P[ i2 ];
977   P[ i2 ] = Ptmp;
978   DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
979 }
980
981 //=======================================================================
982 //function : SortQuadNodes
983 //purpose  : Set 4 nodes of a quadrangle face in a good order.
984 //           Swap 1<->2 or 2<->3 nodes and correspondingly return
985 //           1 or 2 else 0.
986 //=======================================================================
987
988 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
989                                      int               idNodes[] )
990 {
991   gp_Pnt P[4];
992   int i;
993   for ( i = 0; i < 4; i++ ) {
994     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
995     if ( !n ) return 0;
996     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
997   }
998
999   gp_Vec V1(P[0], P[1]);
1000   gp_Vec V2(P[0], P[2]);
1001   gp_Vec V3(P[0], P[3]);
1002
1003   gp_Vec Cross1 = V1 ^ V2;
1004   gp_Vec Cross2 = V2 ^ V3;
1005
1006   i = 0;
1007   if (Cross1.Dot(Cross2) < 0)
1008   {
1009     Cross1 = V2 ^ V1;
1010     Cross2 = V1 ^ V3;
1011
1012     if (Cross1.Dot(Cross2) < 0)
1013       i = 2;
1014     else
1015       i = 1;
1016     swap ( i, i + 1, idNodes, P );
1017
1018 //     for ( int ii = 0; ii < 4; ii++ ) {
1019 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1020 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1021 //     }
1022   }
1023   return i;
1024 }
1025
1026 //=======================================================================
1027 //function : SortHexaNodes
1028 //purpose  : Set 8 nodes of a hexahedron in a good order.
1029 //           Return success status
1030 //=======================================================================
1031
1032 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1033                                       int               idNodes[] )
1034 {
1035   gp_Pnt P[8];
1036   int i;
1037   DUMPSO( "INPUT: ========================================");
1038   for ( i = 0; i < 8; i++ ) {
1039     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1040     if ( !n ) return false;
1041     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1042     DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1043   }
1044   DUMPSO( "========================================");
1045
1046   
1047   set<int> faceNodes;  // ids of bottom face nodes, to be found
1048   set<int> checkedId1; // ids of tried 2-nd nodes
1049   Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1050   const Standard_Real tol = 1.e-6;   // tolerance to find nodes in plane
1051   int iMin, iLoop1 = 0;
1052
1053   // Loop to try the 2-nd nodes
1054
1055   while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1056   {
1057     // Find not checked 2-nd node
1058     for ( i = 1; i < 8; i++ )
1059       if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1060         int id1 = idNodes[i];
1061         swap ( 1, i, idNodes, P );
1062         checkedId1.insert ( id1 );
1063         break;
1064       }
1065   
1066     // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1067     // ie that all but meybe one (id3 which is on the same face) nodes
1068     // lay on the same side from the triangle plane.
1069
1070     bool manyInPlane = false; // more than 4 nodes lay in plane
1071     int iLoop2 = 0;
1072     while ( ++iLoop2 < 6 ) {
1073
1074       // get 1-2-3 plane coeffs
1075       Standard_Real A, B, C, D;
1076       gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1077       if ( N.SquareMagnitude() > gp::Resolution() )
1078       {
1079         gp_Pln pln ( P[0], N );
1080         pln.Coefficients( A, B, C, D );
1081
1082         // find the node (iMin) closest to pln
1083         Standard_Real dist[ 8 ], minDist = DBL_MAX;
1084         set<int> idInPln;
1085         for ( i = 3; i < 8; i++ ) {
1086           dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1087           if ( fabs( dist[i] ) < minDist ) {
1088             minDist = fabs( dist[i] );
1089             iMin = i;
1090           }
1091           if ( fabs( dist[i] ) <= tol )
1092             idInPln.insert( idNodes[i] );
1093         }
1094
1095         // there should not be more than 4 nodes in bottom plane
1096         if ( idInPln.size() > 1 )
1097         {
1098           DUMPSO( "### idInPln.size() = " << idInPln.size());
1099           // idInPlane does not contain the first 3 nodes
1100           if ( manyInPlane || idInPln.size() == 5)
1101             return false; // all nodes in one plane
1102           manyInPlane = true;
1103
1104           // set the 1-st node to be not in plane
1105           for ( i = 3; i < 8; i++ ) {
1106             if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1107               DUMPSO( "### Reset 0-th node");
1108               swap( 0, i, idNodes, P );
1109               break;
1110             }
1111           }
1112
1113           // reset to re-check second nodes
1114           leastDist = DBL_MAX;
1115           faceNodes.clear();
1116           checkedId1.clear();
1117           iLoop1 = 0;
1118           break; // from iLoop2;
1119         }
1120
1121         // check that the other 4 nodes are on the same side
1122         bool sameSide = true;
1123         bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1124         for ( i = 3; sameSide && i < 8; i++ ) {
1125           if ( i != iMin )
1126             sameSide = ( isNeg == dist[i] <= 0.);
1127         }
1128
1129         // keep best solution
1130         if ( sameSide && minDist < leastDist ) {
1131           leastDist = minDist;
1132           faceNodes.clear();
1133           faceNodes.insert( idNodes[ 1 ] );
1134           faceNodes.insert( idNodes[ 2 ] );
1135           faceNodes.insert( idNodes[ iMin ] );
1136           DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1137             << " leastDist = " << leastDist);
1138           if ( leastDist <= DBL_MIN )
1139             break;
1140         }
1141       }
1142
1143       // set next 3-d node to check
1144       int iNext = 2 + iLoop2;
1145       if ( iNext < 8 ) {
1146         DUMPSO( "Try 2-nd");
1147         swap ( 2, iNext, idNodes, P );
1148       }
1149     } // while ( iLoop2 < 6 )
1150   } // iLoop1
1151
1152   if ( faceNodes.empty() ) return false;
1153
1154   // Put the faceNodes in proper places
1155   for ( i = 4; i < 8; i++ ) {
1156     if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1157       // find a place to put
1158       int iTo = 1;
1159       while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1160         iTo++;
1161       DUMPSO( "Set faceNodes");
1162       swap ( iTo, i, idNodes, P );
1163     }
1164   }
1165
1166     
1167   // Set nodes of the found bottom face in good order
1168   DUMPSO( " Found bottom face: ");
1169   i = SortQuadNodes( theMesh, idNodes );
1170   if ( i ) {
1171     gp_Pnt Ptmp = P[ i ];
1172     P[ i ] = P[ i+1 ];
1173     P[ i+1 ] = Ptmp;
1174   }
1175 //   else
1176 //     for ( int ii = 0; ii < 4; ii++ ) {
1177 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1178 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1179 //    }
1180
1181   // Gravity center of the top and bottom faces
1182   gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1183   gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1184
1185   // Get direction from the bottom to the top face
1186   gp_Vec upDir ( aGCb, aGCt );
1187   Standard_Real upDirSize = upDir.Magnitude();
1188   if ( upDirSize <= gp::Resolution() ) return false;
1189   upDir / upDirSize;
1190   
1191   // Assure that the bottom face normal points up
1192   gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1193   Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1194   if ( Nb.Dot( upDir ) < 0 ) {
1195     DUMPSO( "Reverse bottom face");
1196     swap( 1, 3, idNodes, P );
1197   }
1198
1199   // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1200   Standard_Real minDist = DBL_MAX;
1201   for ( i = 4; i < 8; i++ ) {
1202     // projection of P[i] to the plane defined by P[0] and upDir
1203     gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1204     Standard_Real sqDist = P[0].SquareDistance( Pp );
1205     if ( sqDist < minDist ) {
1206       minDist = sqDist;
1207       iMin = i;
1208     }
1209   }
1210   DUMPSO( "Set 4-th");
1211   swap ( 4, iMin, idNodes, P );
1212
1213   // Set nodes of the top face in good order
1214   DUMPSO( "Sort top face");
1215   i = SortQuadNodes( theMesh, &idNodes[4] );
1216   if ( i ) {
1217     i += 4;
1218     gp_Pnt Ptmp = P[ i ];
1219     P[ i ] = P[ i+1 ];
1220     P[ i+1 ] = Ptmp;
1221   }
1222
1223   // Assure that direction of the top face normal is from the bottom face
1224   gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1225   Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1226   if ( Nt.Dot( upDir ) < 0 ) {
1227     DUMPSO( "Reverse top face");
1228     swap( 5, 7, idNodes, P );
1229   }
1230
1231 //   DUMPSO( "OUTPUT: ========================================");
1232 //   for ( i = 0; i < 8; i++ ) {
1233 //     float *p = ugrid->GetPoint(idNodes[i]);
1234 //     DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1235 //   }
1236
1237   return true;
1238 }
1239
1240 //=======================================================================
1241 //function : laplacianSmooth
1242 //purpose  : pulls theNode toward the center of surrounding nodes directly
1243 //           connected to that node along an element edge
1244 //=======================================================================
1245
1246 void laplacianSmooth(SMESHDS_Mesh *                       theMesh,
1247                      const SMDS_MeshNode*                 theNode,
1248                      const set<const SMDS_MeshElement*> & theElems,
1249                      const set<const SMDS_MeshNode*> &    theFixedNodes)
1250 {
1251   // find surrounding nodes
1252   set< const SMDS_MeshNode* > nodeSet;
1253   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1254   while ( elemIt->more() )
1255   {
1256     const SMDS_MeshElement* elem = elemIt->next();
1257     if ( theElems.find( elem ) == theElems.end() )
1258       continue;
1259
1260     int i = 0, iNode = 0;
1261     const SMDS_MeshNode* aNodes [4];
1262     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1263     while ( itN->more() )
1264     {
1265       aNodes[ i ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1266       if ( aNodes[ i ] == theNode )
1267         iNode = i;
1268       else
1269         nodeSet.insert( aNodes[ i ] );
1270       i++;
1271     }
1272     if ( elem->NbNodes() == 4 ) { // remove an opposite node
1273       iNode += ( iNode < 2 ) ? 2 : -2;
1274       nodeSet.erase( aNodes[ iNode ]);
1275     }
1276   }
1277
1278   // compute new coodrs
1279   double coord[] = { 0., 0., 0. };
1280   set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1281   for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1282     const SMDS_MeshNode* node = (*nodeSetIt);
1283     coord[0] += node->X();
1284     coord[1] += node->Y();
1285     coord[2] += node->Z();
1286   }
1287   double nbNodes = nodeSet.size();
1288   theMesh->MoveNode (theNode,
1289                      coord[0]/nbNodes,
1290                      coord[1]/nbNodes,
1291                      coord[2]/nbNodes);
1292 }
1293
1294 //=======================================================================
1295 //function : centroidalSmooth
1296 //purpose  : pulls theNode toward the element-area-weighted centroid of the
1297 //           surrounding elements
1298 //=======================================================================
1299
1300 void centroidalSmooth(SMESHDS_Mesh *                       theMesh,
1301                       const SMDS_MeshNode*                 theNode,
1302                       const set<const SMDS_MeshElement*> & theElems,
1303                       const set<const SMDS_MeshNode*> &    theFixedNodes)
1304 {
1305   gp_XYZ aNewXYZ(0.,0.,0.);
1306   SMESH::Controls::Area anAreaFunc;
1307   double totalArea = 0.;
1308   int nbElems = 0;
1309
1310   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1311   while ( elemIt->more() )
1312   {
1313     const SMDS_MeshElement* elem = elemIt->next();
1314     if ( theElems.find( elem ) == theElems.end() )
1315       continue;
1316
1317     nbElems++;
1318
1319     gp_XYZ elemCenter(0.,0.,0.);
1320     TSequenceOfXYZ aNodePoints;
1321     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1322     while ( itN->more() )
1323     {
1324       const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1325       gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1326       aNodePoints.push_back( aP );
1327       elemCenter += aP;
1328     }
1329     double elemArea = anAreaFunc.GetValue( aNodePoints );
1330     totalArea += elemArea;
1331     elemCenter /= elem->NbNodes();
1332     aNewXYZ += elemCenter * elemArea;
1333   }
1334   aNewXYZ /= totalArea;
1335   theMesh->MoveNode (theNode,
1336                      aNewXYZ.X(),
1337                      aNewXYZ.Y(),
1338                      aNewXYZ.Z());
1339 }
1340
1341 //=======================================================================
1342 //function : Smooth
1343 //purpose  : Smooth theElements during theNbIterations or until a worst
1344 //           element has aspect ratio <= theTgtAspectRatio.
1345 //           Aspect Ratio varies in range [1.0, inf].
1346 //           If theElements is empty, the whole mesh is smoothed.
1347 //           theFixedNodes contains additionally fixed nodes. Nodes built
1348 //           on edges and boundary nodes are always fixed.
1349 //=======================================================================
1350
1351 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1352                                set<const SMDS_MeshNode*> &    theFixedNodes,
1353                                const SmoothMethod             theSmoothMethod,
1354                                const int                      theNbIterations,
1355                                double                         theTgtAspectRatio)
1356 {
1357   MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1358
1359   SMESHDS_Mesh* aMesh = GetMeshDS();
1360   if ( theElems.empty() ) {
1361     // add all faces
1362     SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1363     while ( fIt->more() )
1364       theElems.insert( fIt->next() );
1365   }
1366
1367   set<const SMDS_MeshNode*> setMovableNodes;
1368
1369   // Fill setMovableNodes
1370
1371   map< const SMDS_MeshNode*, int > mapNodeNbFaces;
1372   set< const SMDS_MeshElement* >::iterator itElem;
1373   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1374   {
1375     const SMDS_MeshElement* elem = (*itElem);
1376     if ( !elem || elem->GetType() != SMDSAbs_Face )
1377       continue;
1378
1379     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1380     while ( itN->more() ) {
1381       const SMDS_MeshNode* node =
1382         static_cast<const SMDS_MeshNode*>( itN->next() );
1383
1384       if ( theFixedNodes.find( node ) != theFixedNodes.end() )
1385         continue;
1386
1387       // if node is on edge => it is fixed
1388       SMDS_PositionPtr aPositionPtr = node->GetPosition();
1389       if ( aPositionPtr.get() &&
1390           (aPositionPtr->GetTypeOfPosition() == SMDS_TOP_EDGE ||
1391            aPositionPtr->GetTypeOfPosition() == SMDS_TOP_VERTEX)) {
1392         theFixedNodes.insert( node );
1393         continue;
1394       }
1395       // fill mapNodeNbFaces in order to detect fixed boundary nodes
1396       map<const SMDS_MeshNode*,int>::iterator nodeNbFacesIt =
1397         mapNodeNbFaces.find ( node );
1398       if ( nodeNbFacesIt == mapNodeNbFaces.end() )
1399         mapNodeNbFaces.insert( map<const SMDS_MeshNode*,int>::value_type( node, 1 ));
1400       else
1401         (*nodeNbFacesIt).second++;
1402     }
1403   }
1404   // put not fixed nodes in setMovableNodes
1405   map<const SMDS_MeshNode*,int>::iterator nodeNbFacesIt =
1406     mapNodeNbFaces.begin();
1407   for ( ; nodeNbFacesIt != mapNodeNbFaces.end(); nodeNbFacesIt++ ) {
1408     const SMDS_MeshNode* node = (*nodeNbFacesIt).first;
1409     // a node is on free boundary if it is shared by 1-2 faces
1410     if ( (*nodeNbFacesIt).second > 2 )
1411       setMovableNodes.insert( node );
1412     else
1413       theFixedNodes.insert( node );
1414   }
1415
1416   // SMOOTHING //
1417
1418   if ( theTgtAspectRatio < 1.0 )
1419     theTgtAspectRatio = 1.0;
1420
1421   SMESH::Controls::AspectRatio aQualityFunc;
1422
1423   for ( int it = 0; it < theNbIterations; it++ )
1424   {
1425     Standard_Real maxDisplacement = 0.;
1426     set<const SMDS_MeshNode*>::iterator movableNodesIt
1427       = setMovableNodes.begin();
1428     for ( ; movableNodesIt != setMovableNodes.end(); movableNodesIt++ )
1429     {
1430       const SMDS_MeshNode* node = (*movableNodesIt);
1431       gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1432
1433       // smooth
1434       if ( theSmoothMethod == LAPLACIAN )
1435         laplacianSmooth( aMesh, node, theElems, theFixedNodes );
1436       else
1437         centroidalSmooth( aMesh, node, theElems, theFixedNodes );
1438
1439       // displacement
1440       gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1441       Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1442       if ( aDispl > maxDisplacement )
1443         maxDisplacement = aDispl;
1444     }
1445     // no node movement => exit
1446     if ( maxDisplacement < 1.e-16 ) {
1447       MESSAGE("-- no node movement -- maxDisplacement: " << maxDisplacement << " it "<< it);
1448       break;
1449     }
1450
1451     // check elements quality
1452     double maxRatio  = 0;
1453     for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1454     {
1455       const SMDS_MeshElement* elem = (*itElem);
1456       if ( !elem || elem->GetType() != SMDSAbs_Face )
1457         continue;
1458       TSequenceOfXYZ aPoints;
1459       if ( aQualityFunc.GetPoints( elem, aPoints )) {
1460         double aValue = aQualityFunc.GetValue( aPoints );
1461         if ( aValue > maxRatio )
1462           maxRatio = aValue;
1463       }
1464     }
1465     if ( maxRatio <= theTgtAspectRatio ) {
1466       MESSAGE("-- quality achived -- maxRatio " << maxRatio << " it "<< it);
1467       break;
1468     }
1469     if (it+1 == theNbIterations) {
1470       MESSAGE("-- Iteration limit exceeded --");
1471     }
1472   }
1473 }
1474
1475 //=======================================================================
1476 //function : isReverse
1477 //purpose  : 
1478 //=======================================================================
1479
1480 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1481                       const SMDS_MeshNode* nextNodes[],
1482                       const int            nbNodes,
1483                       const int            iNotSame)
1484 {
1485   int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1486   int iAfterNotSame  = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1487
1488   const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1489   const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1490   const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1491   const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1492
1493   gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1494   gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1495   gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1496   gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1497
1498   gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1499
1500   return (vA ^ vB) * vN < 0.0;
1501 }
1502
1503 //=======================================================================
1504 //function : sweepElement
1505 //purpose  : 
1506 //=======================================================================
1507
1508 static void sweepElement(SMESHDS_Mesh*              aMesh,
1509                          const SMDS_MeshElement*    elem,
1510                          const TNodeOfNodeListMap&  mapNewNodes )
1511 {
1512   // Loop on elem nodes:
1513   // find new nodes and detect same nodes indices
1514   list<const SMDS_MeshNode*>::const_iterator itNN[ 4 ];
1515   const SMDS_MeshNode* prevNod[ 4 ], *nextNod[ 4 ];
1516   int nbSame = 0, iNotSameNode = 0, iSameNode = 0;
1517
1518   TNodeOfNodeListMap::const_iterator mapIt;
1519   int iNode = 0;
1520   SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1521   while ( itN->more() )
1522   {
1523     const SMDS_MeshNode* node =
1524       static_cast<const SMDS_MeshNode*>( itN->next() );
1525     mapIt = mapNewNodes.find( node );
1526     if ( mapIt == mapNewNodes.end() )
1527       return; // not duplicated node
1528
1529     itNN[ iNode ] = (*mapIt).second.begin();
1530     prevNod[ iNode ] = node;
1531     nextNod[ iNode ] = (*mapIt).second.front();
1532     if ( prevNod[ iNode ] != nextNod [ iNode ])
1533       iNotSameNode = iNode;
1534     else {
1535       iSameNode = iNode;
1536       nbSame++;
1537     }
1538     iNode++;
1539   }
1540   int nbNodes = iNode;
1541   if ( nbSame == nbNodes || nbSame > 2) {
1542     MESSAGE( " Too many same nodes of element " << elem->GetID() );
1543     return;
1544   }
1545
1546   int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
1547   if ( nbSame > 0 ) {
1548     iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
1549     iAfterSame  = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
1550     iOpposSame  = ( iSameNode - 2 < 0  ? iSameNode + 2 : iSameNode - 2 );
1551   }
1552
1553   // check element orientation
1554   int i0 = 0, i2 = 2;
1555   if ( nbNodes > 2 && isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
1556 //    MESSAGE("Reversed elem " << elem->GetID() );
1557     i0 = 2;
1558     i2 = 0;
1559     if ( nbSame > 0 ) {
1560       int iAB = iAfterSame + iBeforeSame;
1561       iBeforeSame = iAB - iBeforeSame;
1562       iAfterSame  = iAB - iAfterSame;
1563     }
1564   }
1565
1566   // make new elements
1567   int iStep, nbSteps = (*mapIt).second.size();
1568   for (iStep = 0; iStep < nbSteps; iStep++ )
1569   {
1570     // get next nodes
1571     for ( iNode = 0; iNode < nbNodes; iNode++ ) {
1572       nextNod[ iNode ] = *itNN[ iNode ];
1573       itNN[ iNode ]++;
1574     }
1575     switch ( nbNodes )
1576     {
1577     case 2: { // EDGE
1578
1579       if ( nbSame == 0 )
1580         aMesh->AddFace( prevNod[ 0 ], prevNod[ 1 ], nextNod[ 1 ], nextNod[ 0 ] );
1581       else
1582         aMesh->AddFace( prevNod[ 0 ], prevNod[ 1 ], nextNod[ iNotSameNode ] );
1583       break;
1584     }
1585     case 3: { // TRIANGLE
1586
1587       if ( nbSame == 0 )       // --- 1 pentahedron
1588       {
1589         aMesh->AddVolume (prevNod[ i2 ], prevNod[ 1 ], prevNod[ i0 ],
1590                           nextNod[ i2 ], nextNod[ 1 ], nextNod[ i0 ] );
1591       }
1592       else if ( nbSame == 1 )  // --- 2 tetrahedrons
1593       {
1594         aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1595                           nextNod[ iBeforeSame ]);
1596         aMesh->AddVolume (nextNod[ i2 ], nextNod[ 1 ], nextNod[ i0 ],
1597                           prevNod[ iAfterSame ]);
1598       }
1599       else // 2 same nodes:      --- 1 tetrahedron
1600       {
1601         aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
1602                           nextNod[ iNotSameNode ]);
1603       }
1604       break;
1605     }
1606     case 4: { // QUADRANGLE
1607
1608       if ( nbSame == 0 )       // --- 1 hexahedron
1609       {
1610         aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
1611                           nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
1612       }
1613       else if ( nbSame == 1 )  // --- 2 tetrahedrons + 1 pentahedron
1614       {
1615         aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iSameNode ],
1616                           prevNod[ iAfterSame ],  nextNod[ iBeforeSame ]);
1617         aMesh->AddVolume (nextNod[ iAfterSame ],  nextNod[ iSameNode ],
1618                           nextNod[ iBeforeSame ], prevNod[ iAfterSame ]);
1619         aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ], prevNod[ iAfterSame ],
1620                           nextNod[ iBeforeSame ], nextNod[ iOpposSame ], nextNod[ iAfterSame ] );
1621       }
1622       else if ( nbSame == 2 )  // 1 pentahedron
1623       {
1624         if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
1625           // iBeforeSame is same too
1626           aMesh->AddVolume (prevNod[ iOpposSame ], prevNod[ iBeforeSame ], nextNod[ iOpposSame ],
1627                             prevNod[ iAfterSame ], prevNod[ iSameNode ],   nextNod[ iAfterSame ]);
1628         else
1629           // iAfterSame is same too
1630           aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iSameNode ],  nextNod[ iBeforeSame ],
1631                             prevNod[ iOpposSame ],  prevNod[ iAfterSame ], nextNod[ iOpposSame ]);
1632       }
1633       break;
1634     }
1635     default:
1636       return;
1637     }
1638
1639     // set new prev nodes
1640     for ( iNode = 0; iNode < nbNodes; iNode++ )
1641       prevNod[ iNode ] = nextNod[ iNode ];
1642
1643   } // for steps
1644 }
1645
1646 //=======================================================================
1647 //function : RotationSweep
1648 //purpose  : 
1649 //=======================================================================
1650
1651 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
1652                                      const gp_Ax1&                  theAxis,
1653                                      const double                   theAngle,
1654                                      const int                      theNbSteps,
1655                                      const double                   theTol)
1656 {
1657   gp_Trsf aTrsf;
1658   aTrsf.SetRotation( theAxis, theAngle );
1659
1660   gp_Lin aLine( theAxis );
1661   double aSqTol = theTol * theTol;
1662
1663   SMESHDS_Mesh* aMesh = GetMeshDS();
1664
1665   TNodeOfNodeListMap mapNewNodes;
1666
1667   // loop on theElems
1668   set< const SMDS_MeshElement* >::iterator itElem;
1669   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1670   {
1671     // check element type
1672     const SMDS_MeshElement* elem = (*itElem);
1673     if ( !elem ||
1674         (elem->GetType() != SMDSAbs_Face &&
1675          elem->GetType() != SMDSAbs_Edge ))
1676       continue;
1677
1678     // loop on elem nodes
1679     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1680     while ( itN->more() ) {
1681
1682       // check if a node has been already sweeped
1683       const SMDS_MeshNode* node =
1684         static_cast<const SMDS_MeshNode*>( itN->next() );
1685       if (mapNewNodes.find( node ) != mapNewNodes.end() )
1686         continue; 
1687
1688       list<const SMDS_MeshNode*>& listNewNodes = mapNewNodes[ node ];
1689
1690       // make new nodes
1691       gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
1692       double coord[3];
1693       aXYZ.Coord( coord[0], coord[1], coord[2] );
1694       bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
1695       const SMDS_MeshNode * newNode = node;
1696       for ( int i = 0; i < theNbSteps; i++ ) {
1697         if ( !isOnAxis ) {
1698           aTrsf.Transforms( coord[0], coord[1], coord[2] );
1699           newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1700         }
1701         listNewNodes.push_back( newNode );
1702       }
1703     }
1704     // make new elements
1705     sweepElement( aMesh, elem, mapNewNodes );
1706   }
1707 }
1708 //=======================================================================
1709 //function : ExtrusionSweep
1710 //purpose  : 
1711 //=======================================================================
1712
1713 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
1714                                       const gp_Vec&                  theStep,
1715                                       const int                      theNbSteps)
1716 {
1717   gp_Trsf aTrsf;
1718   aTrsf.SetTranslation( theStep );
1719
1720   SMESHDS_Mesh* aMesh = GetMeshDS();
1721
1722   TNodeOfNodeListMap mapNewNodes;
1723
1724   // loop on theElems
1725   set< const SMDS_MeshElement* >::iterator itElem;
1726   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1727   {
1728     // check element type
1729     const SMDS_MeshElement* elem = (*itElem);
1730     if ( !elem ||
1731         (elem->GetType() != SMDSAbs_Face &&
1732          elem->GetType() != SMDSAbs_Edge))
1733       continue;
1734
1735     // loop on elem nodes
1736     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1737     while ( itN->more() ) {
1738
1739       // check if a node has been already sweeped
1740       const SMDS_MeshNode* node =
1741         static_cast<const SMDS_MeshNode*>( itN->next() );
1742       if (mapNewNodes.find( node ) != mapNewNodes.end() )
1743         continue; 
1744
1745       list<const SMDS_MeshNode*>& listNewNodes = mapNewNodes[ node ];
1746
1747       // make new nodes
1748       double coord[3];
1749       coord[0] = node->X();
1750       coord[1] = node->Y();
1751       coord[2] = node->Z();
1752       for ( int i = 0; i < theNbSteps; i++ ) {
1753         aTrsf.Transforms( coord[0], coord[1], coord[2] );
1754         const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1755         listNewNodes.push_back( newNode );
1756       }
1757     }
1758     // make new elements
1759     sweepElement( aMesh, elem, mapNewNodes );
1760   }
1761 }
1762
1763 //=======================================================================
1764 //function : Transform
1765 //purpose  : 
1766 //=======================================================================
1767
1768 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
1769                                   const gp_Trsf&                 theTrsf,
1770                                   const bool                     theCopy)
1771 {
1772   bool needReverse;
1773   switch ( theTrsf.Form() ) {
1774   case gp_PntMirror:
1775   case gp_Ax2Mirror:
1776     needReverse = true;
1777     break;
1778   default:
1779     needReverse = false;
1780   }
1781
1782   SMESHDS_Mesh* aMesh = GetMeshDS();
1783
1784   // map old node to new one
1785   TNodeNodeMap nodeMap;
1786
1787   // elements sharing moved nodes; those of them which have all
1788   // nodes mirrored but are not in theElems are to be reversed
1789   set<const SMDS_MeshElement*> inverseElemSet;
1790
1791   // loop on theElems
1792   set< const SMDS_MeshElement* >::iterator itElem;
1793   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1794   {
1795     const SMDS_MeshElement* elem = (*itElem);
1796     if ( !elem )
1797       continue;
1798
1799     // loop on elem nodes
1800     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1801     while ( itN->more() ) {
1802
1803       // check if a node has been already transormed
1804       const SMDS_MeshNode* node =
1805         static_cast<const SMDS_MeshNode*>( itN->next() );
1806       if (nodeMap.find( node ) != nodeMap.end() )
1807         continue; 
1808
1809       double coord[3];
1810       coord[0] = node->X();
1811       coord[1] = node->Y();
1812       coord[2] = node->Z();
1813       theTrsf.Transforms( coord[0], coord[1], coord[2] );
1814       const SMDS_MeshNode * newNode = node;
1815       if ( theCopy )
1816         newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
1817       else
1818         aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
1819       nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
1820
1821       // keep inverse elements
1822       if ( !theCopy && needReverse ) {
1823         SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
1824         while ( invElemIt->more() )
1825           inverseElemSet.insert( invElemIt->next() );
1826       }
1827     }
1828   }
1829
1830   // either new elements are to be created
1831   // or a mirrored element are to be reversed
1832   if ( !theCopy && !needReverse)
1833     return;
1834
1835   if ( !inverseElemSet.empty()) {
1836     set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
1837     for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
1838       theElems.insert( *invElemIt );
1839   }
1840
1841   // replicate or reverse elements 
1842
1843   enum {
1844     REV_TETRA   = 0,  //  = nbNodes - 4
1845     REV_PYRAMID = 1,  //  = nbNodes - 4
1846     REV_PENTA   = 2,  //  = nbNodes - 4
1847     REV_FACE    = 3,
1848     REV_HEXA    = 4,  //  = nbNodes - 4
1849     FORWARD     = 5
1850     };
1851   int index[][8] = {
1852     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_TETRA  
1853     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_PYRAMID
1854     { 2, 1, 0, 5, 4, 3, 0, 0 },  // REV_PENTA  
1855     { 2, 1, 0, 3, 0, 0, 0, 0 },  // REV_FACE   
1856     { 2, 1, 0, 3, 6, 5, 4, 7 },  // REV_HEXA   
1857     { 0, 1, 2, 3, 4, 5, 6, 7 }   // FORWARD    
1858   };
1859
1860   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1861   {
1862     const SMDS_MeshElement* elem = (*itElem);
1863     if ( !elem || elem->GetType() == SMDSAbs_Node )
1864       continue;
1865
1866     int nbNodes = elem->NbNodes();
1867     int elemType = elem->GetType();
1868
1869     int* i = index[ FORWARD ];
1870     if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
1871       if ( elemType == SMDSAbs_Face )
1872         i = index[ REV_FACE ];
1873       else
1874         i = index[ nbNodes - 4 ];
1875
1876     // find transformed nodes
1877     const SMDS_MeshNode* nodes[8];
1878     int iNode = 0;
1879     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1880     while ( itN->more() )
1881     {
1882       const SMDS_MeshNode* node =
1883         static_cast<const SMDS_MeshNode*>( itN->next() );
1884       TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
1885       if ( nodeMapIt == nodeMap.end() )
1886         break; // not all nodes transformed
1887       nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
1888     }
1889     if ( iNode != nbNodes )
1890       continue; // not all nodes transformed
1891
1892     if ( theCopy ) 
1893     {
1894       // add a new element
1895       switch ( elemType ) {
1896       case SMDSAbs_Edge:
1897         aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
1898         break;
1899       case SMDSAbs_Face:
1900         if ( nbNodes == 3 )
1901           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
1902         else
1903           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
1904         break;
1905       case SMDSAbs_Volume:
1906         if ( nbNodes == 4 )
1907           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
1908         else if ( nbNodes == 8 )
1909           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
1910                             nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
1911         else if ( nbNodes == 6 )
1912           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
1913                             nodes[ 4 ], nodes[ 5 ]);
1914         else if ( nbNodes == 5 )
1915           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
1916                             nodes[ 4 ]);
1917         break;
1918       default:;
1919       }
1920     }
1921     else
1922     {
1923       // reverse element as it was reversed by transformation
1924       if ( nbNodes > 2 )
1925         aMesh->ChangeElementNodes( elem, nodes, nbNodes );
1926     }
1927   }
1928 }
1929
1930 //=======================================================================
1931 //function : FindCoincidentNodes
1932 //purpose  : Return list of group of nodes close to each other within theTolerance
1933 //=======================================================================
1934
1935 void SMESH_MeshEditor::FindCoincidentNodes (const double         theTolerance,
1936                                             TListOfListOfNodes & theGroupsOfNodes)
1937 {
1938   double tol2 = theTolerance * theTolerance;
1939
1940   list<const SMDS_MeshNode*> nodes;
1941   SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
1942   while ( nIt->more() )
1943     nodes.push_back( nIt->next() );
1944
1945   list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
1946   for ( ; it1 != nodes.end(); it1++ )
1947   {
1948     const SMDS_MeshNode* n1 = *it1;
1949     gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
1950
1951     list<const SMDS_MeshNode*> * groupPtr = 0;
1952     it2 = it1;
1953     for ( it2++; it2 != nodes.end(); it2++ )
1954     {
1955       const SMDS_MeshNode* n2 = *it2;
1956       gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
1957       if ( p1.SquareDistance( p2 ) <= tol2 )
1958       {
1959         if ( !groupPtr ) {
1960           theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
1961           groupPtr = & theGroupsOfNodes.back();
1962           groupPtr->push_back( n1 );
1963         }
1964         groupPtr->push_back( n2 );
1965         it2 = nodes.erase( it2 );
1966         it2--;
1967       }
1968     }
1969   }
1970 }
1971
1972 //=======================================================================
1973 //function : MergeNodes
1974 //purpose  : In each group, the cdr of nodes are substituted by the first one
1975 //           in all elements.
1976 //=======================================================================
1977
1978 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
1979 {
1980   SMESHDS_Mesh* aMesh = GetMeshDS();
1981
1982   TNodeNodeMap nodeNodeMap; // node to replace - new node
1983   set<const SMDS_MeshElement*> elems; // all elements with changed nodes
1984   list< int > rmElemIds, rmNodeIds;
1985
1986   // Fill nodeNodeMap and elems
1987
1988   TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
1989   for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
1990   {
1991     list<const SMDS_MeshNode*>& nodes = *grIt;
1992     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
1993     const SMDS_MeshNode* nToKeep = *nIt;
1994     for ( ; nIt != nodes.end(); nIt++ )
1995     {
1996       const SMDS_MeshNode* nToRemove = *nIt;
1997       nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
1998       if ( nToRemove != nToKeep ) {
1999         rmNodeIds.push_back( nToRemove->GetID() );
2000         addToSameGroups( nToKeep, nToRemove, aMesh );
2001       }
2002
2003       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
2004       while ( invElemIt->more() )
2005         elems.insert( invElemIt->next() );
2006     }
2007   }
2008   // Change element nodes or remove an element 
2009
2010   set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
2011   for ( ; eIt != elems.end(); eIt++ )
2012   {
2013     const SMDS_MeshElement* elem = *eIt;
2014     int nbNodes = elem->NbNodes();
2015     int aShapeId = FindShape( elem );
2016
2017     set<const SMDS_MeshNode*> nodeSet;
2018     const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
2019     int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
2020
2021     // get new seq of nodes
2022     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2023     while ( itN->more() )
2024     {
2025       const SMDS_MeshNode* n =
2026         static_cast<const SMDS_MeshNode*>( itN->next() );
2027
2028       TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
2029       if ( nnIt != nodeNodeMap.end() ) { // n sticks
2030         n = (*nnIt).second;
2031         iRepl[ nbRepl++ ] = iCur;
2032       }
2033       curNodes[ iCur ] = n;
2034       bool isUnique = nodeSet.insert( n ).second;
2035       if ( isUnique )
2036         uniqueNodes[ iUnique++ ] = n;
2037       iCur++;
2038     }
2039
2040     // Analyse element topology after replacement
2041
2042     bool isOk = true;
2043     int nbUniqueNodes = nodeSet.size();
2044     if ( nbNodes != nbUniqueNodes ) // some nodes stick
2045     {
2046       switch ( nbNodes ) {
2047       case 2: ///////////////////////////////////// EDGE
2048         isOk = false; break;
2049       case 3: ///////////////////////////////////// TRIANGLE
2050         isOk = false; break;
2051       case 4:
2052         if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
2053           isOk = false;
2054         else { //////////////////////////////////// QUADRANGLE
2055           if ( nbUniqueNodes < 3 )
2056             isOk = false;
2057           else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
2058             isOk = false; // opposite nodes stick
2059         }
2060         break;
2061       case 6: ///////////////////////////////////// PENTAHEDRON
2062         if ( nbUniqueNodes == 4 ) {
2063           // ---------------------------------> tetrahedron
2064           if (nbRepl == 3 &&
2065               iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
2066             // all top nodes stick: reverse a bottom
2067             uniqueNodes[ 0 ] = curNodes [ 1 ];
2068             uniqueNodes[ 1 ] = curNodes [ 0 ];
2069           }
2070           else if (nbRepl == 3 &&
2071                    iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
2072             // all bottom nodes stick: set a top before
2073             uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
2074             uniqueNodes[ 0 ] = curNodes [ 3 ];
2075             uniqueNodes[ 1 ] = curNodes [ 4 ];
2076             uniqueNodes[ 2 ] = curNodes [ 5 ];
2077           }
2078           else if (nbRepl == 4 &&
2079                    iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
2080             // a lateral face turns into a line: reverse a bottom
2081             uniqueNodes[ 0 ] = curNodes [ 1 ];
2082             uniqueNodes[ 1 ] = curNodes [ 0 ];
2083           }
2084           else
2085             isOk = false;
2086         }
2087         else if ( nbUniqueNodes == 5 ) {
2088           // PENTAHEDRON --------------------> 2 tetrahedrons
2089           if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
2090             // a bottom node sticks with a linked top one
2091             // 1.
2092             SMDS_MeshElement* newElem = 
2093               aMesh->AddVolume(curNodes[ 3 ],
2094                                curNodes[ 4 ],
2095                                curNodes[ 5 ],
2096                                curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
2097             if ( aShapeId )
2098               aMesh->SetMeshElementOnShape( newElem, aShapeId );
2099             // 2. : reverse a bottom
2100             uniqueNodes[ 0 ] = curNodes [ 1 ];
2101             uniqueNodes[ 1 ] = curNodes [ 0 ];
2102             nbUniqueNodes = 4;
2103           }
2104           else
2105             isOk = false;
2106         }
2107         else
2108           isOk = false;
2109         break;
2110       case 8: { //////////////////////////////////// HEXAHEDRON
2111         isOk = false;
2112         SMDS_VolumeTool hexa (elem);
2113         hexa.SetExternalNormal();
2114         if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
2115           //////////////////////// ---> tetrahedron
2116           for ( int iFace = 0; iFace < 6; iFace++ ) {
2117             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2118             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
2119                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
2120                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
2121               // one face turns into a point ...
2122               int iOppFace = hexa.GetOppFaceIndex( iFace );
2123               ind = hexa.GetFaceNodesIndices( iOppFace );
2124               int nbStick = 0;
2125               iUnique = 2; // reverse a tetrahedron bottom
2126               for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
2127                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
2128                   nbStick++;
2129                 else if ( iUnique >= 0 )
2130                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
2131               }
2132               if ( nbStick == 1 ) {
2133                 // ... and the opposite one - into a triangle.
2134                 // set a top node
2135                 ind = hexa.GetFaceNodesIndices( iFace );
2136                 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
2137                 isOk = true;
2138               }
2139               break;
2140             }
2141           }
2142         }
2143         else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
2144           //////////////////// HEXAHEDRON ---> 2 tetrahedrons
2145           for ( int iFace = 0; iFace < 6; iFace++ ) {
2146             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2147             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
2148                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
2149                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
2150               // one face turns into a point ...
2151               int iOppFace = hexa.GetOppFaceIndex( iFace );
2152               ind = hexa.GetFaceNodesIndices( iOppFace );
2153               int nbStick = 0;
2154               iUnique = 2;  // reverse a tetrahedron 1 bottom
2155               for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
2156                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
2157                   nbStick++;
2158                 else if ( iUnique >= 0 )
2159                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
2160               }
2161               if ( nbStick == 0 ) {
2162                 // ... and the opposite one is a quadrangle
2163                 // set a top node
2164                 const int* indTop = hexa.GetFaceNodesIndices( iFace );
2165                 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
2166                 nbUniqueNodes = 4;
2167                 // tetrahedron 2
2168                 SMDS_MeshElement* newElem = 
2169                   aMesh->AddVolume(curNodes[ind[ 0 ]],
2170                                    curNodes[ind[ 3 ]],
2171                                    curNodes[ind[ 2 ]],
2172                                    curNodes[indTop[ 0 ]]);
2173                 if ( aShapeId )
2174                   aMesh->SetMeshElementOnShape( newElem, aShapeId );
2175                 isOk = true;
2176               }
2177               break;
2178             }
2179           }
2180         }
2181         else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
2182           ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
2183           // find indices of quad and tri faces
2184           int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
2185           for ( iFace = 0; iFace < 6; iFace++ ) {
2186             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
2187             nodeSet.clear();
2188             for ( iCur = 0; iCur < 4; iCur++ )
2189               nodeSet.insert( curNodes[ind[ iCur ]] );
2190             nbUniqueNodes = nodeSet.size();
2191             if ( nbUniqueNodes == 3 )
2192               iTriFace[ nbTri++ ] = iFace;
2193             else if ( nbUniqueNodes == 4 )
2194               iQuadFace[ nbQuad++ ] = iFace;
2195           }
2196           if (nbQuad == 2 && nbTri == 4 &&
2197               hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
2198             // 2 opposite quadrangles stuck with a diagonal;
2199             // sample groups of merged indices: (0-4)(2-6)
2200             // --------------------------------------------> 2 tetrahedrons
2201             const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
2202             const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
2203             int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
2204             if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
2205                 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
2206               // stuck with 0-2 diagonal
2207               i0  = ind1[ 3 ];
2208               i1d = ind1[ 0 ];
2209               i2  = ind1[ 1 ];
2210               i3d = ind1[ 2 ];
2211               i0t = ind2[ 1 ];
2212               i2t = ind2[ 3 ];
2213             }
2214             else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
2215                      curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
2216               // stuck with 1-3 diagonal
2217               i0  = ind1[ 0 ];
2218               i1d = ind1[ 1 ];
2219               i2  = ind1[ 2 ];
2220               i3d = ind1[ 3 ];
2221               i0t = ind2[ 0 ];
2222               i2t = ind2[ 1 ];
2223             }
2224             else {
2225               ASSERT(0);
2226             }
2227             // tetrahedron 1
2228             uniqueNodes[ 0 ] = curNodes [ i0 ];
2229             uniqueNodes[ 1 ] = curNodes [ i1d ];
2230             uniqueNodes[ 2 ] = curNodes [ i3d ];
2231             uniqueNodes[ 3 ] = curNodes [ i0t ];
2232             nbUniqueNodes = 4;
2233             // tetrahedron 2
2234             SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
2235                                                          curNodes[ i2 ],
2236                                                          curNodes[ i3d ],
2237                                                          curNodes[ i2t ]);
2238             if ( aShapeId )
2239               aMesh->SetMeshElementOnShape( newElem, aShapeId );
2240             isOk = true;
2241           }
2242           else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
2243                    ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
2244             // --------------------------------------------> prism
2245             // find 2 opposite triangles
2246             nbUniqueNodes = 6;
2247             for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
2248               if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
2249                 // find indices of kept and replaced nodes
2250                 // and fill unique nodes of 2 opposite triangles
2251                 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
2252                 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
2253                 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
2254                 // fill unique nodes
2255                 iUnique = 0;
2256                 isOk = true;
2257                 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
2258                   const SMDS_MeshNode* n     = curNodes[ind1[ iCur ]];
2259                   const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
2260                   if ( n == nInit ) {
2261                     // iCur of a linked node of the opposite face (make normals co-directed):
2262                     int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
2263                     // check that correspondent corners of triangles are linked
2264                     if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
2265                       isOk = false;
2266                     else {
2267                       uniqueNodes[ iUnique ] = n;
2268                       uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
2269                       iUnique++;
2270                     }
2271                   }
2272                 }
2273                 break;
2274               }
2275             }
2276           }
2277         } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
2278         break;
2279       } // HEXAHEDRON
2280
2281       default:
2282         isOk = false;
2283       } // switch ( nbNodes )
2284
2285     } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
2286     
2287     if ( isOk )
2288       aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
2289     else
2290       rmElemIds.push_back( elem->GetID() );
2291
2292   } // loop on elements
2293
2294   // Remove equal nodes and bad elements
2295
2296   Remove( rmNodeIds, true );
2297   Remove( rmElemIds, false );
2298
2299 }
2300
2301 //=======================================================================
2302 //function : MergeEqualElements
2303 //purpose  : Remove all but one of elements built on the same nodes.
2304 //=======================================================================
2305
2306 void SMESH_MeshEditor::MergeEqualElements()
2307 {
2308   SMESHDS_Mesh* aMesh = GetMeshDS();
2309
2310   SMDS_EdgeIteratorPtr   eIt = aMesh->edgesIterator();
2311   SMDS_FaceIteratorPtr   fIt = aMesh->facesIterator();
2312   SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
2313
2314   list< int > rmElemIds; // IDs of elems to remove
2315
2316   for ( int iDim = 1; iDim <= 3; iDim++ ) {
2317
2318     set< set <const SMDS_MeshElement*> > setOfNodeSet;
2319
2320     while ( 1 ) {
2321       // get next element
2322       const SMDS_MeshElement* elem = 0;
2323       if ( iDim == 1 ) {
2324         if ( eIt->more() ) elem = eIt->next();
2325       } else if ( iDim == 2 ) {
2326         if ( fIt->more() ) elem = fIt->next();
2327       } else {
2328         if ( vIt->more() ) elem = vIt->next();
2329       }
2330       if ( !elem ) break;
2331
2332       // get elem nodes
2333       set <const SMDS_MeshElement*> nodeSet;
2334       SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
2335       while ( nodeIt->more() )
2336         nodeSet.insert( nodeIt->next() );
2337
2338       // check uniqueness
2339       bool isUnique = setOfNodeSet.insert( nodeSet ).second;
2340       if ( !isUnique )
2341         rmElemIds.push_back( elem->GetID() );
2342     }
2343   }
2344
2345   Remove( rmElemIds, false );
2346 }
2347
2348 //=======================================================================
2349 //function : findAdjacentFace
2350 //purpose  : 
2351 //=======================================================================
2352 #define CHECKIND(max,val) {if ( (val) >= (max) ) \
2353
2354 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
2355                                                 const SMDS_MeshNode* n2,
2356                                                 const SMDS_MeshElement* elem)
2357 {
2358   SMDS_ElemIteratorPtr invElemIt = n1->facesIterator();
2359   while ( invElemIt->more() ) { // loop on inverse elements of n1
2360     const SMDS_MeshElement* adjElem = invElemIt->next();
2361     if ( elem != adjElem ) {
2362       // get face nodes and find index of n1
2363       int i1, nbN = adjElem->NbNodes(), iNode = 0;
2364       const SMDS_MeshNode* faceNodes[ nbN ], *n;
2365       SMDS_ElemIteratorPtr nIt = adjElem->nodesIterator();
2366       while ( nIt->more() ) {
2367         faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2368         if ( faceNodes[ iNode++ ] == n1 )
2369           i1 = iNode - 1;
2370       }
2371       // find a n2 linked to n1
2372       for ( iNode = 0; iNode < 2; iNode++ ) {
2373         if ( iNode ) // node before n1
2374           n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
2375         else         // node after n1
2376           n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
2377         if ( n == n2 )
2378           return adjElem;
2379       }
2380     }
2381   }
2382   return 0;
2383 }
2384   
2385 //=======================================================================
2386 //function : findFreeBorder
2387 //purpose  : 
2388 //=======================================================================
2389
2390 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
2391
2392 static bool findFreeBorder (const SMDS_MeshNode*                theFirstNode,
2393                             const SMDS_MeshNode*                theSecondNode,
2394                             const SMDS_MeshNode*                theLastNode,
2395                             list< const SMDS_MeshNode* > &      theNodes,
2396                             list< const SMDS_MeshElement* > &   theFaces)
2397 {
2398   if ( !theFirstNode || !theSecondNode )
2399     return false;
2400   // find border face between theFirstNode and theSecondNode
2401   const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
2402   if ( !curElem )
2403     return false;
2404
2405   theFaces.push_back( curElem );
2406   theNodes.push_back( theFirstNode );
2407   theNodes.push_back( theSecondNode );
2408
2409   const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
2410   set < const SMDS_MeshElement* > foundElems;
2411   bool needTheLast = ( theLastNode != 0 );
2412
2413   while ( nStart != theLastNode )
2414   {
2415     if ( nStart == theFirstNode )
2416       return !needTheLast;
2417
2418     // find all free border faces sharing form nStart
2419
2420     list< const SMDS_MeshElement* > curElemList;
2421     list< const SMDS_MeshNode* > nStartList;
2422     SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
2423     while ( invElemIt->more() ) {
2424       const SMDS_MeshElement* e = invElemIt->next();
2425       if ( e == curElem || foundElems.insert( e ).second )
2426       {
2427         // get nodes
2428         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2429         int iNode = 0, nbNodes = e->NbNodes();
2430         while ( nIt->more() )
2431           nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2432         nodes[ iNode ] = nodes[ 0 ];
2433         // check 2 links
2434         for ( iNode = 0; iNode < nbNodes; iNode++ )
2435           if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
2436                (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
2437               ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
2438           {
2439             nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
2440             curElemList.push_back( e );
2441           }
2442       }
2443     }
2444     // analyse the found
2445
2446     int nbNewBorders = curElemList.size();
2447     if ( nbNewBorders == 0 ) {
2448       // no free border furthermore
2449       return !needTheLast;
2450     }
2451     else if ( nbNewBorders == 1 ) {
2452       // one more element found
2453       nIgnore = nStart;
2454       nStart = nStartList.front();
2455       curElem = curElemList.front();
2456       theFaces.push_back( curElem );
2457       theNodes.push_back( nStart );
2458     }
2459     else {
2460       // several continuations found
2461       list< const SMDS_MeshElement* >::iterator curElemIt;
2462       list< const SMDS_MeshNode* >::iterator nStartIt;
2463       // check if one of them reached the last node
2464       if ( needTheLast ) {
2465         for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
2466              curElemIt!= curElemList.end();
2467              curElemIt++, nStartIt++ )
2468           if ( *nStartIt == theLastNode ) {
2469             theFaces.push_back( *curElemIt );
2470             theNodes.push_back( *nStartIt );
2471             return true;
2472           }
2473       }
2474       // find the best free border by the continuations
2475       list<const SMDS_MeshNode*>    contNodes[ 2 ], *cNL;
2476       list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
2477       for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
2478            curElemIt!= curElemList.end();
2479            curElemIt++, nStartIt++ )
2480       {
2481         cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
2482         cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
2483         // find one more free border
2484         if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
2485           cNL->clear();
2486           cFL->clear();
2487         }
2488         else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
2489           // choice: clear a worse one
2490           int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
2491           int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
2492           contNodes[ iWorse ].clear();
2493           contFaces[ iWorse ].clear();
2494         }
2495       }
2496       if ( contNodes[0].empty() && contNodes[1].empty() )
2497         return false;
2498
2499       // append the best free border
2500       cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
2501       cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
2502       theNodes.pop_back(); // remove nIgnore
2503       theNodes.pop_back(); // remove nStart
2504       theFaces.pop_back(); // remove curElem
2505       list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
2506       list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
2507       for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
2508       for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
2509       return true;
2510
2511     } // several continuations found
2512   } // while ( nStart != theLastNode )
2513
2514   return true;
2515 }
2516
2517 //=======================================================================
2518 //function : CheckFreeBorderNodes
2519 //purpose  : Return true if the tree nodes are on a free border
2520 //=======================================================================
2521
2522 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
2523                                             const SMDS_MeshNode* theNode2,
2524                                             const SMDS_MeshNode* theNode3)
2525 {
2526   list< const SMDS_MeshNode* > nodes;
2527   list< const SMDS_MeshElement* > faces;
2528   return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
2529 }
2530
2531 //=======================================================================
2532 //function : SewFreeBorder
2533 //purpose  : 
2534 //=======================================================================
2535
2536 SMESH_MeshEditor::Sew_Error
2537   SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
2538                                    const SMDS_MeshNode* theBordSecondNode,
2539                                    const SMDS_MeshNode* theBordLastNode,
2540                                    const SMDS_MeshNode* theSideFirstNode,
2541                                    const SMDS_MeshNode* theSideSecondNode,
2542                                    const SMDS_MeshNode* theSideThirdNode,
2543                                    bool                 theSideIsFreeBorder)
2544 {
2545   MESSAGE("::SewFreeBorder()");
2546   Sew_Error aResult = SEW_OK;
2547
2548   // ====================================
2549   //    find side nodes and elements
2550   // ====================================
2551
2552   list< const SMDS_MeshNode* > nSide[ 2 ];
2553   list< const SMDS_MeshElement* > eSide[ 2 ];
2554   list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
2555   list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
2556
2557   // Free border 1
2558   // --------------
2559   if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
2560                       nSide[0], eSide[0])) {
2561     MESSAGE(" Free Border 1 not found " );
2562     aResult = SEW_BORDER1_NOT_FOUND;
2563   }
2564   if (theSideIsFreeBorder)
2565   { 
2566     // Free border 2
2567     // --------------
2568     if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
2569                         nSide[1], eSide[1])) {
2570       MESSAGE(" Free Border 2 not found " );
2571       aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
2572     }
2573   }
2574   if ( aResult != SEW_OK )
2575     return aResult;
2576
2577   if (!theSideIsFreeBorder)
2578   {
2579     // Side 2
2580     // --------------
2581
2582     // -------------------------------------------------------------------------
2583     // Algo:
2584     // 1. If nodes to merge are not coincident, move nodes of the free border
2585     //    from the coord sys defined by the direction from the first to last
2586     //    nodes of the border to the correspondent sys of the side 2
2587     // 2. On the side 2, find the links most co-directed with the correspondent
2588     //    links of the free border
2589     // -------------------------------------------------------------------------
2590
2591     // 1. Since sewing may brake if there are volumes to split on the side 2,
2592     //    we wont move nodes but just compute new coordinates for them
2593     typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
2594     TNodeXYZMap nBordXYZ;
2595     list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
2596     list< const SMDS_MeshNode* >::iterator nBordIt;
2597
2598     gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
2599     gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
2600     gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
2601     gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
2602     double tol2 = 1.e-8;
2603     gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
2604     if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
2605     {
2606       // Need node movement.
2607
2608       // find X and Z axes to create trsf
2609       gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
2610       gp_Vec X = Zs ^ Zb;
2611       if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
2612         // Zb || Zs
2613         X = gp_Ax2( gp::Origin(), Zb ).XDirection();
2614
2615       // coord systems
2616       gp_Ax3 toBordAx( Pb1, Zb, X );
2617       gp_Ax3 fromSideAx( Ps1, Zs, X );
2618       gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
2619       // set trsf
2620       gp_Trsf toBordSys, fromSide2Sys;
2621       toBordSys.SetTransformation( toBordAx );
2622       fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
2623       fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
2624       
2625       // move
2626       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
2627         const SMDS_MeshNode* n = *nBordIt;
2628         gp_XYZ xyz( n->X(),n->Y(),n->Z() );
2629         toBordSys.Transforms( xyz );
2630         fromSide2Sys.Transforms( xyz );
2631         nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
2632       }
2633     }
2634     else
2635     {
2636       // just insert nodes XYZ in the nBordXYZ map
2637       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
2638         const SMDS_MeshNode* n = *nBordIt;
2639         nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
2640       }
2641     }
2642
2643     // 2. On the side 2, find the links most co-directed with the correspondent
2644     //    links of the free border
2645
2646     list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
2647     list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
2648     sideNodes.push_back( theSideFirstNode );
2649
2650     bool hasVolumes = false;
2651     LinkID_Gen aLinkID_Gen( GetMeshDS() );
2652     set<long> foundSideLinkIDs, checkedLinkIDs;
2653     SMDS_VolumeTool volume;
2654     const SMDS_MeshNode* faceNodes[ 4 ];
2655
2656     const SMDS_MeshNode*    sideNode;
2657     const SMDS_MeshElement* sideElem;
2658     const SMDS_MeshNode* prevSideNode = theSideFirstNode;
2659     const SMDS_MeshNode* prevBordNode = theBordFirstNode;
2660     nBordIt = bordNodes.begin();
2661     nBordIt++;
2662     // border node position and border link direction to compare with
2663     gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
2664     gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
2665     // choose next side node by link direction or by closeness to
2666     // the current border node:
2667     bool searchByDir = ( *nBordIt != theBordLastNode );
2668     do {
2669       // find the next node on the Side 2
2670       sideNode = 0;
2671       double maxDot = -DBL_MAX, minDist = DBL_MAX;
2672       long linkID;
2673       checkedLinkIDs.clear();
2674       gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
2675
2676       SMDS_ElemIteratorPtr invElemIt
2677         = prevSideNode->GetInverseElementIterator();
2678       while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
2679         const SMDS_MeshElement* elem = invElemIt->next();
2680         // prepare data for a loop on links, of a face or a volume
2681         int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
2682         bool isVolume = volume.Set( elem );
2683         const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
2684         if ( isVolume ) // --volume
2685           hasVolumes = true;
2686         else if ( nbNodes > 2 ) { // --face
2687           // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
2688           SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2689           while ( nIt->more() ) {
2690             nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
2691             if ( nodes[ iNode++ ] == prevSideNode )
2692               iPrevNode = iNode - 1;
2693           }
2694           // there are 2 links to check
2695           nbNodes = 2;
2696         }
2697         else // --edge
2698           continue;
2699         // loop on links, to be precise, on the second node of links
2700         for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2701           const SMDS_MeshNode* n = nodes[ iNode ];
2702           if ( isVolume ) {
2703             if ( !volume.IsLinked( n, prevSideNode ))
2704               continue;
2705           } else {
2706             if ( iNode ) // a node before prevSideNode
2707               n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
2708             else         // a node after prevSideNode
2709               n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
2710           }
2711           // check if this link was already used
2712           long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
2713           bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
2714           if (!isJustChecked &&
2715               foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
2716             // test a link geometrically
2717             gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
2718             bool linkIsBetter = false;
2719             double dot, dist;
2720             if ( searchByDir ) { // choose most co-directed link
2721               dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
2722               linkIsBetter = ( dot > maxDot );
2723             }
2724             else { // choose link with the node closest to bordPos
2725               dist = ( nextXYZ - bordPos ).SquareModulus();
2726               linkIsBetter = ( dist < minDist );
2727             }
2728             if ( linkIsBetter ) {
2729               maxDot = dot;
2730               minDist = dist;
2731               linkID = iLink;
2732               sideNode = n;
2733               sideElem = elem;
2734             }
2735           }
2736         }
2737       } // loop on inverse elements of prevSideNode
2738
2739       if ( !sideNode ) {
2740         MESSAGE(" Cant find path by links of the Side 2 ");
2741         return SEW_BAD_SIDE_NODES;
2742       }
2743       sideNodes.push_back( sideNode );
2744       sideElems.push_back( sideElem );
2745       foundSideLinkIDs.insert ( linkID );
2746       prevSideNode = sideNode;
2747
2748       if ( *nBordIt == theBordLastNode )
2749         searchByDir = false;
2750       else {
2751         // find the next border link to compare with
2752         gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
2753         searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
2754         while ( *nBordIt != theBordLastNode && !searchByDir ) {
2755           prevBordNode = *nBordIt;
2756           nBordIt++;
2757           bordPos = nBordXYZ[ *nBordIt ];
2758           bordDir = bordPos - nBordXYZ[ prevBordNode ];
2759           searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
2760         }
2761       }
2762     }
2763     while ( sideNode != theSideSecondNode );
2764
2765     if ( hasVolumes && sideNodes.size () != bordNodes.size() ) {
2766       MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
2767       return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
2768     }
2769   } // end nodes search on the side 2
2770
2771   // ============================
2772   // sew the border to the side 2
2773   // ============================
2774
2775   int nbNodes[]  = { nSide[0].size(), nSide[1].size() };
2776   int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
2777
2778   TListOfListOfNodes nodeGroupsToMerge;
2779   if ( nbNodes[0] == nbNodes[1] ||
2780       ( theSideIsFreeBorder && !theSideThirdNode)) {
2781
2782     // all nodes are to be merged
2783
2784     for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
2785          nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
2786          nIt[0]++, nIt[1]++ )
2787     {
2788       nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
2789       nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep 
2790       nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
2791     }
2792   }
2793   else {
2794
2795     // insert new nodes into the border and the side to get equal nb of segments
2796
2797     // get normalized parameters of nodes on the borders
2798     double param[ 2 ][ maxNbNodes ];
2799     int iNode, iBord;
2800     for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
2801       list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
2802       list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
2803       const SMDS_MeshNode* nPrev = *nIt;
2804       double bordLength = 0;
2805       for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
2806         const SMDS_MeshNode* nCur = *nIt;
2807         gp_XYZ segment (nCur->X() - nPrev->X(),
2808                         nCur->Y() - nPrev->Y(),
2809                         nCur->Z() - nPrev->Z());
2810         double segmentLen = segment.Modulus();
2811         bordLength += segmentLen;
2812         param[ iBord ][ iNode ] = bordLength;
2813         nPrev = nCur;
2814       }
2815       // normalize within [0,1]
2816       for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
2817         param[ iBord ][ iNode ] /= bordLength;
2818       }
2819     }
2820
2821     // loop on border segments
2822     const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
2823     int i[ 2 ] = { 0, 0 };
2824     nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
2825     nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
2826
2827     TElemOfNodeListMap insertMap;
2828     TElemOfNodeListMap::iterator insertMapIt;
2829     // insertMap is
2830     // key:   elem to insert nodes into
2831     // value: 2 nodes to insert between + nodes to be inserted
2832     do {
2833       bool next[ 2 ] = { false, false };
2834
2835       // find min adjacent segment length after sewing
2836       double nextParam = 10., prevParam = 0;
2837       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
2838         if ( i[ iBord ] + 1 < nbNodes[ iBord ])
2839           nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
2840         if ( i[ iBord ] > 0 )
2841           prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
2842       }
2843       double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
2844       double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
2845       double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
2846           
2847       // choose to insert or to merge nodes
2848       double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
2849       if ( Abs( du ) <= minSegLen * 0.2 ) {
2850         // merge
2851         // ------
2852         nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
2853         const SMDS_MeshNode* n0 = *nIt[0];
2854         const SMDS_MeshNode* n1 = *nIt[1];
2855         nodeGroupsToMerge.back().push_back( n1 );
2856         nodeGroupsToMerge.back().push_back( n0 );
2857         // position of node of the border changes due to merge
2858         param[ 0 ][ i[0] ] += du;
2859         // move n1 for the sake of elem shape evaluation during insertion.
2860         // n1 will be removed by MergeNodes() anyway
2861         const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
2862         next[0] = next[1] = true;
2863       }
2864       else {
2865         // insert
2866         // ------
2867         int intoBord = ( du < 0 ) ? 0 : 1;
2868         const SMDS_MeshElement* elem = *eIt[ intoBord ];
2869         const SMDS_MeshNode*    n1   = nPrev[ intoBord ];
2870         const SMDS_MeshNode*    n2   = *nIt[ intoBord ];
2871         const SMDS_MeshNode*    nIns = *nIt[ 1 - intoBord ];
2872         if ( intoBord == 1 ) {
2873           // move node of the border to be on a link of elem of the side
2874           gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
2875           gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
2876           double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
2877           gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
2878           GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
2879         }
2880         insertMapIt = insertMap.find( elem );
2881         bool notFound = ( insertMapIt == insertMap.end() );
2882         bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
2883         if ( otherLink ) {
2884           // insert into another link of the same element:
2885           // 1. perform insertion into the other link of the elem
2886           list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
2887           const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
2888           const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
2889           InsertNodesIntoLink( elem, n12, n22, nodeList );
2890           // 2. perform insertion into the link of adjacent faces
2891           while (true) {
2892             const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
2893             if ( adjElem )
2894               InsertNodesIntoLink( adjElem, n12, n22, nodeList );
2895             else
2896               break;
2897           }
2898           // 3. find an element appeared on n1 and n2 after the insertion
2899           insertMap.erase( elem );
2900           elem = findAdjacentFace( n1, n2, 0 );
2901         }
2902         if ( notFound || otherLink ) {
2903           // add element and nodes of the side into the insertMap
2904           insertMapIt = insertMap.insert
2905             ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
2906           (*insertMapIt).second.push_back( n1 );
2907           (*insertMapIt).second.push_back( n2 );
2908         }
2909         // add node to be inserted into elem
2910         (*insertMapIt).second.push_back( nIns );
2911         next[ 1 - intoBord ] = true;
2912       }
2913
2914       // go to the next segment
2915       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
2916         if ( next[ iBord ] ) {
2917           if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
2918             eIt[ iBord ]++;
2919           nPrev[ iBord ] = *nIt[ iBord ];
2920           nIt[ iBord ]++; i[ iBord ]++;
2921         }
2922       }
2923     }
2924     while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
2925
2926     // perform insertion of nodes into elements
2927
2928     for (insertMapIt = insertMap.begin();
2929          insertMapIt != insertMap.end();
2930          insertMapIt++ )
2931     {
2932       const SMDS_MeshElement* elem = (*insertMapIt).first;
2933       list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
2934       const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
2935       const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
2936
2937       InsertNodesIntoLink( elem, n1, n2, nodeList );
2938
2939       if ( !theSideIsFreeBorder ) {
2940         // look for and insert nodes into the faces adjacent to elem
2941         while (true) {
2942           const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
2943           if ( adjElem )
2944             InsertNodesIntoLink( adjElem, n1, n2, nodeList );
2945           else
2946             break;
2947         }
2948       }
2949     }
2950
2951   } // end: insert new nodes
2952
2953   MergeNodes ( nodeGroupsToMerge );
2954
2955   return aResult;
2956 }
2957
2958 //=======================================================================
2959 //function : InsertNodesIntoLink
2960 //purpose  : insert theNodesToInsert into theFace between theBetweenNode1
2961 //           and theBetweenNode2 and split theElement
2962 //=======================================================================
2963
2964 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement*     theFace,
2965                                            const SMDS_MeshNode*        theBetweenNode1,
2966                                            const SMDS_MeshNode*        theBetweenNode2,
2967                                            list<const SMDS_MeshNode*>& theNodesToInsert)
2968 {
2969   if ( theFace->GetType() != SMDSAbs_Face ) return;
2970
2971   // find indices of 2 link nodes and of the rest nodes
2972   int iNode = 0, il1, il2, i3, i4;
2973   il1 = il2 = i3 = i4 = -1;
2974   const SMDS_MeshNode* nodes[ 8 ];
2975   SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
2976   while ( nodeIt->more() ) {
2977     const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
2978     if ( n == theBetweenNode1 )
2979       il1 = iNode;
2980     else if ( n == theBetweenNode2 )
2981       il2 = iNode;
2982     else if ( i3 < 0 )
2983       i3 = iNode;
2984     else
2985       i4 = iNode;
2986     nodes[ iNode++ ] = n;
2987   }
2988   if ( il1 < 0 || il2 < 0 || i3 < 0 )
2989     return ;
2990
2991   // arrange link nodes to go one after another regarding the face orientation
2992   bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
2993   if ( reverse ) {
2994     iNode = il1;
2995     il1 = il2;
2996     il2 = iNode;
2997     theNodesToInsert.reverse();
2998   }
2999   // check that not link nodes of a quadrangles are in good order
3000   int nbFaceNodes = theFace->NbNodes();
3001   if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
3002     iNode = i3;
3003     i3 = i4;
3004     i4 = iNode;
3005   } 
3006
3007   // put theNodesToInsert between theBetweenNode1 and theBetweenNode2
3008   int nbLinkNodes = 2 + theNodesToInsert.size();
3009   const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
3010   linkNodes[ 0 ] = nodes[ il1 ];
3011   linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
3012   list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
3013   for ( iNode = 1; nIt != theNodesToInsert.end(); nIt++ ) {
3014     linkNodes[ iNode++ ] = *nIt;
3015   }
3016   // decide how to split a quadrangle: compare possible variants
3017   // and choose which of splits to be a quadrangle
3018   int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
3019   if ( nbFaceNodes == 3 )
3020   {
3021     iBestQuad = nbSplits;
3022     i4 = i3;
3023   }
3024   else if ( nbFaceNodes == 4 )
3025   {
3026     SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
3027     double aBestRate = DBL_MAX;
3028     for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
3029       i1 = 0; i2 = 1;
3030       double aBadRate = 0;
3031       // evaluate elements quality
3032       for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
3033         if ( iSplit == iQuad ) {
3034           SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
3035                                  linkNodes[ i2++ ],
3036                                  nodes[ i3 ],
3037                                  nodes[ i4 ]);
3038           aBadRate += getBadRate( &quad, aCrit );
3039         }
3040         else {
3041           SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
3042                                  linkNodes[ i2++ ],
3043                                  nodes[ iSplit < iQuad ? i4 : i3 ]);
3044           aBadRate += getBadRate( &tria, aCrit );
3045         }
3046       }
3047       // choice
3048       if ( aBadRate < aBestRate ) {
3049         iBestQuad = iQuad;
3050         aBestRate = aBadRate;
3051       }
3052     }
3053   }
3054
3055   // create new elements
3056   SMESHDS_Mesh *aMesh = GetMeshDS();
3057   int aShapeId = FindShape( theFace );
3058   
3059   i1 = 0; i2 = 1;
3060   for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
3061     SMDS_MeshElement* newElem = 0;
3062     if ( iSplit == iBestQuad )
3063       newElem = aMesh->AddFace (linkNodes[ i1++ ],
3064                                 linkNodes[ i2++ ],
3065                                 nodes[ i3 ],
3066                                 nodes[ i4 ]);
3067     else
3068       newElem = aMesh->AddFace (linkNodes[ i1++ ],
3069                                 linkNodes[ i2++ ],
3070                                 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
3071     if ( aShapeId && newElem )
3072       aMesh->SetMeshElementOnShape( newElem, aShapeId );
3073   }
3074
3075   // change nodes of theFace
3076   const SMDS_MeshNode* newNodes[ 4 ];
3077   newNodes[ 0 ] = linkNodes[ i1 ];
3078   newNodes[ 1 ] = linkNodes[ i2 ];
3079   newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
3080   newNodes[ 3 ] = nodes[ i4 ];
3081   aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
3082 }
3083
3084 //=======================================================================
3085 //function : SewSideElements
3086 //purpose  : 
3087 //=======================================================================
3088
3089 SMESH_MeshEditor::Sew_Error
3090   SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
3091                                      set<const SMDS_MeshElement*>& theSide2,
3092                                      const SMDS_MeshNode*          theFirstNode1,
3093                                      const SMDS_MeshNode*          theFirstNode2,
3094                                      const SMDS_MeshNode*          theSecondNode1,
3095                                      const SMDS_MeshNode*          theSecondNode2)
3096 {
3097   MESSAGE ("::::SewSideElements()");
3098   if ( theSide1.size() != theSide2.size() )
3099     return SEW_DIFF_NB_OF_ELEMENTS;
3100
3101   Sew_Error aResult = SEW_OK;
3102   // Algo:
3103   // 1. Build set of faces representing each side
3104   // 2. Find which nodes of the side 1 to merge with ones on the side 2
3105   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
3106
3107   // =======================================================================
3108   // 1. Build set of faces representing each side:
3109   // =======================================================================
3110   // a. build set of nodes belonging to faces
3111   // b. complete set of faces: find missing fices whose nodes are in set of nodes
3112   // c. create temporary faces representing side of volumes if correspondent
3113   //    face does not exist
3114
3115   SMESHDS_Mesh* aMesh = GetMeshDS();
3116   SMDS_Mesh aTmpFacesMesh;
3117   set<const SMDS_MeshElement*> faceSet1, faceSet2;
3118   set<const SMDS_MeshElement*> volSet1,  volSet2;
3119   set<const SMDS_MeshNode*>    nodeSet1, nodeSet2;
3120   set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
3121   set<const SMDS_MeshElement*>  * volSetPtr[] = { &volSet1,  &volSet2  };
3122   set<const SMDS_MeshNode*>    * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
3123   set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
3124   int iSide, iFace, iNode;
3125
3126   for ( iSide = 0; iSide < 2; iSide++ ) {
3127     set<const SMDS_MeshNode*>    * nodeSet = nodeSetPtr[ iSide ];
3128     set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
3129     set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
3130     set<const SMDS_MeshElement*> * volSet  = volSetPtr [ iSide ];
3131     set<const SMDS_MeshElement*>::iterator vIt, eIt;
3132     set<const SMDS_MeshNode*>::iterator    nIt;
3133
3134   // -----------------------------------------------------------
3135   // 1a. Collect nodes of existing faces
3136   //     and build set of face nodes in order to detect missing
3137   //     faces corresponing to sides of volumes
3138   // -----------------------------------------------------------
3139
3140     set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
3141
3142     // loop on the given element of a side
3143     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
3144       const SMDS_MeshElement* elem = *eIt;
3145       if ( elem->GetType() == SMDSAbs_Face ) {
3146         faceSet->insert( elem );
3147         set <const SMDS_MeshNode*> faceNodeSet;
3148         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3149         while ( nodeIt->more() ) {
3150           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3151           nodeSet->insert( n );
3152           faceNodeSet.insert( n );
3153         }
3154         setOfFaceNodeSet.insert( faceNodeSet );
3155       }
3156       else if ( elem->GetType() == SMDSAbs_Volume )
3157         volSet->insert( elem );
3158     }
3159     // ------------------------------------------------------------------------------
3160     // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
3161     // ------------------------------------------------------------------------------
3162
3163     for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
3164       SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
3165       while ( fIt->more() ) { // loop on faces sharing a node
3166         const SMDS_MeshElement* f = fIt->next();
3167         if ( faceSet->find( f ) == faceSet->end() ) {
3168           // check if all nodes are in nodeSet and
3169           // complete setOfFaceNodeSet if they are
3170           set <const SMDS_MeshNode*> faceNodeSet;
3171           SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
3172           bool allInSet = true;
3173           while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
3174             const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3175             if ( nodeSet->find( n ) == nodeSet->end() )
3176               allInSet = false;
3177             else
3178               faceNodeSet.insert( n );
3179           }
3180           if ( allInSet ) {
3181             faceSet->insert( f );
3182             setOfFaceNodeSet.insert( faceNodeSet );
3183           }
3184         }
3185       }
3186     }
3187
3188     // -------------------------------------------------------------------------
3189     // 1c. Create temporary faces representing sides of volumes if correspondent
3190     //     face does not exist
3191     // -------------------------------------------------------------------------
3192
3193     if ( !volSet->empty() )
3194     {
3195       //int nodeSetSize = nodeSet->size();
3196       
3197       // loop on given volumes
3198       for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
3199         SMDS_VolumeTool vol (*vIt);
3200         // loop on volume faces: find free faces
3201         // --------------------------------------
3202         list<const SMDS_MeshElement* > freeFaceList;
3203         for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
3204           if ( !vol.IsFreeFace( iFace ))
3205             continue;
3206           // check if there is already a face with same nodes in a face set
3207           const SMDS_MeshElement* aFreeFace = 0;
3208           const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
3209           int nbNodes = vol.NbFaceNodes( iFace );
3210           set <const SMDS_MeshNode*> faceNodeSet;
3211           vol.GetFaceNodes( iFace, faceNodeSet );
3212           bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
3213           if ( isNewFace ) {
3214             // no such a face is given but it still can exist, check it
3215             if ( nbNodes == 3 )
3216               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
3217             else
3218               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
3219           }
3220           if ( !aFreeFace ) {
3221             // create a temporary face
3222             if ( nbNodes == 3 )
3223               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
3224             else
3225               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
3226           }
3227           if ( aFreeFace )
3228             freeFaceList.push_back( aFreeFace );
3229
3230         } // loop on faces of a volume
3231
3232         // choose one of several free faces
3233         // --------------------------------------
3234         if ( freeFaceList.size() > 1 ) {
3235           // choose a face having max nb of nodes shared by other elems of a side
3236           int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
3237           list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
3238           while ( fIt != freeFaceList.end() ) { // loop on free faces
3239             int nbSharedNodes = 0;
3240             SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
3241             while ( nodeIt->more() ) { // loop on free face nodes
3242               const SMDS_MeshNode* n =
3243                 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3244               SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
3245               while ( invElemIt->more() ) {
3246                 const SMDS_MeshElement* e = invElemIt->next();
3247                 if ( faceSet->find( e ) != faceSet->end() )
3248                   nbSharedNodes++;
3249                 if ( elemSet->find( e ) != elemSet->end() )
3250                   nbSharedNodes++;
3251               }
3252             }
3253             if ( nbSharedNodes >= maxNbNodes ) {
3254               maxNbNodes = nbSharedNodes;
3255               fIt++;
3256             }
3257             else 
3258               freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
3259           }
3260           if ( freeFaceList.size() > 1 )
3261           {
3262             // could not choose one face, use another way
3263             // choose a face most close to the bary center of the opposite side
3264             gp_XYZ aBC( 0., 0., 0. );
3265             set <const SMDS_MeshNode*> addedNodes;
3266             set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
3267             eIt = elemSet2->begin();
3268             for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
3269               SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
3270               while ( nodeIt->more() ) { // loop on free face nodes
3271                 const SMDS_MeshNode* n =
3272                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3273                 if ( addedNodes.insert( n ).second )
3274                   aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
3275               }
3276             }
3277             aBC /= addedNodes.size();
3278             double minDist = DBL_MAX;
3279             fIt = freeFaceList.begin();
3280             while ( fIt != freeFaceList.end() ) { // loop on free faces
3281               double dist = 0;
3282               SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
3283               while ( nodeIt->more() ) { // loop on free face nodes
3284                 const SMDS_MeshNode* n =
3285                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3286                 gp_XYZ p( n->X(),n->Y(),n->Z() );
3287                 dist += ( aBC - p ).SquareModulus();
3288               }
3289               if ( dist < minDist ) {
3290                 minDist = dist;
3291                 freeFaceList.erase( freeFaceList.begin(), fIt++ );
3292               }
3293               else
3294                 fIt = freeFaceList.erase( fIt++ );
3295             }
3296           }
3297         } // choose one of several free faces of a volume
3298
3299         if ( freeFaceList.size() == 1 ) {
3300           const SMDS_MeshElement* aFreeFace = freeFaceList.front();
3301           faceSet->insert( aFreeFace );
3302           // complete a node set with nodes of a found free face
3303 //           for ( iNode = 0; iNode < ; iNode++ )
3304 //             nodeSet->insert( fNodes[ iNode ] );
3305         }
3306
3307       } // loop on volumes of a side
3308
3309 //       // complete a set of faces if new nodes in a nodeSet appeared
3310 //       // ----------------------------------------------------------
3311 //       if ( nodeSetSize != nodeSet->size() ) {
3312 //         for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
3313 //           SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
3314 //           while ( fIt->more() ) { // loop on faces sharing a node
3315 //             const SMDS_MeshElement* f = fIt->next();
3316 //             if ( faceSet->find( f ) == faceSet->end() ) {
3317 //               // check if all nodes are in nodeSet and
3318 //               // complete setOfFaceNodeSet if they are
3319 //               set <const SMDS_MeshNode*> faceNodeSet;
3320 //               SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
3321 //               bool allInSet = true;
3322 //               while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
3323 //                 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
3324 //                 if ( nodeSet->find( n ) == nodeSet->end() )
3325 //                   allInSet = false;
3326 //                 else
3327 //                   faceNodeSet.insert( n );
3328 //               }
3329 //               if ( allInSet ) {
3330 //                 faceSet->insert( f );
3331 //                 setOfFaceNodeSet.insert( faceNodeSet );
3332 //               }
3333 //             }
3334 //           }
3335 //         }
3336 //       }
3337     } // Create temporary faces, if there are volumes given
3338   } // loop on sides
3339
3340   if ( faceSet1.size() != faceSet2.size() ) {
3341     // delete temporary faces: they are in reverseElements of actual nodes
3342     SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
3343     while ( tmpFaceIt->more() )
3344       aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
3345     MESSAGE("Diff nb of faces");
3346     return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3347   }
3348
3349   // ============================================================
3350   // 2. Find nodes to merge:
3351   //              bind a node to remove to a node to put instead
3352   // ============================================================
3353
3354   TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
3355   if ( theFirstNode1 != theFirstNode2 )
3356     nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
3357   if ( theSecondNode1 != theSecondNode2 )
3358     nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
3359
3360   LinkID_Gen aLinkID_Gen( GetMeshDS() );
3361   set< long > linkIdSet; // links to process
3362   linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
3363
3364   typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
3365   list< TPairOfNodes > linkList[2];
3366   linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
3367   linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
3368   // loop on links in linkList; find faces by links and append links
3369   // of the found faces to linkList
3370   list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
3371   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
3372   {
3373     TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
3374     long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
3375     if ( linkIdSet.find( linkID ) == linkIdSet.end() )
3376       continue;
3377
3378     // by links, find faces in the face sets,
3379     // and find indices of link nodes in the found faces;
3380     // in a face set, there is only one or no face sharing a link
3381     // ---------------------------------------------------------------
3382
3383     const SMDS_MeshElement* face[] = { 0, 0 };
3384     const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
3385     const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
3386     int iLinkNode[2][2];
3387     for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
3388       const SMDS_MeshNode* n1 = link[iSide].first;
3389       const SMDS_MeshNode* n2 = link[iSide].second;
3390       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
3391       set< const SMDS_MeshElement* > fMap;
3392       for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
3393         const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
3394         SMDS_ElemIteratorPtr fIt = n->facesIterator();
3395         while ( fIt->more() ) { // loop on faces sharing a node
3396           const SMDS_MeshElement* f = fIt->next();
3397           if (faceSet->find( f ) != faceSet->end() && // f is in face set
3398               ! fMap.insert( f ).second ) // f encounters twice
3399           {
3400             if ( face[ iSide ] ) {
3401               MESSAGE( "2 faces per link " );
3402               aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
3403               break;
3404             }
3405             face[ iSide ] = f;
3406             faceSet->erase( f );
3407             // get face nodes and find ones of a link
3408             iNode = 0;
3409             SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3410             while ( nIt->more() ) {
3411               const SMDS_MeshNode* n =
3412                 static_cast<const SMDS_MeshNode*>( nIt->next() );
3413               if ( n == n1 )
3414                 iLinkNode[ iSide ][ 0 ] = iNode;
3415               else if ( n == n2 )
3416                 iLinkNode[ iSide ][ 1 ] = iNode;
3417               else if ( notLinkNodes[ iSide ][ 0 ] )
3418                 notLinkNodes[ iSide ][ 1 ] = n;
3419               else
3420                 notLinkNodes[ iSide ][ 0 ] = n;
3421               faceNodes[ iSide ][ iNode++ ] = n;
3422             }
3423             faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
3424           }
3425         }
3426       }
3427     }
3428     // check similarity of elements of the sides
3429     if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
3430       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
3431       if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
3432         aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
3433       else
3434         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3435       break; // do not return because it s necessary to remove tmp faces
3436     }
3437
3438     // set nodes to merge
3439     // -------------------
3440
3441     if ( face[0] && face[1] )
3442     {
3443       int nbNodes = face[0]->NbNodes();
3444       if ( nbNodes != face[1]->NbNodes() ) {
3445         MESSAGE("Diff nb of face nodes");
3446         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3447         break; // do not return because it s necessary to remove tmp faces
3448       }
3449       bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
3450       if ( nbNodes == 3 )
3451         nReplaceMap.insert( TNodeNodeMap::value_type
3452                            ( notLinkNodes[0][0], notLinkNodes[1][0] ));
3453       else {
3454         for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
3455           // analyse link orientation in faces
3456           int i1 = iLinkNode[ iSide ][ 0 ];
3457           int i2 = iLinkNode[ iSide ][ 1 ];
3458           reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
3459           // if notLinkNodes are the first and the last ones, then
3460           // their order does not correspond to the link orientation
3461           if (( i1 == 1 && i2 == 2 ) ||
3462               ( i1 == 2 && i2 == 1 ))
3463             reverse[ iSide ] = !reverse[ iSide ];
3464         }
3465         if ( reverse[0] == reverse[1] ) {
3466           nReplaceMap.insert( TNodeNodeMap::value_type
3467                              ( notLinkNodes[0][0], notLinkNodes[1][0] ));
3468           nReplaceMap.insert( TNodeNodeMap::value_type
3469                              ( notLinkNodes[0][1], notLinkNodes[1][1] ));
3470         }
3471         else {
3472           nReplaceMap.insert( TNodeNodeMap::value_type
3473                              ( notLinkNodes[0][0], notLinkNodes[1][1] ));
3474           nReplaceMap.insert( TNodeNodeMap::value_type
3475                              ( notLinkNodes[0][1], notLinkNodes[1][0] ));
3476         }
3477       }
3478
3479       // add other links of the faces to linkList
3480       // -----------------------------------------
3481
3482       const SMDS_MeshNode** nodes = faceNodes[ 0 ];
3483       for ( iNode = 0; iNode < nbNodes; iNode++ )
3484       {
3485         linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
3486         pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
3487         if ( !iter_isnew.second ) { // already in a set: no need to process
3488           linkIdSet.erase( iter_isnew.first );
3489         }
3490         else // new in set == encountered for the first time: add
3491         {
3492           const SMDS_MeshNode* n1 = nodes[ iNode ];
3493           const SMDS_MeshNode* n2 = nodes[ iNode + 1];
3494           linkList[0].push_back ( TPairOfNodes( n1, n2 ));
3495           linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
3496         }
3497       }
3498     } // 2 faces found
3499   } // loop on link lists
3500
3501   if ( aResult == SEW_OK &&
3502       ( linkIt[0] != linkList[0].end() ||
3503        !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
3504     MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
3505             " " << (faceSetPtr[1]->empty()));
3506     aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
3507   }
3508
3509   // ====================================================================
3510   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
3511   // ====================================================================
3512
3513   // delete temporary faces: they are in reverseElements of actual nodes
3514   SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
3515   while ( tmpFaceIt->more() )
3516     aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
3517
3518   if ( aResult != SEW_OK)
3519     return aResult;
3520
3521   list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
3522   // loop on nodes replacement map
3523   TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
3524   for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
3525     if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
3526     {
3527       const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
3528       nodeIDsToRemove.push_back( nToRemove->GetID() );
3529       // loop on elements sharing nToRemove
3530       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3531       while ( invElemIt->more() ) {
3532         const SMDS_MeshElement* e = invElemIt->next();
3533         // get a new suite of nodes: make replacement
3534         int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
3535         const SMDS_MeshNode* nodes[ 8 ];
3536         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3537         while ( nIt->more() ) {
3538           const SMDS_MeshNode* n =
3539             static_cast<const SMDS_MeshNode*>( nIt->next() );
3540           nnIt = nReplaceMap.find( n );
3541           if ( nnIt != nReplaceMap.end() ) {
3542             nbReplaced++;
3543             n = (*nnIt).second;
3544           }
3545           nodes[ i++ ] = n;
3546         }
3547         //       if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
3548         //         elemIDsToRemove.push_back( e->GetID() );
3549         //       else
3550         if ( nbReplaced )
3551           aMesh->ChangeElementNodes( e, nodes, nbNodes );
3552       }
3553   }
3554
3555   Remove( nodeIDsToRemove, true );
3556
3557   return aResult;
3558 }