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