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