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