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