Salome HOME
Fix compilation warnings
[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 "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
35 #include "SMDS_FacePosition.hxx"
36 #include "SMDS_SpacePosition.hxx"
37
38 #include "SMESHDS_Group.hxx"
39 #include "SMESHDS_Mesh.hxx"
40
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_ControlsDef.hxx"
43
44 #include "utilities.h"
45
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopTools_ListOfShape.hxx>
48 #include <math.h>
49 #include <gp_Dir.hxx>
50 #include <gp_Vec.hxx>
51 #include <gp_Ax1.hxx>
52 #include <gp_Trsf.hxx>
53 #include <gp_Lin.hxx>
54 #include <gp_XYZ.hxx>
55 #include <gp_XY.hxx>
56 #include <gp.hxx>
57 #include <gp_Pln.hxx>
58 #include <BRep_Tool.hxx>
59 #include <Geom_Curve.hxx>
60 #include <Geom_Surface.hxx>
61 #include <Geom2d_Curve.hxx>
62 #include <Extrema_GenExtPS.hxx>
63 #include <Extrema_POnSurf.hxx>
64 #include <GeomAdaptor_Surface.hxx>
65 #include <ElCLib.hxx>
66
67 #include <map>
68
69 using namespace std;
70 using namespace SMESH::Controls;
71
72 typedef map<const SMDS_MeshNode*, const SMDS_MeshNode*>              TNodeNodeMap;
73 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> >    TElemOfNodeListMap;
74 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
75 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> >       TNodeOfNodeListMap;
76 typedef TNodeOfNodeListMap::iterator                                 TNodeOfNodeListMapItr;
77 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
78
79 //=======================================================================
80 //function : SMESH_MeshEditor
81 //purpose  : 
82 //=======================================================================
83
84 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
85 myMesh( theMesh )
86 {
87 }
88
89 //=======================================================================
90 //function : Remove
91 //purpose  : Remove a node or an element.
92 //           Modify a compute state of sub-meshes which become empty
93 //=======================================================================
94
95 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
96                                const bool         isNodes )
97 {
98
99   SMESHDS_Mesh* aMesh = GetMeshDS();
100   set< SMESH_subMesh *> smmap;
101   
102   list<int>::const_iterator it = theIDs.begin();
103   for ( ; it != theIDs.end(); it++ )
104   {
105     const SMDS_MeshElement * elem;
106     if ( isNodes )
107       elem = aMesh->FindNode( *it );
108     else
109       elem = aMesh->FindElement( *it );
110     if ( !elem )
111       continue;
112
113     // Find sub-meshes to notify about modification
114     SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
115     while ( nodeIt->more() )
116     {
117       const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
118       const SMDS_PositionPtr& aPosition = node->GetPosition();
119       if ( aPosition.get() ) {
120         int aShapeID = aPosition->GetShapeId();
121         if ( aShapeID ) {
122           TopoDS_Shape aShape = aMesh->IndexToShape( aShapeID );
123           SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShape );
124           if ( sm )
125             smmap.insert( sm );
126         }
127       }
128     }
129
130     // Do remove
131     if ( isNodes )
132       aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
133     else
134       aMesh->RemoveElement( elem );
135   }
136
137   // Notify sub-meshes about modification
138   if ( !smmap.empty() ) {
139     set< SMESH_subMesh *>::iterator smIt;
140     for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
141       (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
142   }
143   return true;
144 }
145
146 //=======================================================================
147 //function : FindShape
148 //purpose  : Return an index of the shape theElem is on
149 //           or zero if a shape not found
150 //=======================================================================
151
152 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
153 {
154   SMESHDS_Mesh * aMesh = GetMeshDS();
155   if ( aMesh->ShapeToMesh().IsNull() )
156     return 0;
157
158   if ( theElem->GetType() == SMDSAbs_Node )
159   {
160     const SMDS_PositionPtr& aPosition =
161       static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
162     if ( aPosition.get() )
163       return aPosition->GetShapeId();
164     else
165       return 0;
166   }
167
168   TopoDS_Shape aShape; // the shape a node is on
169   SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
170   while ( nodeIt->more() )
171   {
172     const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
173     const SMDS_PositionPtr& aPosition = node->GetPosition();
174     if ( aPosition.get() ) {
175         int aShapeID = aPosition->GetShapeId();
176         SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
177         if ( sm )
178         {
179           if ( sm->Contains( theElem ))
180             return aShapeID;
181           if ( aShape.IsNull() )
182             aShape = aMesh->IndexToShape( aShapeID );
183         }
184         else
185         {
186           //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
187         }
188       }
189   }
190
191   // None of nodes is on a proper shape,
192   // find the shape among ancestors of aShape on which a node is
193   if ( aShape.IsNull() ) {
194     //MESSAGE ("::FindShape() - NONE node is on shape")
195     return 0;
196   }
197   TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
198   for ( ; ancIt.More(); ancIt.Next() )
199   {
200       SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
201       if ( sm && sm->Contains( theElem ))
202         return aMesh->ShapeToIndex( ancIt.Value() );
203   }
204
205   //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
206   return 0;
207 }
208
209 //=======================================================================
210 //function : InverseDiag
211 //purpose  : Replace two neighbour triangles with ones built on the same 4 nodes
212 //           but having other common link.
213 //           Return False if args are improper
214 //=======================================================================
215
216 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
217                                     const SMDS_MeshElement * theTria2 )
218 {
219   if (!theTria1 || !theTria2)
220     return false;
221   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
222   if (!F1) return false;
223   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
224   if (!F2) return false;
225
226   //  1 +--+ A  theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
227   //    | /|    theTria2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |  
228   //    |/ |                                         | \|  
229   //  B +--+ 2                                     B +--+ 2
230
231   // put nodes in array and find out indices of the same ones
232   const SMDS_MeshNode* aNodes [6];
233   int sameInd [] = { 0, 0, 0, 0, 0, 0 };
234   int i = 0;
235   SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
236   while ( it->more() )
237   {
238     aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
239
240     if ( i > 2 ) // theTria2
241       // find same node of theTria1
242       for ( int j = 0; j < 3; j++ )
243         if ( aNodes[ i ] == aNodes[ j ]) {
244           sameInd[ j ] = i;
245           sameInd[ i ] = j;
246           break;
247         }
248     // next
249     i++;
250     if ( i == 3 ) {
251       if ( it->more() )
252         return false; // theTria1 is not a triangle
253       it = theTria2->nodesIterator();
254     }
255     if ( i == 6 && it->more() )
256       return false; // theTria2 is not a triangle
257   }
258
259   // find indices of 1,2 and of A,B in theTria1
260   int iA = 0, iB = 0, i1 = 0, i2 = 0;
261   for ( i = 0; i < 6; i++ )
262   {
263     if ( sameInd [ i ] == 0 )
264       if ( i < 3 ) i1 = i;
265       else         i2 = i;
266     else if (i < 3)
267       if ( iA ) iB = i;
268       else      iA = i;
269   }
270   // nodes 1 and 2 should not be the same
271   if ( aNodes[ i1 ] == aNodes[ i2 ] )
272     return false;
273
274
275   // theTria1: A->2
276   aNodes[ iA ] = aNodes[ i2 ];
277   // theTria2: B->1
278   aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
279
280   //MESSAGE( theTria1 << theTria2 );
281
282   GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
283   GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
284
285   //MESSAGE( theTria1 << theTria2 );
286
287   return true;
288 }
289
290 //=======================================================================
291 //function : findTriangles
292 //purpose  : find triangles sharing theNode1-theNode2 link
293 //=======================================================================
294
295 static bool findTriangles(const SMDS_MeshNode *    theNode1,
296                           const SMDS_MeshNode *    theNode2,
297                           const SMDS_MeshElement*& theTria1,
298                           const SMDS_MeshElement*& theTria2)
299 {
300   if ( !theNode1 || !theNode2 ) return false;
301
302   theTria1 = theTria2 = 0;
303
304   set< const SMDS_MeshElement* > emap;
305   SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator();
306   while (it->more()) {
307     const SMDS_MeshElement* elem = it->next();
308     if ( elem->GetType() == SMDSAbs_Face && elem->NbNodes() == 3 )
309       emap.insert( elem );
310   }
311   it = theNode2->GetInverseElementIterator();
312   while (it->more()) {
313     const SMDS_MeshElement* elem = it->next();
314     if ( elem->GetType() == SMDSAbs_Face &&
315          emap.find( elem ) != emap.end() )
316       if ( theTria1 ) {
317         theTria2 = elem;
318         break;
319       } else {
320         theTria1 = elem;
321       }
322   }
323   return ( theTria1 && theTria2 );
324 }
325
326 //=======================================================================
327 //function : InverseDiag
328 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
329 //           with ones built on the same 4 nodes but having other common link.
330 //           Return false if proper faces not found
331 //=======================================================================
332
333 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
334                                     const SMDS_MeshNode * theNode2)
335 {
336   MESSAGE( "::InverseDiag()" );
337
338   const SMDS_MeshElement *tr1, *tr2;
339   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
340     return false;
341
342   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
343   if (!F1) return false;
344   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
345   if (!F2) return false;
346
347   //  1 +--+ A  tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
348   //    | /|    tr2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |  
349   //    |/ |                                    | \|  
350   //  B +--+ 2                                B +--+ 2
351
352   // put nodes in array
353   // and find indices of 1,2 and of A in tr1 and of B in tr2
354   int i, iA1 = 0, i1 = 0;
355   const SMDS_MeshNode* aNodes1 [3];
356   SMDS_ElemIteratorPtr it;
357   for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
358     aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
359     if ( aNodes1[ i ] == theNode1 )
360       iA1 = i; // node A in tr1
361     else if ( aNodes1[ i ] != theNode2 )
362       i1 = i;  // node 1
363   }
364   int iB2 = 0, i2 = 0;
365   const SMDS_MeshNode* aNodes2 [3];
366   for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
367     aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
368     if ( aNodes2[ i ] == theNode2 )
369       iB2 = i; // node B in tr2
370     else if ( aNodes2[ i ] != theNode1 )
371       i2 = i;  // node 2
372   }
373
374   // nodes 1 and 2 should not be the same
375   if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
376     return false;
377
378   // tr1: A->2
379   aNodes1[ iA1 ] = aNodes2[ i2 ];
380   // tr2: B->1
381   aNodes2[ iB2 ] = aNodes1[ i1 ];
382
383   //MESSAGE( tr1 << tr2 );
384
385   GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
386   GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
387
388   //MESSAGE( tr1 << tr2 );
389
390   return true;
391   
392 }
393
394 //=======================================================================
395 //function : getQuadrangleNodes
396 //purpose  : fill theQuadNodes - nodes of a quadrangle resulting from
397 //           fusion of triangles tr1 and tr2 having shared link on
398 //           theNode1 and theNode2
399 //=======================================================================
400
401 bool getQuadrangleNodes(const SMDS_MeshNode *    theQuadNodes [],
402                         const SMDS_MeshNode *    theNode1,
403                         const SMDS_MeshNode *    theNode2,
404                         const SMDS_MeshElement * tr1,
405                         const SMDS_MeshElement * tr2 )
406 {
407   // find the 4-th node to insert into tr1
408   const SMDS_MeshNode* n4 = 0;
409   SMDS_ElemIteratorPtr it = tr2->nodesIterator();
410   while ( !n4 && it->more() )
411   {
412     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
413     bool isDiag = ( n == theNode1 || n == theNode2 );
414     if ( !isDiag )
415       n4 = n;
416   }
417   // Make an array of nodes to be in a quadrangle
418   int iNode = 0, iFirstDiag = -1;
419   it = tr1->nodesIterator();
420   while ( it->more() )
421   {
422     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
423     bool isDiag = ( n == theNode1 || n == theNode2 );
424     if ( isDiag )
425     {
426       if ( iFirstDiag < 0 )
427         iFirstDiag = iNode;
428       else if ( iNode - iFirstDiag == 1 )
429         theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
430     }
431     else if ( n == n4 )
432     {
433       return false; // tr1 and tr2 should not have all the same nodes
434     }
435     theQuadNodes[ iNode++ ] = n;
436   }
437   if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
438     theQuadNodes[ iNode ] = n4;
439
440   return true;
441 }
442
443 //=======================================================================
444 //function : DeleteDiag
445 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
446 //           with a quadrangle built on the same 4 nodes.
447 //           Return false if proper faces not found
448 //=======================================================================
449
450 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
451                                    const SMDS_MeshNode * theNode2)
452 {
453   MESSAGE( "::DeleteDiag()" );
454
455   const SMDS_MeshElement *tr1, *tr2;
456   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
457     return false;
458
459   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
460   if (!F1) return false;
461   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
462   if (!F2) return false;
463
464   const SMDS_MeshNode* aNodes [ 4 ];
465   if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
466     return false;
467
468   //MESSAGE( endl << tr1 << tr2 );
469
470   GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
471   GetMeshDS()->RemoveElement( tr2 );
472
473   //MESSAGE( endl << tr1 );
474
475   return true;
476 }
477
478 //=======================================================================
479 //function : Reorient
480 //purpose  : Reverse theElement orientation
481 //=======================================================================
482
483 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
484 {
485   if (!theElem)
486     return false;
487   SMDS_ElemIteratorPtr it = theElem->nodesIterator();
488   if ( !it || !it->more() )
489     return false;
490
491   switch ( theElem->GetType() ) {
492     
493   case SMDSAbs_Edge:
494   case SMDSAbs_Face:
495   {
496     int i = theElem->NbNodes();
497     vector<const SMDS_MeshNode*> aNodes( i );
498     while ( it->more() )
499       aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
500     return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
501   }
502   case SMDSAbs_Volume:
503   {
504     if (theElem->IsPoly()) {
505       const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
506         static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
507       if (!aPolyedre) {
508         MESSAGE("Warning: bad volumic element");
509         return false;
510       }
511
512       int nbFaces = aPolyedre->NbFaces();
513       vector<const SMDS_MeshNode *> poly_nodes;
514       vector<int> quantities (nbFaces);
515
516       // reverse each face of the polyedre
517       for (int iface = 1; iface <= nbFaces; iface++) {
518         int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
519         quantities[iface - 1] = nbFaceNodes;
520
521         for (inode = nbFaceNodes; inode >= 1; inode--) {
522           const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
523           poly_nodes.push_back(curNode);
524         }
525       }
526
527       return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
528
529     } else {
530       SMDS_VolumeTool vTool;
531       if ( !vTool.Set( theElem ))
532         return false;
533       vTool.Inverse();
534       return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
535     }
536   }
537   default:;
538   }
539
540   return false;
541 }
542
543 //=======================================================================
544 //function : getBadRate
545 //purpose  : 
546 //=======================================================================
547
548 static double getBadRate (const SMDS_MeshElement*               theElem,
549                           SMESH::Controls::NumericalFunctorPtr& theCrit)
550 {
551   SMESH::Controls::TSequenceOfXYZ P;
552   if ( !theElem || !theCrit->GetPoints( theElem, P ))
553     return 1e100;
554   return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
555 }
556   
557 //=======================================================================
558 //function : QuadToTri
559 //purpose  : Cut quadrangles into triangles.
560 //           theCrit is used to select a diagonal to cut
561 //=======================================================================
562
563 bool SMESH_MeshEditor::QuadToTri (set<const SMDS_MeshElement*> &       theElems,
564                                   SMESH::Controls::NumericalFunctorPtr theCrit)
565 {
566   MESSAGE( "::QuadToTri()" );
567
568   if ( !theCrit.get() )
569     return false;
570
571   SMESHDS_Mesh * aMesh = GetMeshDS();
572
573   set< const SMDS_MeshElement * >::iterator itElem;
574   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
575   {
576     const SMDS_MeshElement* elem = (*itElem);
577     if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
578       continue;
579
580     // retrieve element nodes
581     const SMDS_MeshNode* aNodes [4];
582     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
583     int i = 0;
584     while ( itN->more() )
585       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
586
587     // compare two sets of possible triangles
588     double aBadRate1, aBadRate2; // to what extent a set is bad
589     SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
590     SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
591     aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
592       
593     SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
594     SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
595     aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
596
597     int aShapeId = FindShape( elem );
598     //MESSAGE( "aBadRate1 = " << aBadRate1 << "; aBadRate2 = " << aBadRate2
599       //      << " ShapeID = " << aShapeId << endl << elem );
600     
601     if ( aBadRate1 <= aBadRate2 ) {
602       // tr1 + tr2 is better
603       aMesh->ChangeElementNodes( elem, aNodes, 3 );
604       //MESSAGE( endl << elem );
605
606       elem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
607     }
608     else {
609       // tr3 + tr4 is better
610       aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
611       //MESSAGE( endl << elem );
612
613       elem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
614     }
615     //MESSAGE( endl << elem );
616
617     // put a new triangle on the same shape
618     if ( aShapeId )
619       aMesh->SetMeshElementOnShape( elem, aShapeId );
620   }
621
622   return true;
623 }
624
625 //=======================================================================
626 //function : AddToSameGroups
627 //purpose  : add elemToAdd to the groups the elemInGroups belongs to
628 //=======================================================================
629
630 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
631                                         const SMDS_MeshElement* elemInGroups,
632                                         SMESHDS_Mesh *          aMesh)
633 {
634   const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
635   set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
636   for ( ; grIt != groups.end(); grIt++ ) {
637     SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
638     if ( group && group->SMDSGroup().Contains( elemInGroups ))
639       group->SMDSGroup().Add( elemToAdd );
640   }
641 }
642
643 //=======================================================================
644 //function : QuadToTri
645 //purpose  : Cut quadrangles into triangles.
646 //           theCrit is used to select a diagonal to cut
647 //=======================================================================
648
649 bool SMESH_MeshEditor::QuadToTri (std::set<const SMDS_MeshElement*> & theElems,
650                                   const bool                          the13Diag)
651 {
652   MESSAGE( "::QuadToTri()" );
653
654   SMESHDS_Mesh * aMesh = GetMeshDS();
655
656   set< const SMDS_MeshElement * >::iterator itElem;
657   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
658   {
659     const SMDS_MeshElement* elem = (*itElem);
660     if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() != 4 )
661       continue;
662
663     // retrieve element nodes
664     const SMDS_MeshNode* aNodes [4];
665     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
666     int i = 0;
667     while ( itN->more() )
668       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
669
670     int aShapeId = FindShape( elem );
671     const SMDS_MeshElement* newElem = 0;
672     if ( the13Diag )
673     {
674       aMesh->ChangeElementNodes( elem, aNodes, 3 );
675       newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
676     }
677     else
678     {
679       aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
680       newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
681     }
682
683     // put a new triangle on the same shape and add to the same groups
684
685     if ( aShapeId )
686       aMesh->SetMeshElementOnShape( newElem, aShapeId );
687
688     AddToSameGroups( newElem, elem, aMesh );
689   }
690
691   return true;
692 }
693
694 //=======================================================================
695 //function : getAngle
696 //purpose  : 
697 //=======================================================================
698
699 double getAngle(const SMDS_MeshElement * tr1,
700                 const SMDS_MeshElement * tr2,
701                 const SMDS_MeshNode *    n1,
702                 const SMDS_MeshNode *    n2)
703 {
704   double angle = 2*PI; // bad angle
705
706   // get normals
707   SMESH::Controls::TSequenceOfXYZ P1, P2;
708   if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
709        !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
710     return angle;
711   gp_Vec N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
712   if ( N1.SquareMagnitude() <= gp::Resolution() )
713     return angle;
714   gp_Vec N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
715   if ( N2.SquareMagnitude() <= gp::Resolution() )
716     return angle;
717   
718   // find the first diagonal node n1 in the triangles:
719   // take in account a diagonal link orientation
720   const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
721   for ( int t = 0; t < 2; t++ )
722   {
723     SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
724     int i = 0, iDiag = -1;
725     while ( it->more()) {
726       const SMDS_MeshElement *n = it->next();
727       if ( n == n1 || n == n2 )
728         if ( iDiag < 0)
729           iDiag = i;
730         else {
731           if ( i - iDiag == 1 )
732             nFirst[ t ] = ( n == n1 ? n2 : n1 );
733           else
734             nFirst[ t ] = n;
735           break;
736         }
737       i++;
738     }
739   }
740   if ( nFirst[ 0 ] == nFirst[ 1 ] )
741     N2.Reverse();
742
743   angle = N1.Angle( N2 );
744   //SCRUTE( angle );
745   return angle;
746 }
747
748 // =================================================
749 // class generating a unique ID for a pair of nodes
750 // and able to return nodes by that ID
751 // =================================================
752
753 class LinkID_Gen {
754  public:
755
756   LinkID_Gen( const SMESHDS_Mesh* theMesh )
757     :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
758   {}
759
760   long GetLinkID (const SMDS_MeshNode * n1,
761                   const SMDS_MeshNode * n2) const
762   {
763     return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
764   }
765
766   bool GetNodes (const long             theLinkID,
767                  const SMDS_MeshNode* & theNode1,
768                  const SMDS_MeshNode* & theNode2) const
769   {
770     theNode1 = myMesh->FindNode( theLinkID / myMaxID );
771     if ( !theNode1 ) return false;
772     theNode2 = myMesh->FindNode( theLinkID % myMaxID );
773     if ( !theNode2 ) return false;
774     return true;
775   }
776
777  private:
778   LinkID_Gen();
779   const SMESHDS_Mesh* myMesh;
780   long                myMaxID;
781 };
782
783 //=======================================================================
784 //function : TriToQuad
785 //purpose  : Fuse neighbour triangles into quadrangles.
786 //           theCrit is used to select a neighbour to fuse with.
787 //           theMaxAngle is a max angle between element normals at which
788 //           fusion is still performed.
789 //=======================================================================
790
791 bool SMESH_MeshEditor::TriToQuad (set<const SMDS_MeshElement*> &       theElems,
792                                   SMESH::Controls::NumericalFunctorPtr theCrit,
793                                   const double                         theMaxAngle)
794 {
795   MESSAGE( "::TriToQuad()" );
796
797   if ( !theCrit.get() )
798     return false;
799
800   SMESHDS_Mesh * aMesh = GetMeshDS();
801   LinkID_Gen aLinkID_Gen( aMesh );
802
803
804   // Prepare data for algo: build
805   // 1. map of elements with their linkIDs
806   // 2. map of linkIDs with their elements
807
808   map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
809   map< long, list< const SMDS_MeshElement* > >::iterator itLE;
810   map< const SMDS_MeshElement*, set< long > >  mapEl_setLi;
811   map< const SMDS_MeshElement*, set< long > >::iterator itEL;
812
813   set<const SMDS_MeshElement*>::iterator itElem;
814   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
815   {
816     const SMDS_MeshElement* elem = (*itElem);
817     if ( !elem || elem->NbNodes() != 3 )
818       continue;
819
820     // retrieve element nodes
821     const SMDS_MeshNode* aNodes [4];
822     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
823     int i = 0;
824     while ( itN->more() )
825       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
826     ASSERT( i == 3 );
827     aNodes[ 3 ] = aNodes[ 0 ];
828
829     // fill maps
830     for ( i = 0; i < 3; i++ )
831     {
832       long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
833       // check if elements sharing a link can be fused
834       itLE = mapLi_listEl.find( linkID );
835       if ( itLE != mapLi_listEl.end() )
836       {
837         if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link 
838           continue;
839         const SMDS_MeshElement* elem2 = (*itLE).second.front();
840 //         if ( FindShape( elem ) != FindShape( elem2 ))
841 //           continue; // do not fuse triangles laying on different shapes
842         if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
843           continue; // avoid making badly shaped quads
844         (*itLE).second.push_back( elem );
845       }
846       else
847         mapLi_listEl[ linkID ].push_back( elem );
848       mapEl_setLi [ elem ].insert( linkID );
849     }
850   }
851   // Clean the maps from the links shared by a sole element, ie
852   // links to which only one element is bound in mapLi_listEl
853
854   for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ )
855   {
856     int nbElems = (*itLE).second.size();
857     if ( nbElems < 2  ) {
858       const SMDS_MeshElement* elem = (*itLE).second.front();
859       long link = (*itLE).first;
860       mapEl_setLi[ elem ].erase( link );
861       if ( mapEl_setLi[ elem ].empty() )
862         mapEl_setLi.erase( elem );
863     }
864   }
865
866   // Algo: fuse triangles into quadrangles
867   
868   while ( ! mapEl_setLi.empty() )
869   {
870     // Look for the start element:
871     // the element having the least nb of shared links
872
873     const SMDS_MeshElement* startElem = 0;
874     int minNbLinks = 4;
875     for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ )
876     {
877       int nbLinks = (*itEL).second.size();
878       if ( nbLinks < minNbLinks )
879       {
880         startElem = (*itEL).first;
881         minNbLinks = nbLinks;
882         if ( minNbLinks == 1 )
883           break;
884       }
885     }
886
887     // search elements to fuse starting from startElem or links of elements
888     // fused earlyer - startLinks
889     list< long > startLinks;
890     while ( startElem || !startLinks.empty() )
891     {
892       while ( !startElem && !startLinks.empty() )
893       {
894         // Get an element to start, by a link
895         long linkId = startLinks.front();
896         startLinks.pop_front();
897         itLE = mapLi_listEl.find( linkId );
898         if ( itLE != mapLi_listEl.end() )
899         {
900           list< const SMDS_MeshElement* > & listElem = (*itLE).second;
901           list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
902           for ( ; itE != listElem.end() ; itE++ )
903             if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
904               startElem = (*itE);
905           mapLi_listEl.erase( itLE );
906         }
907       }
908
909       if ( startElem )
910       {
911         // Get candidates to be fused
912
913         const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
914         long link12, link13;
915         startElem = 0;
916         ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
917         set< long >& setLi = mapEl_setLi[ tr1 ];
918         ASSERT( !setLi.empty() );
919         set< long >::iterator itLi;
920         for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ )
921         {
922           long linkID = (*itLi);
923           itLE = mapLi_listEl.find( linkID );
924           if ( itLE == mapLi_listEl.end() )
925             continue;
926           const SMDS_MeshElement* elem = (*itLE).second.front();
927           if ( elem == tr1 )
928             elem = (*itLE).second.back();
929           mapLi_listEl.erase( itLE );
930           if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
931             continue;
932           if ( tr2 )
933           {
934             tr3 = elem;
935             link13 = linkID;
936           }
937           else
938           {
939             tr2 = elem;
940             link12 = linkID;
941           }
942
943           // add other links of elem to list of links to re-start from
944           set< long >& links = mapEl_setLi[ elem ];
945           set< long >::iterator it;
946           for ( it = links.begin(); it != links.end(); it++ )
947           {
948             long linkID2 = (*it);
949             if ( linkID2 != linkID )
950               startLinks.push_back( linkID2 );
951           }
952         }
953
954         // Get nodes of possible quadrangles
955
956         const SMDS_MeshNode *n12 [4], *n13 [4];
957         bool Ok12 = false, Ok13 = false;
958         const SMDS_MeshNode *linkNode1, *linkNode2;
959         if ( tr2 &&
960              aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
961              getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
962           Ok12 = true;
963         if ( tr3 &&
964              aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
965              getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
966           Ok13 = true;
967
968         // Choose a pair to fuse
969
970         if ( Ok12 && Ok13 )
971         {
972           SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
973           SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
974           double aBadRate12 = getBadRate( &quad12, theCrit );
975           double aBadRate13 = getBadRate( &quad13, theCrit );
976           if (  aBadRate13 < aBadRate12 )
977             Ok12 = false;
978           else
979             Ok13 = false;
980         }
981
982
983         // Make quadrangles
984         // and remove fused elems and removed links from the maps
985
986         mapEl_setLi.erase( tr1 );
987         if ( Ok12 )
988         {
989           mapEl_setLi.erase( tr2 );
990           mapLi_listEl.erase( link12 );
991           aMesh->ChangeElementNodes( tr1, n12, 4 );
992           aMesh->RemoveElement( tr2 );
993         }
994         else if ( Ok13 )
995         {
996           mapEl_setLi.erase( tr3 );
997           mapLi_listEl.erase( link13 );
998           aMesh->ChangeElementNodes( tr1, n13, 4 );
999           aMesh->RemoveElement( tr3 );
1000         }
1001
1002         // Next element to fuse: the rejected one
1003         if ( tr3 )
1004           startElem = Ok12 ? tr3 : tr2;
1005
1006       } // if ( startElem )
1007     } // while ( startElem || !startLinks.empty() )
1008   } // while ( ! mapEl_setLi.empty() )
1009     
1010   return true;
1011 }
1012
1013
1014 /*#define DUMPSO(txt) \
1015 //  cout << txt << endl;
1016 //=============================================================================
1017 //
1018 //
1019 //
1020 //=============================================================================
1021 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1022 {
1023   if ( i1 == i2 )
1024     return;
1025   int tmp = idNodes[ i1 ];
1026   idNodes[ i1 ] = idNodes[ i2 ];
1027   idNodes[ i2 ] = tmp;
1028   gp_Pnt Ptmp = P[ i1 ];
1029   P[ i1 ] = P[ i2 ];
1030   P[ i2 ] = Ptmp;
1031   DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1032 }
1033
1034 //=======================================================================
1035 //function : SortQuadNodes
1036 //purpose  : Set 4 nodes of a quadrangle face in a good order.
1037 //           Swap 1<->2 or 2<->3 nodes and correspondingly return
1038 //           1 or 2 else 0.
1039 //=======================================================================
1040
1041 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1042                                      int               idNodes[] )
1043 {
1044   gp_Pnt P[4];
1045   int i;
1046   for ( i = 0; i < 4; i++ ) {
1047     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1048     if ( !n ) return 0;
1049     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1050   }
1051
1052   gp_Vec V1(P[0], P[1]);
1053   gp_Vec V2(P[0], P[2]);
1054   gp_Vec V3(P[0], P[3]);
1055
1056   gp_Vec Cross1 = V1 ^ V2;
1057   gp_Vec Cross2 = V2 ^ V3;
1058
1059   i = 0;
1060   if (Cross1.Dot(Cross2) < 0)
1061   {
1062     Cross1 = V2 ^ V1;
1063     Cross2 = V1 ^ V3;
1064
1065     if (Cross1.Dot(Cross2) < 0)
1066       i = 2;
1067     else
1068       i = 1;
1069     swap ( i, i + 1, idNodes, P );
1070
1071 //     for ( int ii = 0; ii < 4; ii++ ) {
1072 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1073 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1074 //     }
1075   }
1076   return i;
1077 }
1078
1079 //=======================================================================
1080 //function : SortHexaNodes
1081 //purpose  : Set 8 nodes of a hexahedron in a good order.
1082 //           Return success status
1083 //=======================================================================
1084
1085 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1086                                       int               idNodes[] )
1087 {
1088   gp_Pnt P[8];
1089   int i;
1090   DUMPSO( "INPUT: ========================================");
1091   for ( i = 0; i < 8; i++ ) {
1092     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1093     if ( !n ) return false;
1094     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1095     DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1096   }
1097   DUMPSO( "========================================");
1098
1099   
1100   set<int> faceNodes;  // ids of bottom face nodes, to be found
1101   set<int> checkedId1; // ids of tried 2-nd nodes
1102   Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1103   const Standard_Real tol = 1.e-6;   // tolerance to find nodes in plane
1104   int iMin, iLoop1 = 0;
1105
1106   // Loop to try the 2-nd nodes
1107
1108   while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1109   {
1110     // Find not checked 2-nd node
1111     for ( i = 1; i < 8; i++ )
1112       if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1113         int id1 = idNodes[i];
1114         swap ( 1, i, idNodes, P );
1115         checkedId1.insert ( id1 );
1116         break;
1117       }
1118   
1119     // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1120     // ie that all but meybe one (id3 which is on the same face) nodes
1121     // lay on the same side from the triangle plane.
1122
1123     bool manyInPlane = false; // more than 4 nodes lay in plane
1124     int iLoop2 = 0;
1125     while ( ++iLoop2 < 6 ) {
1126
1127       // get 1-2-3 plane coeffs
1128       Standard_Real A, B, C, D;
1129       gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1130       if ( N.SquareMagnitude() > gp::Resolution() )
1131       {
1132         gp_Pln pln ( P[0], N );
1133         pln.Coefficients( A, B, C, D );
1134
1135         // find the node (iMin) closest to pln
1136         Standard_Real dist[ 8 ], minDist = DBL_MAX;
1137         set<int> idInPln;
1138         for ( i = 3; i < 8; i++ ) {
1139           dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1140           if ( fabs( dist[i] ) < minDist ) {
1141             minDist = fabs( dist[i] );
1142             iMin = i;
1143           }
1144           if ( fabs( dist[i] ) <= tol )
1145             idInPln.insert( idNodes[i] );
1146         }
1147
1148         // there should not be more than 4 nodes in bottom plane
1149         if ( idInPln.size() > 1 )
1150         {
1151           DUMPSO( "### idInPln.size() = " << idInPln.size());
1152           // idInPlane does not contain the first 3 nodes
1153           if ( manyInPlane || idInPln.size() == 5)
1154             return false; // all nodes in one plane
1155           manyInPlane = true;
1156
1157           // set the 1-st node to be not in plane
1158           for ( i = 3; i < 8; i++ ) {
1159             if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1160               DUMPSO( "### Reset 0-th node");
1161               swap( 0, i, idNodes, P );
1162               break;
1163             }
1164           }
1165
1166           // reset to re-check second nodes
1167           leastDist = DBL_MAX;
1168           faceNodes.clear();
1169           checkedId1.clear();
1170           iLoop1 = 0;
1171           break; // from iLoop2;
1172         }
1173
1174         // check that the other 4 nodes are on the same side
1175         bool sameSide = true;
1176         bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1177         for ( i = 3; sameSide && i < 8; i++ ) {
1178           if ( i != iMin )
1179             sameSide = ( isNeg == dist[i] <= 0.);
1180         }
1181
1182         // keep best solution
1183         if ( sameSide && minDist < leastDist ) {
1184           leastDist = minDist;
1185           faceNodes.clear();
1186           faceNodes.insert( idNodes[ 1 ] );
1187           faceNodes.insert( idNodes[ 2 ] );
1188           faceNodes.insert( idNodes[ iMin ] );
1189           DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1190             << " leastDist = " << leastDist);
1191           if ( leastDist <= DBL_MIN )
1192             break;
1193         }
1194       }
1195
1196       // set next 3-d node to check
1197       int iNext = 2 + iLoop2;
1198       if ( iNext < 8 ) {
1199         DUMPSO( "Try 2-nd");
1200         swap ( 2, iNext, idNodes, P );
1201       }
1202     } // while ( iLoop2 < 6 )
1203   } // iLoop1
1204
1205   if ( faceNodes.empty() ) return false;
1206
1207   // Put the faceNodes in proper places
1208   for ( i = 4; i < 8; i++ ) {
1209     if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1210       // find a place to put
1211       int iTo = 1;
1212       while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1213         iTo++;
1214       DUMPSO( "Set faceNodes");
1215       swap ( iTo, i, idNodes, P );
1216     }
1217   }
1218
1219     
1220   // Set nodes of the found bottom face in good order
1221   DUMPSO( " Found bottom face: ");
1222   i = SortQuadNodes( theMesh, idNodes );
1223   if ( i ) {
1224     gp_Pnt Ptmp = P[ i ];
1225     P[ i ] = P[ i+1 ];
1226     P[ i+1 ] = Ptmp;
1227   }
1228 //   else
1229 //     for ( int ii = 0; ii < 4; ii++ ) {
1230 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1231 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1232 //    }
1233
1234   // Gravity center of the top and bottom faces
1235   gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1236   gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1237
1238   // Get direction from the bottom to the top face
1239   gp_Vec upDir ( aGCb, aGCt );
1240   Standard_Real upDirSize = upDir.Magnitude();
1241   if ( upDirSize <= gp::Resolution() ) return false;
1242   upDir / upDirSize;
1243   
1244   // Assure that the bottom face normal points up
1245   gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1246   Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1247   if ( Nb.Dot( upDir ) < 0 ) {
1248     DUMPSO( "Reverse bottom face");
1249     swap( 1, 3, idNodes, P );
1250   }
1251
1252   // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1253   Standard_Real minDist = DBL_MAX;
1254   for ( i = 4; i < 8; i++ ) {
1255     // projection of P[i] to the plane defined by P[0] and upDir
1256     gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1257     Standard_Real sqDist = P[0].SquareDistance( Pp );
1258     if ( sqDist < minDist ) {
1259       minDist = sqDist;
1260       iMin = i;
1261     }
1262   }
1263   DUMPSO( "Set 4-th");
1264   swap ( 4, iMin, idNodes, P );
1265
1266   // Set nodes of the top face in good order
1267   DUMPSO( "Sort top face");
1268   i = SortQuadNodes( theMesh, &idNodes[4] );
1269   if ( i ) {
1270     i += 4;
1271     gp_Pnt Ptmp = P[ i ];
1272     P[ i ] = P[ i+1 ];
1273     P[ i+1 ] = Ptmp;
1274   }
1275
1276   // Assure that direction of the top face normal is from the bottom face
1277   gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1278   Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1279   if ( Nt.Dot( upDir ) < 0 ) {
1280     DUMPSO( "Reverse top face");
1281     swap( 5, 7, idNodes, P );
1282   }
1283
1284 //   DUMPSO( "OUTPUT: ========================================");
1285 //   for ( i = 0; i < 8; i++ ) {
1286 //     float *p = ugrid->GetPoint(idNodes[i]);
1287 //     DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1288 //   }
1289
1290   return true;
1291 }*/
1292
1293 //=======================================================================
1294 //function : laplacianSmooth
1295 //purpose  : pulls theNode toward the center of surrounding nodes directly
1296 //           connected to that node along an element edge
1297 //=======================================================================
1298
1299 void laplacianSmooth(const SMDS_MeshNode*                 theNode,
1300                      const Handle(Geom_Surface)&          theSurface,
1301                      map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1302 {
1303   // find surrounding nodes
1304
1305   set< const SMDS_MeshNode* > nodeSet;
1306   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1307   while ( elemIt->more() )
1308   {
1309     const SMDS_MeshElement* elem = elemIt->next();
1310     if ( elem->GetType() != SMDSAbs_Face )
1311       continue;
1312
1313     // put all nodes in array
1314     int nbNodes = 0, iNode = 0;
1315     vector< const SMDS_MeshNode*> aNodes( elem->NbNodes() );
1316     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1317     while ( itN->more() )
1318     {
1319       aNodes[ nbNodes ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1320       if ( aNodes[ nbNodes ] == theNode )
1321         iNode = nbNodes; // index of theNode within aNodes
1322       nbNodes++;
1323     }
1324     // add linked nodes
1325     int iAfter = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
1326     nodeSet.insert( aNodes[ iAfter ]);
1327     int iBefore = ( iNode == 0 ) ? nbNodes - 1 : iNode - 1;
1328     nodeSet.insert( aNodes[ iBefore ]);
1329   }
1330
1331   // compute new coodrs
1332
1333   double coord[] = { 0., 0., 0. };
1334   set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1335   for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1336     const SMDS_MeshNode* node = (*nodeSetIt);
1337     if ( theSurface.IsNull() ) { // smooth in 3D
1338       coord[0] += node->X();
1339       coord[1] += node->Y();
1340       coord[2] += node->Z();
1341     }
1342     else { // smooth in 2D
1343       ASSERT( theUVMap.find( node ) != theUVMap.end() );
1344       gp_XY* uv = theUVMap[ node ];
1345       coord[0] += uv->X();
1346       coord[1] += uv->Y();
1347     }
1348   }
1349   int nbNodes = nodeSet.size();
1350   if ( !nbNodes )
1351     return;
1352   coord[0] /= nbNodes;
1353   coord[1] /= nbNodes;
1354
1355   if ( !theSurface.IsNull() ) {
1356     ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1357     theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
1358     gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
1359     coord[0] = p3d.X();
1360     coord[1] = p3d.Y();
1361     coord[2] = p3d.Z();
1362   }
1363   else
1364     coord[2] /= nbNodes;
1365
1366   // move node
1367
1368   const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
1369 }
1370
1371 //=======================================================================
1372 //function : centroidalSmooth
1373 //purpose  : pulls theNode toward the element-area-weighted centroid of the
1374 //           surrounding elements
1375 //=======================================================================
1376
1377 void centroidalSmooth(const SMDS_MeshNode*                 theNode,
1378                       const Handle(Geom_Surface)&          theSurface,
1379                       map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1380 {
1381   gp_XYZ aNewXYZ(0.,0.,0.);
1382   SMESH::Controls::Area anAreaFunc;
1383   double totalArea = 0.;
1384   int nbElems = 0;
1385
1386   // compute new XYZ
1387
1388   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator();
1389   while ( elemIt->more() )
1390   {
1391     const SMDS_MeshElement* elem = elemIt->next();
1392     if ( elem->GetType() != SMDSAbs_Face )
1393       continue;
1394     nbElems++;
1395
1396     gp_XYZ elemCenter(0.,0.,0.);
1397     SMESH::Controls::TSequenceOfXYZ aNodePoints;
1398     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1399     while ( itN->more() )
1400     {
1401       const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1402       gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1403       aNodePoints.push_back( aP );
1404       if ( !theSurface.IsNull() ) { // smooth in 2D
1405         ASSERT( theUVMap.find( aNode ) != theUVMap.end() );
1406         gp_XY* uv = theUVMap[ aNode ];
1407         aP.SetCoord( uv->X(), uv->Y(), 0. );
1408       }
1409       elemCenter += aP;
1410     }
1411     double elemArea = anAreaFunc.GetValue( aNodePoints );
1412     totalArea += elemArea;
1413     elemCenter /= elem->NbNodes();
1414     aNewXYZ += elemCenter * elemArea;
1415   }
1416   aNewXYZ /= totalArea;
1417   if ( !theSurface.IsNull() ) {
1418     ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1419     theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
1420     aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
1421   }
1422
1423   // move node
1424
1425   const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
1426 }
1427
1428 //=======================================================================
1429 //function : getClosestUV
1430 //purpose  : return UV of closest projection
1431 //=======================================================================
1432
1433 static bool getClosestUV (Extrema_GenExtPS& projector,
1434                           const gp_Pnt&     point,
1435                           gp_XY &           result)
1436 {
1437   projector.Perform( point );
1438   if ( projector.IsDone() ) {
1439     double u, v, minVal = DBL_MAX;
1440     for ( int i = projector.NbExt(); i > 0; i-- )
1441       if ( projector.Value( i ) < minVal ) {
1442         minVal = projector.Value( i );
1443         projector.Point( i ).Parameter( u, v );
1444       }
1445     result.SetCoord( u, v );
1446     return true;
1447   }
1448   return false;
1449 }
1450
1451 //=======================================================================
1452 //function : Smooth
1453 //purpose  : Smooth theElements during theNbIterations or until a worst
1454 //           element has aspect ratio <= theTgtAspectRatio.
1455 //           Aspect Ratio varies in range [1.0, inf].
1456 //           If theElements is empty, the whole mesh is smoothed.
1457 //           theFixedNodes contains additionally fixed nodes. Nodes built
1458 //           on edges and boundary nodes are always fixed.
1459 //=======================================================================
1460
1461 void SMESH_MeshEditor::Smooth (set<const SMDS_MeshElement*> & theElems,
1462                                set<const SMDS_MeshNode*> &    theFixedNodes,
1463                                const SmoothMethod             theSmoothMethod,
1464                                const int                      theNbIterations,
1465                                double                         theTgtAspectRatio,
1466                                const bool                     the2D)
1467 {
1468   MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
1469
1470   if ( theTgtAspectRatio < 1.0 )
1471     theTgtAspectRatio = 1.0;
1472
1473   SMESH::Controls::AspectRatio aQualityFunc;
1474
1475   SMESHDS_Mesh* aMesh = GetMeshDS();
1476   
1477   if ( theElems.empty() ) {
1478     // add all faces to theElems
1479     SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
1480     while ( fIt->more() )
1481       theElems.insert( fIt->next() );
1482   }
1483   // get all face ids theElems are on
1484   set< int > faceIdSet;
1485   set< const SMDS_MeshElement* >::iterator itElem;
1486   if ( the2D )
1487     for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1488       int fId = FindShape( *itElem );
1489       // check that corresponding submesh exists and a shape is face
1490       if (fId &&
1491           faceIdSet.find( fId ) == faceIdSet.end() &&
1492           aMesh->MeshElements( fId )) {
1493         TopoDS_Shape F = aMesh->IndexToShape( fId );
1494         if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
1495           faceIdSet.insert( fId );
1496       }
1497     }
1498   faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
1499
1500   // ===============================================
1501   // smooth elements on each TopoDS_Face separately
1502   // ===============================================
1503
1504   set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
1505   for ( ; fId != faceIdSet.rend(); ++fId )
1506   {
1507     // get face surface and submesh
1508     Handle(Geom_Surface) surface;
1509     SMESHDS_SubMesh* faceSubMesh = 0;
1510     TopoDS_Face face;
1511     double fToler2 = 0, vPeriod = 0., uPeriod = 0., f,l;
1512     double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
1513     bool isUPeriodic = false, isVPeriodic = false;
1514     if ( *fId ) {
1515       face = TopoDS::Face( aMesh->IndexToShape( *fId ));
1516       surface = BRep_Tool::Surface( face );
1517       faceSubMesh = aMesh->MeshElements( *fId );
1518       fToler2 = BRep_Tool::Tolerance( face );
1519       fToler2 *= fToler2 * 10.;
1520       isUPeriodic = surface->IsUPeriodic();
1521       if ( isUPeriodic )
1522         vPeriod = surface->UPeriod();
1523       isVPeriodic = surface->IsVPeriodic();
1524       if ( isVPeriodic )
1525         uPeriod = surface->VPeriod();
1526       surface->Bounds( u1, u2, v1, v2 );
1527     }
1528     // ---------------------------------------------------------
1529     // for elements on a face, find movable and fixed nodes and
1530     // compute UV for them
1531     // ---------------------------------------------------------
1532     bool checkBoundaryNodes = false;
1533     set<const SMDS_MeshNode*> setMovableNodes;
1534     map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
1535     list< gp_XY > listUV; // uvs the 2 uvMaps refer to
1536     list< const SMDS_MeshElement* > elemsOnFace;
1537
1538     Extrema_GenExtPS projector;
1539     GeomAdaptor_Surface surfAdaptor;
1540     if ( !surface.IsNull() ) {
1541       surfAdaptor.Load( surface );
1542       projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
1543     }
1544     int nbElemOnFace = 0;
1545     itElem = theElems.begin();
1546      // loop on not yet smoothed elements: look for elems on a face
1547     while ( itElem != theElems.end() )
1548     {
1549       if ( faceSubMesh && nbElemOnFace == faceSubMesh->NbElements() )
1550         break; // all elements found
1551
1552       const SMDS_MeshElement* elem = (*itElem);
1553       if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
1554           ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
1555         ++itElem;
1556         continue;
1557       }
1558       elemsOnFace.push_back( elem );
1559       theElems.erase( itElem++ );
1560       nbElemOnFace++;
1561
1562       // get movable nodes of elem
1563       const SMDS_MeshNode* node;
1564       SMDS_TypeOfPosition posType;
1565       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1566       while ( itN->more() ) {
1567         node = static_cast<const SMDS_MeshNode*>( itN->next() );
1568         const SMDS_PositionPtr& pos = node->GetPosition();
1569         posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1570         if (posType != SMDS_TOP_EDGE &&
1571             posType != SMDS_TOP_VERTEX && 
1572             theFixedNodes.find( node ) == theFixedNodes.end())
1573         {
1574           // check if all faces around the node are on faceSubMesh
1575           // because a node on edge may be bound to face
1576           SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1577           bool all = true;
1578           if ( faceSubMesh ) {
1579             while ( eIt->more() && all ) {
1580               const SMDS_MeshElement* e = eIt->next();
1581               if ( e->GetType() == SMDSAbs_Face )
1582                 all = faceSubMesh->Contains( e );
1583             }
1584           }
1585           if ( all )
1586             setMovableNodes.insert( node );
1587           else
1588             checkBoundaryNodes = true;
1589         }
1590         if ( posType == SMDS_TOP_3DSPACE )
1591           checkBoundaryNodes = true;
1592       }
1593
1594       if ( surface.IsNull() )
1595         continue;
1596
1597       // get nodes to check UV
1598       list< const SMDS_MeshNode* > uvCheckNodes;
1599       itN = elem->nodesIterator();
1600       while ( itN->more() ) {
1601         node = static_cast<const SMDS_MeshNode*>( itN->next() );
1602         if ( uvMap.find( node ) == uvMap.end() )
1603           uvCheckNodes.push_back( node );
1604         // add nodes of elems sharing node
1605 //         SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
1606 //         while ( eIt->more() ) {
1607 //           const SMDS_MeshElement* e = eIt->next();
1608 //           if ( e != elem && e->GetType() == SMDSAbs_Face ) {
1609 //             SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1610 //             while ( nIt->more() ) {
1611 //               const SMDS_MeshNode* n =
1612 //                 static_cast<const SMDS_MeshNode*>( nIt->next() );
1613 //               if ( uvMap.find( n ) == uvMap.end() )
1614 //                 uvCheckNodes.push_back( n );
1615 //             }
1616 //           }
1617 //         }
1618       }
1619       // check UV on face
1620       list< const SMDS_MeshNode* >::iterator n = uvCheckNodes.begin();
1621       for ( ; n != uvCheckNodes.end(); ++n )
1622       {
1623         node = *n;
1624         gp_XY uv( 0, 0 );
1625         const SMDS_PositionPtr& pos = node->GetPosition();
1626         posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
1627         // get existing UV
1628         switch ( posType ) {
1629         case SMDS_TOP_FACE: {
1630           SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
1631           uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
1632           break;
1633         }
1634         case SMDS_TOP_EDGE: {
1635           TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1636           Handle(Geom2d_Curve) pcurve;
1637           if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
1638             pcurve = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), face, f,l );
1639           if ( !pcurve.IsNull() ) {
1640             double u = (( SMDS_EdgePosition* ) pos.get() )->GetUParameter();
1641             uv = pcurve->Value( u ).XY();
1642           }
1643           break;
1644         }
1645         case SMDS_TOP_VERTEX: {
1646           TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
1647           if ( !S.IsNull() && S.ShapeType() == TopAbs_VERTEX )
1648             uv = BRep_Tool::Parameters( TopoDS::Vertex( S ), face ).XY();
1649           break;
1650         }
1651         default:;
1652         }
1653         // check existing UV
1654         bool project = true;
1655         gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
1656         double dist1 = DBL_MAX, dist2 = 0;
1657         if ( posType != SMDS_TOP_3DSPACE ) {
1658           dist1 = pNode.SquareDistance( surface->Value( uv.X(), uv.Y() ));
1659           project = dist1 > fToler2;
1660         }
1661         if ( project ) { // compute new UV
1662           gp_XY newUV;
1663           if ( !getClosestUV( projector, pNode, newUV )) {
1664             MESSAGE("Node Projection Failed " << node);
1665           }
1666           else {
1667             if ( isUPeriodic )
1668               newUV.SetX( ElCLib::InPeriod( newUV.X(), u1, u2 ));
1669             if ( isVPeriodic )
1670               newUV.SetY( ElCLib::InPeriod( newUV.Y(), v1, v2 ));
1671             // check new UV
1672             if ( posType != SMDS_TOP_3DSPACE )
1673               dist2 = pNode.SquareDistance( surface->Value( newUV.X(), newUV.Y() ));
1674             if ( dist2 < dist1 )
1675               uv = newUV;
1676           }
1677         }
1678         // store UV in the map
1679         listUV.push_back( uv );
1680         uvMap.insert( make_pair( node, &listUV.back() ));
1681       }
1682     } // loop on not yet smoothed elements
1683
1684     if ( !faceSubMesh || nbElemOnFace != faceSubMesh->NbElements() )
1685       checkBoundaryNodes = true;
1686
1687     // fix nodes on mesh boundary
1688
1689     if ( checkBoundaryNodes )
1690     {
1691       typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
1692       map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
1693       map< TLink, int >::iterator link_nb;
1694       // put all elements links to linkNbMap
1695       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1696       for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1697       {
1698         // put elem nodes in array
1699         vector< const SMDS_MeshNode* > nodes;
1700         nodes.reserve( (*elemIt)->NbNodes() + 1 );
1701         SMDS_ElemIteratorPtr itN = (*elemIt)->nodesIterator();
1702         while ( itN->more() )
1703           nodes.push_back( static_cast<const SMDS_MeshNode*>( itN->next() ));
1704         nodes.push_back( nodes.front() );
1705         // loop on elem links: insert them in linkNbMap
1706         for ( int iN = 1; iN < nodes.size(); ++iN ) {
1707           TLink link;
1708           if ( nodes[ iN-1 ]->GetID() < nodes[ iN ]->GetID() )
1709             link = make_pair( nodes[ iN-1 ], nodes[ iN ] );
1710           else
1711             link = make_pair( nodes[ iN ], nodes[ iN-1 ] );
1712           link_nb = linkNbMap.find( link );
1713           if ( link_nb == linkNbMap.end() )
1714             linkNbMap.insert( make_pair ( link, 1 ));
1715           else
1716             link_nb->second++;
1717         }
1718       }
1719       // remove nodes that are in links encountered only once from setMovableNodes
1720       for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
1721         if ( link_nb->second == 1 ) {
1722           setMovableNodes.erase( link_nb->first.first );
1723           setMovableNodes.erase( link_nb->first.second );
1724         }
1725       }
1726     }
1727
1728     // -----------------------------------------------------
1729     // for nodes on seam edge, compute one more UV ( uvMap2 );
1730     // find movable nodes linked to nodes on seam and which
1731     // are to be smoothed using the second UV ( uvMap2 )
1732     // -----------------------------------------------------
1733
1734     set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
1735     if ( !surface.IsNull() )
1736     {
1737       TopExp_Explorer eExp( face, TopAbs_EDGE );
1738       for ( ; eExp.More(); eExp.Next() )
1739       {
1740         TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
1741         if ( !BRep_Tool::IsClosed( edge, face ))
1742           continue;
1743         SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
1744         if ( !sm ) continue;
1745         // find out which parameter varies for a node on seam
1746         double f,l;
1747         gp_Pnt2d uv1, uv2;
1748         Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1749         if ( pcurve.IsNull() ) continue;
1750         uv1 = pcurve->Value( f );
1751         edge.Reverse();
1752         pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
1753         if ( pcurve.IsNull() ) continue;
1754         uv2 = pcurve->Value( f );
1755         int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
1756         // assure uv1 < uv2
1757         if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
1758           gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
1759         }
1760         // get nodes on seam and its vertices
1761         list< const SMDS_MeshNode* > seamNodes;
1762         SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
1763         while ( nSeamIt->more() )
1764           seamNodes.push_back( nSeamIt->next() );
1765         TopExp_Explorer vExp( edge, TopAbs_VERTEX );
1766         for ( ; vExp.More(); vExp.Next() ) {
1767           sm = aMesh->MeshElements( vExp.Current() );
1768           if ( sm ) {
1769             nSeamIt = sm->GetNodes();
1770             while ( nSeamIt->more() )
1771               seamNodes.push_back( nSeamIt->next() );
1772           }
1773         }
1774         // loop on nodes on seam
1775         list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
1776         for ( ; noSeIt != seamNodes.end(); ++noSeIt )
1777         {
1778           const SMDS_MeshNode* nSeam = *noSeIt;
1779           map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
1780           if ( n_uv == uvMap.end() )
1781             continue;
1782           // set the first UV
1783           n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
1784           // set the second UV
1785           listUV.push_back( *n_uv->second );
1786           listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
1787           if ( uvMap2.empty() )
1788             uvMap2 = uvMap; // copy the uvMap contents
1789           uvMap2[ nSeam ] = &listUV.back();
1790
1791           // collect movable nodes linked to ones on seam in nodesNearSeam
1792           SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator();
1793           while ( eIt->more() )
1794           {
1795             const SMDS_MeshElement* e = eIt->next();
1796             if ( e->GetType() != SMDSAbs_Face )
1797               continue;
1798             int nbUseMap1 = 0, nbUseMap2 = 0;
1799             SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1800             while ( nIt->more() )
1801             {
1802               const SMDS_MeshNode* n =
1803                 static_cast<const SMDS_MeshNode*>( nIt->next() );
1804               if (n == nSeam ||
1805                   setMovableNodes.find( n ) == setMovableNodes.end() )
1806                 continue;
1807               // add only nodes being closer to uv2 than to uv1
1808               gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
1809                            0.5 * ( n->Y() + nSeam->Y() ),
1810                            0.5 * ( n->Z() + nSeam->Z() ));
1811               gp_XY uv;
1812               getClosestUV( projector, pMid, uv );
1813               if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
1814                 nodesNearSeam.insert( n );
1815                 nbUseMap2++;
1816               }
1817               else
1818                 nbUseMap1++;
1819             }
1820             // for centroidalSmooth all element nodes must
1821             // be on one side of a seam
1822             if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 )
1823             {
1824               SMDS_ElemIteratorPtr nIt = e->nodesIterator();
1825               while ( nIt->more() ) {
1826                 const SMDS_MeshNode* n =
1827                   static_cast<const SMDS_MeshNode*>( nIt->next() );
1828                 setMovableNodes.erase( n );
1829               }
1830             }
1831           }
1832         } // loop on nodes on seam 
1833       } // loop on edge of a face
1834     } // if ( !face.IsNull() )
1835
1836     if ( setMovableNodes.empty() ) {
1837       MESSAGE( "Face id : " << *fId << " - NO SMOOTHING: no nodes to move!!!");
1838       continue; // goto next face
1839     }
1840
1841     // -------------
1842     // SMOOTHING //
1843     // -------------
1844
1845     int it = -1;
1846     double maxRatio = -1., maxDisplacement = -1.;
1847     set<const SMDS_MeshNode*>::iterator nodeToMove;
1848     for ( it = 0; it < theNbIterations; it++ )
1849     {
1850       maxDisplacement = 0.;
1851       nodeToMove = setMovableNodes.begin();
1852       for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1853       {
1854         const SMDS_MeshNode* node = (*nodeToMove);
1855         gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
1856
1857         // smooth
1858         bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
1859         if ( theSmoothMethod == LAPLACIAN )
1860           laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
1861         else
1862           centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
1863
1864         // node displacement
1865         gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
1866         Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
1867         if ( aDispl > maxDisplacement )
1868           maxDisplacement = aDispl;
1869       }
1870       // no node movement => exit
1871       if ( maxDisplacement < 1.e-16 ) {
1872         MESSAGE("-- no node movement --");
1873         break;
1874       }
1875
1876       // check elements quality
1877       maxRatio  = 0;
1878       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
1879       for ( ; elemIt != elemsOnFace.end(); ++elemIt )
1880       {
1881         const SMDS_MeshElement* elem = (*elemIt);
1882         if ( !elem || elem->GetType() != SMDSAbs_Face )
1883           continue;
1884         SMESH::Controls::TSequenceOfXYZ aPoints;
1885         if ( aQualityFunc.GetPoints( elem, aPoints )) {
1886           double aValue = aQualityFunc.GetValue( aPoints );
1887           if ( aValue > maxRatio )
1888             maxRatio = aValue;
1889         }
1890       }
1891       if ( maxRatio <= theTgtAspectRatio ) {
1892         MESSAGE("-- quality achived --");
1893         break;
1894       }
1895       if (it+1 == theNbIterations) {
1896         MESSAGE("-- Iteration limit exceeded --");
1897       }
1898     } // smoothing iterations
1899
1900     MESSAGE(" Face id: " << *fId <<
1901             " Nb iterstions: " << it <<
1902             " Displacement: " << maxDisplacement <<
1903             " Aspect Ratio " << maxRatio);
1904
1905     // ---------------------------------------
1906     // new nodes positions are computed,
1907     // record movement in DS and set new UV
1908     // ---------------------------------------
1909
1910     nodeToMove = setMovableNodes.begin();
1911     for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ )
1912     {
1913       SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
1914       aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
1915       map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
1916       if ( node_uv != uvMap.end() ) {
1917         gp_XY* uv = node_uv->second;
1918         node->SetPosition
1919           ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
1920       }
1921     }
1922
1923   } // loop on face ids
1924 }
1925
1926 //=======================================================================
1927 //function : isReverse
1928 //purpose  : Return true if normal of prevNodes is not co-directied with
1929 //           gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
1930 //           iNotSame is where prevNodes and nextNodes are different
1931 //=======================================================================
1932
1933 static bool isReverse(const SMDS_MeshNode* prevNodes[],
1934                       const SMDS_MeshNode* nextNodes[],
1935                       const int            nbNodes,
1936                       const int            iNotSame)
1937 {
1938   int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
1939   int iAfterNotSame  = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
1940
1941   const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
1942   const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
1943   const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
1944   const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
1945
1946   gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
1947   gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
1948   gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
1949   gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
1950
1951   gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
1952
1953   return (vA ^ vB) * vN < 0.0;
1954 }
1955
1956 //=======================================================================
1957 //function : sweepElement
1958 //purpose  :
1959 //=======================================================================
1960
1961 static void sweepElement(SMESHDS_Mesh*                         aMesh,
1962                          const SMDS_MeshElement*               elem,
1963                          const vector<TNodeOfNodeListMapItr> & newNodesItVec,
1964                          list<const SMDS_MeshElement*>&        newElems)
1965 {
1966   // Loop on elem nodes:
1967   // find new nodes and detect same nodes indices
1968   int nbNodes = elem->NbNodes();
1969   list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
1970   const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ];
1971   int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
1972
1973   for ( iNode = 0; iNode < nbNodes; iNode++ )
1974   {
1975     TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
1976     const SMDS_MeshNode*                 node         = nnIt->first;
1977     const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
1978     if ( listNewNodes.empty() )
1979       return;
1980
1981     itNN[ iNode ] = listNewNodes.begin();
1982     prevNod[ iNode ] = node;
1983     nextNod[ iNode ] = listNewNodes.front();
1984     if ( prevNod[ iNode ] != nextNod [ iNode ])
1985       iNotSameNode = iNode;
1986     else {
1987       iSameNode = iNode;
1988       nbSame++;
1989     }
1990   }
1991   if ( nbSame == nbNodes || nbSame > 2) {
1992     MESSAGE( " Too many same nodes of element " << elem->GetID() );
1993     return;
1994   }
1995
1996   int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
1997   if ( nbSame > 0 ) {
1998     iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
1999     iAfterSame  = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
2000     iOpposSame  = ( iSameNode - 2 < 0  ? iSameNode + 2 : iSameNode - 2 );
2001   }
2002
2003   // check element orientation
2004   int i0 = 0, i2 = 2;
2005   if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
2006     //MESSAGE("Reversed elem " << elem );
2007     i0 = 2;
2008     i2 = 0;
2009     if ( nbSame > 0 ) {
2010       int iAB = iAfterSame + iBeforeSame;
2011       iBeforeSame = iAB - iBeforeSame;
2012       iAfterSame  = iAB - iAfterSame;
2013     }
2014   }
2015
2016   // make new elements
2017   int iStep, nbSteps = newNodesItVec[ 0 ]->second.size();
2018   for (iStep = 0; iStep < nbSteps; iStep++ )
2019   {
2020     // get next nodes
2021     for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2022       nextNod[ iNode ] = *itNN[ iNode ];
2023       itNN[ iNode ]++;
2024     }
2025     SMDS_MeshElement* aNewElem = 0;
2026     switch ( nbNodes )
2027     {
2028     case 0:
2029       return;
2030     case 1: { // NODE
2031       if ( nbSame == 0 )
2032         aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
2033       break;
2034     }
2035     case 2: { // EDGE
2036
2037       if ( nbSame == 0 )
2038         aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2039                                   nextNod[ 1 ], nextNod[ 0 ] );
2040       else
2041         aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2042                                   nextNod[ iNotSameNode ] );
2043       break;
2044     }
2045     case 3: { // TRIANGLE
2046
2047       if ( nbSame == 0 )       // --- pentahedron
2048         aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2049                                      nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
2050
2051       else if ( nbSame == 1 )  // --- pyramid
2052         aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ],  prevNod[ iAfterSame ],
2053                                      nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2054                                      nextNod[ iSameNode ]);
2055
2056       else // 2 same nodes:      --- tetrahedron
2057         aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2058                                      nextNod[ iNotSameNode ]);
2059       break;
2060     }
2061     case 4: { // QUADRANGLE
2062
2063       if ( nbSame == 0 )       // --- hexahedron
2064         aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
2065                                      nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
2066
2067       else if ( nbSame == 1 )  // --- pyramid + pentahedron
2068       {
2069         aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ],  prevNod[ iAfterSame ],
2070                                      nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2071                                      nextNod[ iSameNode ]);
2072         newElems.push_back( aNewElem );
2073         aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iOpposSame ],
2074                                      prevNod[ iBeforeSame ],  nextNod[ iAfterSame ],
2075                                      nextNod[ iOpposSame ],  nextNod[ iBeforeSame ] );
2076       }
2077       else if ( nbSame == 2 )  // pentahedron
2078       {
2079         if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
2080           // iBeforeSame is same too
2081           aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
2082                                        nextNod[ iOpposSame ], prevNod[ iSameNode ],
2083                                        prevNod[ iAfterSame ],  nextNod[ iAfterSame ]);
2084         else
2085           // iAfterSame is same too
2086           aNewElem = aMesh->AddVolume (prevNod[ iSameNode ], prevNod[ iBeforeSame ],
2087                                        nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
2088                                        prevNod[ iOpposSame ],  nextNod[ iOpposSame ]);
2089       }
2090       break;
2091     }
2092     default: {
2093       // realized for extrusion only
2094       vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2095       vector<int> quantities (nbNodes + 2);
2096
2097       quantities[0] = nbNodes; // bottom of prism
2098       for (int inode = 0; inode < nbNodes; inode++) {
2099         polyedre_nodes[inode] = prevNod[inode];
2100       }
2101
2102       quantities[1] = nbNodes; // top of prism
2103       for (int inode = 0; inode < nbNodes; inode++) {
2104         polyedre_nodes[nbNodes + inode] = nextNod[inode];
2105       }
2106
2107       for (int iface = 0; iface < nbNodes; iface++) {
2108         quantities[iface + 2] = 4;
2109         int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2110         polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2111         polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2112         polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2113         polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2114       }
2115       aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2116     }
2117     }
2118     if ( aNewElem )
2119       newElems.push_back( aNewElem );
2120
2121     // set new prev nodes
2122     for ( iNode = 0; iNode < nbNodes; iNode++ )
2123       prevNod[ iNode ] = nextNod[ iNode ];
2124
2125   } // for steps
2126 }
2127
2128 //=======================================================================
2129 //function : makeWalls
2130 //purpose  : create 1D and 2D elements around swept elements
2131 //=======================================================================
2132
2133 static void makeWalls (SMESHDS_Mesh*                 aMesh,
2134                        TNodeOfNodeListMap &          mapNewNodes,
2135                        TElemOfElemListMap &          newElemsMap,
2136                        TElemOfVecOfNnlmiMap &        elemNewNodesMap,
2137                        set<const SMDS_MeshElement*>& elemSet)
2138 {
2139   ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
2140
2141   // Find nodes belonging to only one initial element - sweep them to get edges.
2142
2143   TNodeOfNodeListMapItr nList = mapNewNodes.begin();
2144   for ( ; nList != mapNewNodes.end(); nList++ )
2145   {
2146     const SMDS_MeshNode* node =
2147       static_cast<const SMDS_MeshNode*>( nList->first );
2148     SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2149     int nbInitElems = 0;
2150     while ( eIt->more() && nbInitElems < 2 )
2151       if ( elemSet.find( eIt->next() ) != elemSet.end() )
2152         nbInitElems++;
2153     if ( nbInitElems < 2 ) {
2154       vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2155       list<const SMDS_MeshElement*> newEdges;
2156       sweepElement( aMesh, node, newNodesItVec, newEdges );
2157     }
2158   }
2159
2160   // Make a ceiling for each element ie an equal element of last new nodes.
2161   // Find free links of faces - make edges and sweep them into faces.
2162   
2163   TElemOfElemListMap::iterator   itElem      = newElemsMap.begin();
2164   TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2165   for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ )
2166   {
2167     const SMDS_MeshElement* elem = itElem->first;
2168     vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2169
2170     if ( elem->GetType() == SMDSAbs_Edge )
2171     {
2172       // create a ceiling edge
2173       aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2174                      vecNewNodes[ 1 ]->second.back() );
2175     }
2176     if ( elem->GetType() != SMDSAbs_Face )
2177       continue;
2178
2179     bool hasFreeLinks = false;
2180
2181     set<const SMDS_MeshElement*> avoidSet;
2182     avoidSet.insert( elem );
2183
2184     // loop on a face nodes
2185     set<const SMDS_MeshNode*> aFaceLastNodes;
2186     int iNode, nbNodes = vecNewNodes.size();
2187     for ( iNode = 0; iNode < nbNodes; iNode++ )
2188     {
2189       aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
2190       // look for free links of a face
2191       int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
2192       const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
2193       const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
2194       // check if a link is free
2195       if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet ))
2196       {
2197         hasFreeLinks = true;
2198         // make an edge and a ceiling for a new edge
2199         if ( !aMesh->FindEdge( n1, n2 ))
2200           aMesh->AddEdge( n1, n2 );
2201         n1 = vecNewNodes[ iNode ]->second.back();
2202         n2 = vecNewNodes[ iNext ]->second.back();
2203         if ( !aMesh->FindEdge( n1, n2 ))
2204           aMesh->AddEdge( n1, n2 );
2205       }
2206     }
2207     // sweep free links into faces
2208
2209     if ( hasFreeLinks )
2210     {
2211       list<const SMDS_MeshElement*> & newVolumes = itElem->second;
2212       int iStep, nbSteps = vecNewNodes[0]->second.size();
2213       int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
2214
2215       set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
2216       for ( iNode = 0; iNode < nbNodes; iNode++ )
2217         initNodeSet.insert( vecNewNodes[ iNode ]->first );
2218
2219       for ( volNb = 0; volNb < nbVolumesByStep; volNb++ )
2220       {
2221         list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
2222         iVol = 0;
2223         while ( iVol++ < volNb ) v++;
2224         // find indices of free faces of a volume
2225         list< int > fInd;
2226         SMDS_VolumeTool vTool( *v );
2227         int iF, nbF = vTool.NbFaces();
2228         for ( iF = 0; iF < nbF; iF ++ )
2229           if (vTool.IsFreeFace( iF ) &&
2230               vTool.GetFaceNodes( iF, faceNodeSet ) &&
2231               initNodeSet != faceNodeSet) // except an initial face
2232             fInd.push_back( iF );
2233         if ( fInd.empty() )
2234           continue;
2235
2236         // create faces for all steps
2237         for ( iStep = 0; iStep < nbSteps; iStep++ )
2238         {
2239           vTool.Set( *v );
2240           vTool.SetExternalNormal();
2241           list< int >::iterator ind = fInd.begin();
2242           for ( ; ind != fInd.end(); ind++ )
2243           {
2244             const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
2245             switch ( vTool.NbFaceNodes( *ind ) ) {
2246             case 3:
2247               aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ); break;
2248             case 4:
2249               aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ); break;
2250             default:
2251               {
2252                 int nbPolygonNodes = vTool.NbFaceNodes( *ind );
2253                 vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2254                 for (int inode = 0; inode < nbPolygonNodes; inode++) {
2255                   polygon_nodes[inode] = nodes[inode];
2256                 }
2257                 aMesh->AddPolygonalFace(polygon_nodes);
2258                 break;
2259               }
2260             }
2261           }
2262           // go to the next volume
2263           iVol = 0;
2264           while ( iVol++ < nbVolumesByStep ) v++;
2265         }
2266       }
2267     } // sweep free links into faces
2268
2269     // make a ceiling face with a normal external to a volume
2270       
2271     SMDS_VolumeTool lastVol( itElem->second.back() );
2272     int iF = lastVol.GetFaceIndex( aFaceLastNodes );
2273     if ( iF >= 0 )
2274     {
2275       lastVol.SetExternalNormal();
2276       const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
2277       switch ( lastVol.NbFaceNodes( iF ) ) {
2278       case 3:
2279         if (!hasFreeLinks ||
2280             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
2281           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2282         break;
2283       case 4:
2284         if (!hasFreeLinks ||
2285             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
2286           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] );
2287         break;
2288       default:
2289         {
2290           int nbPolygonNodes = lastVol.NbFaceNodes( iF );
2291           vector<const SMDS_MeshNode*> polygon_nodes (nbPolygonNodes);
2292           for (int inode = 0; inode < nbPolygonNodes; inode++) {
2293             polygon_nodes[inode] = nodes[inode];
2294           }
2295           if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
2296             aMesh->AddPolygonalFace(polygon_nodes);
2297         }
2298         break;
2299       }
2300     }
2301
2302   } // loop on swept elements
2303 }
2304
2305 //=======================================================================
2306 //function : RotationSweep
2307 //purpose  : 
2308 //=======================================================================
2309
2310 void SMESH_MeshEditor::RotationSweep(set<const SMDS_MeshElement*> & theElems,
2311                                      const gp_Ax1&                  theAxis,
2312                                      const double                   theAngle,
2313                                      const int                      theNbSteps,
2314                                      const double                   theTol)
2315 {
2316   MESSAGE( "RotationSweep()");
2317   gp_Trsf aTrsf;
2318   aTrsf.SetRotation( theAxis, theAngle );
2319
2320   gp_Lin aLine( theAxis );
2321   double aSqTol = theTol * theTol;
2322
2323   SMESHDS_Mesh* aMesh = GetMeshDS();
2324
2325   TNodeOfNodeListMap mapNewNodes;
2326   TElemOfVecOfNnlmiMap mapElemNewNodes;
2327   TElemOfElemListMap newElemsMap;
2328
2329   // loop on theElems
2330   set< const SMDS_MeshElement* >::iterator itElem;
2331   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2332   {
2333     const SMDS_MeshElement* elem = (*itElem);
2334     if ( !elem )
2335       continue;
2336     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2337     newNodesItVec.reserve( elem->NbNodes() );
2338
2339     // loop on elem nodes
2340     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2341     while ( itN->more() ) {
2342
2343       // check if a node has been already sweeped
2344       const SMDS_MeshNode* node =
2345         static_cast<const SMDS_MeshNode*>( itN->next() );
2346       TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
2347       if ( nIt == mapNewNodes.end() )
2348       {
2349         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2350         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2351
2352         // make new nodes
2353         gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
2354         double coord[3];
2355         aXYZ.Coord( coord[0], coord[1], coord[2] );
2356         bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
2357         const SMDS_MeshNode * newNode = node;
2358         for ( int i = 0; i < theNbSteps; i++ ) {
2359           if ( !isOnAxis ) {
2360             aTrsf.Transforms( coord[0], coord[1], coord[2] );
2361             newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2362           }
2363           listNewNodes.push_back( newNode );
2364         }
2365       }
2366       newNodesItVec.push_back( nIt );
2367     }
2368     // make new elements
2369     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2370   }
2371
2372   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2373
2374 }
2375 //=======================================================================
2376 //function : ExtrusionSweep
2377 //purpose  : 
2378 //=======================================================================
2379
2380 void SMESH_MeshEditor::ExtrusionSweep(set<const SMDS_MeshElement*> & theElems,
2381                                       const gp_Vec&                  theStep,
2382                                       const int                      theNbSteps)
2383 {
2384   gp_Trsf aTrsf;
2385   aTrsf.SetTranslation( theStep );
2386
2387   SMESHDS_Mesh* aMesh = GetMeshDS();
2388
2389   TNodeOfNodeListMap mapNewNodes;
2390   TElemOfVecOfNnlmiMap mapElemNewNodes;
2391   TElemOfElemListMap newElemsMap;
2392
2393   // loop on theElems
2394   set< const SMDS_MeshElement* >::iterator itElem;
2395   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2396   {
2397     // check element type
2398     const SMDS_MeshElement* elem = (*itElem);
2399     if ( !elem )
2400       continue;
2401
2402     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2403     newNodesItVec.reserve( elem->NbNodes() );
2404
2405     // loop on elem nodes
2406     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2407     while ( itN->more() ) {
2408
2409       // check if a node has been already sweeped
2410       const SMDS_MeshNode* node =
2411         static_cast<const SMDS_MeshNode*>( itN->next() );
2412       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2413       if ( nIt == mapNewNodes.end() )
2414       {
2415         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2416         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2417
2418         // make new nodes
2419         double coord[] = { node->X(), node->Y(), node->Z() };
2420         for ( int i = 0; i < theNbSteps; i++ ) {
2421           aTrsf.Transforms( coord[0], coord[1], coord[2] );
2422           const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2423           listNewNodes.push_back( newNode );
2424         }
2425       }
2426       newNodesItVec.push_back( nIt );
2427     }
2428     // make new elements
2429     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2430   }
2431   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2432 }
2433
2434 //=======================================================================
2435 //class    : SMESH_MeshEditor_PathPoint
2436 //purpose  : auxiliary class 
2437 //=======================================================================
2438 class SMESH_MeshEditor_PathPoint {
2439 public:
2440   SMESH_MeshEditor_PathPoint() {
2441     myPnt.SetCoord(99., 99., 99.);
2442     myTgt.SetCoord(1.,0.,0.);
2443     myAngle=0.;
2444     myPrm=0.;
2445   }
2446   void SetPnt(const gp_Pnt& aP3D){
2447     myPnt=aP3D;
2448   }
2449   void SetTangent(const gp_Dir& aTgt){
2450     myTgt=aTgt;
2451   }
2452   void SetAngle(const double& aBeta){
2453     myAngle=aBeta;
2454   }
2455   void SetParameter(const double& aPrm){
2456     myPrm=aPrm;
2457   }
2458   const gp_Pnt& Pnt()const{
2459     return myPnt;
2460   }
2461   const gp_Dir& Tangent()const{
2462     return myTgt;
2463   }
2464   double Angle()const{
2465     return myAngle;
2466   }
2467   double Parameter()const{
2468     return myPrm;
2469   }
2470
2471 protected:
2472   gp_Pnt myPnt;
2473   gp_Dir myTgt;
2474   double myAngle;
2475   double myPrm;
2476 };
2477
2478 //=======================================================================
2479 //function : ExtrusionAlongTrack
2480 //purpose  : 
2481 //=======================================================================
2482 SMESH_MeshEditor::Extrusion_Error 
2483   SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2484                                          SMESH_subMesh* theTrack,
2485                                          const SMDS_MeshNode* theN1,
2486                                          const bool theHasAngles,
2487                                          std::list<double>& theAngles,
2488                                          const bool theHasRefPoint,
2489                                          const gp_Pnt& theRefPoint)
2490 {
2491   MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2492   int j, aNbTP, aNbE, aNb;
2493   double aT1, aT2, aT, aAngle, aX, aY, aZ;
2494   std::list<double> aPrms;
2495   std::list<double>::iterator aItD;
2496   std::set< const SMDS_MeshElement* >::iterator itElem;
2497
2498   Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2499   gp_Pnt aP3D, aV0;
2500   gp_Vec aVec;
2501   gp_XYZ aGC;
2502   Handle(Geom_Curve) aC3D;
2503   TopoDS_Edge aTrackEdge;
2504   TopoDS_Vertex aV1, aV2;
2505
2506   SMDS_ElemIteratorPtr aItE;
2507   SMDS_NodeIteratorPtr aItN;
2508   SMDSAbs_ElementType aTypeE;
2509
2510   TNodeOfNodeListMap mapNewNodes;
2511   TElemOfVecOfNnlmiMap mapElemNewNodes;
2512   TElemOfElemListMap newElemsMap;
2513
2514   aTolVec=1.e-7;
2515   aTolVec2=aTolVec*aTolVec;
2516
2517   // 1. Check data
2518   aNbE = theElements.size();
2519   // nothing to do
2520   if ( !aNbE )
2521     return EXTR_NO_ELEMENTS;
2522
2523   // 1.1 Track Pattern
2524   ASSERT( theTrack );
2525
2526   SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2527
2528   aItE = pSubMeshDS->GetElements();
2529   while ( aItE->more() ) {
2530     const SMDS_MeshElement* pE = aItE->next();
2531     aTypeE = pE->GetType();
2532     // Pattern must contain links only
2533     if ( aTypeE != SMDSAbs_Edge )
2534       return EXTR_PATH_NOT_EDGE;
2535   }
2536
2537   const TopoDS_Shape& aS = theTrack->GetSubShape();
2538   // Sub shape for the Pattern must be an Edge
2539   if ( aS.ShapeType() != TopAbs_EDGE )
2540     return EXTR_BAD_PATH_SHAPE;
2541
2542   aTrackEdge = TopoDS::Edge( aS );
2543   // the Edge must not be degenerated
2544   if ( BRep_Tool::Degenerated( aTrackEdge ) )
2545     return EXTR_BAD_PATH_SHAPE;
2546
2547   TopExp::Vertices( aTrackEdge, aV1, aV2 );
2548   aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2549   aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2550
2551   aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2552   const SMDS_MeshNode* aN1 = aItN->next();
2553
2554   aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2555   const SMDS_MeshNode* aN2 = aItN->next();
2556
2557   // starting node must be aN1 or aN2 
2558   if ( !( aN1 == theN1 || aN2 == theN1 ) )
2559     return EXTR_BAD_STARTING_NODE;
2560
2561   aNbTP = pSubMeshDS->NbNodes() + 2;
2562
2563   // 1.2. Angles
2564   vector<double> aAngles( aNbTP );
2565
2566   for ( j=0; j < aNbTP; ++j ) {
2567     aAngles[j] = 0.;
2568   }
2569   
2570   if ( theHasAngles ) {
2571     aItD = theAngles.begin();
2572     for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2573       aAngle = *aItD;
2574       aAngles[j] = aAngle;
2575     }
2576   }
2577
2578   // 2. Collect parameters on the track edge  
2579   aPrms.push_back( aT1 );
2580   aPrms.push_back( aT2 );
2581
2582   aItN = pSubMeshDS->GetNodes();
2583   while ( aItN->more() ) {
2584     const SMDS_MeshNode* pNode = aItN->next();
2585     const SMDS_EdgePosition* pEPos =
2586       static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2587     aT = pEPos->GetUParameter();
2588     aPrms.push_back( aT );
2589   }
2590
2591   // sort parameters
2592   aPrms.sort();
2593   if ( aN1 == theN1 ) {
2594     if ( aT1 > aT2 ) {
2595       aPrms.reverse();
2596     }
2597   }
2598   else {
2599     if ( aT2 > aT1 ) {
2600       aPrms.reverse();
2601     }
2602   }
2603
2604   // 3. Path Points
2605   SMESH_MeshEditor_PathPoint aPP;
2606   vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2607   //
2608   aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2609   //
2610   aItD = aPrms.begin();
2611   for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2612     aT = *aItD;
2613     aC3D->D1( aT, aP3D, aVec );
2614     aL2 = aVec.SquareMagnitude();
2615     if ( aL2 < aTolVec2 )
2616       return EXTR_CANT_GET_TANGENT;
2617
2618     gp_Dir aTgt( aVec );
2619     aAngle = aAngles[j];
2620
2621     aPP.SetPnt( aP3D );
2622     aPP.SetTangent( aTgt );
2623     aPP.SetAngle( aAngle );
2624     aPP.SetParameter( aT );
2625     aPPs[j]=aPP;
2626   }
2627
2628   // 3. Center of rotation aV0
2629   aV0 = theRefPoint;
2630   if ( !theHasRefPoint ) {
2631     aNb = 0;
2632     aGC.SetCoord( 0.,0.,0. );
2633
2634     itElem = theElements.begin();
2635     for ( ; itElem != theElements.end(); itElem++ ) {
2636       const SMDS_MeshElement* elem = (*itElem);
2637
2638       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2639       while ( itN->more() ) {
2640         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2641         aX = node->X();
2642         aY = node->Y();
2643         aZ = node->Z();
2644
2645         if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2646           list<const SMDS_MeshNode*> aLNx;
2647           mapNewNodes[node] = aLNx;
2648           //
2649           gp_XYZ aXYZ( aX, aY, aZ );
2650           aGC += aXYZ;
2651           ++aNb;
2652         }
2653       }
2654     }
2655     aGC /= aNb;
2656     aV0.SetXYZ( aGC );
2657   } // if (!theHasRefPoint) {
2658   mapNewNodes.clear();
2659
2660   // 4. Processing the elements
2661   SMESHDS_Mesh* aMesh = GetMeshDS();
2662
2663   for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2664     // check element type
2665     const SMDS_MeshElement* elem = (*itElem);
2666     aTypeE = elem->GetType();
2667     if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2668       continue;
2669
2670     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2671     newNodesItVec.reserve( elem->NbNodes() );
2672
2673     // loop on elem nodes
2674     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2675     while ( itN->more() ) {
2676
2677       // check if a node has been already processed
2678       const SMDS_MeshNode* node = 
2679         static_cast<const SMDS_MeshNode*>( itN->next() );
2680       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2681       if ( nIt == mapNewNodes.end() ) {
2682         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2683         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2684         
2685         // make new nodes
2686         aX = node->X();  aY = node->Y(); aZ = node->Z();
2687         
2688         Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2689         gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2690         gp_Ax1 anAx1, anAxT1T0;
2691         gp_Dir aDT1x, aDT0x, aDT1T0;
2692
2693         aTolAng=1.e-4;
2694
2695         aV0x = aV0;
2696         aPN0.SetCoord(aX, aY, aZ);
2697
2698         const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2699         aP0x = aPP0.Pnt();
2700         aDT0x= aPP0.Tangent();
2701
2702         for ( j = 1; j < aNbTP; ++j ) {
2703           const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2704           aP1x = aPP1.Pnt();
2705           aDT1x = aPP1.Tangent();
2706           aAngle1x = aPP1.Angle();
2707           
2708           gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0; 
2709           // Translation
2710           gp_Vec aV01x( aP0x, aP1x );
2711           aTrsf.SetTranslation( aV01x );
2712           
2713           // traslated point
2714           aV1x = aV0x.Transformed( aTrsf );
2715           aPN1 = aPN0.Transformed( aTrsf );
2716           
2717           // rotation 1 [ T1,T0 ]
2718           aAngleT1T0=-aDT1x.Angle( aDT0x );
2719           if (fabs(aAngleT1T0) > aTolAng) {
2720             aDT1T0=aDT1x^aDT0x;
2721             anAxT1T0.SetLocation( aV1x );
2722             anAxT1T0.SetDirection( aDT1T0 );
2723             aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2724             
2725             aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2726           }
2727
2728           // rotation 2
2729           if ( theHasAngles ) {
2730             anAx1.SetLocation( aV1x );
2731             anAx1.SetDirection( aDT1x );
2732             aTrsfRot.SetRotation( anAx1, aAngle1x );
2733             
2734             aPN1 = aPN1.Transformed( aTrsfRot );
2735           }
2736
2737           // make new node
2738           aX = aPN1.X();
2739           aY = aPN1.Y();
2740           aZ = aPN1.Z();
2741           const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2742           listNewNodes.push_back( newNode );
2743           
2744           aPN0 = aPN1;
2745           aP0x = aP1x;
2746           aV0x = aV1x;
2747           aDT0x = aDT1x;
2748         }
2749       }
2750       newNodesItVec.push_back( nIt );
2751     }
2752     // make new elements
2753     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2754   }
2755   
2756   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2757
2758   return EXTR_OK;
2759 }
2760
2761 //=======================================================================
2762 //function : Transform
2763 //purpose  : 
2764 //=======================================================================
2765
2766 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2767                                   const gp_Trsf&                 theTrsf,
2768                                   const bool                     theCopy)
2769 {
2770   bool needReverse;
2771   switch ( theTrsf.Form() ) {
2772   case gp_PntMirror:
2773   case gp_Ax2Mirror:
2774     needReverse = true;
2775     break;
2776   default:
2777     needReverse = false;
2778   }
2779
2780   SMESHDS_Mesh* aMesh = GetMeshDS();
2781
2782   // map old node to new one
2783   TNodeNodeMap nodeMap;
2784
2785   // elements sharing moved nodes; those of them which have all
2786   // nodes mirrored but are not in theElems are to be reversed
2787   set<const SMDS_MeshElement*> inverseElemSet;
2788
2789   // loop on theElems
2790   set< const SMDS_MeshElement* >::iterator itElem;
2791   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2792   {
2793     const SMDS_MeshElement* elem = (*itElem);
2794     if ( !elem )
2795       continue;
2796
2797     // loop on elem nodes
2798     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2799     while ( itN->more() ) {
2800
2801       // check if a node has been already transformed
2802       const SMDS_MeshNode* node =
2803         static_cast<const SMDS_MeshNode*>( itN->next() );
2804       if (nodeMap.find( node ) != nodeMap.end() )
2805         continue; 
2806
2807       double coord[3];
2808       coord[0] = node->X();
2809       coord[1] = node->Y();
2810       coord[2] = node->Z();
2811       theTrsf.Transforms( coord[0], coord[1], coord[2] );
2812       const SMDS_MeshNode * newNode = node;
2813       if ( theCopy )
2814         newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2815       else {
2816         aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2817         // node position on shape becomes invalid
2818         const_cast< SMDS_MeshNode* > ( node )->SetPosition
2819           ( SMDS_SpacePosition::originSpacePosition() );
2820       }
2821       nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2822
2823       // keep inverse elements
2824       if ( !theCopy && needReverse ) {
2825         SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2826         while ( invElemIt->more() )
2827           inverseElemSet.insert( invElemIt->next() );
2828       }
2829     }
2830   }
2831
2832   // either new elements are to be created
2833   // or a mirrored element are to be reversed
2834   if ( !theCopy && !needReverse)
2835     return;
2836
2837   if ( !inverseElemSet.empty()) {
2838     set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2839     for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2840       theElems.insert( *invElemIt );
2841   }
2842
2843   // replicate or reverse elements 
2844
2845   enum {
2846     REV_TETRA   = 0,  //  = nbNodes - 4
2847     REV_PYRAMID = 1,  //  = nbNodes - 4
2848     REV_PENTA   = 2,  //  = nbNodes - 4
2849     REV_FACE    = 3,
2850     REV_HEXA    = 4,  //  = nbNodes - 4
2851     FORWARD     = 5
2852     };
2853   int index[][8] = {
2854     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_TETRA  
2855     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_PYRAMID
2856     { 2, 1, 0, 5, 4, 3, 0, 0 },  // REV_PENTA  
2857     { 2, 1, 0, 3, 0, 0, 0, 0 },  // REV_FACE   
2858     { 2, 1, 0, 3, 6, 5, 4, 7 },  // REV_HEXA   
2859     { 0, 1, 2, 3, 4, 5, 6, 7 }   // FORWARD    
2860   };
2861
2862   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2863   {
2864     const SMDS_MeshElement* elem = (*itElem);
2865     if ( !elem || elem->GetType() == SMDSAbs_Node )
2866       continue;
2867
2868     int nbNodes = elem->NbNodes();
2869     int elemType = elem->GetType();
2870
2871     if (elem->IsPoly()) {
2872       // Polygon or Polyhedral Volume
2873       switch ( elemType ) {
2874       case SMDSAbs_Face:
2875         {
2876           vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
2877           int iNode = 0;
2878           SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2879           while (itN->more()) {
2880             const SMDS_MeshNode* node =
2881               static_cast<const SMDS_MeshNode*>(itN->next());
2882             TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2883             if (nodeMapIt == nodeMap.end())
2884               break; // not all nodes transformed
2885             if (needReverse) {
2886               // reverse mirrored faces and volumes
2887               poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
2888             } else {
2889               poly_nodes[iNode] = (*nodeMapIt).second;
2890             }
2891             iNode++;
2892           }
2893           if ( iNode != nbNodes )
2894             continue; // not all nodes transformed
2895
2896           if ( theCopy ) {
2897             aMesh->AddPolygonalFace(poly_nodes);
2898           } else {
2899             aMesh->ChangePolygonNodes(elem, poly_nodes);
2900           }
2901         }
2902         break;
2903       case SMDSAbs_Volume:
2904         {
2905           // ATTENTION: Reversing is not yet done!!!
2906           const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
2907             (const SMDS_PolyhedralVolumeOfNodes*) elem;
2908           if (!aPolyedre) {
2909             MESSAGE("Warning: bad volumic element");
2910             continue;
2911           }
2912
2913           vector<const SMDS_MeshNode*> poly_nodes;
2914           vector<int> quantities;
2915
2916           bool allTransformed = true;
2917           int nbFaces = aPolyedre->NbFaces();
2918           for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
2919             int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
2920             for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
2921               const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
2922               TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2923               if (nodeMapIt == nodeMap.end()) {
2924                 allTransformed = false; // not all nodes transformed
2925               } else {
2926                 poly_nodes.push_back((*nodeMapIt).second);
2927               }
2928             }
2929             quantities.push_back(nbFaceNodes);
2930           }
2931           if ( !allTransformed )
2932             continue; // not all nodes transformed
2933
2934           if ( theCopy ) {
2935             aMesh->AddPolyhedralVolume(poly_nodes, quantities);
2936           } else {
2937             aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
2938           }
2939         }
2940         break;
2941       default:;
2942       }
2943       continue;
2944     }
2945
2946     // Regular elements
2947     int* i = index[ FORWARD ];
2948     if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
2949       if ( elemType == SMDSAbs_Face )
2950         i = index[ REV_FACE ];
2951       else
2952         i = index[ nbNodes - 4 ];
2953
2954     // find transformed nodes
2955     const SMDS_MeshNode* nodes[8];
2956     int iNode = 0;
2957     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2958     while ( itN->more() )
2959     {
2960       const SMDS_MeshNode* node =
2961         static_cast<const SMDS_MeshNode*>( itN->next() );
2962       TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
2963       if ( nodeMapIt == nodeMap.end() )
2964         break; // not all nodes transformed
2965       nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
2966     }
2967     if ( iNode != nbNodes )
2968       continue; // not all nodes transformed
2969
2970     if ( theCopy ) 
2971     {
2972       // add a new element
2973       switch ( elemType ) {
2974       case SMDSAbs_Edge:
2975         aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
2976         break;
2977       case SMDSAbs_Face:
2978         if ( nbNodes == 3 )
2979           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
2980         else
2981           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
2982         break;
2983       case SMDSAbs_Volume:
2984         if ( nbNodes == 4 )
2985           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
2986         else if ( nbNodes == 8 )
2987           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2988                             nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
2989         else if ( nbNodes == 6 )
2990           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2991                             nodes[ 4 ], nodes[ 5 ]);
2992         else if ( nbNodes == 5 )
2993           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
2994                             nodes[ 4 ]);
2995         break;
2996       default:;
2997       }
2998     }
2999     else
3000     {
3001       // reverse element as it was reversed by transformation
3002       if ( nbNodes > 2 )
3003         aMesh->ChangeElementNodes( elem, nodes, nbNodes );
3004     }
3005   }
3006 }
3007
3008 //=======================================================================
3009 //function : FindCoincidentNodes
3010 //purpose  : Return list of group of nodes close to each other within theTolerance
3011 //           Search among theNodes or in the whole mesh if theNodes is empty.
3012 //=======================================================================
3013
3014 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
3015                                             const double                theTolerance,
3016                                             TListOfListOfNodes &        theGroupsOfNodes)
3017 {
3018   double tol2 = theTolerance * theTolerance;
3019
3020   list<const SMDS_MeshNode*> nodes;
3021   if ( theNodes.empty() )
3022   { // get all nodes in the mesh
3023     SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
3024     while ( nIt->more() )
3025       nodes.push_back( nIt->next() );
3026   }
3027   else
3028   {
3029     nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
3030   }  
3031
3032   list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
3033   for ( ; it1 != nodes.end(); it1++ )
3034   {
3035     const SMDS_MeshNode* n1 = *it1;
3036     gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
3037
3038     list<const SMDS_MeshNode*> * groupPtr = 0;
3039     it2 = it1;
3040     for ( it2++; it2 != nodes.end(); it2++ )
3041     {
3042       const SMDS_MeshNode* n2 = *it2;
3043       gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
3044       if ( p1.SquareDistance( p2 ) <= tol2 )
3045       {
3046         if ( !groupPtr ) {
3047           theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
3048           groupPtr = & theGroupsOfNodes.back();
3049           groupPtr->push_back( n1 );
3050         }
3051         groupPtr->push_back( n2 );
3052         it2 = nodes.erase( it2 );
3053         it2--;
3054       }
3055     }
3056   }
3057 }
3058
3059 //=======================================================================
3060 //function : SimplifyFace
3061 //purpose  : 
3062 //=======================================================================
3063 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
3064                                     vector<const SMDS_MeshNode *>&      poly_nodes,
3065                                     vector<int>&                        quantities) const
3066 {
3067   int nbNodes = faceNodes.size();
3068
3069   if (nbNodes < 3)
3070     return 0;
3071
3072   set<const SMDS_MeshNode*> nodeSet;
3073
3074   // get simple seq of nodes
3075   const SMDS_MeshNode* simpleNodes[ nbNodes ];
3076   int iSimple = 0, nbUnique = 0;
3077
3078   simpleNodes[iSimple++] = faceNodes[0];
3079   nbUnique++;
3080   for (int iCur = 1; iCur < nbNodes; iCur++) {
3081     if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
3082       simpleNodes[iSimple++] = faceNodes[iCur];
3083       if (nodeSet.insert( faceNodes[iCur] ).second)
3084         nbUnique++;
3085     }
3086   }
3087   int nbSimple = iSimple;
3088   if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
3089     nbSimple--;
3090     iSimple--;
3091   }
3092
3093   if (nbUnique < 3)
3094     return 0;
3095
3096   // separate loops
3097   int nbNew = 0;
3098   bool foundLoop = (nbSimple > nbUnique);
3099   while (foundLoop) {
3100     foundLoop = false;
3101     set<const SMDS_MeshNode*> loopSet;
3102     for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
3103       const SMDS_MeshNode* n = simpleNodes[iSimple];
3104       if (!loopSet.insert( n ).second) {
3105         foundLoop = true;
3106
3107         // separate loop
3108         int iC = 0, curLast = iSimple;
3109         for (; iC < curLast; iC++) {
3110           if (simpleNodes[iC] == n) break;
3111         }
3112         int loopLen = curLast - iC;
3113         if (loopLen > 2) {
3114           // create sub-element
3115           nbNew++;
3116           quantities.push_back(loopLen);
3117           for (; iC < curLast; iC++) {
3118             poly_nodes.push_back(simpleNodes[iC]);
3119           }
3120         }
3121         // shift the rest nodes (place from the first loop position)
3122         for (iC = curLast + 1; iC < nbSimple; iC++) {
3123           simpleNodes[iC - loopLen] = simpleNodes[iC];
3124         }
3125         nbSimple -= loopLen;
3126         iSimple -= loopLen;
3127       }
3128     } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
3129   } // while (foundLoop)
3130
3131   if (iSimple > 2) {
3132     nbNew++;
3133     quantities.push_back(iSimple);
3134     for (int i = 0; i < iSimple; i++)
3135       poly_nodes.push_back(simpleNodes[i]);
3136   }
3137
3138   return nbNew;
3139 }
3140
3141 //=======================================================================
3142 //function : MergeNodes
3143 //purpose  : In each group, the cdr of nodes are substituted by the first one
3144 //           in all elements.
3145 //=======================================================================
3146
3147 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
3148 {
3149   SMESHDS_Mesh* aMesh = GetMeshDS();
3150
3151   TNodeNodeMap nodeNodeMap; // node to replace - new node
3152   set<const SMDS_MeshElement*> elems; // all elements with changed nodes
3153   list< int > rmElemIds, rmNodeIds;
3154
3155   // Fill nodeNodeMap and elems
3156
3157   TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
3158   for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
3159   {
3160     list<const SMDS_MeshNode*>& nodes = *grIt;
3161     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
3162     const SMDS_MeshNode* nToKeep = *nIt;
3163     for ( ; nIt != nodes.end(); nIt++ )
3164     {
3165       const SMDS_MeshNode* nToRemove = *nIt;
3166       nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
3167       if ( nToRemove != nToKeep ) {
3168         rmNodeIds.push_back( nToRemove->GetID() );
3169         AddToSameGroups( nToKeep, nToRemove, aMesh );
3170       }
3171
3172       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3173       while ( invElemIt->more() )
3174         elems.insert( invElemIt->next() );
3175     }
3176   }
3177   // Change element nodes or remove an element 
3178
3179   set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
3180   for ( ; eIt != elems.end(); eIt++ )
3181   {
3182     const SMDS_MeshElement* elem = *eIt;
3183     int nbNodes = elem->NbNodes();
3184     int aShapeId = FindShape( elem );
3185
3186     set<const SMDS_MeshNode*> nodeSet;
3187     const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
3188     int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
3189
3190     // get new seq of nodes
3191     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3192     while ( itN->more() )
3193     {
3194       const SMDS_MeshNode* n =
3195         static_cast<const SMDS_MeshNode*>( itN->next() );
3196
3197       TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
3198       if ( nnIt != nodeNodeMap.end() ) { // n sticks
3199         n = (*nnIt).second;
3200         iRepl[ nbRepl++ ] = iCur;
3201       }
3202       curNodes[ iCur ] = n;
3203       bool isUnique = nodeSet.insert( n ).second;
3204       if ( isUnique )
3205         uniqueNodes[ iUnique++ ] = n;
3206       iCur++;
3207     }
3208
3209     // Analyse element topology after replacement
3210
3211     bool isOk = true;
3212     int nbUniqueNodes = nodeSet.size();
3213     if ( nbNodes != nbUniqueNodes ) // some nodes stick
3214     {
3215       // Polygons and Polyhedral volumes
3216       if (elem->IsPoly()) {
3217
3218         if (elem->GetType() == SMDSAbs_Face) {
3219           // Polygon
3220           vector<const SMDS_MeshNode *> face_nodes (nbNodes);
3221           int inode = 0;
3222           for (; inode < nbNodes; inode++) {
3223             face_nodes[inode] = curNodes[inode];
3224           }
3225
3226           vector<const SMDS_MeshNode *> polygons_nodes;
3227           vector<int> quantities;
3228           int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
3229
3230           if (nbNew > 0) {
3231             inode = 0;
3232             for (int iface = 0; iface < nbNew - 1; iface++) {
3233               int nbNodes = quantities[iface];
3234               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
3235               for (int ii = 0; ii < nbNodes; ii++, inode++) {
3236                 poly_nodes[ii] = polygons_nodes[inode];
3237               }
3238               SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
3239               if (aShapeId)
3240                 aMesh->SetMeshElementOnShape(newElem, aShapeId);
3241             }
3242             aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
3243           } else {
3244             rmElemIds.push_back(elem->GetID());
3245           }
3246
3247         } else if (elem->GetType() == SMDSAbs_Volume) {
3248           // Polyhedral volume
3249           if (nbUniqueNodes < 4) {
3250             rmElemIds.push_back(elem->GetID());
3251           } else {
3252             // each face has to be analized in order to check volume validity
3253             const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3254               static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3255             if (aPolyedre) {
3256               int nbFaces = aPolyedre->NbFaces();
3257
3258               vector<const SMDS_MeshNode *> poly_nodes;
3259               vector<int> quantities;
3260
3261               for (int iface = 1; iface <= nbFaces; iface++) {
3262                 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3263                 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
3264
3265                 for (int inode = 1; inode <= nbFaceNodes; inode++) {
3266                   const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
3267                   TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
3268                   if (nnIt != nodeNodeMap.end()) { // faceNode sticks
3269                     faceNode = (*nnIt).second;
3270                   }
3271                   faceNodes[inode - 1] = faceNode;
3272                 }
3273
3274                 SimplifyFace(faceNodes, poly_nodes, quantities);
3275               }
3276
3277               if (quantities.size() > 3) {
3278                 // to be done: remove coincident faces
3279               }
3280
3281               if (quantities.size() > 3)
3282                 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3283               else
3284                 rmElemIds.push_back(elem->GetID());
3285
3286             } else {
3287               rmElemIds.push_back(elem->GetID());
3288             }
3289           }
3290         } else {
3291         }
3292
3293         continue;
3294       }
3295
3296       // Regular elements
3297       switch ( nbNodes ) {
3298       case 2: ///////////////////////////////////// EDGE
3299         isOk = false; break;
3300       case 3: ///////////////////////////////////// TRIANGLE
3301         isOk = false; break;
3302       case 4:
3303         if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
3304           isOk = false;
3305         else { //////////////////////////////////// QUADRANGLE
3306           if ( nbUniqueNodes < 3 )
3307             isOk = false;
3308           else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
3309             isOk = false; // opposite nodes stick
3310         }
3311         break;
3312       case 6: ///////////////////////////////////// PENTAHEDRON
3313         if ( nbUniqueNodes == 4 ) {
3314           // ---------------------------------> tetrahedron
3315           if (nbRepl == 3 &&
3316               iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
3317             // all top nodes stick: reverse a bottom
3318             uniqueNodes[ 0 ] = curNodes [ 1 ];
3319             uniqueNodes[ 1 ] = curNodes [ 0 ];
3320           }
3321           else if (nbRepl == 3 &&
3322                    iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
3323             // all bottom nodes stick: set a top before
3324             uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
3325             uniqueNodes[ 0 ] = curNodes [ 3 ];
3326             uniqueNodes[ 1 ] = curNodes [ 4 ];
3327             uniqueNodes[ 2 ] = curNodes [ 5 ];
3328           }
3329           else if (nbRepl == 4 &&
3330                    iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
3331             // a lateral face turns into a line: reverse a bottom
3332             uniqueNodes[ 0 ] = curNodes [ 1 ];
3333             uniqueNodes[ 1 ] = curNodes [ 0 ];
3334           }
3335           else
3336             isOk = false;
3337         }
3338         else if ( nbUniqueNodes == 5 ) {
3339           // PENTAHEDRON --------------------> 2 tetrahedrons
3340           if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
3341             // a bottom node sticks with a linked top one
3342             // 1.
3343             SMDS_MeshElement* newElem = 
3344               aMesh->AddVolume(curNodes[ 3 ],
3345                                curNodes[ 4 ],
3346                                curNodes[ 5 ],
3347                                curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
3348             if ( aShapeId )
3349               aMesh->SetMeshElementOnShape( newElem, aShapeId );
3350             // 2. : reverse a bottom
3351             uniqueNodes[ 0 ] = curNodes [ 1 ];
3352             uniqueNodes[ 1 ] = curNodes [ 0 ];
3353             nbUniqueNodes = 4;
3354           }
3355           else
3356             isOk = false;
3357         }
3358         else
3359           isOk = false;
3360         break;
3361       case 8: { //////////////////////////////////// HEXAHEDRON
3362         isOk = false;
3363         SMDS_VolumeTool hexa (elem);
3364         hexa.SetExternalNormal();
3365         if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
3366           //////////////////////// ---> tetrahedron
3367           for ( int iFace = 0; iFace < 6; iFace++ ) {
3368             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3369             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3370                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3371                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3372               // one face turns into a point ...
3373               int iOppFace = hexa.GetOppFaceIndex( iFace );
3374               ind = hexa.GetFaceNodesIndices( iOppFace );
3375               int nbStick = 0;
3376               iUnique = 2; // reverse a tetrahedron bottom
3377               for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
3378                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3379                   nbStick++;
3380                 else if ( iUnique >= 0 )
3381                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3382               }
3383               if ( nbStick == 1 ) {
3384                 // ... and the opposite one - into a triangle.
3385                 // set a top node
3386                 ind = hexa.GetFaceNodesIndices( iFace );
3387                 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
3388                 isOk = true;
3389               }
3390               break;
3391             }
3392           }
3393         }
3394         else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
3395           //////////////////// HEXAHEDRON ---> 2 tetrahedrons
3396           for ( int iFace = 0; iFace < 6; iFace++ ) {
3397             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3398             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3399                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3400                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3401               // one face turns into a point ...
3402               int iOppFace = hexa.GetOppFaceIndex( iFace );
3403               ind = hexa.GetFaceNodesIndices( iOppFace );
3404               int nbStick = 0;
3405               iUnique = 2;  // reverse a tetrahedron 1 bottom
3406               for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
3407                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3408                   nbStick++;
3409                 else if ( iUnique >= 0 )
3410                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3411               }
3412               if ( nbStick == 0 ) {
3413                 // ... and the opposite one is a quadrangle
3414                 // set a top node
3415                 const int* indTop = hexa.GetFaceNodesIndices( iFace );
3416                 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
3417                 nbUniqueNodes = 4;
3418                 // tetrahedron 2
3419                 SMDS_MeshElement* newElem = 
3420                   aMesh->AddVolume(curNodes[ind[ 0 ]],
3421                                    curNodes[ind[ 3 ]],
3422                                    curNodes[ind[ 2 ]],
3423                                    curNodes[indTop[ 0 ]]);
3424                 if ( aShapeId )
3425                   aMesh->SetMeshElementOnShape( newElem, aShapeId );
3426                 isOk = true;
3427               }
3428               break;
3429             }
3430           }
3431         }
3432         else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
3433           ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
3434           // find indices of quad and tri faces
3435           int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
3436           for ( iFace = 0; iFace < 6; iFace++ ) {
3437             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3438             nodeSet.clear();
3439             for ( iCur = 0; iCur < 4; iCur++ )
3440               nodeSet.insert( curNodes[ind[ iCur ]] );
3441             nbUniqueNodes = nodeSet.size();
3442             if ( nbUniqueNodes == 3 )
3443               iTriFace[ nbTri++ ] = iFace;
3444             else if ( nbUniqueNodes == 4 )
3445               iQuadFace[ nbQuad++ ] = iFace;
3446           }
3447           if (nbQuad == 2 && nbTri == 4 &&
3448               hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
3449             // 2 opposite quadrangles stuck with a diagonal;
3450             // sample groups of merged indices: (0-4)(2-6)
3451             // --------------------------------------------> 2 tetrahedrons
3452             const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
3453             const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
3454             int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
3455             if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
3456                 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
3457               // stuck with 0-2 diagonal
3458               i0  = ind1[ 3 ];
3459               i1d = ind1[ 0 ];
3460               i2  = ind1[ 1 ];
3461               i3d = ind1[ 2 ];
3462               i0t = ind2[ 1 ];
3463               i2t = ind2[ 3 ];
3464             }
3465             else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
3466                      curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
3467               // stuck with 1-3 diagonal
3468               i0  = ind1[ 0 ];
3469               i1d = ind1[ 1 ];
3470               i2  = ind1[ 2 ];
3471               i3d = ind1[ 3 ];
3472               i0t = ind2[ 0 ];
3473               i2t = ind2[ 1 ];
3474             }
3475             else {
3476               ASSERT(0);
3477             }
3478             // tetrahedron 1
3479             uniqueNodes[ 0 ] = curNodes [ i0 ];
3480             uniqueNodes[ 1 ] = curNodes [ i1d ];
3481             uniqueNodes[ 2 ] = curNodes [ i3d ];
3482             uniqueNodes[ 3 ] = curNodes [ i0t ];
3483             nbUniqueNodes = 4;
3484             // tetrahedron 2
3485             SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
3486                                                          curNodes[ i2 ],
3487                                                          curNodes[ i3d ],
3488                                                          curNodes[ i2t ]);
3489             if ( aShapeId )
3490               aMesh->SetMeshElementOnShape( newElem, aShapeId );
3491             isOk = true;
3492           }
3493           else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
3494                    ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
3495             // --------------------------------------------> prism
3496             // find 2 opposite triangles
3497             nbUniqueNodes = 6;
3498             for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
3499               if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
3500                 // find indices of kept and replaced nodes
3501                 // and fill unique nodes of 2 opposite triangles
3502                 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
3503                 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
3504                 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
3505                 // fill unique nodes
3506                 iUnique = 0;
3507                 isOk = true;
3508                 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
3509                   const SMDS_MeshNode* n     = curNodes[ind1[ iCur ]];
3510                   const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
3511                   if ( n == nInit ) {
3512                     // iCur of a linked node of the opposite face (make normals co-directed):
3513                     int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
3514                     // check that correspondent corners of triangles are linked
3515                     if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
3516                       isOk = false;
3517                     else {
3518                       uniqueNodes[ iUnique ] = n;
3519                       uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
3520                       iUnique++;
3521                     }
3522                   }
3523                 }
3524                 break;
3525               }
3526             }
3527           }
3528         } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
3529         break;
3530       } // HEXAHEDRON
3531
3532       default:
3533         isOk = false;
3534       } // switch ( nbNodes )
3535
3536     } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
3537     
3538     if ( isOk ) {
3539       if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
3540         // Change nodes of polyedre
3541         const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3542           static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3543         if (aPolyedre) {
3544           int nbFaces = aPolyedre->NbFaces();
3545
3546           vector<const SMDS_MeshNode *> poly_nodes;
3547           vector<int> quantities (nbFaces);
3548
3549           for (int iface = 1; iface <= nbFaces; iface++) {
3550             int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3551             quantities[iface - 1] = nbFaceNodes;
3552
3553             for (inode = 1; inode <= nbFaceNodes; inode++) {
3554               const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
3555
3556               TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
3557               if (nnIt != nodeNodeMap.end()) { // curNode sticks
3558                 curNode = (*nnIt).second;
3559               }
3560               poly_nodes.push_back(curNode);
3561             }
3562           }
3563           aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
3564         }
3565       } else {
3566         // Change regular element or polygon
3567         aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
3568       }
3569     } else {
3570       // Remove invalid regular element or invalid polygon
3571       rmElemIds.push_back( elem->GetID() );
3572     }
3573
3574   } // loop on elements
3575
3576   // Remove equal nodes and bad elements
3577
3578   Remove( rmNodeIds, true );
3579   Remove( rmElemIds, false );
3580
3581 }
3582
3583 //=======================================================================
3584 //function : MergeEqualElements
3585 //purpose  : Remove all but one of elements built on the same nodes.
3586 //=======================================================================
3587
3588 void SMESH_MeshEditor::MergeEqualElements()
3589 {
3590   SMESHDS_Mesh* aMesh = GetMeshDS();
3591
3592   SMDS_EdgeIteratorPtr   eIt = aMesh->edgesIterator();
3593   SMDS_FaceIteratorPtr   fIt = aMesh->facesIterator();
3594   SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
3595
3596   list< int > rmElemIds; // IDs of elems to remove
3597
3598   for ( int iDim = 1; iDim <= 3; iDim++ ) {
3599
3600     set< set <const SMDS_MeshElement*> > setOfNodeSet;
3601
3602     while ( 1 ) {
3603       // get next element
3604       const SMDS_MeshElement* elem = 0;
3605       if ( iDim == 1 ) {
3606         if ( eIt->more() ) elem = eIt->next();
3607       } else if ( iDim == 2 ) {
3608         if ( fIt->more() ) elem = fIt->next();
3609       } else {
3610         if ( vIt->more() ) elem = vIt->next();
3611       }
3612       if ( !elem ) break;
3613
3614       // get elem nodes
3615       set <const SMDS_MeshElement*> nodeSet;
3616       SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3617       while ( nodeIt->more() )
3618         nodeSet.insert( nodeIt->next() );
3619
3620       // check uniqueness
3621       bool isUnique = setOfNodeSet.insert( nodeSet ).second;
3622       if ( !isUnique )
3623         rmElemIds.push_back( elem->GetID() );
3624     }
3625   }
3626
3627   Remove( rmElemIds, false );
3628 }
3629
3630 //=======================================================================
3631 //function : FindFaceInSet
3632 //purpose  : Return a face having linked nodes n1 and n2 and which is
3633 //           - not in avoidSet,
3634 //           - in elemSet provided that !elemSet.empty()
3635 //=======================================================================
3636
3637 const SMDS_MeshElement*
3638   SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode*                n1,
3639                                   const SMDS_MeshNode*                n2,
3640                                   const set<const SMDS_MeshElement*>& elemSet,
3641                                   const set<const SMDS_MeshElement*>& avoidSet)
3642
3643 {
3644   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
3645   while ( invElemIt->more() ) { // loop on inverse elements of n1
3646     const SMDS_MeshElement* elem = invElemIt->next();
3647     if (elem->GetType() != SMDSAbs_Face ||
3648         avoidSet.find( elem ) != avoidSet.end() )
3649       continue;
3650     if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
3651       continue;
3652     // get face nodes and find index of n1
3653     int i1, nbN = elem->NbNodes(), iNode = 0;
3654     const SMDS_MeshNode* faceNodes[ nbN ], *n;
3655     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3656     while ( nIt->more() ) {
3657       faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3658       if ( faceNodes[ iNode++ ] == n1 )
3659         i1 = iNode - 1;
3660     }
3661     // find a n2 linked to n1
3662     for ( iNode = 0; iNode < 2; iNode++ ) {
3663       if ( iNode ) // node before n1
3664         n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
3665       else         // node after n1
3666         n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
3667       if ( n == n2 )
3668         return elem;
3669     }
3670   }
3671   return 0;
3672 }
3673
3674 //=======================================================================
3675 //function : findAdjacentFace
3676 //purpose  : 
3677 //=======================================================================
3678
3679 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
3680                                                 const SMDS_MeshNode* n2,
3681                                                 const SMDS_MeshElement* elem)
3682 {
3683   set<const SMDS_MeshElement*> elemSet, avoidSet;
3684   if ( elem )
3685     avoidSet.insert ( elem );
3686   return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3687 }
3688   
3689 //=======================================================================
3690 //function : findFreeBorder
3691 //purpose  : 
3692 //=======================================================================
3693
3694 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
3695
3696 static bool findFreeBorder (const SMDS_MeshNode*                theFirstNode,
3697                             const SMDS_MeshNode*                theSecondNode,
3698                             const SMDS_MeshNode*                theLastNode,
3699                             list< const SMDS_MeshNode* > &      theNodes,
3700                             list< const SMDS_MeshElement* > &   theFaces)
3701 {
3702   if ( !theFirstNode || !theSecondNode )
3703     return false;
3704   // find border face between theFirstNode and theSecondNode
3705   const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
3706   if ( !curElem )
3707     return false;
3708
3709   theFaces.push_back( curElem );
3710   theNodes.push_back( theFirstNode );
3711   theNodes.push_back( theSecondNode );
3712
3713   const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
3714   set < const SMDS_MeshElement* > foundElems;
3715   bool needTheLast = ( theLastNode != 0 );
3716
3717   while ( nStart != theLastNode )
3718   {
3719     if ( nStart == theFirstNode )
3720       return !needTheLast;
3721
3722     // find all free border faces sharing form nStart
3723
3724     list< const SMDS_MeshElement* > curElemList;
3725     list< const SMDS_MeshNode* > nStartList;
3726     SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
3727     while ( invElemIt->more() ) {
3728       const SMDS_MeshElement* e = invElemIt->next();
3729       if ( e == curElem || foundElems.insert( e ).second )
3730       {
3731         // get nodes
3732         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3733         int iNode = 0, nbNodes = e->NbNodes();
3734         while ( nIt->more() )
3735           nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3736         nodes[ iNode ] = nodes[ 0 ];
3737         // check 2 links
3738         for ( iNode = 0; iNode < nbNodes; iNode++ )
3739           if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
3740                (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
3741               ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
3742           {
3743             nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
3744             curElemList.push_back( e );
3745           }
3746       }
3747     }
3748     // analyse the found
3749
3750     int nbNewBorders = curElemList.size();
3751     if ( nbNewBorders == 0 ) {
3752       // no free border furthermore
3753       return !needTheLast;
3754     }
3755     else if ( nbNewBorders == 1 ) {
3756       // one more element found
3757       nIgnore = nStart;
3758       nStart = nStartList.front();
3759       curElem = curElemList.front();
3760       theFaces.push_back( curElem );
3761       theNodes.push_back( nStart );
3762     }
3763     else {
3764       // several continuations found
3765       list< const SMDS_MeshElement* >::iterator curElemIt;
3766       list< const SMDS_MeshNode* >::iterator nStartIt;
3767       // check if one of them reached the last node
3768       if ( needTheLast ) {
3769         for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3770              curElemIt!= curElemList.end();
3771              curElemIt++, nStartIt++ )
3772           if ( *nStartIt == theLastNode ) {
3773             theFaces.push_back( *curElemIt );
3774             theNodes.push_back( *nStartIt );
3775             return true;
3776           }
3777       }
3778       // find the best free border by the continuations
3779       list<const SMDS_MeshNode*>    contNodes[ 2 ], *cNL;
3780       list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3781       for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3782            curElemIt!= curElemList.end();
3783            curElemIt++, nStartIt++ )
3784       {
3785         cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3786         cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3787         // find one more free border
3788         if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3789           cNL->clear();
3790           cFL->clear();
3791         }
3792         else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3793           // choice: clear a worse one
3794           int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3795           int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3796           contNodes[ iWorse ].clear();
3797           contFaces[ iWorse ].clear();
3798         }
3799       }
3800       if ( contNodes[0].empty() && contNodes[1].empty() )
3801         return false;
3802
3803       // append the best free border
3804       cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3805       cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3806       theNodes.pop_back(); // remove nIgnore
3807       theNodes.pop_back(); // remove nStart
3808       theFaces.pop_back(); // remove curElem
3809       list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3810       list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3811       for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3812       for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3813       return true;
3814
3815     } // several continuations found
3816   } // while ( nStart != theLastNode )
3817
3818   return true;
3819 }
3820
3821 //=======================================================================
3822 //function : CheckFreeBorderNodes
3823 //purpose  : Return true if the tree nodes are on a free border
3824 //=======================================================================
3825
3826 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3827                                             const SMDS_MeshNode* theNode2,
3828                                             const SMDS_MeshNode* theNode3)
3829 {
3830   list< const SMDS_MeshNode* > nodes;
3831   list< const SMDS_MeshElement* > faces;
3832   return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3833 }
3834
3835 //=======================================================================
3836 //function : SewFreeBorder
3837 //purpose  : 
3838 //=======================================================================
3839
3840 SMESH_MeshEditor::Sew_Error
3841   SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3842                                    const SMDS_MeshNode* theBordSecondNode,
3843                                    const SMDS_MeshNode* theBordLastNode,
3844                                    const SMDS_MeshNode* theSideFirstNode,
3845                                    const SMDS_MeshNode* theSideSecondNode,
3846                                    const SMDS_MeshNode* theSideThirdNode,
3847                                    const bool           theSideIsFreeBorder,
3848                                    const bool           toCreatePolygons,
3849                                    const bool           toCreatePolyedrs)
3850 {
3851   MESSAGE("::SewFreeBorder()");
3852   Sew_Error aResult = SEW_OK;
3853
3854   // ====================================
3855   //    find side nodes and elements
3856   // ====================================
3857
3858   list< const SMDS_MeshNode* > nSide[ 2 ];
3859   list< const SMDS_MeshElement* > eSide[ 2 ];
3860   list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3861   list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3862
3863   // Free border 1
3864   // --------------
3865   if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3866                       nSide[0], eSide[0])) {
3867     MESSAGE(" Free Border 1 not found " );
3868     aResult = SEW_BORDER1_NOT_FOUND;
3869   }
3870   if (theSideIsFreeBorder)
3871   { 
3872     // Free border 2
3873     // --------------
3874     if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3875                         nSide[1], eSide[1])) {
3876       MESSAGE(" Free Border 2 not found " );
3877       aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
3878     }
3879   }
3880   if ( aResult != SEW_OK )
3881     return aResult;
3882
3883   if (!theSideIsFreeBorder)
3884   {
3885     // Side 2
3886     // --------------
3887
3888     // -------------------------------------------------------------------------
3889     // Algo:
3890     // 1. If nodes to merge are not coincident, move nodes of the free border
3891     //    from the coord sys defined by the direction from the first to last
3892     //    nodes of the border to the correspondent sys of the side 2
3893     // 2. On the side 2, find the links most co-directed with the correspondent
3894     //    links of the free border
3895     // -------------------------------------------------------------------------
3896
3897     // 1. Since sewing may brake if there are volumes to split on the side 2,
3898     //    we wont move nodes but just compute new coordinates for them
3899     typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
3900     TNodeXYZMap nBordXYZ;
3901     list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
3902     list< const SMDS_MeshNode* >::iterator nBordIt;
3903
3904     gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
3905     gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
3906     gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
3907     gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
3908     double tol2 = 1.e-8;
3909     gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
3910     if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
3911     {
3912       // Need node movement.
3913
3914       // find X and Z axes to create trsf
3915       gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
3916       gp_Vec X = Zs ^ Zb;
3917       if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
3918         // Zb || Zs
3919         X = gp_Ax2( gp::Origin(), Zb ).XDirection();
3920
3921       // coord systems
3922       gp_Ax3 toBordAx( Pb1, Zb, X );
3923       gp_Ax3 fromSideAx( Ps1, Zs, X );
3924       gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
3925       // set trsf
3926       gp_Trsf toBordSys, fromSide2Sys;
3927       toBordSys.SetTransformation( toBordAx );
3928       fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
3929       fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
3930       
3931       // move
3932       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3933         const SMDS_MeshNode* n = *nBordIt;
3934         gp_XYZ xyz( n->X(),n->Y(),n->Z() );
3935         toBordSys.Transforms( xyz );
3936         fromSide2Sys.Transforms( xyz );
3937         nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
3938       }
3939     }
3940     else
3941     {
3942       // just insert nodes XYZ in the nBordXYZ map
3943       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
3944         const SMDS_MeshNode* n = *nBordIt;
3945         nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
3946       }
3947     }
3948
3949     // 2. On the side 2, find the links most co-directed with the correspondent
3950     //    links of the free border
3951
3952     list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
3953     list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
3954     sideNodes.push_back( theSideFirstNode );
3955
3956     bool hasVolumes = false;
3957     LinkID_Gen aLinkID_Gen( GetMeshDS() );
3958     set<long> foundSideLinkIDs, checkedLinkIDs;
3959     SMDS_VolumeTool volume;
3960     //const SMDS_MeshNode* faceNodes[ 4 ];
3961
3962     const SMDS_MeshNode*    sideNode;
3963     const SMDS_MeshElement* sideElem;
3964     const SMDS_MeshNode* prevSideNode = theSideFirstNode;
3965     const SMDS_MeshNode* prevBordNode = theBordFirstNode;
3966     nBordIt = bordNodes.begin();
3967     nBordIt++;
3968     // border node position and border link direction to compare with
3969     gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
3970     gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
3971     // choose next side node by link direction or by closeness to
3972     // the current border node:
3973     bool searchByDir = ( *nBordIt != theBordLastNode );
3974     do {
3975       // find the next node on the Side 2
3976       sideNode = 0;
3977       double maxDot = -DBL_MAX, minDist = DBL_MAX;
3978       long linkID;
3979       checkedLinkIDs.clear();
3980       gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
3981
3982       SMDS_ElemIteratorPtr invElemIt
3983         = prevSideNode->GetInverseElementIterator();
3984       while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
3985         const SMDS_MeshElement* elem = invElemIt->next();
3986         // prepare data for a loop on links, of a face or a volume
3987         int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
3988         const SMDS_MeshNode* faceNodes[ nbNodes ];
3989         bool isVolume = volume.Set( elem );
3990         const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
3991         if ( isVolume ) // --volume
3992           hasVolumes = true;
3993         else if ( nbNodes > 2 ) { // --face
3994           // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
3995           SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3996           while ( nIt->more() ) {
3997             nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3998             if ( nodes[ iNode++ ] == prevSideNode )
3999               iPrevNode = iNode - 1;
4000           }
4001           // there are 2 links to check
4002           nbNodes = 2;
4003         }
4004         else // --edge
4005           continue;
4006         // loop on links, to be precise, on the second node of links
4007         for ( iNode = 0; iNode < nbNodes; iNode++ ) {
4008           const SMDS_MeshNode* n = nodes[ iNode ];
4009           if ( isVolume ) {
4010             if ( !volume.IsLinked( n, prevSideNode ))
4011               continue;
4012           } else {
4013             if ( iNode ) // a node before prevSideNode
4014               n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
4015             else         // a node after prevSideNode
4016               n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
4017           }
4018           // check if this link was already used
4019           long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
4020           bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
4021           if (!isJustChecked &&
4022               foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
4023             // test a link geometrically
4024             gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
4025             bool linkIsBetter = false;
4026             double dot, dist;
4027             if ( searchByDir ) { // choose most co-directed link
4028               dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
4029               linkIsBetter = ( dot > maxDot );
4030             }
4031             else { // choose link with the node closest to bordPos
4032               dist = ( nextXYZ - bordPos ).SquareModulus();
4033               linkIsBetter = ( dist < minDist );
4034             }
4035             if ( linkIsBetter ) {
4036               maxDot = dot;
4037               minDist = dist;
4038               linkID = iLink;
4039               sideNode = n;
4040               sideElem = elem;
4041             }
4042           }
4043         }
4044       } // loop on inverse elements of prevSideNode
4045
4046       if ( !sideNode ) {
4047         MESSAGE(" Cant find path by links of the Side 2 ");
4048         return SEW_BAD_SIDE_NODES;
4049       }
4050       sideNodes.push_back( sideNode );
4051       sideElems.push_back( sideElem );
4052       foundSideLinkIDs.insert ( linkID );
4053       prevSideNode = sideNode;
4054
4055       if ( *nBordIt == theBordLastNode )
4056         searchByDir = false;
4057       else {
4058         // find the next border link to compare with
4059         gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
4060         searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4061         while ( *nBordIt != theBordLastNode && !searchByDir ) {
4062           prevBordNode = *nBordIt;
4063           nBordIt++;
4064           bordPos = nBordXYZ[ *nBordIt ];
4065           bordDir = bordPos - nBordXYZ[ prevBordNode ];
4066           searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4067         }
4068       }
4069     }
4070     while ( sideNode != theSideSecondNode );
4071
4072     if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
4073       MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
4074       return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
4075     }
4076   } // end nodes search on the side 2
4077
4078   // ============================
4079   // sew the border to the side 2
4080   // ============================
4081
4082   int nbNodes[]  = { nSide[0].size(), nSide[1].size() };
4083   int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
4084
4085   TListOfListOfNodes nodeGroupsToMerge;
4086   if ( nbNodes[0] == nbNodes[1] ||
4087       ( theSideIsFreeBorder && !theSideThirdNode)) {
4088
4089     // all nodes are to be merged
4090
4091     for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
4092          nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
4093          nIt[0]++, nIt[1]++ )
4094     {
4095       nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4096       nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep 
4097       nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
4098     }
4099   }
4100   else {
4101
4102     // insert new nodes into the border and the side to get equal nb of segments
4103
4104     // get normalized parameters of nodes on the borders
4105     double param[ 2 ][ maxNbNodes ];
4106     int iNode, iBord;
4107     for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4108       list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
4109       list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
4110       const SMDS_MeshNode* nPrev = *nIt;
4111       double bordLength = 0;
4112       for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
4113         const SMDS_MeshNode* nCur = *nIt;
4114         gp_XYZ segment (nCur->X() - nPrev->X(),
4115                         nCur->Y() - nPrev->Y(),
4116                         nCur->Z() - nPrev->Z());
4117         double segmentLen = segment.Modulus();
4118         bordLength += segmentLen;
4119         param[ iBord ][ iNode ] = bordLength;
4120         nPrev = nCur;
4121       }
4122       // normalize within [0,1]
4123       for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
4124         param[ iBord ][ iNode ] /= bordLength;
4125       }
4126     }
4127
4128     // loop on border segments
4129     const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
4130     int i[ 2 ] = { 0, 0 };
4131     nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
4132     nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
4133
4134     TElemOfNodeListMap insertMap;
4135     TElemOfNodeListMap::iterator insertMapIt;
4136     // insertMap is
4137     // key:   elem to insert nodes into
4138     // value: 2 nodes to insert between + nodes to be inserted
4139     do {
4140       bool next[ 2 ] = { false, false };
4141
4142       // find min adjacent segment length after sewing
4143       double nextParam = 10., prevParam = 0;
4144       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4145         if ( i[ iBord ] + 1 < nbNodes[ iBord ])
4146           nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
4147         if ( i[ iBord ] > 0 )
4148           prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
4149       }
4150       double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4151       double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4152       double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
4153           
4154       // choose to insert or to merge nodes
4155       double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
4156       if ( Abs( du ) <= minSegLen * 0.2 ) {
4157         // merge
4158         // ------
4159         nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4160         const SMDS_MeshNode* n0 = *nIt[0];
4161         const SMDS_MeshNode* n1 = *nIt[1];
4162         nodeGroupsToMerge.back().push_back( n1 );
4163         nodeGroupsToMerge.back().push_back( n0 );
4164         // position of node of the border changes due to merge
4165         param[ 0 ][ i[0] ] += du;
4166         // move n1 for the sake of elem shape evaluation during insertion.
4167         // n1 will be removed by MergeNodes() anyway
4168         const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
4169         next[0] = next[1] = true;
4170       }
4171       else {
4172         // insert
4173         // ------
4174         int intoBord = ( du < 0 ) ? 0 : 1;
4175         const SMDS_MeshElement* elem = *eIt[ intoBord ];
4176         const SMDS_MeshNode*    n1   = nPrev[ intoBord ];
4177         const SMDS_MeshNode*    n2   = *nIt[ intoBord ];
4178         const SMDS_MeshNode*    nIns = *nIt[ 1 - intoBord ];
4179         if ( intoBord == 1 ) {
4180           // move node of the border to be on a link of elem of the side
4181           gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
4182           gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
4183           double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
4184           gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
4185           GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
4186         }
4187         insertMapIt = insertMap.find( elem );
4188         bool notFound = ( insertMapIt == insertMap.end() );
4189         bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
4190         if ( otherLink ) {
4191           // insert into another link of the same element:
4192           // 1. perform insertion into the other link of the elem
4193           list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4194           const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
4195           const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
4196           InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
4197           // 2. perform insertion into the link of adjacent faces
4198           while (true) {
4199             const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
4200             if ( adjElem )
4201               InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
4202             else
4203               break;
4204           }
4205           if (toCreatePolyedrs) {
4206             // perform insertion into the links of adjacent volumes
4207             UpdateVolumes(n12, n22, nodeList);
4208           }
4209           // 3. find an element appeared on n1 and n2 after the insertion
4210           insertMap.erase( elem );
4211           elem = findAdjacentFace( n1, n2, 0 );
4212         }
4213         if ( notFound || otherLink ) {
4214           // add element and nodes of the side into the insertMap
4215           insertMapIt = insertMap.insert
4216             ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
4217           (*insertMapIt).second.push_back( n1 );
4218           (*insertMapIt).second.push_back( n2 );
4219         }
4220         // add node to be inserted into elem
4221         (*insertMapIt).second.push_back( nIns );
4222         next[ 1 - intoBord ] = true;
4223       }
4224
4225       // go to the next segment
4226       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4227         if ( next[ iBord ] ) {
4228           if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
4229             eIt[ iBord ]++;
4230           nPrev[ iBord ] = *nIt[ iBord ];
4231           nIt[ iBord ]++; i[ iBord ]++;
4232         }
4233       }
4234     }
4235     while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
4236
4237     // perform insertion of nodes into elements
4238
4239     for (insertMapIt = insertMap.begin();
4240          insertMapIt != insertMap.end();
4241          insertMapIt++ )
4242     {
4243       const SMDS_MeshElement* elem = (*insertMapIt).first;
4244       list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4245       const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
4246       const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
4247
4248       InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
4249
4250       if ( !theSideIsFreeBorder ) {
4251         // look for and insert nodes into the faces adjacent to elem
4252         while (true) {
4253           const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
4254           if ( adjElem )
4255             InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
4256           else
4257             break;
4258         }
4259       }
4260       if (toCreatePolyedrs) {
4261         // perform insertion into the links of adjacent volumes
4262         UpdateVolumes(n1, n2, nodeList);
4263       }
4264     }
4265
4266   } // end: insert new nodes
4267
4268   MergeNodes ( nodeGroupsToMerge );
4269
4270   return aResult;
4271 }
4272
4273 //=======================================================================
4274 //function : InsertNodesIntoLink
4275 //purpose  : insert theNodesToInsert into theFace between theBetweenNode1
4276 //           and theBetweenNode2 and split theElement
4277 //=======================================================================
4278
4279 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement*     theFace,
4280                                            const SMDS_MeshNode*        theBetweenNode1,
4281                                            const SMDS_MeshNode*        theBetweenNode2,
4282                                            list<const SMDS_MeshNode*>& theNodesToInsert,
4283                                            const bool                  toCreatePoly)
4284 {
4285   if ( theFace->GetType() != SMDSAbs_Face ) return;
4286
4287   // find indices of 2 link nodes and of the rest nodes
4288   int iNode = 0, il1, il2, i3, i4;
4289   il1 = il2 = i3 = i4 = -1;
4290   const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
4291   SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
4292   while ( nodeIt->more() ) {
4293     const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4294     if ( n == theBetweenNode1 )
4295       il1 = iNode;
4296     else if ( n == theBetweenNode2 )
4297       il2 = iNode;
4298     else if ( i3 < 0 )
4299       i3 = iNode;
4300     else
4301       i4 = iNode;
4302     nodes[ iNode++ ] = n;
4303   }
4304   if ( il1 < 0 || il2 < 0 || i3 < 0 )
4305     return ;
4306
4307   // arrange link nodes to go one after another regarding the face orientation
4308   bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
4309   list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
4310   if ( reverse ) {
4311     iNode = il1;
4312     il1 = il2;
4313     il2 = iNode;
4314     aNodesToInsert.reverse();
4315   }
4316   // check that not link nodes of a quadrangles are in good order
4317   int nbFaceNodes = theFace->NbNodes();
4318   if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
4319     iNode = i3;
4320     i3 = i4;
4321     i4 = iNode;
4322   } 
4323
4324   if (toCreatePoly || theFace->IsPoly()) {
4325
4326     iNode = 0;
4327     vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
4328
4329     // add nodes of face up to first node of link
4330     bool isFLN = false;
4331     nodeIt = theFace->nodesIterator();
4332     while ( nodeIt->more() && !isFLN ) {
4333       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4334       poly_nodes[iNode++] = n;
4335       if (n == nodes[il1]) {
4336         isFLN = true;
4337       }
4338     }
4339
4340     // add nodes to insert
4341     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4342     for (; nIt != aNodesToInsert.end(); nIt++) {
4343       poly_nodes[iNode++] = *nIt;
4344     }
4345
4346     // add nodes of face starting from last node of link
4347     while ( nodeIt->more() ) {
4348       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4349       poly_nodes[iNode++] = n;
4350     }
4351
4352     // edit or replace the face
4353     SMESHDS_Mesh *aMesh = GetMeshDS();
4354
4355     if (theFace->IsPoly()) {
4356       aMesh->ChangePolygonNodes(theFace, poly_nodes);
4357
4358     } else {
4359       int aShapeId = FindShape( theFace );
4360
4361       SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4362       if ( aShapeId && newElem )
4363         aMesh->SetMeshElementOnShape( newElem, aShapeId );
4364
4365       aMesh->RemoveElement(theFace);
4366     }
4367     return;
4368   }
4369
4370   // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
4371   int nbLinkNodes = 2 + aNodesToInsert.size();
4372   const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
4373   linkNodes[ 0 ] = nodes[ il1 ];
4374   linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
4375   list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4376   for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
4377     linkNodes[ iNode++ ] = *nIt;
4378   }
4379   // decide how to split a quadrangle: compare possible variants
4380   // and choose which of splits to be a quadrangle
4381   int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
4382   if ( nbFaceNodes == 3 )
4383   {
4384     iBestQuad = nbSplits;
4385     i4 = i3;
4386   }
4387   else if ( nbFaceNodes == 4 )
4388   {
4389     SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
4390     double aBestRate = DBL_MAX;
4391     for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
4392       i1 = 0; i2 = 1;
4393       double aBadRate = 0;
4394       // evaluate elements quality
4395       for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
4396         if ( iSplit == iQuad ) {
4397           SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
4398                                  linkNodes[ i2++ ],
4399                                  nodes[ i3 ],
4400                                  nodes[ i4 ]);
4401           aBadRate += getBadRate( &quad, aCrit );
4402         }
4403         else {
4404           SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
4405                                  linkNodes[ i2++ ],
4406                                  nodes[ iSplit < iQuad ? i4 : i3 ]);
4407           aBadRate += getBadRate( &tria, aCrit );
4408         }
4409       }
4410       // choice
4411       if ( aBadRate < aBestRate ) {
4412         iBestQuad = iQuad;
4413         aBestRate = aBadRate;
4414       }
4415     }
4416   }
4417
4418   // create new elements
4419   SMESHDS_Mesh *aMesh = GetMeshDS();
4420   int aShapeId = FindShape( theFace );
4421   
4422   i1 = 0; i2 = 1;
4423   for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
4424     SMDS_MeshElement* newElem = 0;
4425     if ( iSplit == iBestQuad )
4426       newElem = aMesh->AddFace (linkNodes[ i1++ ],
4427                                 linkNodes[ i2++ ],
4428                                 nodes[ i3 ],
4429                                 nodes[ i4 ]);
4430     else
4431       newElem = aMesh->AddFace (linkNodes[ i1++ ],
4432                                 linkNodes[ i2++ ],
4433                                 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
4434     if ( aShapeId && newElem )
4435       aMesh->SetMeshElementOnShape( newElem, aShapeId );
4436   }
4437
4438   // change nodes of theFace
4439   const SMDS_MeshNode* newNodes[ 4 ];
4440   newNodes[ 0 ] = linkNodes[ i1 ];
4441   newNodes[ 1 ] = linkNodes[ i2 ];
4442   newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
4443   newNodes[ 3 ] = nodes[ i4 ];
4444   aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
4445 }
4446
4447 //=======================================================================
4448 //function : UpdateVolumes
4449 //purpose  : 
4450 //=======================================================================
4451 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode*        theBetweenNode1,
4452                                       const SMDS_MeshNode*        theBetweenNode2,
4453                                       list<const SMDS_MeshNode*>& theNodesToInsert)
4454 {
4455   SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
4456   while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
4457     const SMDS_MeshElement* elem = invElemIt->next();
4458     if (elem->GetType() != SMDSAbs_Volume)
4459       continue;
4460
4461     // check, if current volume has link theBetweenNode1 - theBetweenNode2
4462     SMDS_VolumeTool aVolume (elem);
4463     if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
4464       continue;
4465
4466     // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
4467     int iface, nbFaces = aVolume.NbFaces();
4468     vector<const SMDS_MeshNode *> poly_nodes;
4469     vector<int> quantities (nbFaces);
4470
4471     for (iface = 0; iface < nbFaces; iface++) {
4472       int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
4473       // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
4474       const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
4475
4476       for (int inode = 0; inode < nbFaceNodes; inode++) {
4477         poly_nodes.push_back(faceNodes[inode]);
4478
4479         if (nbInserted == 0) {
4480           if (faceNodes[inode] == theBetweenNode1) {
4481             if (faceNodes[inode + 1] == theBetweenNode2) {
4482               nbInserted = theNodesToInsert.size();
4483
4484               // add nodes to insert
4485               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
4486               for (; nIt != theNodesToInsert.end(); nIt++) {
4487                 poly_nodes.push_back(*nIt);
4488               }
4489             }
4490           } else if (faceNodes[inode] == theBetweenNode2) {
4491             if (faceNodes[inode + 1] == theBetweenNode1) {
4492               nbInserted = theNodesToInsert.size();
4493
4494               // add nodes to insert in reversed order
4495               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
4496               nIt--;
4497               for (; nIt != theNodesToInsert.begin(); nIt--) {
4498                 poly_nodes.push_back(*nIt);
4499               }
4500               poly_nodes.push_back(*nIt);
4501             }
4502           } else {
4503           }
4504         }
4505       }
4506       quantities[iface] = nbFaceNodes + nbInserted;
4507     }
4508
4509     // Replace or update the volume
4510     SMESHDS_Mesh *aMesh = GetMeshDS();
4511
4512     if (elem->IsPoly()) {
4513       aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4514
4515     } else {
4516       int aShapeId = FindShape( elem );
4517
4518       SMDS_MeshElement* newElem =
4519         aMesh->AddPolyhedralVolume(poly_nodes, quantities);
4520       if (aShapeId && newElem)
4521         aMesh->SetMeshElementOnShape(newElem, aShapeId);
4522
4523       aMesh->RemoveElement(elem);
4524     }
4525   }
4526 }
4527
4528 //=======================================================================
4529 //function : SewSideElements
4530 //purpose  : 
4531 //=======================================================================
4532
4533 SMESH_MeshEditor::Sew_Error
4534   SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
4535                                      set<const SMDS_MeshElement*>& theSide2,
4536                                      const SMDS_MeshNode*          theFirstNode1,
4537                                      const SMDS_MeshNode*          theFirstNode2,
4538                                      const SMDS_MeshNode*          theSecondNode1,
4539                                      const SMDS_MeshNode*          theSecondNode2)
4540 {
4541   MESSAGE ("::::SewSideElements()");
4542   if ( theSide1.size() != theSide2.size() )
4543     return SEW_DIFF_NB_OF_ELEMENTS;
4544
4545   Sew_Error aResult = SEW_OK;
4546   // Algo:
4547   // 1. Build set of faces representing each side
4548   // 2. Find which nodes of the side 1 to merge with ones on the side 2
4549   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4550
4551   // =======================================================================
4552   // 1. Build set of faces representing each side:
4553   // =======================================================================
4554   // a. build set of nodes belonging to faces
4555   // b. complete set of faces: find missing fices whose nodes are in set of nodes
4556   // c. create temporary faces representing side of volumes if correspondent
4557   //    face does not exist
4558
4559   SMESHDS_Mesh* aMesh = GetMeshDS();
4560   SMDS_Mesh aTmpFacesMesh;
4561   set<const SMDS_MeshElement*> faceSet1, faceSet2;
4562   set<const SMDS_MeshElement*> volSet1,  volSet2;
4563   set<const SMDS_MeshNode*>    nodeSet1, nodeSet2;
4564   set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
4565   set<const SMDS_MeshElement*>  * volSetPtr[] = { &volSet1,  &volSet2  };
4566   set<const SMDS_MeshNode*>    * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
4567   set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
4568   int iSide, iFace, iNode;
4569
4570   for ( iSide = 0; iSide < 2; iSide++ ) {
4571     set<const SMDS_MeshNode*>    * nodeSet = nodeSetPtr[ iSide ];
4572     set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
4573     set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4574     set<const SMDS_MeshElement*> * volSet  = volSetPtr [ iSide ];
4575     set<const SMDS_MeshElement*>::iterator vIt, eIt;
4576     set<const SMDS_MeshNode*>::iterator    nIt;
4577
4578   // -----------------------------------------------------------
4579   // 1a. Collect nodes of existing faces
4580   //     and build set of face nodes in order to detect missing
4581   //     faces corresponing to sides of volumes
4582   // -----------------------------------------------------------
4583
4584     set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
4585
4586     // loop on the given element of a side
4587     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
4588       const SMDS_MeshElement* elem = *eIt;
4589       if ( elem->GetType() == SMDSAbs_Face ) {
4590         faceSet->insert( elem );
4591         set <const SMDS_MeshNode*> faceNodeSet;
4592         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
4593         while ( nodeIt->more() ) {
4594           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4595           nodeSet->insert( n );
4596           faceNodeSet.insert( n );
4597         }
4598         setOfFaceNodeSet.insert( faceNodeSet );
4599       }
4600       else if ( elem->GetType() == SMDSAbs_Volume )
4601         volSet->insert( elem );
4602     }
4603     // ------------------------------------------------------------------------------
4604     // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
4605     // ------------------------------------------------------------------------------
4606
4607     for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4608       SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4609       while ( fIt->more() ) { // loop on faces sharing a node
4610         const SMDS_MeshElement* f = fIt->next();
4611         if ( faceSet->find( f ) == faceSet->end() ) {
4612           // check if all nodes are in nodeSet and
4613           // complete setOfFaceNodeSet if they are
4614           set <const SMDS_MeshNode*> faceNodeSet;
4615           SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4616           bool allInSet = true;
4617           while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4618             const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4619             if ( nodeSet->find( n ) == nodeSet->end() )
4620               allInSet = false;
4621             else
4622               faceNodeSet.insert( n );
4623           }
4624           if ( allInSet ) {
4625             faceSet->insert( f );
4626             setOfFaceNodeSet.insert( faceNodeSet );
4627           }
4628         }
4629       }
4630     }
4631
4632     // -------------------------------------------------------------------------
4633     // 1c. Create temporary faces representing sides of volumes if correspondent
4634     //     face does not exist
4635     // -------------------------------------------------------------------------
4636
4637     if ( !volSet->empty() )
4638     {
4639       //int nodeSetSize = nodeSet->size();
4640       
4641       // loop on given volumes
4642       for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
4643         SMDS_VolumeTool vol (*vIt);
4644         // loop on volume faces: find free faces
4645         // --------------------------------------
4646         list<const SMDS_MeshElement* > freeFaceList;
4647         for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
4648           if ( !vol.IsFreeFace( iFace ))
4649             continue;
4650           // check if there is already a face with same nodes in a face set
4651           const SMDS_MeshElement* aFreeFace = 0;
4652           const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
4653           int nbNodes = vol.NbFaceNodes( iFace );
4654           set <const SMDS_MeshNode*> faceNodeSet;
4655           vol.GetFaceNodes( iFace, faceNodeSet );
4656           bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
4657           if ( isNewFace ) {
4658             // no such a face is given but it still can exist, check it
4659             if ( nbNodes == 3 ) {
4660               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
4661             } else if ( nbNodes == 4 ) {
4662               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4663             } else {
4664               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4665               for (int inode = 0; inode < nbNodes; inode++) {
4666                 poly_nodes[inode] = fNodes[inode];
4667               }
4668               aFreeFace = aMesh->FindFace(poly_nodes);
4669             }
4670           }
4671           if ( !aFreeFace ) {
4672             // create a temporary face
4673             if ( nbNodes == 3 ) {
4674               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
4675             } else if ( nbNodes == 4 ) {
4676               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4677             } else {
4678               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4679               for (int inode = 0; inode < nbNodes; inode++) {
4680                 poly_nodes[inode] = fNodes[inode];
4681               }
4682               aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
4683             }
4684           }
4685           if ( aFreeFace )
4686             freeFaceList.push_back( aFreeFace );
4687
4688         } // loop on faces of a volume
4689
4690         // choose one of several free faces
4691         // --------------------------------------
4692         if ( freeFaceList.size() > 1 ) {
4693           // choose a face having max nb of nodes shared by other elems of a side
4694           int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
4695           list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
4696           while ( fIt != freeFaceList.end() ) { // loop on free faces
4697             int nbSharedNodes = 0;
4698             SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4699             while ( nodeIt->more() ) { // loop on free face nodes
4700               const SMDS_MeshNode* n =
4701                 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4702               SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
4703               while ( invElemIt->more() ) {
4704                 const SMDS_MeshElement* e = invElemIt->next();
4705                 if ( faceSet->find( e ) != faceSet->end() )
4706                   nbSharedNodes++;
4707                 if ( elemSet->find( e ) != elemSet->end() )
4708                   nbSharedNodes++;
4709               }
4710             }
4711             if ( nbSharedNodes >= maxNbNodes ) {
4712               maxNbNodes = nbSharedNodes;
4713               fIt++;
4714             }
4715             else 
4716               freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
4717           }
4718           if ( freeFaceList.size() > 1 )
4719           {
4720             // could not choose one face, use another way
4721             // choose a face most close to the bary center of the opposite side
4722             gp_XYZ aBC( 0., 0., 0. );
4723             set <const SMDS_MeshNode*> addedNodes;
4724             set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
4725             eIt = elemSet2->begin();
4726             for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
4727               SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
4728               while ( nodeIt->more() ) { // loop on free face nodes
4729                 const SMDS_MeshNode* n =
4730                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4731                 if ( addedNodes.insert( n ).second )
4732                   aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
4733               }
4734             }
4735             aBC /= addedNodes.size();
4736             double minDist = DBL_MAX;
4737             fIt = freeFaceList.begin();
4738             while ( fIt != freeFaceList.end() ) { // loop on free faces
4739               double dist = 0;
4740               SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4741               while ( nodeIt->more() ) { // loop on free face nodes
4742                 const SMDS_MeshNode* n =
4743                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4744                 gp_XYZ p( n->X(),n->Y(),n->Z() );
4745                 dist += ( aBC - p ).SquareModulus();
4746               }
4747               if ( dist < minDist ) {
4748                 minDist = dist;
4749                 freeFaceList.erase( freeFaceList.begin(), fIt++ );
4750               }
4751               else
4752                 fIt = freeFaceList.erase( fIt++ );
4753             }
4754           }
4755         } // choose one of several free faces of a volume
4756
4757         if ( freeFaceList.size() == 1 ) {
4758           const SMDS_MeshElement* aFreeFace = freeFaceList.front();
4759           faceSet->insert( aFreeFace );
4760           // complete a node set with nodes of a found free face
4761 //           for ( iNode = 0; iNode < ; iNode++ )
4762 //             nodeSet->insert( fNodes[ iNode ] );
4763         }
4764
4765       } // loop on volumes of a side
4766
4767 //       // complete a set of faces if new nodes in a nodeSet appeared
4768 //       // ----------------------------------------------------------
4769 //       if ( nodeSetSize != nodeSet->size() ) {
4770 //         for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4771 //           SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4772 //           while ( fIt->more() ) { // loop on faces sharing a node
4773 //             const SMDS_MeshElement* f = fIt->next();
4774 //             if ( faceSet->find( f ) == faceSet->end() ) {
4775 //               // check if all nodes are in nodeSet and
4776 //               // complete setOfFaceNodeSet if they are
4777 //               set <const SMDS_MeshNode*> faceNodeSet;
4778 //               SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4779 //               bool allInSet = true;
4780 //               while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4781 //                 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4782 //                 if ( nodeSet->find( n ) == nodeSet->end() )
4783 //                   allInSet = false;
4784 //                 else
4785 //                   faceNodeSet.insert( n );
4786 //               }
4787 //               if ( allInSet ) {
4788 //                 faceSet->insert( f );
4789 //                 setOfFaceNodeSet.insert( faceNodeSet );
4790 //               }
4791 //             }
4792 //           }
4793 //         }
4794 //       }
4795     } // Create temporary faces, if there are volumes given
4796   } // loop on sides
4797
4798   if ( faceSet1.size() != faceSet2.size() ) {
4799     // delete temporary faces: they are in reverseElements of actual nodes
4800     SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4801     while ( tmpFaceIt->more() )
4802       aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4803     MESSAGE("Diff nb of faces");
4804     return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4805   }
4806
4807   // ============================================================
4808   // 2. Find nodes to merge:
4809   //              bind a node to remove to a node to put instead
4810   // ============================================================
4811
4812   TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
4813   if ( theFirstNode1 != theFirstNode2 )
4814     nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
4815   if ( theSecondNode1 != theSecondNode2 )
4816     nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
4817
4818   LinkID_Gen aLinkID_Gen( GetMeshDS() );
4819   set< long > linkIdSet; // links to process
4820   linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
4821
4822   typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
4823   list< TPairOfNodes > linkList[2];
4824   linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
4825   linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
4826   // loop on links in linkList; find faces by links and append links
4827   // of the found faces to linkList
4828   list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
4829   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
4830   {
4831     TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
4832     long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
4833     if ( linkIdSet.find( linkID ) == linkIdSet.end() )
4834       continue;
4835
4836     // by links, find faces in the face sets,
4837     // and find indices of link nodes in the found faces;
4838     // in a face set, there is only one or no face sharing a link
4839     // ---------------------------------------------------------------
4840
4841     const SMDS_MeshElement* face[] = { 0, 0 };
4842     const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
4843     const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
4844     int iLinkNode[2][2];
4845     for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4846       const SMDS_MeshNode* n1 = link[iSide].first;
4847       const SMDS_MeshNode* n2 = link[iSide].second;
4848       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4849       set< const SMDS_MeshElement* > fMap;
4850       for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
4851         const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
4852         SMDS_ElemIteratorPtr fIt = n->facesIterator();
4853         while ( fIt->more() ) { // loop on faces sharing a node
4854           const SMDS_MeshElement* f = fIt->next();
4855           if (faceSet->find( f ) != faceSet->end() && // f is in face set
4856               ! fMap.insert( f ).second ) // f encounters twice
4857           {
4858             if ( face[ iSide ] ) {
4859               MESSAGE( "2 faces per link " );
4860               aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
4861               break;
4862             }
4863             face[ iSide ] = f;
4864             faceSet->erase( f );
4865             // get face nodes and find ones of a link
4866             iNode = 0;
4867             SMDS_ElemIteratorPtr nIt = f->nodesIterator();
4868             while ( nIt->more() ) {
4869               const SMDS_MeshNode* n =
4870                 static_cast<const SMDS_MeshNode*>( nIt->next() );
4871               if ( n == n1 )
4872                 iLinkNode[ iSide ][ 0 ] = iNode;
4873               else if ( n == n2 )
4874                 iLinkNode[ iSide ][ 1 ] = iNode;
4875               else if ( notLinkNodes[ iSide ][ 0 ] )
4876                 notLinkNodes[ iSide ][ 1 ] = n;
4877               else
4878                 notLinkNodes[ iSide ][ 0 ] = n;
4879               faceNodes[ iSide ][ iNode++ ] = n;
4880             }
4881             faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
4882           }
4883         }
4884       }
4885     }
4886     // check similarity of elements of the sides
4887     if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
4888       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
4889       if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
4890         aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
4891       else
4892         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4893       break; // do not return because it s necessary to remove tmp faces
4894     }
4895
4896     // set nodes to merge
4897     // -------------------
4898
4899     if ( face[0] && face[1] )
4900     {
4901       int nbNodes = face[0]->NbNodes();
4902       if ( nbNodes != face[1]->NbNodes() ) {
4903         MESSAGE("Diff nb of face nodes");
4904         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4905         break; // do not return because it s necessary to remove tmp faces
4906       }
4907       bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
4908       if ( nbNodes == 3 )
4909         nReplaceMap.insert( TNodeNodeMap::value_type
4910                            ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4911       else {
4912         for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4913           // analyse link orientation in faces
4914           int i1 = iLinkNode[ iSide ][ 0 ];
4915           int i2 = iLinkNode[ iSide ][ 1 ];
4916           reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
4917           // if notLinkNodes are the first and the last ones, then
4918           // their order does not correspond to the link orientation
4919           if (( i1 == 1 && i2 == 2 ) ||
4920               ( i1 == 2 && i2 == 1 ))
4921             reverse[ iSide ] = !reverse[ iSide ];
4922         }
4923         if ( reverse[0] == reverse[1] ) {
4924           nReplaceMap.insert( TNodeNodeMap::value_type
4925                              ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4926           nReplaceMap.insert( TNodeNodeMap::value_type
4927                              ( notLinkNodes[0][1], notLinkNodes[1][1] ));
4928         }
4929         else {
4930           nReplaceMap.insert( TNodeNodeMap::value_type
4931                              ( notLinkNodes[0][0], notLinkNodes[1][1] ));
4932           nReplaceMap.insert( TNodeNodeMap::value_type
4933                              ( notLinkNodes[0][1], notLinkNodes[1][0] ));
4934         }
4935       }
4936
4937       // add other links of the faces to linkList
4938       // -----------------------------------------
4939
4940       const SMDS_MeshNode** nodes = faceNodes[ 0 ];
4941       for ( iNode = 0; iNode < nbNodes; iNode++ )
4942       {
4943         linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
4944         pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
4945         if ( !iter_isnew.second ) { // already in a set: no need to process
4946           linkIdSet.erase( iter_isnew.first );
4947         }
4948         else // new in set == encountered for the first time: add
4949         {
4950           const SMDS_MeshNode* n1 = nodes[ iNode ];
4951           const SMDS_MeshNode* n2 = nodes[ iNode + 1];
4952           linkList[0].push_back ( TPairOfNodes( n1, n2 ));
4953           linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
4954         }
4955       }
4956     } // 2 faces found
4957   } // loop on link lists
4958
4959   if ( aResult == SEW_OK &&
4960       ( linkIt[0] != linkList[0].end() ||
4961        !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
4962     MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
4963             " " << (faceSetPtr[1]->empty()));
4964     aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4965   }
4966
4967   // ====================================================================
4968   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4969   // ====================================================================
4970
4971   // delete temporary faces: they are in reverseElements of actual nodes
4972   SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4973   while ( tmpFaceIt->more() )
4974     aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4975
4976   if ( aResult != SEW_OK)
4977     return aResult;
4978
4979   list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
4980   // loop on nodes replacement map
4981   TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
4982   for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
4983     if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
4984     {
4985       const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
4986       nodeIDsToRemove.push_back( nToRemove->GetID() );
4987       // loop on elements sharing nToRemove
4988       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
4989       while ( invElemIt->more() ) {
4990         const SMDS_MeshElement* e = invElemIt->next();
4991         // get a new suite of nodes: make replacement
4992         int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
4993         const SMDS_MeshNode* nodes[ 8 ];
4994         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4995         while ( nIt->more() ) {
4996           const SMDS_MeshNode* n =
4997             static_cast<const SMDS_MeshNode*>( nIt->next() );
4998           nnIt = nReplaceMap.find( n );
4999           if ( nnIt != nReplaceMap.end() ) {
5000             nbReplaced++;
5001             n = (*nnIt).second;
5002           }
5003           nodes[ i++ ] = n;
5004         }
5005         //       if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
5006         //         elemIDsToRemove.push_back( e->GetID() );
5007         //       else
5008         if ( nbReplaced )
5009           aMesh->ChangeElementNodes( e, nodes, nbNodes );
5010       }
5011   }
5012
5013   Remove( nodeIDsToRemove, true );
5014
5015   return aResult;
5016 }