Salome HOME
Inmprovement extrusion algorithm in MeshEditor
[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
2415 //=======================================================================
2416 //function : CreateNode
2417 //purpose  : 
2418 //=======================================================================
2419 const SMDS_MeshNode* SMESH_MeshEditor::CreateNode(const double x,
2420                                                   const double y,
2421                                                   const double z,
2422                                                   const double tolnode)
2423 {
2424   gp_Pnt P1(x,y,z);
2425   SMESHDS_Mesh * aMesh = myMesh->GetMeshDS();
2426   // try to search in sequence of existing nodes
2427   SMDS_NodeIteratorPtr itn = aMesh->nodesIterator();
2428   while(itn->more()) {
2429     const SMDS_MeshNode* aN = static_cast<const SMDS_MeshNode*> (itn->next());
2430     gp_Pnt P2(aN->X(),aN->Y(),aN->Z());
2431     if(P1.Distance(P2)<tolnode)
2432       return aN;
2433   }    
2434   // create new node and return it
2435   const SMDS_MeshNode* NewNode = aMesh->AddNode(x,y,z);
2436   return NewNode;
2437 }
2438
2439
2440 //=======================================================================
2441 //function : ExtrusionSweep
2442 //purpose  :
2443 //=======================================================================
2444
2445 void SMESH_MeshEditor::ExtrusionSweep
2446                     (set<const SMDS_MeshElement*> & theElems,
2447                      const gp_Vec&                  theStep,
2448                      const int                      theNbSteps,
2449                      TElemOfElemListMap&            newElemsMap,
2450                      const int                      theFlags,
2451                      const double                   theTolerance)
2452 {
2453   gp_Trsf aTrsf;
2454   aTrsf.SetTranslation( theStep );
2455
2456   SMESHDS_Mesh* aMesh = GetMeshDS();
2457
2458   TNodeOfNodeListMap mapNewNodes;
2459   TElemOfVecOfNnlmiMap mapElemNewNodes;
2460   //TElemOfElemListMap newElemsMap;
2461
2462   // loop on theElems
2463   set< const SMDS_MeshElement* >::iterator itElem;
2464   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2465   {
2466     // check element type
2467     const SMDS_MeshElement* elem = (*itElem);
2468     if ( !elem )
2469       continue;
2470
2471     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2472     newNodesItVec.reserve( elem->NbNodes() );
2473
2474     // loop on elem nodes
2475     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2476     while ( itN->more() ) {
2477
2478       // check if a node has been already sweeped
2479       const SMDS_MeshNode* node =
2480         static_cast<const SMDS_MeshNode*>( itN->next() );
2481       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2482       if ( nIt == mapNewNodes.end() )
2483       {
2484         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2485         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2486
2487         // make new nodes
2488         double coord[] = { node->X(), node->Y(), node->Z() };
2489         for ( int i = 0; i < theNbSteps; i++ ) {
2490           aTrsf.Transforms( coord[0], coord[1], coord[2] );
2491           if( theFlags & EXTRUSION_FLAG_SEW ) {
2492             const SMDS_MeshNode * newNode = CreateNode(coord[0], coord[1],
2493                                                        coord[2], theTolerance);
2494             listNewNodes.push_back( newNode );
2495           }
2496           else {
2497             const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2498             listNewNodes.push_back( newNode );
2499           }
2500         }
2501       }
2502       newNodesItVec.push_back( nIt );
2503     }
2504     // make new elements
2505     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2506   }
2507   if( theFlags & EXTRUSION_FLAG_BOUNDARY ) {
2508     makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems );
2509   }
2510 }
2511
2512 //=======================================================================
2513 //class    : SMESH_MeshEditor_PathPoint
2514 //purpose  : auxiliary class
2515 //=======================================================================
2516 class SMESH_MeshEditor_PathPoint {
2517 public:
2518   SMESH_MeshEditor_PathPoint() {
2519     myPnt.SetCoord(99., 99., 99.);
2520     myTgt.SetCoord(1.,0.,0.);
2521     myAngle=0.;
2522     myPrm=0.;
2523   }
2524   void SetPnt(const gp_Pnt& aP3D){
2525     myPnt=aP3D;
2526   }
2527   void SetTangent(const gp_Dir& aTgt){
2528     myTgt=aTgt;
2529   }
2530   void SetAngle(const double& aBeta){
2531     myAngle=aBeta;
2532   }
2533   void SetParameter(const double& aPrm){
2534     myPrm=aPrm;
2535   }
2536   const gp_Pnt& Pnt()const{
2537     return myPnt;
2538   }
2539   const gp_Dir& Tangent()const{
2540     return myTgt;
2541   }
2542   double Angle()const{
2543     return myAngle;
2544   }
2545   double Parameter()const{
2546     return myPrm;
2547   }
2548
2549 protected:
2550   gp_Pnt myPnt;
2551   gp_Dir myTgt;
2552   double myAngle;
2553   double myPrm;
2554 };
2555
2556 //=======================================================================
2557 //function : ExtrusionAlongTrack
2558 //purpose  :
2559 //=======================================================================
2560 SMESH_MeshEditor::Extrusion_Error
2561   SMESH_MeshEditor::ExtrusionAlongTrack (std::set<const SMDS_MeshElement*> & theElements,
2562                                          SMESH_subMesh* theTrack,
2563                                          const SMDS_MeshNode* theN1,
2564                                          const bool theHasAngles,
2565                                          std::list<double>& theAngles,
2566                                          const bool theHasRefPoint,
2567                                          const gp_Pnt& theRefPoint)
2568 {
2569   MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
2570   int j, aNbTP, aNbE, aNb;
2571   double aT1, aT2, aT, aAngle, aX, aY, aZ;
2572   std::list<double> aPrms;
2573   std::list<double>::iterator aItD;
2574   std::set< const SMDS_MeshElement* >::iterator itElem;
2575
2576   Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
2577   gp_Pnt aP3D, aV0;
2578   gp_Vec aVec;
2579   gp_XYZ aGC;
2580   Handle(Geom_Curve) aC3D;
2581   TopoDS_Edge aTrackEdge;
2582   TopoDS_Vertex aV1, aV2;
2583
2584   SMDS_ElemIteratorPtr aItE;
2585   SMDS_NodeIteratorPtr aItN;
2586   SMDSAbs_ElementType aTypeE;
2587
2588   TNodeOfNodeListMap mapNewNodes;
2589   TElemOfVecOfNnlmiMap mapElemNewNodes;
2590   TElemOfElemListMap newElemsMap;
2591
2592   aTolVec=1.e-7;
2593   aTolVec2=aTolVec*aTolVec;
2594
2595   // 1. Check data
2596   aNbE = theElements.size();
2597   // nothing to do
2598   if ( !aNbE )
2599     return EXTR_NO_ELEMENTS;
2600
2601   // 1.1 Track Pattern
2602   ASSERT( theTrack );
2603
2604   SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
2605
2606   aItE = pSubMeshDS->GetElements();
2607   while ( aItE->more() ) {
2608     const SMDS_MeshElement* pE = aItE->next();
2609     aTypeE = pE->GetType();
2610     // Pattern must contain links only
2611     if ( aTypeE != SMDSAbs_Edge )
2612       return EXTR_PATH_NOT_EDGE;
2613   }
2614
2615   const TopoDS_Shape& aS = theTrack->GetSubShape();
2616   // Sub shape for the Pattern must be an Edge
2617   if ( aS.ShapeType() != TopAbs_EDGE )
2618     return EXTR_BAD_PATH_SHAPE;
2619
2620   aTrackEdge = TopoDS::Edge( aS );
2621   // the Edge must not be degenerated
2622   if ( BRep_Tool::Degenerated( aTrackEdge ) )
2623     return EXTR_BAD_PATH_SHAPE;
2624
2625   TopExp::Vertices( aTrackEdge, aV1, aV2 );
2626   aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
2627   aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
2628
2629   aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
2630   const SMDS_MeshNode* aN1 = aItN->next();
2631
2632   aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
2633   const SMDS_MeshNode* aN2 = aItN->next();
2634
2635   // starting node must be aN1 or aN2
2636   if ( !( aN1 == theN1 || aN2 == theN1 ) )
2637     return EXTR_BAD_STARTING_NODE;
2638
2639   aNbTP = pSubMeshDS->NbNodes() + 2;
2640
2641   // 1.2. Angles
2642   vector<double> aAngles( aNbTP );
2643
2644   for ( j=0; j < aNbTP; ++j ) {
2645     aAngles[j] = 0.;
2646   }
2647
2648   if ( theHasAngles ) {
2649     aItD = theAngles.begin();
2650     for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
2651       aAngle = *aItD;
2652       aAngles[j] = aAngle;
2653     }
2654   }
2655
2656   // 2. Collect parameters on the track edge
2657   aPrms.push_back( aT1 );
2658   aPrms.push_back( aT2 );
2659
2660   aItN = pSubMeshDS->GetNodes();
2661   while ( aItN->more() ) {
2662     const SMDS_MeshNode* pNode = aItN->next();
2663     const SMDS_EdgePosition* pEPos =
2664       static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
2665     aT = pEPos->GetUParameter();
2666     aPrms.push_back( aT );
2667   }
2668
2669   // sort parameters
2670   aPrms.sort();
2671   if ( aN1 == theN1 ) {
2672     if ( aT1 > aT2 ) {
2673       aPrms.reverse();
2674     }
2675   }
2676   else {
2677     if ( aT2 > aT1 ) {
2678       aPrms.reverse();
2679     }
2680   }
2681
2682   // 3. Path Points
2683   SMESH_MeshEditor_PathPoint aPP;
2684   vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
2685   //
2686   aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
2687   //
2688   aItD = aPrms.begin();
2689   for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
2690     aT = *aItD;
2691     aC3D->D1( aT, aP3D, aVec );
2692     aL2 = aVec.SquareMagnitude();
2693     if ( aL2 < aTolVec2 )
2694       return EXTR_CANT_GET_TANGENT;
2695
2696     gp_Dir aTgt( aVec );
2697     aAngle = aAngles[j];
2698
2699     aPP.SetPnt( aP3D );
2700     aPP.SetTangent( aTgt );
2701     aPP.SetAngle( aAngle );
2702     aPP.SetParameter( aT );
2703     aPPs[j]=aPP;
2704   }
2705
2706   // 3. Center of rotation aV0
2707   aV0 = theRefPoint;
2708   if ( !theHasRefPoint ) {
2709     aNb = 0;
2710     aGC.SetCoord( 0.,0.,0. );
2711
2712     itElem = theElements.begin();
2713     for ( ; itElem != theElements.end(); itElem++ ) {
2714       const SMDS_MeshElement* elem = (*itElem);
2715
2716       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2717       while ( itN->more() ) {
2718         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
2719         aX = node->X();
2720         aY = node->Y();
2721         aZ = node->Z();
2722
2723         if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
2724           list<const SMDS_MeshNode*> aLNx;
2725           mapNewNodes[node] = aLNx;
2726           //
2727           gp_XYZ aXYZ( aX, aY, aZ );
2728           aGC += aXYZ;
2729           ++aNb;
2730         }
2731       }
2732     }
2733     aGC /= aNb;
2734     aV0.SetXYZ( aGC );
2735   } // if (!theHasRefPoint) {
2736   mapNewNodes.clear();
2737
2738   // 4. Processing the elements
2739   SMESHDS_Mesh* aMesh = GetMeshDS();
2740
2741   for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
2742     // check element type
2743     const SMDS_MeshElement* elem = (*itElem);
2744     aTypeE = elem->GetType();
2745     if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
2746       continue;
2747
2748     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
2749     newNodesItVec.reserve( elem->NbNodes() );
2750
2751     // loop on elem nodes
2752     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2753     while ( itN->more() ) {
2754
2755       // check if a node has been already processed
2756       const SMDS_MeshNode* node =
2757         static_cast<const SMDS_MeshNode*>( itN->next() );
2758       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
2759       if ( nIt == mapNewNodes.end() ) {
2760         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
2761         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
2762
2763         // make new nodes
2764         aX = node->X();  aY = node->Y(); aZ = node->Z();
2765
2766         Standard_Real aAngle1x, aAngleT1T0, aTolAng;
2767         gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
2768         gp_Ax1 anAx1, anAxT1T0;
2769         gp_Dir aDT1x, aDT0x, aDT1T0;
2770
2771         aTolAng=1.e-4;
2772
2773         aV0x = aV0;
2774         aPN0.SetCoord(aX, aY, aZ);
2775
2776         const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
2777         aP0x = aPP0.Pnt();
2778         aDT0x= aPP0.Tangent();
2779
2780         for ( j = 1; j < aNbTP; ++j ) {
2781           const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
2782           aP1x = aPP1.Pnt();
2783           aDT1x = aPP1.Tangent();
2784           aAngle1x = aPP1.Angle();
2785
2786           gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
2787           // Translation
2788           gp_Vec aV01x( aP0x, aP1x );
2789           aTrsf.SetTranslation( aV01x );
2790
2791           // traslated point
2792           aV1x = aV0x.Transformed( aTrsf );
2793           aPN1 = aPN0.Transformed( aTrsf );
2794
2795           // rotation 1 [ T1,T0 ]
2796           aAngleT1T0=-aDT1x.Angle( aDT0x );
2797           if (fabs(aAngleT1T0) > aTolAng) {
2798             aDT1T0=aDT1x^aDT0x;
2799             anAxT1T0.SetLocation( aV1x );
2800             anAxT1T0.SetDirection( aDT1T0 );
2801             aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
2802
2803             aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
2804           }
2805
2806           // rotation 2
2807           if ( theHasAngles ) {
2808             anAx1.SetLocation( aV1x );
2809             anAx1.SetDirection( aDT1x );
2810             aTrsfRot.SetRotation( anAx1, aAngle1x );
2811
2812             aPN1 = aPN1.Transformed( aTrsfRot );
2813           }
2814
2815           // make new node
2816           aX = aPN1.X();
2817           aY = aPN1.Y();
2818           aZ = aPN1.Z();
2819           const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
2820           listNewNodes.push_back( newNode );
2821
2822           aPN0 = aPN1;
2823           aP0x = aP1x;
2824           aV0x = aV1x;
2825           aDT0x = aDT1x;
2826         }
2827       }
2828       newNodesItVec.push_back( nIt );
2829     }
2830     // make new elements
2831     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem] );
2832   }
2833
2834   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements );
2835
2836   return EXTR_OK;
2837 }
2838
2839 //=======================================================================
2840 //function : Transform
2841 //purpose  :
2842 //=======================================================================
2843
2844 void SMESH_MeshEditor::Transform (set<const SMDS_MeshElement*> & theElems,
2845                                   const gp_Trsf&                 theTrsf,
2846                                   const bool                     theCopy)
2847 {
2848   bool needReverse;
2849   switch ( theTrsf.Form() ) {
2850   case gp_PntMirror:
2851   case gp_Ax2Mirror:
2852     needReverse = true;
2853     break;
2854   default:
2855     needReverse = false;
2856   }
2857
2858   SMESHDS_Mesh* aMesh = GetMeshDS();
2859
2860   // map old node to new one
2861   TNodeNodeMap nodeMap;
2862
2863   // elements sharing moved nodes; those of them which have all
2864   // nodes mirrored but are not in theElems are to be reversed
2865   set<const SMDS_MeshElement*> inverseElemSet;
2866
2867   // loop on theElems
2868   set< const SMDS_MeshElement* >::iterator itElem;
2869   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2870   {
2871     const SMDS_MeshElement* elem = (*itElem);
2872     if ( !elem )
2873       continue;
2874
2875     // loop on elem nodes
2876     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2877     while ( itN->more() ) {
2878
2879       // check if a node has been already transformed
2880       const SMDS_MeshNode* node =
2881         static_cast<const SMDS_MeshNode*>( itN->next() );
2882       if (nodeMap.find( node ) != nodeMap.end() )
2883         continue;
2884
2885       double coord[3];
2886       coord[0] = node->X();
2887       coord[1] = node->Y();
2888       coord[2] = node->Z();
2889       theTrsf.Transforms( coord[0], coord[1], coord[2] );
2890       const SMDS_MeshNode * newNode = node;
2891       if ( theCopy )
2892         newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
2893       else {
2894         aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
2895         // node position on shape becomes invalid
2896         const_cast< SMDS_MeshNode* > ( node )->SetPosition
2897           ( SMDS_SpacePosition::originSpacePosition() );
2898       }
2899       nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
2900
2901       // keep inverse elements
2902       if ( !theCopy && needReverse ) {
2903         SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
2904         while ( invElemIt->more() )
2905           inverseElemSet.insert( invElemIt->next() );
2906       }
2907     }
2908   }
2909
2910   // either new elements are to be created
2911   // or a mirrored element are to be reversed
2912   if ( !theCopy && !needReverse)
2913     return;
2914
2915   if ( !inverseElemSet.empty()) {
2916     set<const SMDS_MeshElement*>::iterator invElemIt = inverseElemSet.begin();
2917     for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
2918       theElems.insert( *invElemIt );
2919   }
2920
2921   // replicate or reverse elements
2922
2923   enum {
2924     REV_TETRA   = 0,  //  = nbNodes - 4
2925     REV_PYRAMID = 1,  //  = nbNodes - 4
2926     REV_PENTA   = 2,  //  = nbNodes - 4
2927     REV_FACE    = 3,
2928     REV_HEXA    = 4,  //  = nbNodes - 4
2929     FORWARD     = 5
2930     };
2931   int index[][8] = {
2932     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_TETRA
2933     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_PYRAMID
2934     { 2, 1, 0, 5, 4, 3, 0, 0 },  // REV_PENTA
2935     { 2, 1, 0, 3, 0, 0, 0, 0 },  // REV_FACE
2936     { 2, 1, 0, 3, 6, 5, 4, 7 },  // REV_HEXA
2937     { 0, 1, 2, 3, 4, 5, 6, 7 }   // FORWARD
2938   };
2939
2940   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
2941   {
2942     const SMDS_MeshElement* elem = (*itElem);
2943     if ( !elem || elem->GetType() == SMDSAbs_Node )
2944       continue;
2945
2946     int nbNodes = elem->NbNodes();
2947     int elemType = elem->GetType();
2948
2949     if (elem->IsPoly()) {
2950       // Polygon or Polyhedral Volume
2951       switch ( elemType ) {
2952       case SMDSAbs_Face:
2953         {
2954           vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
2955           int iNode = 0;
2956           SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2957           while (itN->more()) {
2958             const SMDS_MeshNode* node =
2959               static_cast<const SMDS_MeshNode*>(itN->next());
2960             TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
2961             if (nodeMapIt == nodeMap.end())
2962               break; // not all nodes transformed
2963             if (needReverse) {
2964               // reverse mirrored faces and volumes
2965               poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
2966             } else {
2967               poly_nodes[iNode] = (*nodeMapIt).second;
2968             }
2969             iNode++;
2970           }
2971           if ( iNode != nbNodes )
2972             continue; // not all nodes transformed
2973
2974           if ( theCopy ) {
2975             aMesh->AddPolygonalFace(poly_nodes);
2976           } else {
2977             aMesh->ChangePolygonNodes(elem, poly_nodes);
2978           }
2979         }
2980         break;
2981       case SMDSAbs_Volume:
2982         {
2983           // ATTENTION: Reversing is not yet done!!!
2984           const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
2985             (const SMDS_PolyhedralVolumeOfNodes*) elem;
2986           if (!aPolyedre) {
2987             MESSAGE("Warning: bad volumic element");
2988             continue;
2989           }
2990
2991           vector<const SMDS_MeshNode*> poly_nodes;
2992           vector<int> quantities;
2993
2994           bool allTransformed = true;
2995           int nbFaces = aPolyedre->NbFaces();
2996           for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
2997             int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
2998             for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
2999               const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
3000               TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
3001               if (nodeMapIt == nodeMap.end()) {
3002                 allTransformed = false; // not all nodes transformed
3003               } else {
3004                 poly_nodes.push_back((*nodeMapIt).second);
3005               }
3006             }
3007             quantities.push_back(nbFaceNodes);
3008           }
3009           if ( !allTransformed )
3010             continue; // not all nodes transformed
3011
3012           if ( theCopy ) {
3013             aMesh->AddPolyhedralVolume(poly_nodes, quantities);
3014           } else {
3015             aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3016           }
3017         }
3018         break;
3019       default:;
3020       }
3021       continue;
3022     }
3023
3024     // Regular elements
3025     int* i = index[ FORWARD ];
3026     if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
3027       if ( elemType == SMDSAbs_Face )
3028         i = index[ REV_FACE ];
3029       else
3030         i = index[ nbNodes - 4 ];
3031
3032     // find transformed nodes
3033     const SMDS_MeshNode* nodes[8];
3034     int iNode = 0;
3035     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3036     while ( itN->more() )
3037     {
3038       const SMDS_MeshNode* node =
3039         static_cast<const SMDS_MeshNode*>( itN->next() );
3040       TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
3041       if ( nodeMapIt == nodeMap.end() )
3042         break; // not all nodes transformed
3043       nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
3044     }
3045     if ( iNode != nbNodes )
3046       continue; // not all nodes transformed
3047
3048     if ( theCopy )
3049     {
3050       // add a new element
3051       switch ( elemType ) {
3052       case SMDSAbs_Edge:
3053         aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] );
3054         break;
3055       case SMDSAbs_Face:
3056         if ( nbNodes == 3 )
3057           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] );
3058         else
3059           aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]);
3060         break;
3061       case SMDSAbs_Volume:
3062         if ( nbNodes == 4 )
3063           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] );
3064         else if ( nbNodes == 8 )
3065           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3066                             nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]);
3067         else if ( nbNodes == 6 )
3068           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3069                             nodes[ 4 ], nodes[ 5 ]);
3070         else if ( nbNodes == 5 )
3071           aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
3072                             nodes[ 4 ]);
3073         break;
3074       default:;
3075       }
3076     }
3077     else
3078     {
3079       // reverse element as it was reversed by transformation
3080       if ( nbNodes > 2 )
3081         aMesh->ChangeElementNodes( elem, nodes, nbNodes );
3082     }
3083   }
3084 }
3085
3086 //=======================================================================
3087 //function : FindCoincidentNodes
3088 //purpose  : Return list of group of nodes close to each other within theTolerance
3089 //           Search among theNodes or in the whole mesh if theNodes is empty.
3090 //=======================================================================
3091
3092 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
3093                                             const double                theTolerance,
3094                                             TListOfListOfNodes &        theGroupsOfNodes)
3095 {
3096   double tol2 = theTolerance * theTolerance;
3097
3098   list<const SMDS_MeshNode*> nodes;
3099   if ( theNodes.empty() )
3100   { // get all nodes in the mesh
3101     SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
3102     while ( nIt->more() )
3103       nodes.push_back( nIt->next() );
3104   }
3105   else
3106   {
3107     nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
3108   }
3109
3110   list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
3111   for ( ; it1 != nodes.end(); it1++ )
3112   {
3113     const SMDS_MeshNode* n1 = *it1;
3114     gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
3115
3116     list<const SMDS_MeshNode*> * groupPtr = 0;
3117     it2 = it1;
3118     for ( it2++; it2 != nodes.end(); it2++ )
3119     {
3120       const SMDS_MeshNode* n2 = *it2;
3121       gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
3122       if ( p1.SquareDistance( p2 ) <= tol2 )
3123       {
3124         if ( !groupPtr ) {
3125           theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
3126           groupPtr = & theGroupsOfNodes.back();
3127           groupPtr->push_back( n1 );
3128         }
3129         groupPtr->push_back( n2 );
3130         it2 = nodes.erase( it2 );
3131         it2--;
3132       }
3133     }
3134   }
3135 }
3136
3137 //=======================================================================
3138 //function : SimplifyFace
3139 //purpose  :
3140 //=======================================================================
3141 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
3142                                     vector<const SMDS_MeshNode *>&      poly_nodes,
3143                                     vector<int>&                        quantities) const
3144 {
3145   int nbNodes = faceNodes.size();
3146
3147   if (nbNodes < 3)
3148     return 0;
3149
3150   set<const SMDS_MeshNode*> nodeSet;
3151
3152   // get simple seq of nodes
3153   const SMDS_MeshNode* simpleNodes[ nbNodes ];
3154   int iSimple = 0, nbUnique = 0;
3155
3156   simpleNodes[iSimple++] = faceNodes[0];
3157   nbUnique++;
3158   for (int iCur = 1; iCur < nbNodes; iCur++) {
3159     if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
3160       simpleNodes[iSimple++] = faceNodes[iCur];
3161       if (nodeSet.insert( faceNodes[iCur] ).second)
3162         nbUnique++;
3163     }
3164   }
3165   int nbSimple = iSimple;
3166   if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
3167     nbSimple--;
3168     iSimple--;
3169   }
3170
3171   if (nbUnique < 3)
3172     return 0;
3173
3174   // separate loops
3175   int nbNew = 0;
3176   bool foundLoop = (nbSimple > nbUnique);
3177   while (foundLoop) {
3178     foundLoop = false;
3179     set<const SMDS_MeshNode*> loopSet;
3180     for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
3181       const SMDS_MeshNode* n = simpleNodes[iSimple];
3182       if (!loopSet.insert( n ).second) {
3183         foundLoop = true;
3184
3185         // separate loop
3186         int iC = 0, curLast = iSimple;
3187         for (; iC < curLast; iC++) {
3188           if (simpleNodes[iC] == n) break;
3189         }
3190         int loopLen = curLast - iC;
3191         if (loopLen > 2) {
3192           // create sub-element
3193           nbNew++;
3194           quantities.push_back(loopLen);
3195           for (; iC < curLast; iC++) {
3196             poly_nodes.push_back(simpleNodes[iC]);
3197           }
3198         }
3199         // shift the rest nodes (place from the first loop position)
3200         for (iC = curLast + 1; iC < nbSimple; iC++) {
3201           simpleNodes[iC - loopLen] = simpleNodes[iC];
3202         }
3203         nbSimple -= loopLen;
3204         iSimple -= loopLen;
3205       }
3206     } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
3207   } // while (foundLoop)
3208
3209   if (iSimple > 2) {
3210     nbNew++;
3211     quantities.push_back(iSimple);
3212     for (int i = 0; i < iSimple; i++)
3213       poly_nodes.push_back(simpleNodes[i]);
3214   }
3215
3216   return nbNew;
3217 }
3218
3219 //=======================================================================
3220 //function : MergeNodes
3221 //purpose  : In each group, the cdr of nodes are substituted by the first one
3222 //           in all elements.
3223 //=======================================================================
3224
3225 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
3226 {
3227   SMESHDS_Mesh* aMesh = GetMeshDS();
3228
3229   TNodeNodeMap nodeNodeMap; // node to replace - new node
3230   set<const SMDS_MeshElement*> elems; // all elements with changed nodes
3231   list< int > rmElemIds, rmNodeIds;
3232
3233   // Fill nodeNodeMap and elems
3234
3235   TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
3236   for ( ; grIt != theGroupsOfNodes.end(); grIt++ )
3237   {
3238     list<const SMDS_MeshNode*>& nodes = *grIt;
3239     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
3240     const SMDS_MeshNode* nToKeep = *nIt;
3241     for ( ; nIt != nodes.end(); nIt++ )
3242     {
3243       const SMDS_MeshNode* nToRemove = *nIt;
3244       nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
3245       if ( nToRemove != nToKeep ) {
3246         rmNodeIds.push_back( nToRemove->GetID() );
3247         AddToSameGroups( nToKeep, nToRemove, aMesh );
3248       }
3249
3250       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
3251       while ( invElemIt->more() )
3252         elems.insert( invElemIt->next() );
3253     }
3254   }
3255   // Change element nodes or remove an element
3256
3257   set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
3258   for ( ; eIt != elems.end(); eIt++ )
3259   {
3260     const SMDS_MeshElement* elem = *eIt;
3261     int nbNodes = elem->NbNodes();
3262     int aShapeId = FindShape( elem );
3263
3264     set<const SMDS_MeshNode*> nodeSet;
3265     const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
3266     int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
3267
3268     // get new seq of nodes
3269     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3270     while ( itN->more() )
3271     {
3272       const SMDS_MeshNode* n =
3273         static_cast<const SMDS_MeshNode*>( itN->next() );
3274
3275       TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
3276       if ( nnIt != nodeNodeMap.end() ) { // n sticks
3277         n = (*nnIt).second;
3278         iRepl[ nbRepl++ ] = iCur;
3279       }
3280       curNodes[ iCur ] = n;
3281       bool isUnique = nodeSet.insert( n ).second;
3282       if ( isUnique )
3283         uniqueNodes[ iUnique++ ] = n;
3284       iCur++;
3285     }
3286
3287     // Analyse element topology after replacement
3288
3289     bool isOk = true;
3290     int nbUniqueNodes = nodeSet.size();
3291     if ( nbNodes != nbUniqueNodes ) // some nodes stick
3292     {
3293       // Polygons and Polyhedral volumes
3294       if (elem->IsPoly()) {
3295
3296         if (elem->GetType() == SMDSAbs_Face) {
3297           // Polygon
3298           vector<const SMDS_MeshNode *> face_nodes (nbNodes);
3299           int inode = 0;
3300           for (; inode < nbNodes; inode++) {
3301             face_nodes[inode] = curNodes[inode];
3302           }
3303
3304           vector<const SMDS_MeshNode *> polygons_nodes;
3305           vector<int> quantities;
3306           int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
3307
3308           if (nbNew > 0) {
3309             inode = 0;
3310             for (int iface = 0; iface < nbNew - 1; iface++) {
3311               int nbNodes = quantities[iface];
3312               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
3313               for (int ii = 0; ii < nbNodes; ii++, inode++) {
3314                 poly_nodes[ii] = polygons_nodes[inode];
3315               }
3316               SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
3317               if (aShapeId)
3318                 aMesh->SetMeshElementOnShape(newElem, aShapeId);
3319             }
3320             aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
3321           } else {
3322             rmElemIds.push_back(elem->GetID());
3323           }
3324
3325         } else if (elem->GetType() == SMDSAbs_Volume) {
3326           // Polyhedral volume
3327           if (nbUniqueNodes < 4) {
3328             rmElemIds.push_back(elem->GetID());
3329           } else {
3330             // each face has to be analized in order to check volume validity
3331             const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3332               static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3333             if (aPolyedre) {
3334               int nbFaces = aPolyedre->NbFaces();
3335
3336               vector<const SMDS_MeshNode *> poly_nodes;
3337               vector<int> quantities;
3338
3339               for (int iface = 1; iface <= nbFaces; iface++) {
3340                 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3341                 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
3342
3343                 for (int inode = 1; inode <= nbFaceNodes; inode++) {
3344                   const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
3345                   TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
3346                   if (nnIt != nodeNodeMap.end()) { // faceNode sticks
3347                     faceNode = (*nnIt).second;
3348                   }
3349                   faceNodes[inode - 1] = faceNode;
3350                 }
3351
3352                 SimplifyFace(faceNodes, poly_nodes, quantities);
3353               }
3354
3355               if (quantities.size() > 3) {
3356                 // to be done: remove coincident faces
3357               }
3358
3359               if (quantities.size() > 3)
3360                 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
3361               else
3362                 rmElemIds.push_back(elem->GetID());
3363
3364             } else {
3365               rmElemIds.push_back(elem->GetID());
3366             }
3367           }
3368         } else {
3369         }
3370
3371         continue;
3372       }
3373
3374       // Regular elements
3375       switch ( nbNodes ) {
3376       case 2: ///////////////////////////////////// EDGE
3377         isOk = false; break;
3378       case 3: ///////////////////////////////////// TRIANGLE
3379         isOk = false; break;
3380       case 4:
3381         if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
3382           isOk = false;
3383         else { //////////////////////////////////// QUADRANGLE
3384           if ( nbUniqueNodes < 3 )
3385             isOk = false;
3386           else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
3387             isOk = false; // opposite nodes stick
3388         }
3389         break;
3390       case 6: ///////////////////////////////////// PENTAHEDRON
3391         if ( nbUniqueNodes == 4 ) {
3392           // ---------------------------------> tetrahedron
3393           if (nbRepl == 3 &&
3394               iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
3395             // all top nodes stick: reverse a bottom
3396             uniqueNodes[ 0 ] = curNodes [ 1 ];
3397             uniqueNodes[ 1 ] = curNodes [ 0 ];
3398           }
3399           else if (nbRepl == 3 &&
3400                    iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
3401             // all bottom nodes stick: set a top before
3402             uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
3403             uniqueNodes[ 0 ] = curNodes [ 3 ];
3404             uniqueNodes[ 1 ] = curNodes [ 4 ];
3405             uniqueNodes[ 2 ] = curNodes [ 5 ];
3406           }
3407           else if (nbRepl == 4 &&
3408                    iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
3409             // a lateral face turns into a line: reverse a bottom
3410             uniqueNodes[ 0 ] = curNodes [ 1 ];
3411             uniqueNodes[ 1 ] = curNodes [ 0 ];
3412           }
3413           else
3414             isOk = false;
3415         }
3416         else if ( nbUniqueNodes == 5 ) {
3417           // PENTAHEDRON --------------------> 2 tetrahedrons
3418           if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
3419             // a bottom node sticks with a linked top one
3420             // 1.
3421             SMDS_MeshElement* newElem =
3422               aMesh->AddVolume(curNodes[ 3 ],
3423                                curNodes[ 4 ],
3424                                curNodes[ 5 ],
3425                                curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
3426             if ( aShapeId )
3427               aMesh->SetMeshElementOnShape( newElem, aShapeId );
3428             // 2. : reverse a bottom
3429             uniqueNodes[ 0 ] = curNodes [ 1 ];
3430             uniqueNodes[ 1 ] = curNodes [ 0 ];
3431             nbUniqueNodes = 4;
3432           }
3433           else
3434             isOk = false;
3435         }
3436         else
3437           isOk = false;
3438         break;
3439       case 8: { //////////////////////////////////// HEXAHEDRON
3440         isOk = false;
3441         SMDS_VolumeTool hexa (elem);
3442         hexa.SetExternalNormal();
3443         if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
3444           //////////////////////// ---> tetrahedron
3445           for ( int iFace = 0; iFace < 6; iFace++ ) {
3446             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3447             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3448                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3449                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3450               // one face turns into a point ...
3451               int iOppFace = hexa.GetOppFaceIndex( iFace );
3452               ind = hexa.GetFaceNodesIndices( iOppFace );
3453               int nbStick = 0;
3454               iUnique = 2; // reverse a tetrahedron bottom
3455               for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
3456                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3457                   nbStick++;
3458                 else if ( iUnique >= 0 )
3459                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3460               }
3461               if ( nbStick == 1 ) {
3462                 // ... and the opposite one - into a triangle.
3463                 // set a top node
3464                 ind = hexa.GetFaceNodesIndices( iFace );
3465                 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
3466                 isOk = true;
3467               }
3468               break;
3469             }
3470           }
3471         }
3472         else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
3473           //////////////////// HEXAHEDRON ---> 2 tetrahedrons
3474           for ( int iFace = 0; iFace < 6; iFace++ ) {
3475             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3476             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
3477                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
3478                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
3479               // one face turns into a point ...
3480               int iOppFace = hexa.GetOppFaceIndex( iFace );
3481               ind = hexa.GetFaceNodesIndices( iOppFace );
3482               int nbStick = 0;
3483               iUnique = 2;  // reverse a tetrahedron 1 bottom
3484               for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
3485                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
3486                   nbStick++;
3487                 else if ( iUnique >= 0 )
3488                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
3489               }
3490               if ( nbStick == 0 ) {
3491                 // ... and the opposite one is a quadrangle
3492                 // set a top node
3493                 const int* indTop = hexa.GetFaceNodesIndices( iFace );
3494                 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
3495                 nbUniqueNodes = 4;
3496                 // tetrahedron 2
3497                 SMDS_MeshElement* newElem =
3498                   aMesh->AddVolume(curNodes[ind[ 0 ]],
3499                                    curNodes[ind[ 3 ]],
3500                                    curNodes[ind[ 2 ]],
3501                                    curNodes[indTop[ 0 ]]);
3502                 if ( aShapeId )
3503                   aMesh->SetMeshElementOnShape( newElem, aShapeId );
3504                 isOk = true;
3505               }
3506               break;
3507             }
3508           }
3509         }
3510         else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
3511           ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
3512           // find indices of quad and tri faces
3513           int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
3514           for ( iFace = 0; iFace < 6; iFace++ ) {
3515             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
3516             nodeSet.clear();
3517             for ( iCur = 0; iCur < 4; iCur++ )
3518               nodeSet.insert( curNodes[ind[ iCur ]] );
3519             nbUniqueNodes = nodeSet.size();
3520             if ( nbUniqueNodes == 3 )
3521               iTriFace[ nbTri++ ] = iFace;
3522             else if ( nbUniqueNodes == 4 )
3523               iQuadFace[ nbQuad++ ] = iFace;
3524           }
3525           if (nbQuad == 2 && nbTri == 4 &&
3526               hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
3527             // 2 opposite quadrangles stuck with a diagonal;
3528             // sample groups of merged indices: (0-4)(2-6)
3529             // --------------------------------------------> 2 tetrahedrons
3530             const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
3531             const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
3532             int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
3533             if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
3534                 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
3535               // stuck with 0-2 diagonal
3536               i0  = ind1[ 3 ];
3537               i1d = ind1[ 0 ];
3538               i2  = ind1[ 1 ];
3539               i3d = ind1[ 2 ];
3540               i0t = ind2[ 1 ];
3541               i2t = ind2[ 3 ];
3542             }
3543             else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
3544                      curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
3545               // stuck with 1-3 diagonal
3546               i0  = ind1[ 0 ];
3547               i1d = ind1[ 1 ];
3548               i2  = ind1[ 2 ];
3549               i3d = ind1[ 3 ];
3550               i0t = ind2[ 0 ];
3551               i2t = ind2[ 1 ];
3552             }
3553             else {
3554               ASSERT(0);
3555             }
3556             // tetrahedron 1
3557             uniqueNodes[ 0 ] = curNodes [ i0 ];
3558             uniqueNodes[ 1 ] = curNodes [ i1d ];
3559             uniqueNodes[ 2 ] = curNodes [ i3d ];
3560             uniqueNodes[ 3 ] = curNodes [ i0t ];
3561             nbUniqueNodes = 4;
3562             // tetrahedron 2
3563             SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
3564                                                          curNodes[ i2 ],
3565                                                          curNodes[ i3d ],
3566                                                          curNodes[ i2t ]);
3567             if ( aShapeId )
3568               aMesh->SetMeshElementOnShape( newElem, aShapeId );
3569             isOk = true;
3570           }
3571           else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
3572                    ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
3573             // --------------------------------------------> prism
3574             // find 2 opposite triangles
3575             nbUniqueNodes = 6;
3576             for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
3577               if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
3578                 // find indices of kept and replaced nodes
3579                 // and fill unique nodes of 2 opposite triangles
3580                 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
3581                 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
3582                 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
3583                 // fill unique nodes
3584                 iUnique = 0;
3585                 isOk = true;
3586                 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
3587                   const SMDS_MeshNode* n     = curNodes[ind1[ iCur ]];
3588                   const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
3589                   if ( n == nInit ) {
3590                     // iCur of a linked node of the opposite face (make normals co-directed):
3591                     int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
3592                     // check that correspondent corners of triangles are linked
3593                     if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
3594                       isOk = false;
3595                     else {
3596                       uniqueNodes[ iUnique ] = n;
3597                       uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
3598                       iUnique++;
3599                     }
3600                   }
3601                 }
3602                 break;
3603               }
3604             }
3605           }
3606         } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
3607         break;
3608       } // HEXAHEDRON
3609
3610       default:
3611         isOk = false;
3612       } // switch ( nbNodes )
3613
3614     } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
3615
3616     if ( isOk ) {
3617       if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
3618         // Change nodes of polyedre
3619         const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
3620           static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
3621         if (aPolyedre) {
3622           int nbFaces = aPolyedre->NbFaces();
3623
3624           vector<const SMDS_MeshNode *> poly_nodes;
3625           vector<int> quantities (nbFaces);
3626
3627           for (int iface = 1; iface <= nbFaces; iface++) {
3628             int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
3629             quantities[iface - 1] = nbFaceNodes;
3630
3631             for (inode = 1; inode <= nbFaceNodes; inode++) {
3632               const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
3633
3634               TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
3635               if (nnIt != nodeNodeMap.end()) { // curNode sticks
3636                 curNode = (*nnIt).second;
3637               }
3638               poly_nodes.push_back(curNode);
3639             }
3640           }
3641           aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
3642         }
3643       } else {
3644         // Change regular element or polygon
3645         aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
3646       }
3647     } else {
3648       // Remove invalid regular element or invalid polygon
3649       rmElemIds.push_back( elem->GetID() );
3650     }
3651
3652   } // loop on elements
3653
3654   // Remove equal nodes and bad elements
3655
3656   Remove( rmNodeIds, true );
3657   Remove( rmElemIds, false );
3658
3659 }
3660
3661 //=======================================================================
3662 //function : MergeEqualElements
3663 //purpose  : Remove all but one of elements built on the same nodes.
3664 //=======================================================================
3665
3666 void SMESH_MeshEditor::MergeEqualElements()
3667 {
3668   SMESHDS_Mesh* aMesh = GetMeshDS();
3669
3670   SMDS_EdgeIteratorPtr   eIt = aMesh->edgesIterator();
3671   SMDS_FaceIteratorPtr   fIt = aMesh->facesIterator();
3672   SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
3673
3674   list< int > rmElemIds; // IDs of elems to remove
3675
3676   for ( int iDim = 1; iDim <= 3; iDim++ ) {
3677
3678     set< set <const SMDS_MeshElement*> > setOfNodeSet;
3679
3680     while ( 1 ) {
3681       // get next element
3682       const SMDS_MeshElement* elem = 0;
3683       if ( iDim == 1 ) {
3684         if ( eIt->more() ) elem = eIt->next();
3685       } else if ( iDim == 2 ) {
3686         if ( fIt->more() ) elem = fIt->next();
3687       } else {
3688         if ( vIt->more() ) elem = vIt->next();
3689       }
3690       if ( !elem ) break;
3691
3692       // get elem nodes
3693       set <const SMDS_MeshElement*> nodeSet;
3694       SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
3695       while ( nodeIt->more() )
3696         nodeSet.insert( nodeIt->next() );
3697
3698       // check uniqueness
3699       bool isUnique = setOfNodeSet.insert( nodeSet ).second;
3700       if ( !isUnique )
3701         rmElemIds.push_back( elem->GetID() );
3702     }
3703   }
3704
3705   Remove( rmElemIds, false );
3706 }
3707
3708 //=======================================================================
3709 //function : FindFaceInSet
3710 //purpose  : Return a face having linked nodes n1 and n2 and which is
3711 //           - not in avoidSet,
3712 //           - in elemSet provided that !elemSet.empty()
3713 //=======================================================================
3714
3715 const SMDS_MeshElement*
3716   SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode*                n1,
3717                                   const SMDS_MeshNode*                n2,
3718                                   const set<const SMDS_MeshElement*>& elemSet,
3719                                   const set<const SMDS_MeshElement*>& avoidSet)
3720
3721 {
3722   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator();
3723   while ( invElemIt->more() ) { // loop on inverse elements of n1
3724     const SMDS_MeshElement* elem = invElemIt->next();
3725     if (elem->GetType() != SMDSAbs_Face ||
3726         avoidSet.find( elem ) != avoidSet.end() )
3727       continue;
3728     if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
3729       continue;
3730     // get face nodes and find index of n1
3731     int i1, nbN = elem->NbNodes(), iNode = 0;
3732     const SMDS_MeshNode* faceNodes[ nbN ], *n;
3733     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3734     while ( nIt->more() ) {
3735       faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3736       if ( faceNodes[ iNode++ ] == n1 )
3737         i1 = iNode - 1;
3738     }
3739     // find a n2 linked to n1
3740     for ( iNode = 0; iNode < 2; iNode++ ) {
3741       if ( iNode ) // node before n1
3742         n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
3743       else         // node after n1
3744         n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
3745       if ( n == n2 )
3746         return elem;
3747     }
3748   }
3749   return 0;
3750 }
3751
3752 //=======================================================================
3753 //function : findAdjacentFace
3754 //purpose  :
3755 //=======================================================================
3756
3757 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
3758                                                 const SMDS_MeshNode* n2,
3759                                                 const SMDS_MeshElement* elem)
3760 {
3761   set<const SMDS_MeshElement*> elemSet, avoidSet;
3762   if ( elem )
3763     avoidSet.insert ( elem );
3764   return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3765 }
3766
3767 //=======================================================================
3768 //function : findFreeBorder
3769 //purpose  :
3770 //=======================================================================
3771
3772 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
3773
3774 static bool findFreeBorder (const SMDS_MeshNode*                theFirstNode,
3775                             const SMDS_MeshNode*                theSecondNode,
3776                             const SMDS_MeshNode*                theLastNode,
3777                             list< const SMDS_MeshNode* > &      theNodes,
3778                             list< const SMDS_MeshElement* > &   theFaces)
3779 {
3780   if ( !theFirstNode || !theSecondNode )
3781     return false;
3782   // find border face between theFirstNode and theSecondNode
3783   const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
3784   if ( !curElem )
3785     return false;
3786
3787   theFaces.push_back( curElem );
3788   theNodes.push_back( theFirstNode );
3789   theNodes.push_back( theSecondNode );
3790
3791   const SMDS_MeshNode* nodes [5], *nIgnore = theFirstNode, * nStart = theSecondNode;
3792   set < const SMDS_MeshElement* > foundElems;
3793   bool needTheLast = ( theLastNode != 0 );
3794
3795   while ( nStart != theLastNode )
3796   {
3797     if ( nStart == theFirstNode )
3798       return !needTheLast;
3799
3800     // find all free border faces sharing form nStart
3801
3802     list< const SMDS_MeshElement* > curElemList;
3803     list< const SMDS_MeshNode* > nStartList;
3804     SMDS_ElemIteratorPtr invElemIt = nStart->facesIterator();
3805     while ( invElemIt->more() ) {
3806       const SMDS_MeshElement* e = invElemIt->next();
3807       if ( e == curElem || foundElems.insert( e ).second )
3808       {
3809         // get nodes
3810         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3811         int iNode = 0, nbNodes = e->NbNodes();
3812         while ( nIt->more() )
3813           nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
3814         nodes[ iNode ] = nodes[ 0 ];
3815         // check 2 links
3816         for ( iNode = 0; iNode < nbNodes; iNode++ )
3817           if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
3818                (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
3819               ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
3820           {
3821             nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
3822             curElemList.push_back( e );
3823           }
3824       }
3825     }
3826     // analyse the found
3827
3828     int nbNewBorders = curElemList.size();
3829     if ( nbNewBorders == 0 ) {
3830       // no free border furthermore
3831       return !needTheLast;
3832     }
3833     else if ( nbNewBorders == 1 ) {
3834       // one more element found
3835       nIgnore = nStart;
3836       nStart = nStartList.front();
3837       curElem = curElemList.front();
3838       theFaces.push_back( curElem );
3839       theNodes.push_back( nStart );
3840     }
3841     else {
3842       // several continuations found
3843       list< const SMDS_MeshElement* >::iterator curElemIt;
3844       list< const SMDS_MeshNode* >::iterator nStartIt;
3845       // check if one of them reached the last node
3846       if ( needTheLast ) {
3847         for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3848              curElemIt!= curElemList.end();
3849              curElemIt++, nStartIt++ )
3850           if ( *nStartIt == theLastNode ) {
3851             theFaces.push_back( *curElemIt );
3852             theNodes.push_back( *nStartIt );
3853             return true;
3854           }
3855       }
3856       // find the best free border by the continuations
3857       list<const SMDS_MeshNode*>    contNodes[ 2 ], *cNL;
3858       list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
3859       for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
3860            curElemIt!= curElemList.end();
3861            curElemIt++, nStartIt++ )
3862       {
3863         cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
3864         cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
3865         // find one more free border
3866         if ( ! findFreeBorder( nIgnore, nStart, theLastNode, *cNL, *cFL )) {
3867           cNL->clear();
3868           cFL->clear();
3869         }
3870         else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
3871           // choice: clear a worse one
3872           int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
3873           int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
3874           contNodes[ iWorse ].clear();
3875           contFaces[ iWorse ].clear();
3876         }
3877       }
3878       if ( contNodes[0].empty() && contNodes[1].empty() )
3879         return false;
3880
3881       // append the best free border
3882       cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
3883       cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
3884       theNodes.pop_back(); // remove nIgnore
3885       theNodes.pop_back(); // remove nStart
3886       theFaces.pop_back(); // remove curElem
3887       list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
3888       list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
3889       for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
3890       for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
3891       return true;
3892
3893     } // several continuations found
3894   } // while ( nStart != theLastNode )
3895
3896   return true;
3897 }
3898
3899 //=======================================================================
3900 //function : CheckFreeBorderNodes
3901 //purpose  : Return true if the tree nodes are on a free border
3902 //=======================================================================
3903
3904 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
3905                                             const SMDS_MeshNode* theNode2,
3906                                             const SMDS_MeshNode* theNode3)
3907 {
3908   list< const SMDS_MeshNode* > nodes;
3909   list< const SMDS_MeshElement* > faces;
3910   return findFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
3911 }
3912
3913 //=======================================================================
3914 //function : SewFreeBorder
3915 //purpose  :
3916 //=======================================================================
3917
3918 SMESH_MeshEditor::Sew_Error
3919   SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
3920                                    const SMDS_MeshNode* theBordSecondNode,
3921                                    const SMDS_MeshNode* theBordLastNode,
3922                                    const SMDS_MeshNode* theSideFirstNode,
3923                                    const SMDS_MeshNode* theSideSecondNode,
3924                                    const SMDS_MeshNode* theSideThirdNode,
3925                                    const bool           theSideIsFreeBorder,
3926                                    const bool           toCreatePolygons,
3927                                    const bool           toCreatePolyedrs)
3928 {
3929   MESSAGE("::SewFreeBorder()");
3930   Sew_Error aResult = SEW_OK;
3931
3932   // ====================================
3933   //    find side nodes and elements
3934   // ====================================
3935
3936   list< const SMDS_MeshNode* > nSide[ 2 ];
3937   list< const SMDS_MeshElement* > eSide[ 2 ];
3938   list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
3939   list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
3940
3941   // Free border 1
3942   // --------------
3943   if (!findFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
3944                       nSide[0], eSide[0])) {
3945     MESSAGE(" Free Border 1 not found " );
3946     aResult = SEW_BORDER1_NOT_FOUND;
3947   }
3948   if (theSideIsFreeBorder)
3949   {
3950     // Free border 2
3951     // --------------
3952     if (!findFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
3953                         nSide[1], eSide[1])) {
3954       MESSAGE(" Free Border 2 not found " );
3955       aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
3956     }
3957   }
3958   if ( aResult != SEW_OK )
3959     return aResult;
3960
3961   if (!theSideIsFreeBorder)
3962   {
3963     // Side 2
3964     // --------------
3965
3966     // -------------------------------------------------------------------------
3967     // Algo:
3968     // 1. If nodes to merge are not coincident, move nodes of the free border
3969     //    from the coord sys defined by the direction from the first to last
3970     //    nodes of the border to the correspondent sys of the side 2
3971     // 2. On the side 2, find the links most co-directed with the correspondent
3972     //    links of the free border
3973     // -------------------------------------------------------------------------
3974
3975     // 1. Since sewing may brake if there are volumes to split on the side 2,
3976     //    we wont move nodes but just compute new coordinates for them
3977     typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
3978     TNodeXYZMap nBordXYZ;
3979     list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
3980     list< const SMDS_MeshNode* >::iterator nBordIt;
3981
3982     gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
3983     gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
3984     gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
3985     gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
3986     double tol2 = 1.e-8;
3987     gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
3988     if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 )
3989     {
3990       // Need node movement.
3991
3992       // find X and Z axes to create trsf
3993       gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
3994       gp_Vec X = Zs ^ Zb;
3995       if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
3996         // Zb || Zs
3997         X = gp_Ax2( gp::Origin(), Zb ).XDirection();
3998
3999       // coord systems
4000       gp_Ax3 toBordAx( Pb1, Zb, X );
4001       gp_Ax3 fromSideAx( Ps1, Zs, X );
4002       gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
4003       // set trsf
4004       gp_Trsf toBordSys, fromSide2Sys;
4005       toBordSys.SetTransformation( toBordAx );
4006       fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
4007       fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
4008
4009       // move
4010       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
4011         const SMDS_MeshNode* n = *nBordIt;
4012         gp_XYZ xyz( n->X(),n->Y(),n->Z() );
4013         toBordSys.Transforms( xyz );
4014         fromSide2Sys.Transforms( xyz );
4015         nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
4016       }
4017     }
4018     else
4019     {
4020       // just insert nodes XYZ in the nBordXYZ map
4021       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
4022         const SMDS_MeshNode* n = *nBordIt;
4023         nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
4024       }
4025     }
4026
4027     // 2. On the side 2, find the links most co-directed with the correspondent
4028     //    links of the free border
4029
4030     list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
4031     list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
4032     sideNodes.push_back( theSideFirstNode );
4033
4034     bool hasVolumes = false;
4035     LinkID_Gen aLinkID_Gen( GetMeshDS() );
4036     set<long> foundSideLinkIDs, checkedLinkIDs;
4037     SMDS_VolumeTool volume;
4038     //const SMDS_MeshNode* faceNodes[ 4 ];
4039
4040     const SMDS_MeshNode*    sideNode;
4041     const SMDS_MeshElement* sideElem;
4042     const SMDS_MeshNode* prevSideNode = theSideFirstNode;
4043     const SMDS_MeshNode* prevBordNode = theBordFirstNode;
4044     nBordIt = bordNodes.begin();
4045     nBordIt++;
4046     // border node position and border link direction to compare with
4047     gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
4048     gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
4049     // choose next side node by link direction or by closeness to
4050     // the current border node:
4051     bool searchByDir = ( *nBordIt != theBordLastNode );
4052     do {
4053       // find the next node on the Side 2
4054       sideNode = 0;
4055       double maxDot = -DBL_MAX, minDist = DBL_MAX;
4056       long linkID;
4057       checkedLinkIDs.clear();
4058       gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
4059
4060       SMDS_ElemIteratorPtr invElemIt
4061         = prevSideNode->GetInverseElementIterator();
4062       while ( invElemIt->more() ) { // loop on inverse elements on the Side 2
4063         const SMDS_MeshElement* elem = invElemIt->next();
4064         // prepare data for a loop on links, of a face or a volume
4065         int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
4066         const SMDS_MeshNode* faceNodes[ nbNodes ];
4067         bool isVolume = volume.Set( elem );
4068         const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
4069         if ( isVolume ) // --volume
4070           hasVolumes = true;
4071         else if ( nbNodes > 2 ) { // --face
4072           // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
4073           SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
4074           while ( nIt->more() ) {
4075             nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
4076             if ( nodes[ iNode++ ] == prevSideNode )
4077               iPrevNode = iNode - 1;
4078           }
4079           // there are 2 links to check
4080           nbNodes = 2;
4081         }
4082         else // --edge
4083           continue;
4084         // loop on links, to be precise, on the second node of links
4085         for ( iNode = 0; iNode < nbNodes; iNode++ ) {
4086           const SMDS_MeshNode* n = nodes[ iNode ];
4087           if ( isVolume ) {
4088             if ( !volume.IsLinked( n, prevSideNode ))
4089               continue;
4090           } else {
4091             if ( iNode ) // a node before prevSideNode
4092               n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
4093             else         // a node after prevSideNode
4094               n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
4095           }
4096           // check if this link was already used
4097           long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
4098           bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
4099           if (!isJustChecked &&
4100               foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() ) {
4101             // test a link geometrically
4102             gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
4103             bool linkIsBetter = false;
4104             double dot, dist;
4105             if ( searchByDir ) { // choose most co-directed link
4106               dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
4107               linkIsBetter = ( dot > maxDot );
4108             }
4109             else { // choose link with the node closest to bordPos
4110               dist = ( nextXYZ - bordPos ).SquareModulus();
4111               linkIsBetter = ( dist < minDist );
4112             }
4113             if ( linkIsBetter ) {
4114               maxDot = dot;
4115               minDist = dist;
4116               linkID = iLink;
4117               sideNode = n;
4118               sideElem = elem;
4119             }
4120           }
4121         }
4122       } // loop on inverse elements of prevSideNode
4123
4124       if ( !sideNode ) {
4125         MESSAGE(" Cant find path by links of the Side 2 ");
4126         return SEW_BAD_SIDE_NODES;
4127       }
4128       sideNodes.push_back( sideNode );
4129       sideElems.push_back( sideElem );
4130       foundSideLinkIDs.insert ( linkID );
4131       prevSideNode = sideNode;
4132
4133       if ( *nBordIt == theBordLastNode )
4134         searchByDir = false;
4135       else {
4136         // find the next border link to compare with
4137         gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
4138         searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4139         while ( *nBordIt != theBordLastNode && !searchByDir ) {
4140           prevBordNode = *nBordIt;
4141           nBordIt++;
4142           bordPos = nBordXYZ[ *nBordIt ];
4143           bordDir = bordPos - nBordXYZ[ prevBordNode ];
4144           searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
4145         }
4146       }
4147     }
4148     while ( sideNode != theSideSecondNode );
4149
4150     if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
4151       MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
4152       return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
4153     }
4154   } // end nodes search on the side 2
4155
4156   // ============================
4157   // sew the border to the side 2
4158   // ============================
4159
4160   int nbNodes[]  = { nSide[0].size(), nSide[1].size() };
4161   int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
4162
4163   TListOfListOfNodes nodeGroupsToMerge;
4164   if ( nbNodes[0] == nbNodes[1] ||
4165       ( theSideIsFreeBorder && !theSideThirdNode)) {
4166
4167     // all nodes are to be merged
4168
4169     for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
4170          nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
4171          nIt[0]++, nIt[1]++ )
4172     {
4173       nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4174       nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
4175       nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
4176     }
4177   }
4178   else {
4179
4180     // insert new nodes into the border and the side to get equal nb of segments
4181
4182     // get normalized parameters of nodes on the borders
4183     double param[ 2 ][ maxNbNodes ];
4184     int iNode, iBord;
4185     for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4186       list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
4187       list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
4188       const SMDS_MeshNode* nPrev = *nIt;
4189       double bordLength = 0;
4190       for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
4191         const SMDS_MeshNode* nCur = *nIt;
4192         gp_XYZ segment (nCur->X() - nPrev->X(),
4193                         nCur->Y() - nPrev->Y(),
4194                         nCur->Z() - nPrev->Z());
4195         double segmentLen = segment.Modulus();
4196         bordLength += segmentLen;
4197         param[ iBord ][ iNode ] = bordLength;
4198         nPrev = nCur;
4199       }
4200       // normalize within [0,1]
4201       for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
4202         param[ iBord ][ iNode ] /= bordLength;
4203       }
4204     }
4205
4206     // loop on border segments
4207     const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
4208     int i[ 2 ] = { 0, 0 };
4209     nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
4210     nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
4211
4212     TElemOfNodeListMap insertMap;
4213     TElemOfNodeListMap::iterator insertMapIt;
4214     // insertMap is
4215     // key:   elem to insert nodes into
4216     // value: 2 nodes to insert between + nodes to be inserted
4217     do {
4218       bool next[ 2 ] = { false, false };
4219
4220       // find min adjacent segment length after sewing
4221       double nextParam = 10., prevParam = 0;
4222       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4223         if ( i[ iBord ] + 1 < nbNodes[ iBord ])
4224           nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
4225         if ( i[ iBord ] > 0 )
4226           prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
4227       }
4228       double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4229       double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
4230       double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
4231
4232       // choose to insert or to merge nodes
4233       double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
4234       if ( Abs( du ) <= minSegLen * 0.2 ) {
4235         // merge
4236         // ------
4237         nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
4238         const SMDS_MeshNode* n0 = *nIt[0];
4239         const SMDS_MeshNode* n1 = *nIt[1];
4240         nodeGroupsToMerge.back().push_back( n1 );
4241         nodeGroupsToMerge.back().push_back( n0 );
4242         // position of node of the border changes due to merge
4243         param[ 0 ][ i[0] ] += du;
4244         // move n1 for the sake of elem shape evaluation during insertion.
4245         // n1 will be removed by MergeNodes() anyway
4246         const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
4247         next[0] = next[1] = true;
4248       }
4249       else {
4250         // insert
4251         // ------
4252         int intoBord = ( du < 0 ) ? 0 : 1;
4253         const SMDS_MeshElement* elem = *eIt[ intoBord ];
4254         const SMDS_MeshNode*    n1   = nPrev[ intoBord ];
4255         const SMDS_MeshNode*    n2   = *nIt[ intoBord ];
4256         const SMDS_MeshNode*    nIns = *nIt[ 1 - intoBord ];
4257         if ( intoBord == 1 ) {
4258           // move node of the border to be on a link of elem of the side
4259           gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
4260           gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
4261           double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
4262           gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
4263           GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
4264         }
4265         insertMapIt = insertMap.find( elem );
4266         bool notFound = ( insertMapIt == insertMap.end() );
4267         bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
4268         if ( otherLink ) {
4269           // insert into another link of the same element:
4270           // 1. perform insertion into the other link of the elem
4271           list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4272           const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
4273           const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
4274           InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
4275           // 2. perform insertion into the link of adjacent faces
4276           while (true) {
4277             const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
4278             if ( adjElem )
4279               InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
4280             else
4281               break;
4282           }
4283           if (toCreatePolyedrs) {
4284             // perform insertion into the links of adjacent volumes
4285             UpdateVolumes(n12, n22, nodeList);
4286           }
4287           // 3. find an element appeared on n1 and n2 after the insertion
4288           insertMap.erase( elem );
4289           elem = findAdjacentFace( n1, n2, 0 );
4290         }
4291         if ( notFound || otherLink ) {
4292           // add element and nodes of the side into the insertMap
4293           insertMapIt = insertMap.insert
4294             ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
4295           (*insertMapIt).second.push_back( n1 );
4296           (*insertMapIt).second.push_back( n2 );
4297         }
4298         // add node to be inserted into elem
4299         (*insertMapIt).second.push_back( nIns );
4300         next[ 1 - intoBord ] = true;
4301       }
4302
4303       // go to the next segment
4304       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
4305         if ( next[ iBord ] ) {
4306           if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
4307             eIt[ iBord ]++;
4308           nPrev[ iBord ] = *nIt[ iBord ];
4309           nIt[ iBord ]++; i[ iBord ]++;
4310         }
4311       }
4312     }
4313     while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
4314
4315     // perform insertion of nodes into elements
4316
4317     for (insertMapIt = insertMap.begin();
4318          insertMapIt != insertMap.end();
4319          insertMapIt++ )
4320     {
4321       const SMDS_MeshElement* elem = (*insertMapIt).first;
4322       list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
4323       const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
4324       const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
4325
4326       InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
4327
4328       if ( !theSideIsFreeBorder ) {
4329         // look for and insert nodes into the faces adjacent to elem
4330         while (true) {
4331           const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
4332           if ( adjElem )
4333             InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
4334           else
4335             break;
4336         }
4337       }
4338       if (toCreatePolyedrs) {
4339         // perform insertion into the links of adjacent volumes
4340         UpdateVolumes(n1, n2, nodeList);
4341       }
4342     }
4343
4344   } // end: insert new nodes
4345
4346   MergeNodes ( nodeGroupsToMerge );
4347
4348   return aResult;
4349 }
4350
4351 //=======================================================================
4352 //function : InsertNodesIntoLink
4353 //purpose  : insert theNodesToInsert into theFace between theBetweenNode1
4354 //           and theBetweenNode2 and split theElement
4355 //=======================================================================
4356
4357 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement*     theFace,
4358                                            const SMDS_MeshNode*        theBetweenNode1,
4359                                            const SMDS_MeshNode*        theBetweenNode2,
4360                                            list<const SMDS_MeshNode*>& theNodesToInsert,
4361                                            const bool                  toCreatePoly)
4362 {
4363   if ( theFace->GetType() != SMDSAbs_Face ) return;
4364
4365   // find indices of 2 link nodes and of the rest nodes
4366   int iNode = 0, il1, il2, i3, i4;
4367   il1 = il2 = i3 = i4 = -1;
4368   const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
4369   SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
4370   while ( nodeIt->more() ) {
4371     const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4372     if ( n == theBetweenNode1 )
4373       il1 = iNode;
4374     else if ( n == theBetweenNode2 )
4375       il2 = iNode;
4376     else if ( i3 < 0 )
4377       i3 = iNode;
4378     else
4379       i4 = iNode;
4380     nodes[ iNode++ ] = n;
4381   }
4382   if ( il1 < 0 || il2 < 0 || i3 < 0 )
4383     return ;
4384
4385   // arrange link nodes to go one after another regarding the face orientation
4386   bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
4387   list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
4388   if ( reverse ) {
4389     iNode = il1;
4390     il1 = il2;
4391     il2 = iNode;
4392     aNodesToInsert.reverse();
4393   }
4394   // check that not link nodes of a quadrangles are in good order
4395   int nbFaceNodes = theFace->NbNodes();
4396   if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
4397     iNode = i3;
4398     i3 = i4;
4399     i4 = iNode;
4400   }
4401
4402   if (toCreatePoly || theFace->IsPoly()) {
4403
4404     iNode = 0;
4405     vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
4406
4407     // add nodes of face up to first node of link
4408     bool isFLN = false;
4409     nodeIt = theFace->nodesIterator();
4410     while ( nodeIt->more() && !isFLN ) {
4411       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4412       poly_nodes[iNode++] = n;
4413       if (n == nodes[il1]) {
4414         isFLN = true;
4415       }
4416     }
4417
4418     // add nodes to insert
4419     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4420     for (; nIt != aNodesToInsert.end(); nIt++) {
4421       poly_nodes[iNode++] = *nIt;
4422     }
4423
4424     // add nodes of face starting from last node of link
4425     while ( nodeIt->more() ) {
4426       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4427       poly_nodes[iNode++] = n;
4428     }
4429
4430     // edit or replace the face
4431     SMESHDS_Mesh *aMesh = GetMeshDS();
4432
4433     if (theFace->IsPoly()) {
4434       aMesh->ChangePolygonNodes(theFace, poly_nodes);
4435
4436     } else {
4437       int aShapeId = FindShape( theFace );
4438
4439       SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4440       if ( aShapeId && newElem )
4441         aMesh->SetMeshElementOnShape( newElem, aShapeId );
4442
4443       aMesh->RemoveElement(theFace);
4444     }
4445     return;
4446   }
4447
4448   // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
4449   int nbLinkNodes = 2 + aNodesToInsert.size();
4450   const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
4451   linkNodes[ 0 ] = nodes[ il1 ];
4452   linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
4453   list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
4454   for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
4455     linkNodes[ iNode++ ] = *nIt;
4456   }
4457   // decide how to split a quadrangle: compare possible variants
4458   // and choose which of splits to be a quadrangle
4459   int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
4460   if ( nbFaceNodes == 3 )
4461   {
4462     iBestQuad = nbSplits;
4463     i4 = i3;
4464   }
4465   else if ( nbFaceNodes == 4 )
4466   {
4467     SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
4468     double aBestRate = DBL_MAX;
4469     for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
4470       i1 = 0; i2 = 1;
4471       double aBadRate = 0;
4472       // evaluate elements quality
4473       for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
4474         if ( iSplit == iQuad ) {
4475           SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
4476                                  linkNodes[ i2++ ],
4477                                  nodes[ i3 ],
4478                                  nodes[ i4 ]);
4479           aBadRate += getBadRate( &quad, aCrit );
4480         }
4481         else {
4482           SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
4483                                  linkNodes[ i2++ ],
4484                                  nodes[ iSplit < iQuad ? i4 : i3 ]);
4485           aBadRate += getBadRate( &tria, aCrit );
4486         }
4487       }
4488       // choice
4489       if ( aBadRate < aBestRate ) {
4490         iBestQuad = iQuad;
4491         aBestRate = aBadRate;
4492       }
4493     }
4494   }
4495
4496   // create new elements
4497   SMESHDS_Mesh *aMesh = GetMeshDS();
4498   int aShapeId = FindShape( theFace );
4499
4500   i1 = 0; i2 = 1;
4501   for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
4502     SMDS_MeshElement* newElem = 0;
4503     if ( iSplit == iBestQuad )
4504       newElem = aMesh->AddFace (linkNodes[ i1++ ],
4505                                 linkNodes[ i2++ ],
4506                                 nodes[ i3 ],
4507                                 nodes[ i4 ]);
4508     else
4509       newElem = aMesh->AddFace (linkNodes[ i1++ ],
4510                                 linkNodes[ i2++ ],
4511                                 nodes[ iSplit < iBestQuad ? i4 : i3 ]);
4512     if ( aShapeId && newElem )
4513       aMesh->SetMeshElementOnShape( newElem, aShapeId );
4514   }
4515
4516   // change nodes of theFace
4517   const SMDS_MeshNode* newNodes[ 4 ];
4518   newNodes[ 0 ] = linkNodes[ i1 ];
4519   newNodes[ 1 ] = linkNodes[ i2 ];
4520   newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
4521   newNodes[ 3 ] = nodes[ i4 ];
4522   aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
4523 }
4524
4525 //=======================================================================
4526 //function : UpdateVolumes
4527 //purpose  :
4528 //=======================================================================
4529 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode*        theBetweenNode1,
4530                                       const SMDS_MeshNode*        theBetweenNode2,
4531                                       list<const SMDS_MeshNode*>& theNodesToInsert)
4532 {
4533   SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator();
4534   while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
4535     const SMDS_MeshElement* elem = invElemIt->next();
4536     if (elem->GetType() != SMDSAbs_Volume)
4537       continue;
4538
4539     // check, if current volume has link theBetweenNode1 - theBetweenNode2
4540     SMDS_VolumeTool aVolume (elem);
4541     if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
4542       continue;
4543
4544     // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
4545     int iface, nbFaces = aVolume.NbFaces();
4546     vector<const SMDS_MeshNode *> poly_nodes;
4547     vector<int> quantities (nbFaces);
4548
4549     for (iface = 0; iface < nbFaces; iface++) {
4550       int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
4551       // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
4552       const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
4553
4554       for (int inode = 0; inode < nbFaceNodes; inode++) {
4555         poly_nodes.push_back(faceNodes[inode]);
4556
4557         if (nbInserted == 0) {
4558           if (faceNodes[inode] == theBetweenNode1) {
4559             if (faceNodes[inode + 1] == theBetweenNode2) {
4560               nbInserted = theNodesToInsert.size();
4561
4562               // add nodes to insert
4563               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
4564               for (; nIt != theNodesToInsert.end(); nIt++) {
4565                 poly_nodes.push_back(*nIt);
4566               }
4567             }
4568           } else if (faceNodes[inode] == theBetweenNode2) {
4569             if (faceNodes[inode + 1] == theBetweenNode1) {
4570               nbInserted = theNodesToInsert.size();
4571
4572               // add nodes to insert in reversed order
4573               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
4574               nIt--;
4575               for (; nIt != theNodesToInsert.begin(); nIt--) {
4576                 poly_nodes.push_back(*nIt);
4577               }
4578               poly_nodes.push_back(*nIt);
4579             }
4580           } else {
4581           }
4582         }
4583       }
4584       quantities[iface] = nbFaceNodes + nbInserted;
4585     }
4586
4587     // Replace or update the volume
4588     SMESHDS_Mesh *aMesh = GetMeshDS();
4589
4590     if (elem->IsPoly()) {
4591       aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4592
4593     } else {
4594       int aShapeId = FindShape( elem );
4595
4596       SMDS_MeshElement* newElem =
4597         aMesh->AddPolyhedralVolume(poly_nodes, quantities);
4598       if (aShapeId && newElem)
4599         aMesh->SetMeshElementOnShape(newElem, aShapeId);
4600
4601       aMesh->RemoveElement(elem);
4602     }
4603   }
4604 }
4605
4606 //=======================================================================
4607 //function : SewSideElements
4608 //purpose  :
4609 //=======================================================================
4610
4611 SMESH_MeshEditor::Sew_Error
4612   SMESH_MeshEditor::SewSideElements (set<const SMDS_MeshElement*>& theSide1,
4613                                      set<const SMDS_MeshElement*>& theSide2,
4614                                      const SMDS_MeshNode*          theFirstNode1,
4615                                      const SMDS_MeshNode*          theFirstNode2,
4616                                      const SMDS_MeshNode*          theSecondNode1,
4617                                      const SMDS_MeshNode*          theSecondNode2)
4618 {
4619   MESSAGE ("::::SewSideElements()");
4620   if ( theSide1.size() != theSide2.size() )
4621     return SEW_DIFF_NB_OF_ELEMENTS;
4622
4623   Sew_Error aResult = SEW_OK;
4624   // Algo:
4625   // 1. Build set of faces representing each side
4626   // 2. Find which nodes of the side 1 to merge with ones on the side 2
4627   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
4628
4629   // =======================================================================
4630   // 1. Build set of faces representing each side:
4631   // =======================================================================
4632   // a. build set of nodes belonging to faces
4633   // b. complete set of faces: find missing fices whose nodes are in set of nodes
4634   // c. create temporary faces representing side of volumes if correspondent
4635   //    face does not exist
4636
4637   SMESHDS_Mesh* aMesh = GetMeshDS();
4638   SMDS_Mesh aTmpFacesMesh;
4639   set<const SMDS_MeshElement*> faceSet1, faceSet2;
4640   set<const SMDS_MeshElement*> volSet1,  volSet2;
4641   set<const SMDS_MeshNode*>    nodeSet1, nodeSet2;
4642   set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
4643   set<const SMDS_MeshElement*>  * volSetPtr[] = { &volSet1,  &volSet2  };
4644   set<const SMDS_MeshNode*>    * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
4645   set<const SMDS_MeshElement*> * elemSetPtr[] = { &theSide1, &theSide2 };
4646   int iSide, iFace, iNode;
4647
4648   for ( iSide = 0; iSide < 2; iSide++ ) {
4649     set<const SMDS_MeshNode*>    * nodeSet = nodeSetPtr[ iSide ];
4650     set<const SMDS_MeshElement*> * elemSet = elemSetPtr[ iSide ];
4651     set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4652     set<const SMDS_MeshElement*> * volSet  = volSetPtr [ iSide ];
4653     set<const SMDS_MeshElement*>::iterator vIt, eIt;
4654     set<const SMDS_MeshNode*>::iterator    nIt;
4655
4656   // -----------------------------------------------------------
4657   // 1a. Collect nodes of existing faces
4658   //     and build set of face nodes in order to detect missing
4659   //     faces corresponing to sides of volumes
4660   // -----------------------------------------------------------
4661
4662     set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
4663
4664     // loop on the given element of a side
4665     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
4666       const SMDS_MeshElement* elem = *eIt;
4667       if ( elem->GetType() == SMDSAbs_Face ) {
4668         faceSet->insert( elem );
4669         set <const SMDS_MeshNode*> faceNodeSet;
4670         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
4671         while ( nodeIt->more() ) {
4672           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4673           nodeSet->insert( n );
4674           faceNodeSet.insert( n );
4675         }
4676         setOfFaceNodeSet.insert( faceNodeSet );
4677       }
4678       else if ( elem->GetType() == SMDSAbs_Volume )
4679         volSet->insert( elem );
4680     }
4681     // ------------------------------------------------------------------------------
4682     // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
4683     // ------------------------------------------------------------------------------
4684
4685     for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4686       SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4687       while ( fIt->more() ) { // loop on faces sharing a node
4688         const SMDS_MeshElement* f = fIt->next();
4689         if ( faceSet->find( f ) == faceSet->end() ) {
4690           // check if all nodes are in nodeSet and
4691           // complete setOfFaceNodeSet if they are
4692           set <const SMDS_MeshNode*> faceNodeSet;
4693           SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4694           bool allInSet = true;
4695           while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4696             const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4697             if ( nodeSet->find( n ) == nodeSet->end() )
4698               allInSet = false;
4699             else
4700               faceNodeSet.insert( n );
4701           }
4702           if ( allInSet ) {
4703             faceSet->insert( f );
4704             setOfFaceNodeSet.insert( faceNodeSet );
4705           }
4706         }
4707       }
4708     }
4709
4710     // -------------------------------------------------------------------------
4711     // 1c. Create temporary faces representing sides of volumes if correspondent
4712     //     face does not exist
4713     // -------------------------------------------------------------------------
4714
4715     if ( !volSet->empty() )
4716     {
4717       //int nodeSetSize = nodeSet->size();
4718
4719       // loop on given volumes
4720       for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
4721         SMDS_VolumeTool vol (*vIt);
4722         // loop on volume faces: find free faces
4723         // --------------------------------------
4724         list<const SMDS_MeshElement* > freeFaceList;
4725         for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
4726           if ( !vol.IsFreeFace( iFace ))
4727             continue;
4728           // check if there is already a face with same nodes in a face set
4729           const SMDS_MeshElement* aFreeFace = 0;
4730           const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
4731           int nbNodes = vol.NbFaceNodes( iFace );
4732           set <const SMDS_MeshNode*> faceNodeSet;
4733           vol.GetFaceNodes( iFace, faceNodeSet );
4734           bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
4735           if ( isNewFace ) {
4736             // no such a face is given but it still can exist, check it
4737             if ( nbNodes == 3 ) {
4738               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
4739             } else if ( nbNodes == 4 ) {
4740               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4741             } else {
4742               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4743               for (int inode = 0; inode < nbNodes; inode++) {
4744                 poly_nodes[inode] = fNodes[inode];
4745               }
4746               aFreeFace = aMesh->FindFace(poly_nodes);
4747             }
4748           }
4749           if ( !aFreeFace ) {
4750             // create a temporary face
4751             if ( nbNodes == 3 ) {
4752               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
4753             } else if ( nbNodes == 4 ) {
4754               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
4755             } else {
4756               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4757               for (int inode = 0; inode < nbNodes; inode++) {
4758                 poly_nodes[inode] = fNodes[inode];
4759               }
4760               aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
4761             }
4762           }
4763           if ( aFreeFace )
4764             freeFaceList.push_back( aFreeFace );
4765
4766         } // loop on faces of a volume
4767
4768         // choose one of several free faces
4769         // --------------------------------------
4770         if ( freeFaceList.size() > 1 ) {
4771           // choose a face having max nb of nodes shared by other elems of a side
4772           int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
4773           list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
4774           while ( fIt != freeFaceList.end() ) { // loop on free faces
4775             int nbSharedNodes = 0;
4776             SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4777             while ( nodeIt->more() ) { // loop on free face nodes
4778               const SMDS_MeshNode* n =
4779                 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4780               SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
4781               while ( invElemIt->more() ) {
4782                 const SMDS_MeshElement* e = invElemIt->next();
4783                 if ( faceSet->find( e ) != faceSet->end() )
4784                   nbSharedNodes++;
4785                 if ( elemSet->find( e ) != elemSet->end() )
4786                   nbSharedNodes++;
4787               }
4788             }
4789             if ( nbSharedNodes >= maxNbNodes ) {
4790               maxNbNodes = nbSharedNodes;
4791               fIt++;
4792             }
4793             else
4794               freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
4795           }
4796           if ( freeFaceList.size() > 1 )
4797           {
4798             // could not choose one face, use another way
4799             // choose a face most close to the bary center of the opposite side
4800             gp_XYZ aBC( 0., 0., 0. );
4801             set <const SMDS_MeshNode*> addedNodes;
4802             set<const SMDS_MeshElement*> * elemSet2 = elemSetPtr[ 1 - iSide ];
4803             eIt = elemSet2->begin();
4804             for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
4805               SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
4806               while ( nodeIt->more() ) { // loop on free face nodes
4807                 const SMDS_MeshNode* n =
4808                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4809                 if ( addedNodes.insert( n ).second )
4810                   aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
4811               }
4812             }
4813             aBC /= addedNodes.size();
4814             double minDist = DBL_MAX;
4815             fIt = freeFaceList.begin();
4816             while ( fIt != freeFaceList.end() ) { // loop on free faces
4817               double dist = 0;
4818               SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
4819               while ( nodeIt->more() ) { // loop on free face nodes
4820                 const SMDS_MeshNode* n =
4821                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4822                 gp_XYZ p( n->X(),n->Y(),n->Z() );
4823                 dist += ( aBC - p ).SquareModulus();
4824               }
4825               if ( dist < minDist ) {
4826                 minDist = dist;
4827                 freeFaceList.erase( freeFaceList.begin(), fIt++ );
4828               }
4829               else
4830                 fIt = freeFaceList.erase( fIt++ );
4831             }
4832           }
4833         } // choose one of several free faces of a volume
4834
4835         if ( freeFaceList.size() == 1 ) {
4836           const SMDS_MeshElement* aFreeFace = freeFaceList.front();
4837           faceSet->insert( aFreeFace );
4838           // complete a node set with nodes of a found free face
4839 //           for ( iNode = 0; iNode < ; iNode++ )
4840 //             nodeSet->insert( fNodes[ iNode ] );
4841         }
4842
4843       } // loop on volumes of a side
4844
4845 //       // complete a set of faces if new nodes in a nodeSet appeared
4846 //       // ----------------------------------------------------------
4847 //       if ( nodeSetSize != nodeSet->size() ) {
4848 //         for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
4849 //           SMDS_ElemIteratorPtr fIt = (*nIt)->facesIterator();
4850 //           while ( fIt->more() ) { // loop on faces sharing a node
4851 //             const SMDS_MeshElement* f = fIt->next();
4852 //             if ( faceSet->find( f ) == faceSet->end() ) {
4853 //               // check if all nodes are in nodeSet and
4854 //               // complete setOfFaceNodeSet if they are
4855 //               set <const SMDS_MeshNode*> faceNodeSet;
4856 //               SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
4857 //               bool allInSet = true;
4858 //               while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
4859 //                 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
4860 //                 if ( nodeSet->find( n ) == nodeSet->end() )
4861 //                   allInSet = false;
4862 //                 else
4863 //                   faceNodeSet.insert( n );
4864 //               }
4865 //               if ( allInSet ) {
4866 //                 faceSet->insert( f );
4867 //                 setOfFaceNodeSet.insert( faceNodeSet );
4868 //               }
4869 //             }
4870 //           }
4871 //         }
4872 //       }
4873     } // Create temporary faces, if there are volumes given
4874   } // loop on sides
4875
4876   if ( faceSet1.size() != faceSet2.size() ) {
4877     // delete temporary faces: they are in reverseElements of actual nodes
4878     SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
4879     while ( tmpFaceIt->more() )
4880       aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
4881     MESSAGE("Diff nb of faces");
4882     return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4883   }
4884
4885   // ============================================================
4886   // 2. Find nodes to merge:
4887   //              bind a node to remove to a node to put instead
4888   // ============================================================
4889
4890   TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
4891   if ( theFirstNode1 != theFirstNode2 )
4892     nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
4893   if ( theSecondNode1 != theSecondNode2 )
4894     nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
4895
4896   LinkID_Gen aLinkID_Gen( GetMeshDS() );
4897   set< long > linkIdSet; // links to process
4898   linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
4899
4900   typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > TPairOfNodes;
4901   list< TPairOfNodes > linkList[2];
4902   linkList[0].push_back( TPairOfNodes( theFirstNode1, theSecondNode1 ));
4903   linkList[1].push_back( TPairOfNodes( theFirstNode2, theSecondNode2 ));
4904   // loop on links in linkList; find faces by links and append links
4905   // of the found faces to linkList
4906   list< TPairOfNodes >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
4907   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ )
4908   {
4909     TPairOfNodes link[] = { *linkIt[0], *linkIt[1] };
4910     long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
4911     if ( linkIdSet.find( linkID ) == linkIdSet.end() )
4912       continue;
4913
4914     // by links, find faces in the face sets,
4915     // and find indices of link nodes in the found faces;
4916     // in a face set, there is only one or no face sharing a link
4917     // ---------------------------------------------------------------
4918
4919     const SMDS_MeshElement* face[] = { 0, 0 };
4920     const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
4921     const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
4922     int iLinkNode[2][2];
4923     for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4924       const SMDS_MeshNode* n1 = link[iSide].first;
4925       const SMDS_MeshNode* n2 = link[iSide].second;
4926       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
4927       set< const SMDS_MeshElement* > fMap;
4928       for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
4929         const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
4930         SMDS_ElemIteratorPtr fIt = n->facesIterator();
4931         while ( fIt->more() ) { // loop on faces sharing a node
4932           const SMDS_MeshElement* f = fIt->next();
4933           if (faceSet->find( f ) != faceSet->end() && // f is in face set
4934               ! fMap.insert( f ).second ) // f encounters twice
4935           {
4936             if ( face[ iSide ] ) {
4937               MESSAGE( "2 faces per link " );
4938               aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
4939               break;
4940             }
4941             face[ iSide ] = f;
4942             faceSet->erase( f );
4943             // get face nodes and find ones of a link
4944             iNode = 0;
4945             SMDS_ElemIteratorPtr nIt = f->nodesIterator();
4946             while ( nIt->more() ) {
4947               const SMDS_MeshNode* n =
4948                 static_cast<const SMDS_MeshNode*>( nIt->next() );
4949               if ( n == n1 )
4950                 iLinkNode[ iSide ][ 0 ] = iNode;
4951               else if ( n == n2 )
4952                 iLinkNode[ iSide ][ 1 ] = iNode;
4953               else if ( notLinkNodes[ iSide ][ 0 ] )
4954                 notLinkNodes[ iSide ][ 1 ] = n;
4955               else
4956                 notLinkNodes[ iSide ][ 0 ] = n;
4957               faceNodes[ iSide ][ iNode++ ] = n;
4958             }
4959             faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
4960           }
4961         }
4962       }
4963     }
4964     // check similarity of elements of the sides
4965     if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
4966       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
4967       if ( nReplaceMap.size() == 2 ) // faces on input nodes not found
4968         aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
4969       else
4970         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4971       break; // do not return because it s necessary to remove tmp faces
4972     }
4973
4974     // set nodes to merge
4975     // -------------------
4976
4977     if ( face[0] && face[1] )
4978     {
4979       int nbNodes = face[0]->NbNodes();
4980       if ( nbNodes != face[1]->NbNodes() ) {
4981         MESSAGE("Diff nb of face nodes");
4982         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
4983         break; // do not return because it s necessary to remove tmp faces
4984       }
4985       bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
4986       if ( nbNodes == 3 )
4987         nReplaceMap.insert( TNodeNodeMap::value_type
4988                            ( notLinkNodes[0][0], notLinkNodes[1][0] ));
4989       else {
4990         for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
4991           // analyse link orientation in faces
4992           int i1 = iLinkNode[ iSide ][ 0 ];
4993           int i2 = iLinkNode[ iSide ][ 1 ];
4994           reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
4995           // if notLinkNodes are the first and the last ones, then
4996           // their order does not correspond to the link orientation
4997           if (( i1 == 1 && i2 == 2 ) ||
4998               ( i1 == 2 && i2 == 1 ))
4999             reverse[ iSide ] = !reverse[ iSide ];
5000         }
5001         if ( reverse[0] == reverse[1] ) {
5002           nReplaceMap.insert( TNodeNodeMap::value_type
5003                              ( notLinkNodes[0][0], notLinkNodes[1][0] ));
5004           nReplaceMap.insert( TNodeNodeMap::value_type
5005                              ( notLinkNodes[0][1], notLinkNodes[1][1] ));
5006         }
5007         else {
5008           nReplaceMap.insert( TNodeNodeMap::value_type
5009                              ( notLinkNodes[0][0], notLinkNodes[1][1] ));
5010           nReplaceMap.insert( TNodeNodeMap::value_type
5011                              ( notLinkNodes[0][1], notLinkNodes[1][0] ));
5012         }
5013       }
5014
5015       // add other links of the faces to linkList
5016       // -----------------------------------------
5017
5018       const SMDS_MeshNode** nodes = faceNodes[ 0 ];
5019       for ( iNode = 0; iNode < nbNodes; iNode++ )
5020       {
5021         linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
5022         pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
5023         if ( !iter_isnew.second ) { // already in a set: no need to process
5024           linkIdSet.erase( iter_isnew.first );
5025         }
5026         else // new in set == encountered for the first time: add
5027         {
5028           const SMDS_MeshNode* n1 = nodes[ iNode ];
5029           const SMDS_MeshNode* n2 = nodes[ iNode + 1];
5030           linkList[0].push_back ( TPairOfNodes( n1, n2 ));
5031           linkList[1].push_back ( TPairOfNodes( nReplaceMap[n1], nReplaceMap[n2] ));
5032         }
5033       }
5034     } // 2 faces found
5035   } // loop on link lists
5036
5037   if ( aResult == SEW_OK &&
5038       ( linkIt[0] != linkList[0].end() ||
5039        !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
5040     MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
5041             " " << (faceSetPtr[1]->empty()));
5042     aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
5043   }
5044
5045   // ====================================================================
5046   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
5047   // ====================================================================
5048
5049   // delete temporary faces: they are in reverseElements of actual nodes
5050   SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
5051   while ( tmpFaceIt->more() )
5052     aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
5053
5054   if ( aResult != SEW_OK)
5055     return aResult;
5056
5057   list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
5058   // loop on nodes replacement map
5059   TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
5060   for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
5061     if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second )
5062     {
5063       const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
5064       nodeIDsToRemove.push_back( nToRemove->GetID() );
5065       // loop on elements sharing nToRemove
5066       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
5067       while ( invElemIt->more() ) {
5068         const SMDS_MeshElement* e = invElemIt->next();
5069         // get a new suite of nodes: make replacement
5070         int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
5071         const SMDS_MeshNode* nodes[ 8 ];
5072         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5073         while ( nIt->more() ) {
5074           const SMDS_MeshNode* n =
5075             static_cast<const SMDS_MeshNode*>( nIt->next() );
5076           nnIt = nReplaceMap.find( n );
5077           if ( nnIt != nReplaceMap.end() ) {
5078             nbReplaced++;
5079             n = (*nnIt).second;
5080           }
5081           nodes[ i++ ] = n;
5082         }
5083         //       if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
5084         //         elemIDsToRemove.push_back( e->GetID() );
5085         //       else
5086         if ( nbReplaced )
5087           aMesh->ChangeElementNodes( e, nodes, nbNodes );
5088       }
5089   }
5090
5091   Remove( nodeIDsToRemove, true );
5092
5093   return aResult;
5094 }