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