Salome HOME
NPAL14335 (EDF 344 SMESH : "ERROR : Iterator not implemented " when loading a script)
[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.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 // File      : SMESH_MeshEditor.cxx
25 // Created   : Mon Apr 12 16:10:22 2004
26 // Author    : Edward AGAPOV (eap)
27
28
29 #include "SMESH_MeshEditor.hxx"
30
31 #include "SMDS_FaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
35 #include "SMDS_FacePosition.hxx"
36 #include "SMDS_SpacePosition.hxx"
37 #include "SMDS_QuadraticFaceOfNodes.hxx"
38
39 #include "SMESHDS_Group.hxx"
40 #include "SMESHDS_Mesh.hxx"
41
42 #include "SMESH_subMesh.hxx"
43 #include "SMESH_ControlsDef.hxx"
44 #include "SMESH_MesherHelper.hxx"
45
46 #include "utilities.h"
47
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TopTools_ListOfShape.hxx>
50 #include <math.h>
51 #include <gp_Dir.hxx>
52 #include <gp_Vec.hxx>
53 #include <gp_Ax1.hxx>
54 #include <gp_Trsf.hxx>
55 #include <gp_Lin.hxx>
56 #include <gp_XYZ.hxx>
57 #include <gp_XY.hxx>
58 #include <gp.hxx>
59 #include <gp_Pln.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Geom_Curve.hxx>
62 #include <Geom_Surface.hxx>
63 #include <Geom2d_Curve.hxx>
64 #include <Extrema_GenExtPS.hxx>
65 #include <Extrema_POnSurf.hxx>
66 #include <GeomAdaptor_Surface.hxx>
67 #include <ElCLib.hxx>
68 #include <TColStd_ListOfInteger.hxx>
69 #include <TopoDS_Face.hxx>
70
71 #include <map>
72 #include <set>
73
74 using namespace std;
75 using namespace SMESH::Controls;
76
77 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshNode*> >    TElemOfNodeListMap;
78 typedef map<const SMDS_MeshElement*, list<const SMDS_MeshElement*> > TElemOfElemListMap;
79 typedef map<const SMDS_MeshNode*, list<const SMDS_MeshNode*> >       TNodeOfNodeListMap;
80 typedef TNodeOfNodeListMap::iterator                                 TNodeOfNodeListMapItr;
81 //typedef map<const SMDS_MeshNode*, vector<const SMDS_MeshNode*> >     TNodeOfNodeVecMap;
82 //typedef TNodeOfNodeVecMap::iterator                                  TNodeOfNodeVecMapItr;
83 typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeListMapItr> > TElemOfVecOfNnlmiMap;
84 //typedef map<const SMDS_MeshElement*, vector<TNodeOfNodeVecMapItr> >  TElemOfVecOfMapNodesMap;
85
86 typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > NLink;
87
88 //=======================================================================
89 //function : SMESH_MeshEditor
90 //purpose  :
91 //=======================================================================
92
93 SMESH_MeshEditor::SMESH_MeshEditor( SMESH_Mesh* theMesh ):
94 myMesh( theMesh )
95 {
96 }
97
98 //=======================================================================
99 //function : Remove
100 //purpose  : Remove a node or an element.
101 //           Modify a compute state of sub-meshes which become empty
102 //=======================================================================
103
104 bool SMESH_MeshEditor::Remove (const list< int >& theIDs,
105                                const bool         isNodes )
106 {
107   myLastCreatedElems.Clear();
108   myLastCreatedNodes.Clear();
109
110   SMESHDS_Mesh* aMesh = GetMeshDS();
111   set< SMESH_subMesh *> smmap;
112
113   list<int>::const_iterator it = theIDs.begin();
114   for ( ; it != theIDs.end(); it++ ) {
115     const SMDS_MeshElement * elem;
116     if ( isNodes )
117       elem = aMesh->FindNode( *it );
118     else
119       elem = aMesh->FindElement( *it );
120     if ( !elem )
121       continue;
122
123     // Find sub-meshes to notify about modification
124     SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
125     while ( nodeIt->more() ) {
126       const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
127       const SMDS_PositionPtr& aPosition = node->GetPosition();
128       if ( aPosition.get() ) {
129         if ( int aShapeID = aPosition->GetShapeId() ) {
130           if ( SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( aShapeID ) )
131             smmap.insert( sm );
132         }
133       }
134     }
135
136     // Do remove
137     if ( isNodes )
138       aMesh->RemoveNode( static_cast< const SMDS_MeshNode* >( elem ));
139     else
140       aMesh->RemoveElement( elem );
141   }
142
143   // Notify sub-meshes about modification
144   if ( !smmap.empty() ) {
145     set< SMESH_subMesh *>::iterator smIt;
146     for ( smIt = smmap.begin(); smIt != smmap.end(); smIt++ )
147       (*smIt)->ComputeStateEngine( SMESH_subMesh::MESH_ENTITY_REMOVED );
148   }
149
150   // Check if the whole mesh becomes empty
151   if ( SMESH_subMesh * sm = GetMesh()->GetSubMeshContaining( 1 ) )
152     sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
153
154   return true;
155 }
156
157 //=======================================================================
158 //function : FindShape
159 //purpose  : Return an index of the shape theElem is on
160 //           or zero if a shape not found
161 //=======================================================================
162
163 int SMESH_MeshEditor::FindShape (const SMDS_MeshElement * theElem)
164 {
165   myLastCreatedElems.Clear();
166   myLastCreatedNodes.Clear();
167
168   SMESHDS_Mesh * aMesh = GetMeshDS();
169   if ( aMesh->ShapeToMesh().IsNull() )
170     return 0;
171
172   if ( theElem->GetType() == SMDSAbs_Node ) {
173     const SMDS_PositionPtr& aPosition =
174       static_cast<const SMDS_MeshNode*>( theElem )->GetPosition();
175     if ( aPosition.get() )
176       return aPosition->GetShapeId();
177     else
178       return 0;
179   }
180
181   TopoDS_Shape aShape; // the shape a node is on
182   SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
183   while ( nodeIt->more() ) {
184     const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
185     const SMDS_PositionPtr& aPosition = node->GetPosition();
186     if ( aPosition.get() ) {
187       int aShapeID = aPosition->GetShapeId();
188       SMESHDS_SubMesh * sm = aMesh->MeshElements( aShapeID );
189       if ( sm ) {
190         if ( sm->Contains( theElem ))
191           return aShapeID;
192         if ( aShape.IsNull() )
193           aShape = aMesh->IndexToShape( aShapeID );
194       }
195       else {
196         //MESSAGE ( "::FindShape() No SubShape for aShapeID " << aShapeID );
197       }
198     }
199   }
200
201   // None of nodes is on a proper shape,
202   // find the shape among ancestors of aShape on which a node is
203   if ( aShape.IsNull() ) {
204     //MESSAGE ("::FindShape() - NONE node is on shape")
205     return 0;
206   }
207   TopTools_ListIteratorOfListOfShape ancIt( GetMesh()->GetAncestors( aShape ));
208   for ( ; ancIt.More(); ancIt.Next() ) {
209     SMESHDS_SubMesh * sm = aMesh->MeshElements( ancIt.Value() );
210     if ( sm && sm->Contains( theElem ))
211       return aMesh->ShapeToIndex( ancIt.Value() );
212   }
213
214   //MESSAGE ("::FindShape() - SHAPE NOT FOUND")
215   return 0;
216 }
217
218 //=======================================================================
219 //function : IsMedium
220 //purpose  : 
221 //=======================================================================
222
223 bool SMESH_MeshEditor::IsMedium(const SMDS_MeshNode*      node,
224                                 const SMDSAbs_ElementType typeToCheck)
225 {
226   bool isMedium = false;
227   SMDS_ElemIteratorPtr it = node->GetInverseElementIterator();
228   while (it->more()) {
229     const SMDS_MeshElement* elem = it->next();
230     isMedium = elem->IsMediumNode(node);
231     if ( typeToCheck == SMDSAbs_All || elem->GetType() == typeToCheck )
232       break;
233   }
234   return isMedium;
235 }
236
237 //=======================================================================
238 //function : ShiftNodesQuadTria
239 //purpose  : auxilary
240 //           Shift nodes in the array corresponded to quadratic triangle
241 //           example: (0,1,2,3,4,5) -> (1,2,0,4,5,3)
242 //=======================================================================
243 static void ShiftNodesQuadTria(const SMDS_MeshNode* aNodes[])
244 {
245   const SMDS_MeshNode* nd1 = aNodes[0];
246   aNodes[0] = aNodes[1];
247   aNodes[1] = aNodes[2];
248   aNodes[2] = nd1;
249   const SMDS_MeshNode* nd2 = aNodes[3];
250   aNodes[3] = aNodes[4];
251   aNodes[4] = aNodes[5];
252   aNodes[5] = nd2;
253 }
254
255 //=======================================================================
256 //function : GetNodesFromTwoTria
257 //purpose  : auxilary
258 //           Shift nodes in the array corresponded to quadratic triangle
259 //           example: (0,1,2,3,4,5) -> (1,2,0,4,5,3)
260 //=======================================================================
261 static bool GetNodesFromTwoTria(const SMDS_MeshElement * theTria1,
262                                 const SMDS_MeshElement * theTria2,
263                                 const SMDS_MeshNode* N1[],
264                                 const SMDS_MeshNode* N2[])
265 {
266   SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
267   int i=0;
268   while(i<6) {
269     N1[i] = static_cast<const SMDS_MeshNode*>( it->next() );
270     i++;
271   }
272   if(it->more()) return false;
273   it = theTria2->nodesIterator();
274   i=0;
275   while(i<6) {
276     N2[i] = static_cast<const SMDS_MeshNode*>( it->next() );
277     i++;
278   }
279   if(it->more()) return false;
280
281   int sames[3] = {-1,-1,-1};
282   int nbsames = 0;
283   int j;
284   for(i=0; i<3; i++) {
285     for(j=0; j<3; j++) {
286       if(N1[i]==N2[j]) {
287         sames[i] = j;
288         nbsames++;
289         break;
290       }
291     }
292   }
293   if(nbsames!=2) return false;
294   if(sames[0]>-1) {
295     ShiftNodesQuadTria(N1);
296     if(sames[1]>-1) {
297       ShiftNodesQuadTria(N1);
298     }
299   }
300   i = sames[0] + sames[1] + sames[2];
301   for(; i<2; i++) {
302     ShiftNodesQuadTria(N2);
303   }
304   // now we receive following N1 and N2 (using numeration as above image)
305   // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6) 
306   // i.e. first nodes from both arrays determ new diagonal
307   return true;
308 }
309
310 //=======================================================================
311 //function : InverseDiag
312 //purpose  : Replace two neighbour triangles with ones built on the same 4 nodes
313 //           but having other common link.
314 //           Return False if args are improper
315 //=======================================================================
316
317 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshElement * theTria1,
318                                     const SMDS_MeshElement * theTria2 )
319 {
320   myLastCreatedElems.Clear();
321   myLastCreatedNodes.Clear();
322
323   if (!theTria1 || !theTria2)
324     return false;
325
326   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria1 );
327   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( theTria2 );
328   if (F1 && F2) {
329
330     //  1 +--+ A  theTria1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
331     //    | /|    theTria2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |
332     //    |/ |                                         | \|
333     //  B +--+ 2                                     B +--+ 2
334
335     // put nodes in array and find out indices of the same ones
336     const SMDS_MeshNode* aNodes [6];
337     int sameInd [] = { 0, 0, 0, 0, 0, 0 };
338     int i = 0;
339     SMDS_ElemIteratorPtr it = theTria1->nodesIterator();
340     while ( it->more() ) {
341       aNodes[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
342       
343       if ( i > 2 ) // theTria2
344         // find same node of theTria1
345         for ( int j = 0; j < 3; j++ )
346           if ( aNodes[ i ] == aNodes[ j ]) {
347             sameInd[ j ] = i;
348             sameInd[ i ] = j;
349             break;
350           }
351       // next
352       i++;
353       if ( i == 3 ) {
354         if ( it->more() )
355           return false; // theTria1 is not a triangle
356         it = theTria2->nodesIterator();
357       }
358       if ( i == 6 && it->more() )
359         return false; // theTria2 is not a triangle
360     }
361     
362     // find indices of 1,2 and of A,B in theTria1
363     int iA = 0, iB = 0, i1 = 0, i2 = 0;
364     for ( i = 0; i < 6; i++ ) {
365       if ( sameInd [ i ] == 0 )
366         if ( i < 3 ) i1 = i;
367         else         i2 = i;
368       else if (i < 3)
369         if ( iA ) iB = i;
370         else      iA = i;
371     }
372     // nodes 1 and 2 should not be the same
373     if ( aNodes[ i1 ] == aNodes[ i2 ] )
374       return false;
375
376     // theTria1: A->2
377     aNodes[ iA ] = aNodes[ i2 ];
378     // theTria2: B->1
379     aNodes[ sameInd[ iB ]] = aNodes[ i1 ];
380
381     //MESSAGE( theTria1 << theTria2 );
382     
383     GetMeshDS()->ChangeElementNodes( theTria1, aNodes, 3 );
384     GetMeshDS()->ChangeElementNodes( theTria2, &aNodes[ 3 ], 3 );
385     
386     //MESSAGE( theTria1 << theTria2 );
387
388     return true;
389   
390   } // end if(F1 && F2)
391
392   // check case of quadratic faces
393   const SMDS_QuadraticFaceOfNodes* QF1 =
394     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (theTria1);
395   if(!QF1) return false;
396   const SMDS_QuadraticFaceOfNodes* QF2 =
397     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (theTria2);
398   if(!QF2) return false;
399
400   //       5
401   //  1 +--+--+ 2  theTria1: (1 2 4 5 9 7) or (2 4 1 9 7 5) or (4 1 2 7 5 9)
402   //    |    /|    theTria2: (2 3 4 6 8 9) or (3 4 2 8 9 6) or (4 2 3 9 6 8)
403   //    |   / |  
404   //  7 +  +  + 6
405   //    | /9  |
406   //    |/    |
407   //  4 +--+--+ 3  
408   //       8
409   
410   const SMDS_MeshNode* N1 [6];
411   const SMDS_MeshNode* N2 [6];
412   if(!GetNodesFromTwoTria(theTria1,theTria2,N1,N2))
413     return false;
414   // now we receive following N1 and N2 (using numeration as above image)
415   // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6) 
416   // i.e. first nodes from both arrays determ new diagonal
417
418   const SMDS_MeshNode* N1new [6];
419   const SMDS_MeshNode* N2new [6];
420   N1new[0] = N1[0];
421   N1new[1] = N2[0];
422   N1new[2] = N2[1];
423   N1new[3] = N1[4];
424   N1new[4] = N2[3];
425   N1new[5] = N1[5];
426   N2new[0] = N1[0];
427   N2new[1] = N1[1];
428   N2new[2] = N2[0];
429   N2new[3] = N1[3];
430   N2new[4] = N2[5];
431   N2new[5] = N1[4];
432   // replaces nodes in faces
433   GetMeshDS()->ChangeElementNodes( theTria1, N1new, 6 );
434   GetMeshDS()->ChangeElementNodes( theTria2, N2new, 6 );
435
436   return true;
437 }
438
439 //=======================================================================
440 //function : findTriangles
441 //purpose  : find triangles sharing theNode1-theNode2 link
442 //=======================================================================
443
444 static bool findTriangles(const SMDS_MeshNode *    theNode1,
445                           const SMDS_MeshNode *    theNode2,
446                           const SMDS_MeshElement*& theTria1,
447                           const SMDS_MeshElement*& theTria2)
448 {
449   if ( !theNode1 || !theNode2 ) return false;
450
451   theTria1 = theTria2 = 0;
452
453   set< const SMDS_MeshElement* > emap;
454   SMDS_ElemIteratorPtr it = theNode1->GetInverseElementIterator(SMDSAbs_Face);
455   while (it->more()) {
456     const SMDS_MeshElement* elem = it->next();
457     if ( elem->NbNodes() == 3 )
458       emap.insert( elem );
459   }
460   it = theNode2->GetInverseElementIterator(SMDSAbs_Face);
461   while (it->more()) {
462     const SMDS_MeshElement* elem = it->next();
463     if ( emap.find( elem ) != emap.end() )
464       if ( theTria1 ) {
465         // theTria1 must be element with minimum ID
466         if( theTria1->GetID() < elem->GetID() ) {
467           theTria2 = elem;
468         }
469         else {
470           theTria2 = theTria1;
471           theTria1 = elem;
472         }
473         break;
474       }
475       else {
476         theTria1 = elem;
477       }
478   }
479   return ( theTria1 && theTria2 );
480 }
481
482 //=======================================================================
483 //function : InverseDiag
484 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
485 //           with ones built on the same 4 nodes but having other common link.
486 //           Return false if proper faces not found
487 //=======================================================================
488
489 bool SMESH_MeshEditor::InverseDiag (const SMDS_MeshNode * theNode1,
490                                     const SMDS_MeshNode * theNode2)
491 {
492   myLastCreatedElems.Clear();
493   myLastCreatedNodes.Clear();
494
495   MESSAGE( "::InverseDiag()" );
496
497   const SMDS_MeshElement *tr1, *tr2;
498   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
499     return false;
500
501   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
502   //if (!F1) return false;
503   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
504   //if (!F2) return false;
505   if (F1 && F2) {
506
507     //  1 +--+ A  tr1: ( 1 A B ) A->2 ( 1 2 B ) 1 +--+ A
508     //    | /|    tr2: ( B A 2 ) B->1 ( 1 A 2 )   |\ |
509     //    |/ |                                    | \|
510     //  B +--+ 2                                B +--+ 2
511
512     // put nodes in array
513     // and find indices of 1,2 and of A in tr1 and of B in tr2
514     int i, iA1 = 0, i1 = 0;
515     const SMDS_MeshNode* aNodes1 [3];
516     SMDS_ElemIteratorPtr it;
517     for (i = 0, it = tr1->nodesIterator(); it->more(); i++ ) {
518       aNodes1[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
519       if ( aNodes1[ i ] == theNode1 )
520         iA1 = i; // node A in tr1
521       else if ( aNodes1[ i ] != theNode2 )
522         i1 = i;  // node 1
523     }
524     int iB2 = 0, i2 = 0;
525     const SMDS_MeshNode* aNodes2 [3];
526     for (i = 0, it = tr2->nodesIterator(); it->more(); i++ ) {
527       aNodes2[ i ] = static_cast<const SMDS_MeshNode*>( it->next() );
528       if ( aNodes2[ i ] == theNode2 )
529         iB2 = i; // node B in tr2
530       else if ( aNodes2[ i ] != theNode1 )
531         i2 = i;  // node 2
532     }
533     
534     // nodes 1 and 2 should not be the same
535     if ( aNodes1[ i1 ] == aNodes2[ i2 ] )
536       return false;
537
538     // tr1: A->2
539     aNodes1[ iA1 ] = aNodes2[ i2 ];
540     // tr2: B->1
541     aNodes2[ iB2 ] = aNodes1[ i1 ];
542
543     //MESSAGE( tr1 << tr2 );
544
545     GetMeshDS()->ChangeElementNodes( tr1, aNodes1, 3 );
546     GetMeshDS()->ChangeElementNodes( tr2, aNodes2, 3 );
547
548     //MESSAGE( tr1 << tr2 );
549     
550     return true;
551   }
552
553   // check case of quadratic faces
554   const SMDS_QuadraticFaceOfNodes* QF1 =
555     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (tr1);
556   if(!QF1) return false;
557   const SMDS_QuadraticFaceOfNodes* QF2 =
558     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (tr2);
559   if(!QF2) return false;
560   return InverseDiag(tr1,tr2);
561 }
562
563 //=======================================================================
564 //function : getQuadrangleNodes
565 //purpose  : fill theQuadNodes - nodes of a quadrangle resulting from
566 //           fusion of triangles tr1 and tr2 having shared link on
567 //           theNode1 and theNode2
568 //=======================================================================
569
570 bool getQuadrangleNodes(const SMDS_MeshNode *    theQuadNodes [],
571                         const SMDS_MeshNode *    theNode1,
572                         const SMDS_MeshNode *    theNode2,
573                         const SMDS_MeshElement * tr1,
574                         const SMDS_MeshElement * tr2 )
575 {
576   if( tr1->NbNodes() != tr2->NbNodes() )
577     return false;
578   // find the 4-th node to insert into tr1
579   const SMDS_MeshNode* n4 = 0;
580   SMDS_ElemIteratorPtr it = tr2->nodesIterator();
581   int i=0;
582   //while ( !n4 && it->more() ) {
583   while ( !n4 && i<3 ) {
584     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
585     i++;
586     bool isDiag = ( n == theNode1 || n == theNode2 );
587     if ( !isDiag )
588       n4 = n;
589   }
590   // Make an array of nodes to be in a quadrangle
591   int iNode = 0, iFirstDiag = -1;
592   it = tr1->nodesIterator();
593   i=0;
594   //while ( it->more() ) {
595   while ( i<3 ) {
596     const SMDS_MeshNode * n = static_cast<const SMDS_MeshNode*>( it->next() );
597     i++;
598     bool isDiag = ( n == theNode1 || n == theNode2 );
599     if ( isDiag ) {
600       if ( iFirstDiag < 0 )
601         iFirstDiag = iNode;
602       else if ( iNode - iFirstDiag == 1 )
603         theQuadNodes[ iNode++ ] = n4; // insert the 4-th node between diagonal nodes
604     }
605     else if ( n == n4 ) {
606       return false; // tr1 and tr2 should not have all the same nodes
607     }
608     theQuadNodes[ iNode++ ] = n;
609   }
610   if ( iNode == 3 ) // diagonal nodes have 0 and 2 indices
611     theQuadNodes[ iNode ] = n4;
612
613   return true;
614 }
615
616 //=======================================================================
617 //function : DeleteDiag
618 //purpose  : Replace two neighbour triangles sharing theNode1-theNode2 link
619 //           with a quadrangle built on the same 4 nodes.
620 //           Return false if proper faces not found
621 //=======================================================================
622
623 bool SMESH_MeshEditor::DeleteDiag (const SMDS_MeshNode * theNode1,
624                                    const SMDS_MeshNode * theNode2)
625 {
626   myLastCreatedElems.Clear();
627   myLastCreatedNodes.Clear();
628
629   MESSAGE( "::DeleteDiag()" );
630
631   const SMDS_MeshElement *tr1, *tr2;
632   if ( !findTriangles( theNode1, theNode2, tr1, tr2 ))
633     return false;
634
635   const SMDS_FaceOfNodes* F1 = dynamic_cast<const SMDS_FaceOfNodes*>( tr1 );
636   //if (!F1) return false;
637   const SMDS_FaceOfNodes* F2 = dynamic_cast<const SMDS_FaceOfNodes*>( tr2 );
638   //if (!F2) return false;
639   if (F1 && F2) {
640
641     const SMDS_MeshNode* aNodes [ 4 ];
642     if ( ! getQuadrangleNodes( aNodes, theNode1, theNode2, tr1, tr2 ))
643       return false;
644
645     //MESSAGE( endl << tr1 << tr2 );
646
647     GetMeshDS()->ChangeElementNodes( tr1, aNodes, 4 );
648     myLastCreatedElems.Append(tr1);
649     GetMeshDS()->RemoveElement( tr2 );
650
651     //MESSAGE( endl << tr1 );
652
653     return true;
654   }
655
656   // check case of quadratic faces
657   const SMDS_QuadraticFaceOfNodes* QF1 =
658     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (tr1);
659   if(!QF1) return false;
660   const SMDS_QuadraticFaceOfNodes* QF2 =
661     dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (tr2);
662   if(!QF2) return false;
663
664   //       5
665   //  1 +--+--+ 2  tr1: (1 2 4 5 9 7) or (2 4 1 9 7 5) or (4 1 2 7 5 9)
666   //    |    /|    tr2: (2 3 4 6 8 9) or (3 4 2 8 9 6) or (4 2 3 9 6 8)
667   //    |   / |  
668   //  7 +  +  + 6
669   //    | /9  |
670   //    |/    |
671   //  4 +--+--+ 3  
672   //       8
673   
674   const SMDS_MeshNode* N1 [6];
675   const SMDS_MeshNode* N2 [6];
676   if(!GetNodesFromTwoTria(tr1,tr2,N1,N2))
677     return false;
678   // now we receive following N1 and N2 (using numeration as above image)
679   // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6) 
680   // i.e. first nodes from both arrays determ new diagonal
681
682   const SMDS_MeshNode* aNodes[8];
683   aNodes[0] = N1[0];
684   aNodes[1] = N1[1];
685   aNodes[2] = N2[0];
686   aNodes[3] = N2[1];
687   aNodes[4] = N1[3];
688   aNodes[5] = N2[5];
689   aNodes[6] = N2[3];
690   aNodes[7] = N1[5];
691
692   GetMeshDS()->ChangeElementNodes( tr1, aNodes, 8 );
693   myLastCreatedElems.Append(tr1);
694   GetMeshDS()->RemoveElement( tr2 );
695
696   // remove middle node (9)
697   GetMeshDS()->RemoveNode( N1[4] );
698
699   return true;
700 }
701
702 //=======================================================================
703 //function : Reorient
704 //purpose  : Reverse theElement orientation
705 //=======================================================================
706
707 bool SMESH_MeshEditor::Reorient (const SMDS_MeshElement * theElem)
708 {
709   myLastCreatedElems.Clear();
710   myLastCreatedNodes.Clear();
711
712   if (!theElem)
713     return false;
714   SMDS_ElemIteratorPtr it = theElem->nodesIterator();
715   if ( !it || !it->more() )
716     return false;
717
718   switch ( theElem->GetType() ) {
719
720   case SMDSAbs_Edge:
721   case SMDSAbs_Face: {
722     if(!theElem->IsQuadratic()) {
723       int i = theElem->NbNodes();
724       vector<const SMDS_MeshNode*> aNodes( i );
725       while ( it->more() )
726         aNodes[ --i ]= static_cast<const SMDS_MeshNode*>( it->next() );
727       return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], theElem->NbNodes() );
728     }
729     else {
730       // quadratic elements
731       if(theElem->GetType()==SMDSAbs_Edge) {
732         vector<const SMDS_MeshNode*> aNodes(3);
733         aNodes[1]= static_cast<const SMDS_MeshNode*>( it->next() );
734         aNodes[0]= static_cast<const SMDS_MeshNode*>( it->next() );
735         aNodes[2]= static_cast<const SMDS_MeshNode*>( it->next() );
736         return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], 3 );
737       }
738       else {
739         int nbn = theElem->NbNodes();
740         vector<const SMDS_MeshNode*> aNodes(nbn);
741         aNodes[0]= static_cast<const SMDS_MeshNode*>( it->next() );
742         int i=1;
743         for(; i<nbn/2; i++) {
744           aNodes[nbn/2-i]= static_cast<const SMDS_MeshNode*>( it->next() );
745         }
746         for(i=0; i<nbn/2; i++) {
747           aNodes[nbn-i-1]= static_cast<const SMDS_MeshNode*>( it->next() );
748         }
749         return GetMeshDS()->ChangeElementNodes( theElem, &aNodes[0], nbn );
750       }
751     }
752   }
753   case SMDSAbs_Volume: {
754     if (theElem->IsPoly()) {
755       const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
756         static_cast<const SMDS_PolyhedralVolumeOfNodes*>( theElem );
757       if (!aPolyedre) {
758         MESSAGE("Warning: bad volumic element");
759         return false;
760       }
761
762       int nbFaces = aPolyedre->NbFaces();
763       vector<const SMDS_MeshNode *> poly_nodes;
764       vector<int> quantities (nbFaces);
765
766       // reverse each face of the polyedre
767       for (int iface = 1; iface <= nbFaces; iface++) {
768         int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
769         quantities[iface - 1] = nbFaceNodes;
770         
771         for (inode = nbFaceNodes; inode >= 1; inode--) {
772           const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
773           poly_nodes.push_back(curNode);
774         }
775       }
776       
777       return GetMeshDS()->ChangePolyhedronNodes( theElem, poly_nodes, quantities );
778
779     }
780     else {
781       SMDS_VolumeTool vTool;
782       if ( !vTool.Set( theElem ))
783         return false;
784       vTool.Inverse();
785       return GetMeshDS()->ChangeElementNodes( theElem, vTool.GetNodes(), vTool.NbNodes() );
786     }
787   }
788   default:;
789   }
790
791   return false;
792 }
793
794 //=======================================================================
795 //function : getBadRate
796 //purpose  :
797 //=======================================================================
798
799 static double getBadRate (const SMDS_MeshElement*               theElem,
800                           SMESH::Controls::NumericalFunctorPtr& theCrit)
801 {
802   SMESH::Controls::TSequenceOfXYZ P;
803   if ( !theElem || !theCrit->GetPoints( theElem, P ))
804     return 1e100;
805   return theCrit->GetBadRate( theCrit->GetValue( P ), theElem->NbNodes() );
806   //return theCrit->GetBadRate( theCrit->GetValue( theElem->GetID() ), theElem->NbNodes() );
807 }
808
809 //=======================================================================
810 //function : QuadToTri
811 //purpose  : Cut quadrangles into triangles.
812 //           theCrit is used to select a diagonal to cut
813 //=======================================================================
814
815 bool SMESH_MeshEditor::QuadToTri (TIDSortedElemSet &                   theElems,
816                                   SMESH::Controls::NumericalFunctorPtr theCrit)
817 {
818   myLastCreatedElems.Clear();
819   myLastCreatedNodes.Clear();
820
821   MESSAGE( "::QuadToTri()" );
822
823   if ( !theCrit.get() )
824     return false;
825
826   SMESHDS_Mesh * aMesh = GetMeshDS();
827
828   Handle(Geom_Surface) surface;
829   SMESH_MesherHelper   helper( *GetMesh() );
830
831   TIDSortedElemSet::iterator itElem;
832   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
833     const SMDS_MeshElement* elem = *itElem;
834     if ( !elem || elem->GetType() != SMDSAbs_Face )
835       continue;
836     if ( elem->NbNodes() != ( elem->IsQuadratic() ? 8 : 4 ))
837       continue;
838
839     // retrieve element nodes
840     const SMDS_MeshNode* aNodes [8];
841     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
842     int i = 0;
843     while ( itN->more() )
844       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
845
846     // compare two sets of possible triangles
847     double aBadRate1, aBadRate2; // to what extent a set is bad
848     SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
849     SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
850     aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
851
852     SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
853     SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
854     aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
855
856     int aShapeId = FindShape( elem );
857     const SMDS_MeshElement* newElem = 0;
858
859     if( !elem->IsQuadratic() ) {
860
861       // split liner quadrangle
862
863       if ( aBadRate1 <= aBadRate2 ) {
864         // tr1 + tr2 is better
865         aMesh->ChangeElementNodes( elem, aNodes, 3 );
866         newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
867       }
868       else {
869         // tr3 + tr4 is better
870         aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
871         newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
872       }
873     }
874     else {
875
876       // split quadratic quadrangle
877
878       // get surface elem is on
879       if ( aShapeId != helper.GetSubShapeID() ) {
880         surface.Nullify();
881         TopoDS_Shape shape;
882         if ( aShapeId > 0 )
883           shape = aMesh->IndexToShape( aShapeId );
884         if ( !shape.IsNull() && shape.ShapeType() == TopAbs_FACE ) {
885           TopoDS_Face face = TopoDS::Face( shape );
886           surface = BRep_Tool::Surface( face );
887           if ( !surface.IsNull() )
888             helper.SetSubShape( shape );
889         }
890       }
891       // get elem nodes
892       const SMDS_MeshNode* aNodes [8];
893       const SMDS_MeshNode* inFaceNode = 0;
894       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
895       int i = 0;
896       while ( itN->more() ) {
897         aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
898         if ( !inFaceNode && helper.GetNodeUVneedInFaceNode() &&
899              aNodes[ i-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
900         {
901           inFaceNode = aNodes[ i-1 ];
902         } 
903       }
904       // find middle point for (0,1,2,3)
905       // and create a node in this point;
906       gp_XYZ p( 0,0,0 );
907       if ( surface.IsNull() ) {
908         for(i=0; i<4; i++)
909           p += gp_XYZ(aNodes[i]->X(), aNodes[i]->Y(), aNodes[i]->Z() );
910         p /= 4;
911       }
912       else {
913         TopoDS_Face face = TopoDS::Face( helper.GetSubShape() );
914         gp_XY uv( 0,0 );
915         for(i=0; i<4; i++)
916           uv += helper.GetNodeUV( face, aNodes[i], inFaceNode );
917         uv /= 4.;
918         p = surface->Value( uv.X(), uv.Y() ).XYZ();
919       }
920       const SMDS_MeshNode* newN = aMesh->AddNode( p.X(), p.Y(), p.Z() );
921       myLastCreatedNodes.Append(newN);
922
923       // create a new element
924       const SMDS_MeshNode* N[6];
925       if ( aBadRate1 <= aBadRate2 ) {
926         N[0] = aNodes[0];
927         N[1] = aNodes[1];
928         N[2] = aNodes[2];
929         N[3] = aNodes[4];
930         N[4] = aNodes[5];
931         N[5] = newN;
932         newElem = aMesh->AddFace(aNodes[2], aNodes[3], aNodes[0],
933                                  aNodes[6], aNodes[7], newN );
934       }
935       else {
936         N[0] = aNodes[1];
937         N[1] = aNodes[2];
938         N[2] = aNodes[3];
939         N[3] = aNodes[5];
940         N[4] = aNodes[6];
941         N[5] = newN;
942         newElem = aMesh->AddFace(aNodes[3], aNodes[0], aNodes[1],
943                                  aNodes[7], aNodes[4], newN );
944       }
945       aMesh->ChangeElementNodes( elem, N, 6 );
946
947     } // quadratic case
948
949     // care of a new element
950
951     myLastCreatedElems.Append(newElem);
952     AddToSameGroups( newElem, elem, aMesh );
953
954     // put a new triangle on the same shape
955     if ( aShapeId )
956       aMesh->SetMeshElementOnShape( newElem, aShapeId );
957   }
958   return true;
959 }
960
961 //=======================================================================
962 //function : BestSplit
963 //purpose  : Find better diagonal for cutting.
964 //=======================================================================
965 int SMESH_MeshEditor::BestSplit (const SMDS_MeshElement*              theQuad,
966                                  SMESH::Controls::NumericalFunctorPtr theCrit)
967 {
968   myLastCreatedElems.Clear();
969   myLastCreatedNodes.Clear();
970
971   if (!theCrit.get())
972     return -1;
973
974   if (!theQuad || theQuad->GetType() != SMDSAbs_Face )
975     return -1;
976
977   if( theQuad->NbNodes()==4 ||
978       (theQuad->NbNodes()==8 && theQuad->IsQuadratic()) ) {
979
980     // retrieve element nodes
981     const SMDS_MeshNode* aNodes [4];
982     SMDS_ElemIteratorPtr itN = theQuad->nodesIterator();
983     int i = 0;
984     //while (itN->more())
985     while (i<4) {
986       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
987     }
988     // compare two sets of possible triangles
989     double aBadRate1, aBadRate2; // to what extent a set is bad
990     SMDS_FaceOfNodes tr1 ( aNodes[0], aNodes[1], aNodes[2] );
991     SMDS_FaceOfNodes tr2 ( aNodes[2], aNodes[3], aNodes[0] );
992     aBadRate1 = getBadRate( &tr1, theCrit ) + getBadRate( &tr2, theCrit );
993
994     SMDS_FaceOfNodes tr3 ( aNodes[1], aNodes[2], aNodes[3] );
995     SMDS_FaceOfNodes tr4 ( aNodes[3], aNodes[0], aNodes[1] );
996     aBadRate2 = getBadRate( &tr3, theCrit ) + getBadRate( &tr4, theCrit );
997
998     if (aBadRate1 <= aBadRate2) // tr1 + tr2 is better
999       return 1; // diagonal 1-3
1000
1001     return 2; // diagonal 2-4
1002   }
1003   return -1;
1004 }
1005
1006 //=======================================================================
1007 //function : AddToSameGroups
1008 //purpose  : add elemToAdd to the groups the elemInGroups belongs to
1009 //=======================================================================
1010
1011 void SMESH_MeshEditor::AddToSameGroups (const SMDS_MeshElement* elemToAdd,
1012                                         const SMDS_MeshElement* elemInGroups,
1013                                         SMESHDS_Mesh *          aMesh)
1014 {
1015   const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
1016   set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
1017   for ( ; grIt != groups.end(); grIt++ ) {
1018     SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
1019     if ( group && group->SMDSGroup().Contains( elemInGroups ))
1020       group->SMDSGroup().Add( elemToAdd );
1021   }
1022 }
1023
1024
1025 //=======================================================================
1026 //function : RemoveElemFromGroups
1027 //purpose  : Remove removeelem to the groups the elemInGroups belongs to
1028 //=======================================================================
1029 void SMESH_MeshEditor::RemoveElemFromGroups (const SMDS_MeshElement* removeelem,
1030                                              SMESHDS_Mesh *          aMesh)
1031 {
1032   const set<SMESHDS_GroupBase*>& groups = aMesh->GetGroups();
1033   if (!groups.empty()) 
1034   {
1035     set<SMESHDS_GroupBase*>::const_iterator GrIt = groups.begin();
1036     for (; GrIt != groups.end(); GrIt++) 
1037     {
1038       SMESHDS_Group* grp = dynamic_cast<SMESHDS_Group*>(*GrIt);
1039       if (!grp || grp->IsEmpty()) continue;
1040       grp->SMDSGroup().Remove(removeelem);
1041     }
1042   }
1043 }
1044
1045
1046 //=======================================================================
1047 //function : QuadToTri
1048 //purpose  : Cut quadrangles into triangles.
1049 //           theCrit is used to select a diagonal to cut
1050 //=======================================================================
1051
1052 bool SMESH_MeshEditor::QuadToTri (TIDSortedElemSet & theElems,
1053                                   const bool         the13Diag)
1054 {
1055   myLastCreatedElems.Clear();
1056   myLastCreatedNodes.Clear();
1057
1058   MESSAGE( "::QuadToTri()" );
1059
1060   SMESHDS_Mesh * aMesh = GetMeshDS();
1061
1062   Handle(Geom_Surface) surface;
1063   SMESH_MesherHelper   helper( *GetMesh() );
1064
1065   TIDSortedElemSet::iterator itElem;
1066   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1067     const SMDS_MeshElement* elem = *itElem;
1068     if ( !elem || elem->GetType() != SMDSAbs_Face )
1069       continue;
1070     bool isquad = elem->NbNodes()==4 || elem->NbNodes()==8;
1071     if(!isquad) continue;
1072
1073     if(elem->NbNodes()==4) {
1074       // retrieve element nodes
1075       const SMDS_MeshNode* aNodes [4];
1076       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1077       int i = 0;
1078       while ( itN->more() )
1079         aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1080
1081       int aShapeId = FindShape( elem );
1082       const SMDS_MeshElement* newElem = 0;
1083       if ( the13Diag ) {
1084         aMesh->ChangeElementNodes( elem, aNodes, 3 );
1085         newElem = aMesh->AddFace( aNodes[2], aNodes[3], aNodes[0] );
1086       }
1087       else {
1088         aMesh->ChangeElementNodes( elem, &aNodes[1], 3 );
1089         newElem = aMesh->AddFace( aNodes[3], aNodes[0], aNodes[1] );
1090       }
1091       myLastCreatedElems.Append(newElem);
1092       // put a new triangle on the same shape and add to the same groups
1093       if ( aShapeId )
1094         aMesh->SetMeshElementOnShape( newElem, aShapeId );
1095       AddToSameGroups( newElem, elem, aMesh );
1096     }
1097
1098     // Quadratic quadrangle
1099
1100     if( elem->NbNodes()==8 && elem->IsQuadratic() ) {
1101
1102       // get surface elem is on
1103       int aShapeId = FindShape( elem );
1104       if ( aShapeId != helper.GetSubShapeID() ) {
1105         surface.Nullify();
1106         TopoDS_Shape shape;
1107         if ( aShapeId > 0 )
1108           shape = aMesh->IndexToShape( aShapeId );
1109         if ( !shape.IsNull() && shape.ShapeType() == TopAbs_FACE ) {
1110           TopoDS_Face face = TopoDS::Face( shape );
1111           surface = BRep_Tool::Surface( face );
1112           if ( !surface.IsNull() )
1113             helper.SetSubShape( shape );
1114         }
1115       }
1116
1117       const SMDS_MeshNode* aNodes [8];
1118       const SMDS_MeshNode* inFaceNode = 0;
1119       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1120       int i = 0;
1121       while ( itN->more() ) {
1122         aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1123         if ( !inFaceNode && helper.GetNodeUVneedInFaceNode() &&
1124              aNodes[ i-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1125         {
1126           inFaceNode = aNodes[ i-1 ];
1127         } 
1128       }
1129
1130       // find middle point for (0,1,2,3)
1131       // and create a node in this point;
1132       gp_XYZ p( 0,0,0 );
1133       if ( surface.IsNull() ) {
1134         for(i=0; i<4; i++)
1135           p += gp_XYZ(aNodes[i]->X(), aNodes[i]->Y(), aNodes[i]->Z() );
1136         p /= 4;
1137       }
1138       else {
1139         TopoDS_Face geomFace = TopoDS::Face( helper.GetSubShape() );
1140         gp_XY uv( 0,0 );
1141         for(i=0; i<4; i++)
1142           uv += helper.GetNodeUV( geomFace, aNodes[i], inFaceNode );
1143         uv /= 4.;
1144         p = surface->Value( uv.X(), uv.Y() ).XYZ();
1145       }
1146       const SMDS_MeshNode* newN = aMesh->AddNode( p.X(), p.Y(), p.Z() );
1147       myLastCreatedNodes.Append(newN);
1148
1149       // create a new element
1150       const SMDS_MeshElement* newElem = 0;
1151       const SMDS_MeshNode* N[6];
1152       if ( the13Diag ) {
1153         N[0] = aNodes[0];
1154         N[1] = aNodes[1];
1155         N[2] = aNodes[2];
1156         N[3] = aNodes[4];
1157         N[4] = aNodes[5];
1158         N[5] = newN;
1159         newElem = aMesh->AddFace(aNodes[2], aNodes[3], aNodes[0],
1160                                  aNodes[6], aNodes[7], newN );
1161       }
1162       else {
1163         N[0] = aNodes[1];
1164         N[1] = aNodes[2];
1165         N[2] = aNodes[3];
1166         N[3] = aNodes[5];
1167         N[4] = aNodes[6];
1168         N[5] = newN;
1169         newElem = aMesh->AddFace(aNodes[3], aNodes[0], aNodes[1],
1170                                  aNodes[7], aNodes[4], newN );
1171       }
1172       myLastCreatedElems.Append(newElem);
1173       aMesh->ChangeElementNodes( elem, N, 6 );
1174       // put a new triangle on the same shape and add to the same groups
1175       if ( aShapeId )
1176         aMesh->SetMeshElementOnShape( newElem, aShapeId );
1177       AddToSameGroups( newElem, elem, aMesh );
1178     }
1179   }
1180
1181   return true;
1182 }
1183
1184 //=======================================================================
1185 //function : getAngle
1186 //purpose  :
1187 //=======================================================================
1188
1189 double getAngle(const SMDS_MeshElement * tr1,
1190                 const SMDS_MeshElement * tr2,
1191                 const SMDS_MeshNode *    n1,
1192                 const SMDS_MeshNode *    n2)
1193 {
1194   double angle = 2*PI; // bad angle
1195
1196   // get normals
1197   SMESH::Controls::TSequenceOfXYZ P1, P2;
1198   if ( !SMESH::Controls::NumericalFunctor::GetPoints( tr1, P1 ) ||
1199        !SMESH::Controls::NumericalFunctor::GetPoints( tr2, P2 ))
1200     return angle;
1201   gp_Vec N1,N2;
1202   if(!tr1->IsQuadratic())
1203     N1 = gp_Vec( P1(2) - P1(1) ) ^ gp_Vec( P1(3) - P1(1) );
1204   else
1205     N1 = gp_Vec( P1(3) - P1(1) ) ^ gp_Vec( P1(5) - P1(1) );
1206   if ( N1.SquareMagnitude() <= gp::Resolution() )
1207     return angle;
1208   if(!tr2->IsQuadratic())
1209     N2 = gp_Vec( P2(2) - P2(1) ) ^ gp_Vec( P2(3) - P2(1) );
1210   else
1211     N2 = gp_Vec( P2(3) - P2(1) ) ^ gp_Vec( P2(5) - P2(1) );
1212   if ( N2.SquareMagnitude() <= gp::Resolution() )
1213     return angle;
1214
1215   // find the first diagonal node n1 in the triangles:
1216   // take in account a diagonal link orientation
1217   const SMDS_MeshElement *nFirst[2], *tr[] = { tr1, tr2 };
1218   for ( int t = 0; t < 2; t++ ) {
1219     SMDS_ElemIteratorPtr it = tr[ t ]->nodesIterator();
1220     int i = 0, iDiag = -1;
1221     while ( it->more()) {
1222       const SMDS_MeshElement *n = it->next();
1223       if ( n == n1 || n == n2 )
1224         if ( iDiag < 0)
1225           iDiag = i;
1226         else {
1227           if ( i - iDiag == 1 )
1228             nFirst[ t ] = ( n == n1 ? n2 : n1 );
1229           else
1230             nFirst[ t ] = n;
1231           break;
1232         }
1233       i++;
1234     }
1235   }
1236   if ( nFirst[ 0 ] == nFirst[ 1 ] )
1237     N2.Reverse();
1238
1239   angle = N1.Angle( N2 );
1240   //SCRUTE( angle );
1241   return angle;
1242 }
1243
1244 // =================================================
1245 // class generating a unique ID for a pair of nodes
1246 // and able to return nodes by that ID
1247 // =================================================
1248 class LinkID_Gen {
1249  public:
1250
1251   LinkID_Gen( const SMESHDS_Mesh* theMesh )
1252     :myMesh( theMesh ), myMaxID( theMesh->MaxNodeID() + 1)
1253   {}
1254
1255   long GetLinkID (const SMDS_MeshNode * n1,
1256                   const SMDS_MeshNode * n2) const
1257   {
1258     return ( Min(n1->GetID(),n2->GetID()) * myMaxID + Max(n1->GetID(),n2->GetID()));
1259   }
1260
1261   bool GetNodes (const long             theLinkID,
1262                  const SMDS_MeshNode* & theNode1,
1263                  const SMDS_MeshNode* & theNode2) const
1264   {
1265     theNode1 = myMesh->FindNode( theLinkID / myMaxID );
1266     if ( !theNode1 ) return false;
1267     theNode2 = myMesh->FindNode( theLinkID % myMaxID );
1268     if ( !theNode2 ) return false;
1269     return true;
1270   }
1271
1272  private:
1273   LinkID_Gen();
1274   const SMESHDS_Mesh* myMesh;
1275   long                myMaxID;
1276 };
1277
1278
1279 //=======================================================================
1280 //function : TriToQuad
1281 //purpose  : Fuse neighbour triangles into quadrangles.
1282 //           theCrit is used to select a neighbour to fuse with.
1283 //           theMaxAngle is a max angle between element normals at which
1284 //           fusion is still performed.
1285 //=======================================================================
1286
1287 bool SMESH_MeshEditor::TriToQuad (TIDSortedElemSet &                   theElems,
1288                                   SMESH::Controls::NumericalFunctorPtr theCrit,
1289                                   const double                         theMaxAngle)
1290 {
1291   myLastCreatedElems.Clear();
1292   myLastCreatedNodes.Clear();
1293
1294   MESSAGE( "::TriToQuad()" );
1295
1296   if ( !theCrit.get() )
1297     return false;
1298
1299   SMESHDS_Mesh * aMesh = GetMeshDS();
1300   //LinkID_Gen aLinkID_Gen( aMesh );
1301
1302   // Prepare data for algo: build
1303   // 1. map of elements with their linkIDs
1304   // 2. map of linkIDs with their elements
1305
1306   //map< long, list< const SMDS_MeshElement* > > mapLi_listEl;
1307   //map< long, list< const SMDS_MeshElement* > >::iterator itLE;
1308   //map< const SMDS_MeshElement*, set< long > >  mapEl_setLi;
1309   //map< const SMDS_MeshElement*, set< long > >::iterator itEL;
1310
1311   map< NLink, list< const SMDS_MeshElement* > > mapLi_listEl;
1312   map< NLink, list< const SMDS_MeshElement* > >::iterator itLE;
1313   map< const SMDS_MeshElement*, set< NLink > >  mapEl_setLi;
1314   map< const SMDS_MeshElement*, set< NLink > >::iterator itEL;
1315
1316   TIDSortedElemSet::iterator itElem;
1317   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
1318     const SMDS_MeshElement* elem = *itElem;
1319     //if ( !elem || elem->NbNodes() != 3 )
1320     //  continue;
1321     if(!elem || elem->GetType() != SMDSAbs_Face ) continue;
1322     bool IsTria = elem->NbNodes()==3 || (elem->NbNodes()==6 && elem->IsQuadratic());
1323     if(!IsTria) continue;
1324
1325     // retrieve element nodes
1326     const SMDS_MeshNode* aNodes [4];
1327     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1328     int i = 0;
1329     //while ( itN->more() )
1330     while ( i<3 )
1331       aNodes[ i++ ] = static_cast<const SMDS_MeshNode*>( itN->next() );
1332     ASSERT( i == 3 );
1333     aNodes[ 3 ] = aNodes[ 0 ];
1334
1335     // fill maps
1336     for ( i = 0; i < 3; i++ ) {
1337       //long linkID = aLinkID_Gen.GetLinkID( aNodes[ i ], aNodes[ i+1 ] );
1338       NLink link(( aNodes[i] < aNodes[i+1] ? aNodes[i] : aNodes[i+1] ),
1339                  ( aNodes[i] < aNodes[i+1] ? aNodes[i+1] : aNodes[i] ));
1340       // check if elements sharing a link can be fused
1341       //itLE = mapLi_listEl.find( linkID );
1342       itLE = mapLi_listEl.find( link );
1343       if ( itLE != mapLi_listEl.end() ) {
1344         if ((*itLE).second.size() > 1 ) // consider only 2 elems adjacent by a link
1345           continue;
1346         const SMDS_MeshElement* elem2 = (*itLE).second.front();
1347         //if ( FindShape( elem ) != FindShape( elem2 ))
1348         //  continue; // do not fuse triangles laying on different shapes
1349         if ( getAngle( elem, elem2, aNodes[i], aNodes[i+1] ) > theMaxAngle )
1350           continue; // avoid making badly shaped quads
1351         (*itLE).second.push_back( elem );
1352       }
1353       else {
1354         //mapLi_listEl[ linkID ].push_back( elem );
1355         mapLi_listEl[ link ].push_back( elem );
1356       }
1357       //mapEl_setLi [ elem ].insert( linkID );
1358       mapEl_setLi [ elem ].insert( link );
1359     }
1360   }
1361   // Clean the maps from the links shared by a sole element, ie
1362   // links to which only one element is bound in mapLi_listEl
1363
1364   for ( itLE = mapLi_listEl.begin(); itLE != mapLi_listEl.end(); itLE++ ) {
1365     int nbElems = (*itLE).second.size();
1366     if ( nbElems < 2  ) {
1367       const SMDS_MeshElement* elem = (*itLE).second.front();
1368       //long link = (*itLE).first;
1369       NLink link = (*itLE).first;
1370       mapEl_setLi[ elem ].erase( link );
1371       if ( mapEl_setLi[ elem ].empty() )
1372         mapEl_setLi.erase( elem );
1373     }
1374   }
1375
1376   // Algo: fuse triangles into quadrangles
1377
1378   while ( ! mapEl_setLi.empty() ) {
1379     // Look for the start element:
1380     // the element having the least nb of shared links
1381
1382     const SMDS_MeshElement* startElem = 0;
1383     int minNbLinks = 4;
1384     for ( itEL = mapEl_setLi.begin(); itEL != mapEl_setLi.end(); itEL++ ) {
1385       int nbLinks = (*itEL).second.size();
1386       if ( nbLinks < minNbLinks ) {
1387         startElem = (*itEL).first;
1388         minNbLinks = nbLinks;
1389         if ( minNbLinks == 1 )
1390           break;
1391       }
1392     }
1393
1394     // search elements to fuse starting from startElem or links of elements
1395     // fused earlyer - startLinks
1396     //list< long > startLinks;
1397     list< NLink > startLinks;
1398     while ( startElem || !startLinks.empty() ) {
1399       while ( !startElem && !startLinks.empty() ) {
1400         // Get an element to start, by a link
1401         //long linkId = startLinks.front();
1402         NLink linkId = startLinks.front();
1403         startLinks.pop_front();
1404         itLE = mapLi_listEl.find( linkId );
1405         if ( itLE != mapLi_listEl.end() ) {
1406           list< const SMDS_MeshElement* > & listElem = (*itLE).second;
1407           list< const SMDS_MeshElement* >::iterator itE = listElem.begin();
1408           for ( ; itE != listElem.end() ; itE++ )
1409             if ( mapEl_setLi.find( (*itE) ) != mapEl_setLi.end() )
1410               startElem = (*itE);
1411           mapLi_listEl.erase( itLE );
1412         }
1413       }
1414
1415       if ( startElem ) {
1416         // Get candidates to be fused
1417         const SMDS_MeshElement *tr1 = startElem, *tr2 = 0, *tr3 = 0;
1418         //long link12, link13;
1419         NLink link12, link13;
1420         startElem = 0;
1421         ASSERT( mapEl_setLi.find( tr1 ) != mapEl_setLi.end() );
1422         //set< long >& setLi = mapEl_setLi[ tr1 ];
1423         set< NLink >& setLi = mapEl_setLi[ tr1 ];
1424         ASSERT( !setLi.empty() );
1425         //set< long >::iterator itLi;
1426         set< NLink >::iterator itLi;
1427         for ( itLi = setLi.begin(); itLi != setLi.end(); itLi++ ) {
1428           //long linkID = (*itLi);
1429           NLink linkID = (*itLi);
1430           itLE = mapLi_listEl.find( linkID );
1431           if ( itLE == mapLi_listEl.end() )
1432             continue;
1433
1434           const SMDS_MeshElement* elem = (*itLE).second.front();
1435           if ( elem == tr1 )
1436             elem = (*itLE).second.back();
1437           mapLi_listEl.erase( itLE );
1438           if ( mapEl_setLi.find( elem ) == mapEl_setLi.end())
1439             continue;
1440           if ( tr2 ) {
1441             tr3 = elem;
1442             link13 = linkID;
1443           }
1444           else {
1445             tr2 = elem;
1446             link12 = linkID;
1447           }
1448
1449           // add other links of elem to list of links to re-start from
1450           //set< long >& links = mapEl_setLi[ elem ];
1451           //set< long >::iterator it;
1452           set< NLink >& links = mapEl_setLi[ elem ];
1453           set< NLink >::iterator it;
1454           for ( it = links.begin(); it != links.end(); it++ ) {
1455             //long linkID2 = (*it);
1456             NLink linkID2 = (*it);
1457             if ( linkID2 != linkID )
1458               startLinks.push_back( linkID2 );
1459           }
1460         }
1461
1462         // Get nodes of possible quadrangles
1463         const SMDS_MeshNode *n12 [4], *n13 [4];
1464         bool Ok12 = false, Ok13 = false;
1465         //const SMDS_MeshNode *linkNode1, *linkNode2;
1466         const SMDS_MeshNode *linkNode1, *linkNode2;
1467         if(tr2) {
1468           //const SMDS_MeshNode *linkNode1 = link12.first;
1469           //const SMDS_MeshNode *linkNode2 = link12.second;
1470           linkNode1 = link12.first;
1471           linkNode2 = link12.second;
1472           //if ( tr2 &&
1473           //     aLinkID_Gen.GetNodes( link12, linkNode1, linkNode2 ) &&
1474           //     getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
1475           //  Ok12 = true;
1476           if ( tr2 && getQuadrangleNodes( n12, linkNode1, linkNode2, tr1, tr2 ))
1477             Ok12 = true;
1478         }
1479         if(tr3) {
1480           linkNode1 = link13.first;
1481           linkNode2 = link13.second;
1482           //if ( tr3 &&
1483           //     aLinkID_Gen.GetNodes( link13, linkNode1, linkNode2 ) &&
1484           //     getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
1485           //  Ok13 = true;
1486           if ( tr3 && getQuadrangleNodes( n13, linkNode1, linkNode2, tr1, tr3 ))
1487             Ok13 = true;
1488         }
1489
1490         // Choose a pair to fuse
1491         if ( Ok12 && Ok13 ) {
1492           SMDS_FaceOfNodes quad12 ( n12[ 0 ], n12[ 1 ], n12[ 2 ], n12[ 3 ] );
1493           SMDS_FaceOfNodes quad13 ( n13[ 0 ], n13[ 1 ], n13[ 2 ], n13[ 3 ] );
1494           double aBadRate12 = getBadRate( &quad12, theCrit );
1495           double aBadRate13 = getBadRate( &quad13, theCrit );
1496           if (  aBadRate13 < aBadRate12 )
1497             Ok12 = false;
1498           else
1499             Ok13 = false;
1500         }
1501
1502         // Make quadrangles
1503         // and remove fused elems and removed links from the maps
1504         mapEl_setLi.erase( tr1 );
1505         if ( Ok12 ) {
1506           mapEl_setLi.erase( tr2 );
1507           mapLi_listEl.erase( link12 );
1508           if(tr1->NbNodes()==3) {
1509             if( tr1->GetID() < tr2->GetID() ) {
1510               aMesh->ChangeElementNodes( tr1, n12, 4 );
1511               myLastCreatedElems.Append(tr1);
1512               aMesh->RemoveElement( tr2 );
1513             }
1514             else {
1515               aMesh->ChangeElementNodes( tr2, n12, 4 );
1516               myLastCreatedElems.Append(tr2);
1517               aMesh->RemoveElement( tr1);
1518             }
1519           }
1520           else {
1521             const SMDS_MeshNode* N1 [6];
1522             const SMDS_MeshNode* N2 [6];
1523             GetNodesFromTwoTria(tr1,tr2,N1,N2);
1524             // now we receive following N1 and N2 (using numeration as above image)
1525             // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6) 
1526             // i.e. first nodes from both arrays determ new diagonal
1527             const SMDS_MeshNode* aNodes[8];
1528             aNodes[0] = N1[0];
1529             aNodes[1] = N1[1];
1530             aNodes[2] = N2[0];
1531             aNodes[3] = N2[1];
1532             aNodes[4] = N1[3];
1533             aNodes[5] = N2[5];
1534             aNodes[6] = N2[3];
1535             aNodes[7] = N1[5];
1536             if( tr1->GetID() < tr2->GetID() ) {
1537               GetMeshDS()->ChangeElementNodes( tr1, aNodes, 8 );
1538               myLastCreatedElems.Append(tr1);
1539               GetMeshDS()->RemoveElement( tr2 );
1540             }
1541             else {
1542               GetMeshDS()->ChangeElementNodes( tr2, aNodes, 8 );
1543               myLastCreatedElems.Append(tr2);
1544               GetMeshDS()->RemoveElement( tr1 );
1545             }
1546             // remove middle node (9)
1547             GetMeshDS()->RemoveNode( N1[4] );
1548           }
1549         }
1550         else if ( Ok13 ) {
1551           mapEl_setLi.erase( tr3 );
1552           mapLi_listEl.erase( link13 );
1553           if(tr1->NbNodes()==3) {
1554             if( tr1->GetID() < tr2->GetID() ) {
1555               aMesh->ChangeElementNodes( tr1, n13, 4 );
1556               myLastCreatedElems.Append(tr1);
1557               aMesh->RemoveElement( tr3 );
1558             }
1559             else {
1560               aMesh->ChangeElementNodes( tr3, n13, 4 );
1561               myLastCreatedElems.Append(tr3);
1562               aMesh->RemoveElement( tr1 );
1563             }
1564           }
1565           else {
1566             const SMDS_MeshNode* N1 [6];
1567             const SMDS_MeshNode* N2 [6];
1568             GetNodesFromTwoTria(tr1,tr3,N1,N2);
1569             // now we receive following N1 and N2 (using numeration as above image)
1570             // tria1 : (1 2 4 5 9 7)  and  tria2 : (3 4 2 8 9 6) 
1571             // i.e. first nodes from both arrays determ new diagonal
1572             const SMDS_MeshNode* aNodes[8];
1573             aNodes[0] = N1[0];
1574             aNodes[1] = N1[1];
1575             aNodes[2] = N2[0];
1576             aNodes[3] = N2[1];
1577             aNodes[4] = N1[3];
1578             aNodes[5] = N2[5];
1579             aNodes[6] = N2[3];
1580             aNodes[7] = N1[5];
1581             if( tr1->GetID() < tr2->GetID() ) {
1582               GetMeshDS()->ChangeElementNodes( tr1, aNodes, 8 );
1583               myLastCreatedElems.Append(tr1);
1584               GetMeshDS()->RemoveElement( tr3 );
1585             }
1586             else {
1587               GetMeshDS()->ChangeElementNodes( tr3, aNodes, 8 );
1588               myLastCreatedElems.Append(tr3);
1589               GetMeshDS()->RemoveElement( tr1 );
1590             }
1591             // remove middle node (9)
1592             GetMeshDS()->RemoveNode( N1[4] );
1593           }
1594         }
1595
1596         // Next element to fuse: the rejected one
1597         if ( tr3 )
1598           startElem = Ok12 ? tr3 : tr2;
1599
1600       } // if ( startElem )
1601     } // while ( startElem || !startLinks.empty() )
1602   } // while ( ! mapEl_setLi.empty() )
1603
1604   return true;
1605 }
1606
1607
1608 /*#define DUMPSO(txt) \
1609 //  cout << txt << endl;
1610 //=============================================================================
1611 //
1612 //
1613 //
1614 //=============================================================================
1615 static void swap( int i1, int i2, int idNodes[], gp_Pnt P[] )
1616 {
1617   if ( i1 == i2 )
1618     return;
1619   int tmp = idNodes[ i1 ];
1620   idNodes[ i1 ] = idNodes[ i2 ];
1621   idNodes[ i2 ] = tmp;
1622   gp_Pnt Ptmp = P[ i1 ];
1623   P[ i1 ] = P[ i2 ];
1624   P[ i2 ] = Ptmp;
1625   DUMPSO( i1 << "(" << idNodes[ i2 ] << ") <-> " << i2 << "(" << idNodes[ i1 ] << ")");
1626 }
1627
1628 //=======================================================================
1629 //function : SortQuadNodes
1630 //purpose  : Set 4 nodes of a quadrangle face in a good order.
1631 //           Swap 1<->2 or 2<->3 nodes and correspondingly return
1632 //           1 or 2 else 0.
1633 //=======================================================================
1634
1635 int SMESH_MeshEditor::SortQuadNodes (const SMDS_Mesh * theMesh,
1636                                      int               idNodes[] )
1637 {
1638   gp_Pnt P[4];
1639   int i;
1640   for ( i = 0; i < 4; i++ ) {
1641     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1642     if ( !n ) return 0;
1643     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1644   }
1645
1646   gp_Vec V1(P[0], P[1]);
1647   gp_Vec V2(P[0], P[2]);
1648   gp_Vec V3(P[0], P[3]);
1649
1650   gp_Vec Cross1 = V1 ^ V2;
1651   gp_Vec Cross2 = V2 ^ V3;
1652
1653   i = 0;
1654   if (Cross1.Dot(Cross2) < 0)
1655   {
1656     Cross1 = V2 ^ V1;
1657     Cross2 = V1 ^ V3;
1658
1659     if (Cross1.Dot(Cross2) < 0)
1660       i = 2;
1661     else
1662       i = 1;
1663     swap ( i, i + 1, idNodes, P );
1664
1665 //     for ( int ii = 0; ii < 4; ii++ ) {
1666 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1667 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1668 //     }
1669   }
1670   return i;
1671 }
1672
1673 //=======================================================================
1674 //function : SortHexaNodes
1675 //purpose  : Set 8 nodes of a hexahedron in a good order.
1676 //           Return success status
1677 //=======================================================================
1678
1679 bool SMESH_MeshEditor::SortHexaNodes (const SMDS_Mesh * theMesh,
1680                                       int               idNodes[] )
1681 {
1682   gp_Pnt P[8];
1683   int i;
1684   DUMPSO( "INPUT: ========================================");
1685   for ( i = 0; i < 8; i++ ) {
1686     const SMDS_MeshNode *n = theMesh->FindNode( idNodes[i] );
1687     if ( !n ) return false;
1688     P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
1689     DUMPSO( i << "(" << idNodes[i] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1690   }
1691   DUMPSO( "========================================");
1692
1693
1694   set<int> faceNodes;  // ids of bottom face nodes, to be found
1695   set<int> checkedId1; // ids of tried 2-nd nodes
1696   Standard_Real leastDist = DBL_MAX; // dist of the 4-th node from 123 plane
1697   const Standard_Real tol = 1.e-6;   // tolerance to find nodes in plane
1698   int iMin, iLoop1 = 0;
1699
1700   // Loop to try the 2-nd nodes
1701
1702   while ( leastDist > DBL_MIN && ++iLoop1 < 8 )
1703   {
1704     // Find not checked 2-nd node
1705     for ( i = 1; i < 8; i++ )
1706       if ( checkedId1.find( idNodes[i] ) == checkedId1.end() ) {
1707         int id1 = idNodes[i];
1708         swap ( 1, i, idNodes, P );
1709         checkedId1.insert ( id1 );
1710         break;
1711       }
1712
1713     // Find the 3-d node so that 1-2-3 triangle to be on a hexa face,
1714     // ie that all but meybe one (id3 which is on the same face) nodes
1715     // lay on the same side from the triangle plane.
1716
1717     bool manyInPlane = false; // more than 4 nodes lay in plane
1718     int iLoop2 = 0;
1719     while ( ++iLoop2 < 6 ) {
1720
1721       // get 1-2-3 plane coeffs
1722       Standard_Real A, B, C, D;
1723       gp_Vec N = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1724       if ( N.SquareMagnitude() > gp::Resolution() )
1725       {
1726         gp_Pln pln ( P[0], N );
1727         pln.Coefficients( A, B, C, D );
1728
1729         // find the node (iMin) closest to pln
1730         Standard_Real dist[ 8 ], minDist = DBL_MAX;
1731         set<int> idInPln;
1732         for ( i = 3; i < 8; i++ ) {
1733           dist[i] = A * P[i].X() + B * P[i].Y() + C * P[i].Z() + D;
1734           if ( fabs( dist[i] ) < minDist ) {
1735             minDist = fabs( dist[i] );
1736             iMin = i;
1737           }
1738           if ( fabs( dist[i] ) <= tol )
1739             idInPln.insert( idNodes[i] );
1740         }
1741
1742         // there should not be more than 4 nodes in bottom plane
1743         if ( idInPln.size() > 1 )
1744         {
1745           DUMPSO( "### idInPln.size() = " << idInPln.size());
1746           // idInPlane does not contain the first 3 nodes
1747           if ( manyInPlane || idInPln.size() == 5)
1748             return false; // all nodes in one plane
1749           manyInPlane = true;
1750
1751           // set the 1-st node to be not in plane
1752           for ( i = 3; i < 8; i++ ) {
1753             if ( idInPln.find( idNodes[ i ] ) == idInPln.end() ) {
1754               DUMPSO( "### Reset 0-th node");
1755               swap( 0, i, idNodes, P );
1756               break;
1757             }
1758           }
1759
1760           // reset to re-check second nodes
1761           leastDist = DBL_MAX;
1762           faceNodes.clear();
1763           checkedId1.clear();
1764           iLoop1 = 0;
1765           break; // from iLoop2;
1766         }
1767
1768         // check that the other 4 nodes are on the same side
1769         bool sameSide = true;
1770         bool isNeg = dist[ iMin == 3 ? 4 : 3 ] <= 0.;
1771         for ( i = 3; sameSide && i < 8; i++ ) {
1772           if ( i != iMin )
1773             sameSide = ( isNeg == dist[i] <= 0.);
1774         }
1775
1776         // keep best solution
1777         if ( sameSide && minDist < leastDist ) {
1778           leastDist = minDist;
1779           faceNodes.clear();
1780           faceNodes.insert( idNodes[ 1 ] );
1781           faceNodes.insert( idNodes[ 2 ] );
1782           faceNodes.insert( idNodes[ iMin ] );
1783           DUMPSO( "loop " << iLoop2 << " id2 " << idNodes[ 1 ] << " id3 " << idNodes[ 2 ]
1784             << " leastDist = " << leastDist);
1785           if ( leastDist <= DBL_MIN )
1786             break;
1787         }
1788       }
1789
1790       // set next 3-d node to check
1791       int iNext = 2 + iLoop2;
1792       if ( iNext < 8 ) {
1793         DUMPSO( "Try 2-nd");
1794         swap ( 2, iNext, idNodes, P );
1795       }
1796     } // while ( iLoop2 < 6 )
1797   } // iLoop1
1798
1799   if ( faceNodes.empty() ) return false;
1800
1801   // Put the faceNodes in proper places
1802   for ( i = 4; i < 8; i++ ) {
1803     if ( faceNodes.find( idNodes[ i ] ) != faceNodes.end() ) {
1804       // find a place to put
1805       int iTo = 1;
1806       while ( faceNodes.find( idNodes[ iTo ] ) != faceNodes.end() )
1807         iTo++;
1808       DUMPSO( "Set faceNodes");
1809       swap ( iTo, i, idNodes, P );
1810     }
1811   }
1812
1813
1814   // Set nodes of the found bottom face in good order
1815   DUMPSO( " Found bottom face: ");
1816   i = SortQuadNodes( theMesh, idNodes );
1817   if ( i ) {
1818     gp_Pnt Ptmp = P[ i ];
1819     P[ i ] = P[ i+1 ];
1820     P[ i+1 ] = Ptmp;
1821   }
1822 //   else
1823 //     for ( int ii = 0; ii < 4; ii++ ) {
1824 //       const SMDS_MeshNode *n = theMesh->FindNode( idNodes[ii] );
1825 //       DUMPSO( ii << "(" << idNodes[ii] <<") : "<<n->X()<<" "<<n->Y()<<" "<<n->Z());
1826 //    }
1827
1828   // Gravity center of the top and bottom faces
1829   gp_Pnt aGCb = ( P[0].XYZ() + P[1].XYZ() + P[2].XYZ() + P[3].XYZ() ) / 4.;
1830   gp_Pnt aGCt = ( P[4].XYZ() + P[5].XYZ() + P[6].XYZ() + P[7].XYZ() ) / 4.;
1831
1832   // Get direction from the bottom to the top face
1833   gp_Vec upDir ( aGCb, aGCt );
1834   Standard_Real upDirSize = upDir.Magnitude();
1835   if ( upDirSize <= gp::Resolution() ) return false;
1836   upDir / upDirSize;
1837
1838   // Assure that the bottom face normal points up
1839   gp_Vec Nb = gp_Vec (P[0], P[1]).Crossed( gp_Vec (P[0], P[2]) );
1840   Nb += gp_Vec (P[0], P[2]).Crossed( gp_Vec (P[0], P[3]) );
1841   if ( Nb.Dot( upDir ) < 0 ) {
1842     DUMPSO( "Reverse bottom face");
1843     swap( 1, 3, idNodes, P );
1844   }
1845
1846   // Find 5-th node - the one closest to the 1-st among the last 4 nodes.
1847   Standard_Real minDist = DBL_MAX;
1848   for ( i = 4; i < 8; i++ ) {
1849     // projection of P[i] to the plane defined by P[0] and upDir
1850     gp_Pnt Pp = P[i].Translated( upDir * ( upDir.Dot( gp_Vec( P[i], P[0] ))));
1851     Standard_Real sqDist = P[0].SquareDistance( Pp );
1852     if ( sqDist < minDist ) {
1853       minDist = sqDist;
1854       iMin = i;
1855     }
1856   }
1857   DUMPSO( "Set 4-th");
1858   swap ( 4, iMin, idNodes, P );
1859
1860   // Set nodes of the top face in good order
1861   DUMPSO( "Sort top face");
1862   i = SortQuadNodes( theMesh, &idNodes[4] );
1863   if ( i ) {
1864     i += 4;
1865     gp_Pnt Ptmp = P[ i ];
1866     P[ i ] = P[ i+1 ];
1867     P[ i+1 ] = Ptmp;
1868   }
1869
1870   // Assure that direction of the top face normal is from the bottom face
1871   gp_Vec Nt = gp_Vec (P[4], P[5]).Crossed( gp_Vec (P[4], P[6]) );
1872   Nt += gp_Vec (P[4], P[6]).Crossed( gp_Vec (P[4], P[7]) );
1873   if ( Nt.Dot( upDir ) < 0 ) {
1874     DUMPSO( "Reverse top face");
1875     swap( 5, 7, idNodes, P );
1876   }
1877
1878 //   DUMPSO( "OUTPUT: ========================================");
1879 //   for ( i = 0; i < 8; i++ ) {
1880 //     float *p = ugrid->GetPoint(idNodes[i]);
1881 //     DUMPSO( i << "(" << idNodes[i] << ") : " << p[0] << " " << p[1] << " " << p[2]);
1882 //   }
1883
1884   return true;
1885 }*/
1886
1887 //=======================================================================
1888 //function : laplacianSmooth
1889 //purpose  : pulls theNode toward the center of surrounding nodes directly
1890 //           connected to that node along an element edge
1891 //=======================================================================
1892
1893 void laplacianSmooth(const SMDS_MeshNode*                 theNode,
1894                      const Handle(Geom_Surface)&          theSurface,
1895                      map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1896 {
1897   // find surrounding nodes
1898
1899   set< const SMDS_MeshNode* > nodeSet;
1900   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator(SMDSAbs_Face);
1901   while ( elemIt->more() )
1902   {
1903     const SMDS_MeshElement* elem = elemIt->next();
1904
1905     for ( int i = 0; i < elem->NbNodes(); ++i ) {
1906       if ( elem->GetNode( i ) == theNode ) {
1907         // add linked nodes
1908         int iBefore = i - 1;
1909         int iAfter = i + 1;
1910         if ( elem->IsQuadratic() ) {
1911           int nbCorners = elem->NbNodes() / 2;
1912           if ( iAfter >= nbCorners )
1913             iAfter = 0; // elem->GetNode() wraps index
1914           if ( iBefore == -1 )
1915             iBefore = nbCorners - 1;
1916         }
1917         nodeSet.insert( elem->GetNode( iAfter ));
1918         nodeSet.insert( elem->GetNode( iBefore ));
1919         break;
1920       }
1921     }
1922   }
1923
1924   // compute new coodrs
1925
1926   double coord[] = { 0., 0., 0. };
1927   set< const SMDS_MeshNode* >::iterator nodeSetIt = nodeSet.begin();
1928   for ( ; nodeSetIt != nodeSet.end(); nodeSetIt++ ) {
1929     const SMDS_MeshNode* node = (*nodeSetIt);
1930     if ( theSurface.IsNull() ) { // smooth in 3D
1931       coord[0] += node->X();
1932       coord[1] += node->Y();
1933       coord[2] += node->Z();
1934     }
1935     else { // smooth in 2D
1936       ASSERT( theUVMap.find( node ) != theUVMap.end() );
1937       gp_XY* uv = theUVMap[ node ];
1938       coord[0] += uv->X();
1939       coord[1] += uv->Y();
1940     }
1941   }
1942   int nbNodes = nodeSet.size();
1943   if ( !nbNodes )
1944     return;
1945   coord[0] /= nbNodes;
1946   coord[1] /= nbNodes;
1947
1948   if ( !theSurface.IsNull() ) {
1949     ASSERT( theUVMap.find( theNode ) != theUVMap.end() );
1950     theUVMap[ theNode ]->SetCoord( coord[0], coord[1] );
1951     gp_Pnt p3d = theSurface->Value( coord[0], coord[1] );
1952     coord[0] = p3d.X();
1953     coord[1] = p3d.Y();
1954     coord[2] = p3d.Z();
1955   }
1956   else
1957     coord[2] /= nbNodes;
1958
1959   // move node
1960
1961   const_cast< SMDS_MeshNode* >( theNode )->setXYZ(coord[0],coord[1],coord[2]);
1962 }
1963
1964 //=======================================================================
1965 //function : centroidalSmooth
1966 //purpose  : pulls theNode toward the element-area-weighted centroid of the
1967 //           surrounding elements
1968 //=======================================================================
1969
1970 void centroidalSmooth(const SMDS_MeshNode*                 theNode,
1971                       const Handle(Geom_Surface)&          theSurface,
1972                       map< const SMDS_MeshNode*, gp_XY* >& theUVMap)
1973 {
1974   gp_XYZ aNewXYZ(0.,0.,0.);
1975   SMESH::Controls::Area anAreaFunc;
1976   double totalArea = 0.;
1977   int nbElems = 0;
1978
1979   // compute new XYZ
1980
1981   SMDS_ElemIteratorPtr elemIt = theNode->GetInverseElementIterator(SMDSAbs_Face);
1982   while ( elemIt->more() )
1983   {
1984     const SMDS_MeshElement* elem = elemIt->next();
1985     nbElems++;
1986
1987     gp_XYZ elemCenter(0.,0.,0.);
1988     SMESH::Controls::TSequenceOfXYZ aNodePoints;
1989     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
1990     int nn = elem->NbNodes();
1991     if(elem->IsQuadratic()) nn = nn/2;
1992     int i=0;
1993     //while ( itN->more() ) {
1994     while ( i<nn ) {
1995       const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( itN->next() );
1996       i++;
1997       gp_XYZ aP( aNode->X(), aNode->Y(), aNode->Z() );
1998       aNodePoints.push_back( aP );
1999       if ( !theSurface.IsNull() ) { // smooth in 2D
2000         ASSERT( theUVMap.find( aNode ) != theUVMap.end() );
2001         gp_XY* uv = theUVMap[ aNode ];
2002         aP.SetCoord( uv->X(), uv->Y(), 0. );
2003       }
2004       elemCenter += aP;
2005     }
2006     double elemArea = anAreaFunc.GetValue( aNodePoints );
2007     totalArea += elemArea;
2008     elemCenter /= nn;
2009     aNewXYZ += elemCenter * elemArea;
2010   }
2011   aNewXYZ /= totalArea;
2012   if ( !theSurface.IsNull() ) {
2013     theUVMap[ theNode ]->SetCoord( aNewXYZ.X(), aNewXYZ.Y() );
2014     aNewXYZ = theSurface->Value( aNewXYZ.X(), aNewXYZ.Y() ).XYZ();
2015   }
2016
2017   // move node
2018
2019   const_cast< SMDS_MeshNode* >( theNode )->setXYZ(aNewXYZ.X(),aNewXYZ.Y(),aNewXYZ.Z());
2020 }
2021
2022 //=======================================================================
2023 //function : getClosestUV
2024 //purpose  : return UV of closest projection
2025 //=======================================================================
2026
2027 static bool getClosestUV (Extrema_GenExtPS& projector,
2028                           const gp_Pnt&     point,
2029                           gp_XY &           result)
2030 {
2031   projector.Perform( point );
2032   if ( projector.IsDone() ) {
2033     double u, v, minVal = DBL_MAX;
2034     for ( int i = projector.NbExt(); i > 0; i-- )
2035       if ( projector.Value( i ) < minVal ) {
2036         minVal = projector.Value( i );
2037         projector.Point( i ).Parameter( u, v );
2038       }
2039     result.SetCoord( u, v );
2040     return true;
2041   }
2042   return false;
2043 }
2044
2045 //=======================================================================
2046 //function : Smooth
2047 //purpose  : Smooth theElements during theNbIterations or until a worst
2048 //           element has aspect ratio <= theTgtAspectRatio.
2049 //           Aspect Ratio varies in range [1.0, inf].
2050 //           If theElements is empty, the whole mesh is smoothed.
2051 //           theFixedNodes contains additionally fixed nodes. Nodes built
2052 //           on edges and boundary nodes are always fixed.
2053 //=======================================================================
2054
2055 void SMESH_MeshEditor::Smooth (TIDSortedElemSet &          theElems,
2056                                set<const SMDS_MeshNode*> & theFixedNodes,
2057                                const SmoothMethod          theSmoothMethod,
2058                                const int                   theNbIterations,
2059                                double                      theTgtAspectRatio,
2060                                const bool                  the2D)
2061 {
2062   myLastCreatedElems.Clear();
2063   myLastCreatedNodes.Clear();
2064
2065   MESSAGE((theSmoothMethod==LAPLACIAN ? "LAPLACIAN" : "CENTROIDAL") << "--::Smooth()");
2066
2067   if ( theTgtAspectRatio < 1.0 )
2068     theTgtAspectRatio = 1.0;
2069
2070   const double disttol = 1.e-16;
2071
2072   SMESH::Controls::AspectRatio aQualityFunc;
2073
2074   SMESHDS_Mesh* aMesh = GetMeshDS();
2075
2076   if ( theElems.empty() ) {
2077     // add all faces to theElems
2078     SMDS_FaceIteratorPtr fIt = aMesh->facesIterator();
2079     while ( fIt->more() ) {
2080       const SMDS_MeshElement* face = fIt->next();
2081       theElems.insert( face );
2082     }
2083   }
2084   // get all face ids theElems are on
2085   set< int > faceIdSet;
2086   TIDSortedElemSet::iterator itElem;
2087   if ( the2D )
2088     for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
2089       int fId = FindShape( *itElem );
2090       // check that corresponding submesh exists and a shape is face
2091       if (fId &&
2092           faceIdSet.find( fId ) == faceIdSet.end() &&
2093           aMesh->MeshElements( fId )) {
2094         TopoDS_Shape F = aMesh->IndexToShape( fId );
2095         if ( !F.IsNull() && F.ShapeType() == TopAbs_FACE )
2096           faceIdSet.insert( fId );
2097       }
2098     }
2099   faceIdSet.insert( 0 ); // to smooth elements that are not on any TopoDS_Face
2100
2101   // ===============================================
2102   // smooth elements on each TopoDS_Face separately
2103   // ===============================================
2104
2105   set< int >::reverse_iterator fId = faceIdSet.rbegin(); // treate 0 fId at the end
2106   for ( ; fId != faceIdSet.rend(); ++fId ) {
2107     // get face surface and submesh
2108     Handle(Geom_Surface) surface;
2109     SMESHDS_SubMesh* faceSubMesh = 0;
2110     TopoDS_Face face;
2111     double fToler2 = 0, vPeriod = 0., uPeriod = 0., f,l;
2112     double u1 = 0, u2 = 0, v1 = 0, v2 = 0;
2113     bool isUPeriodic = false, isVPeriodic = false;
2114     if ( *fId ) {
2115       face = TopoDS::Face( aMesh->IndexToShape( *fId ));
2116       surface = BRep_Tool::Surface( face );
2117       faceSubMesh = aMesh->MeshElements( *fId );
2118       fToler2 = BRep_Tool::Tolerance( face );
2119       fToler2 *= fToler2 * 10.;
2120       isUPeriodic = surface->IsUPeriodic();
2121       if ( isUPeriodic )
2122         vPeriod = surface->UPeriod();
2123       isVPeriodic = surface->IsVPeriodic();
2124       if ( isVPeriodic )
2125         uPeriod = surface->VPeriod();
2126       surface->Bounds( u1, u2, v1, v2 );
2127     }
2128     // ---------------------------------------------------------
2129     // for elements on a face, find movable and fixed nodes and
2130     // compute UV for them
2131     // ---------------------------------------------------------
2132     bool checkBoundaryNodes = false;
2133     bool isQuadratic = false;
2134     set<const SMDS_MeshNode*> setMovableNodes;
2135     map< const SMDS_MeshNode*, gp_XY* > uvMap, uvMap2;
2136     list< gp_XY > listUV; // uvs the 2 uvMaps refer to
2137     list< const SMDS_MeshElement* > elemsOnFace;
2138
2139     Extrema_GenExtPS projector;
2140     GeomAdaptor_Surface surfAdaptor;
2141     if ( !surface.IsNull() ) {
2142       surfAdaptor.Load( surface );
2143       projector.Initialize( surfAdaptor, 20,20, 1e-5,1e-5 );
2144     }
2145     int nbElemOnFace = 0;
2146     itElem = theElems.begin();
2147      // loop on not yet smoothed elements: look for elems on a face
2148     while ( itElem != theElems.end() ) {
2149       if ( faceSubMesh && nbElemOnFace == faceSubMesh->NbElements() )
2150         break; // all elements found
2151
2152       const SMDS_MeshElement* elem = *itElem;
2153       if ( !elem || elem->GetType() != SMDSAbs_Face || elem->NbNodes() < 3 ||
2154           ( faceSubMesh && !faceSubMesh->Contains( elem ))) {
2155         ++itElem;
2156         continue;
2157       }
2158       elemsOnFace.push_back( elem );
2159       theElems.erase( itElem++ );
2160       nbElemOnFace++;
2161
2162       if ( !isQuadratic )
2163         isQuadratic = elem->IsQuadratic();
2164
2165       // get movable nodes of elem
2166       const SMDS_MeshNode* node;
2167       SMDS_TypeOfPosition posType;
2168       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
2169       int nn = 0, nbn =  elem->NbNodes();
2170       if(elem->IsQuadratic())
2171         nbn = nbn/2;
2172       while ( nn++ < nbn ) {
2173         node = static_cast<const SMDS_MeshNode*>( itN->next() );
2174         const SMDS_PositionPtr& pos = node->GetPosition();
2175         posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
2176         if (posType != SMDS_TOP_EDGE &&
2177             posType != SMDS_TOP_VERTEX &&
2178             theFixedNodes.find( node ) == theFixedNodes.end())
2179         {
2180           // check if all faces around the node are on faceSubMesh
2181           // because a node on edge may be bound to face
2182           SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Face);
2183           bool all = true;
2184           if ( faceSubMesh ) {
2185             while ( eIt->more() && all ) {
2186               const SMDS_MeshElement* e = eIt->next();
2187               all = faceSubMesh->Contains( e );
2188             }
2189           }
2190           if ( all )
2191             setMovableNodes.insert( node );
2192           else
2193             checkBoundaryNodes = true;
2194         }
2195         if ( posType == SMDS_TOP_3DSPACE )
2196           checkBoundaryNodes = true;
2197       }
2198
2199       if ( surface.IsNull() )
2200         continue;
2201
2202       // get nodes to check UV
2203       list< const SMDS_MeshNode* > uvCheckNodes;
2204       itN = elem->nodesIterator();
2205       nn = 0; nbn =  elem->NbNodes();
2206       if(elem->IsQuadratic())
2207         nbn = nbn/2;
2208       while ( nn++ < nbn ) {
2209         node = static_cast<const SMDS_MeshNode*>( itN->next() );
2210         if ( uvMap.find( node ) == uvMap.end() )
2211           uvCheckNodes.push_back( node );
2212         // add nodes of elems sharing node
2213 //         SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Face);
2214 //         while ( eIt->more() ) {
2215 //           const SMDS_MeshElement* e = eIt->next();
2216 //           if ( e != elem ) {
2217 //             SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2218 //             while ( nIt->more() ) {
2219 //               const SMDS_MeshNode* n =
2220 //                 static_cast<const SMDS_MeshNode*>( nIt->next() );
2221 //               if ( uvMap.find( n ) == uvMap.end() )
2222 //                 uvCheckNodes.push_back( n );
2223 //             }
2224 //           }
2225 //         }
2226       }
2227       // check UV on face
2228       list< const SMDS_MeshNode* >::iterator n = uvCheckNodes.begin();
2229       for ( ; n != uvCheckNodes.end(); ++n ) {
2230         node = *n;
2231         gp_XY uv( 0, 0 );
2232         const SMDS_PositionPtr& pos = node->GetPosition();
2233         posType = pos.get() ? pos->GetTypeOfPosition() : SMDS_TOP_3DSPACE;
2234         // get existing UV
2235         switch ( posType ) {
2236         case SMDS_TOP_FACE: {
2237           SMDS_FacePosition* fPos = ( SMDS_FacePosition* ) pos.get();
2238           uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
2239           break;
2240         }
2241         case SMDS_TOP_EDGE: {
2242           TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
2243           Handle(Geom2d_Curve) pcurve;
2244           if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
2245             pcurve = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), face, f,l );
2246           if ( !pcurve.IsNull() ) {
2247             double u = (( SMDS_EdgePosition* ) pos.get() )->GetUParameter();
2248             uv = pcurve->Value( u ).XY();
2249           }
2250           break;
2251         }
2252         case SMDS_TOP_VERTEX: {
2253           TopoDS_Shape S = aMesh->IndexToShape( pos->GetShapeId() );
2254           if ( !S.IsNull() && S.ShapeType() == TopAbs_VERTEX )
2255             uv = BRep_Tool::Parameters( TopoDS::Vertex( S ), face ).XY();
2256           break;
2257         }
2258         default:;
2259         }
2260         // check existing UV
2261         bool project = true;
2262         gp_Pnt pNode ( node->X(), node->Y(), node->Z() );
2263         double dist1 = DBL_MAX, dist2 = 0;
2264         if ( posType != SMDS_TOP_3DSPACE ) {
2265           dist1 = pNode.SquareDistance( surface->Value( uv.X(), uv.Y() ));
2266           project = dist1 > fToler2;
2267         }
2268         if ( project ) { // compute new UV
2269           gp_XY newUV;
2270           if ( !getClosestUV( projector, pNode, newUV )) {
2271             MESSAGE("Node Projection Failed " << node);
2272           }
2273           else {
2274             if ( isUPeriodic )
2275               newUV.SetX( ElCLib::InPeriod( newUV.X(), u1, u2 ));
2276             if ( isVPeriodic )
2277               newUV.SetY( ElCLib::InPeriod( newUV.Y(), v1, v2 ));
2278             // check new UV
2279             if ( posType != SMDS_TOP_3DSPACE )
2280               dist2 = pNode.SquareDistance( surface->Value( newUV.X(), newUV.Y() ));
2281             if ( dist2 < dist1 )
2282               uv = newUV;
2283           }
2284         }
2285         // store UV in the map
2286         listUV.push_back( uv );
2287         uvMap.insert( make_pair( node, &listUV.back() ));
2288       }
2289     } // loop on not yet smoothed elements
2290
2291     if ( !faceSubMesh || nbElemOnFace != faceSubMesh->NbElements() )
2292       checkBoundaryNodes = true;
2293
2294     // fix nodes on mesh boundary
2295
2296     if ( checkBoundaryNodes ) {
2297       typedef pair<const SMDS_MeshNode*, const SMDS_MeshNode*> TLink;
2298       map< TLink, int > linkNbMap; // how many times a link encounters in elemsOnFace
2299       map< TLink, int >::iterator link_nb;
2300       // put all elements links to linkNbMap
2301       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
2302       for ( ; elemIt != elemsOnFace.end(); ++elemIt ) {
2303         const SMDS_MeshElement* elem = (*elemIt);
2304         int nbn =  elem->NbNodes();
2305         if(elem->IsQuadratic())
2306           nbn = nbn/2;
2307         // loop on elem links: insert them in linkNbMap
2308         const SMDS_MeshNode* curNode, *prevNode = elem->GetNode( nbn );
2309         for ( int iN = 0; iN < nbn; ++iN ) {
2310           curNode = elem->GetNode( iN );
2311           TLink link;
2312           if ( curNode < prevNode ) link = make_pair( curNode , prevNode );
2313           else                      link = make_pair( prevNode , curNode );
2314           prevNode = curNode;
2315           link_nb = linkNbMap.find( link );
2316           if ( link_nb == linkNbMap.end() )
2317             linkNbMap.insert( make_pair ( link, 1 ));
2318           else
2319             link_nb->second++;
2320         }
2321       }
2322       // remove nodes that are in links encountered only once from setMovableNodes
2323       for ( link_nb = linkNbMap.begin(); link_nb != linkNbMap.end(); ++link_nb ) {
2324         if ( link_nb->second == 1 ) {
2325           setMovableNodes.erase( link_nb->first.first );
2326           setMovableNodes.erase( link_nb->first.second );
2327         }
2328       }
2329     }
2330
2331     // -----------------------------------------------------
2332     // for nodes on seam edge, compute one more UV ( uvMap2 );
2333     // find movable nodes linked to nodes on seam and which
2334     // are to be smoothed using the second UV ( uvMap2 )
2335     // -----------------------------------------------------
2336
2337     set<const SMDS_MeshNode*> nodesNearSeam; // to smooth using uvMap2
2338     if ( !surface.IsNull() ) {
2339       TopExp_Explorer eExp( face, TopAbs_EDGE );
2340       for ( ; eExp.More(); eExp.Next() ) {
2341         TopoDS_Edge edge = TopoDS::Edge( eExp.Current() );
2342         if ( !BRep_Tool::IsClosed( edge, face ))
2343           continue;
2344         SMESHDS_SubMesh* sm = aMesh->MeshElements( edge );
2345         if ( !sm ) continue;
2346         // find out which parameter varies for a node on seam
2347         double f,l;
2348         gp_Pnt2d uv1, uv2;
2349         Handle(Geom2d_Curve) pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
2350         if ( pcurve.IsNull() ) continue;
2351         uv1 = pcurve->Value( f );
2352         edge.Reverse();
2353         pcurve = BRep_Tool::CurveOnSurface( edge, face, f, l );
2354         if ( pcurve.IsNull() ) continue;
2355         uv2 = pcurve->Value( f );
2356         int iPar = Abs( uv1.X() - uv2.X() ) > Abs( uv1.Y() - uv2.Y() ) ? 1 : 2;
2357         // assure uv1 < uv2
2358         if ( uv1.Coord( iPar ) > uv2.Coord( iPar )) {
2359           gp_Pnt2d tmp = uv1; uv1 = uv2; uv2 = tmp;
2360         }
2361         // get nodes on seam and its vertices
2362         list< const SMDS_MeshNode* > seamNodes;
2363         SMDS_NodeIteratorPtr nSeamIt = sm->GetNodes();
2364         while ( nSeamIt->more() ) {
2365           const SMDS_MeshNode* node = nSeamIt->next();
2366           if ( !isQuadratic || !IsMedium( node ))
2367             seamNodes.push_back( node );
2368         }
2369         TopExp_Explorer vExp( edge, TopAbs_VERTEX );
2370         for ( ; vExp.More(); vExp.Next() ) {
2371           sm = aMesh->MeshElements( vExp.Current() );
2372           if ( sm ) {
2373             nSeamIt = sm->GetNodes();
2374             while ( nSeamIt->more() )
2375               seamNodes.push_back( nSeamIt->next() );
2376           }
2377         }
2378         // loop on nodes on seam
2379         list< const SMDS_MeshNode* >::iterator noSeIt = seamNodes.begin();
2380         for ( ; noSeIt != seamNodes.end(); ++noSeIt ) {
2381           const SMDS_MeshNode* nSeam = *noSeIt;
2382           map< const SMDS_MeshNode*, gp_XY* >::iterator n_uv = uvMap.find( nSeam );
2383           if ( n_uv == uvMap.end() )
2384             continue;
2385           // set the first UV
2386           n_uv->second->SetCoord( iPar, uv1.Coord( iPar ));
2387           // set the second UV
2388           listUV.push_back( *n_uv->second );
2389           listUV.back().SetCoord( iPar, uv2.Coord( iPar ));
2390           if ( uvMap2.empty() )
2391             uvMap2 = uvMap; // copy the uvMap contents
2392           uvMap2[ nSeam ] = &listUV.back();
2393
2394           // collect movable nodes linked to ones on seam in nodesNearSeam
2395           SMDS_ElemIteratorPtr eIt = nSeam->GetInverseElementIterator(SMDSAbs_Face);
2396           while ( eIt->more() ) {
2397             const SMDS_MeshElement* e = eIt->next();
2398             int nbUseMap1 = 0, nbUseMap2 = 0;
2399             SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2400             int nn = 0, nbn =  e->NbNodes();
2401             if(e->IsQuadratic()) nbn = nbn/2;
2402             while ( nn++ < nbn )
2403             {
2404               const SMDS_MeshNode* n =
2405                 static_cast<const SMDS_MeshNode*>( nIt->next() );
2406               if (n == nSeam ||
2407                   setMovableNodes.find( n ) == setMovableNodes.end() )
2408                 continue;
2409               // add only nodes being closer to uv2 than to uv1
2410               gp_Pnt pMid (0.5 * ( n->X() + nSeam->X() ),
2411                            0.5 * ( n->Y() + nSeam->Y() ),
2412                            0.5 * ( n->Z() + nSeam->Z() ));
2413               gp_XY uv;
2414               getClosestUV( projector, pMid, uv );
2415               if ( uv.Coord( iPar ) > uvMap[ n ]->Coord( iPar ) ) {
2416                 nodesNearSeam.insert( n );
2417                 nbUseMap2++;
2418               }
2419               else
2420                 nbUseMap1++;
2421             }
2422             // for centroidalSmooth all element nodes must
2423             // be on one side of a seam
2424             if ( theSmoothMethod == CENTROIDAL && nbUseMap1 && nbUseMap2 ) {
2425               SMDS_ElemIteratorPtr nIt = e->nodesIterator();
2426               nn = 0;
2427               while ( nn++ < nbn ) {
2428                 const SMDS_MeshNode* n =
2429                   static_cast<const SMDS_MeshNode*>( nIt->next() );
2430                 setMovableNodes.erase( n );
2431               }
2432             }
2433           }
2434         } // loop on nodes on seam
2435       } // loop on edge of a face
2436     } // if ( !face.IsNull() )
2437
2438     if ( setMovableNodes.empty() ) {
2439       MESSAGE( "Face id : " << *fId << " - NO SMOOTHING: no nodes to move!!!");
2440       continue; // goto next face
2441     }
2442
2443     // -------------
2444     // SMOOTHING //
2445     // -------------
2446
2447     int it = -1;
2448     double maxRatio = -1., maxDisplacement = -1.;
2449     set<const SMDS_MeshNode*>::iterator nodeToMove;
2450     for ( it = 0; it < theNbIterations; it++ ) {
2451       maxDisplacement = 0.;
2452       nodeToMove = setMovableNodes.begin();
2453       for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ ) {
2454         const SMDS_MeshNode* node = (*nodeToMove);
2455         gp_XYZ aPrevPos ( node->X(), node->Y(), node->Z() );
2456
2457         // smooth
2458         bool map2 = ( nodesNearSeam.find( node ) != nodesNearSeam.end() );
2459         if ( theSmoothMethod == LAPLACIAN )
2460           laplacianSmooth( node, surface, map2 ? uvMap2 : uvMap );
2461         else
2462           centroidalSmooth( node, surface, map2 ? uvMap2 : uvMap );
2463
2464         // node displacement
2465         gp_XYZ aNewPos ( node->X(), node->Y(), node->Z() );
2466         Standard_Real aDispl = (aPrevPos - aNewPos).SquareModulus();
2467         if ( aDispl > maxDisplacement )
2468           maxDisplacement = aDispl;
2469       }
2470       // no node movement => exit
2471       //if ( maxDisplacement < 1.e-16 ) {
2472       if ( maxDisplacement < disttol ) {
2473         MESSAGE("-- no node movement --");
2474         break;
2475       }
2476
2477       // check elements quality
2478       maxRatio  = 0;
2479       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
2480       for ( ; elemIt != elemsOnFace.end(); ++elemIt ) {
2481         const SMDS_MeshElement* elem = (*elemIt);
2482         if ( !elem || elem->GetType() != SMDSAbs_Face )
2483           continue;
2484         SMESH::Controls::TSequenceOfXYZ aPoints;
2485         if ( aQualityFunc.GetPoints( elem, aPoints )) {
2486           double aValue = aQualityFunc.GetValue( aPoints );
2487           if ( aValue > maxRatio )
2488             maxRatio = aValue;
2489         }
2490       }
2491       if ( maxRatio <= theTgtAspectRatio ) {
2492         MESSAGE("-- quality achived --");
2493         break;
2494       }
2495       if (it+1 == theNbIterations) {
2496         MESSAGE("-- Iteration limit exceeded --");
2497       }
2498     } // smoothing iterations
2499
2500     MESSAGE(" Face id: " << *fId <<
2501             " Nb iterstions: " << it <<
2502             " Displacement: " << maxDisplacement <<
2503             " Aspect Ratio " << maxRatio);
2504
2505     // ---------------------------------------
2506     // new nodes positions are computed,
2507     // record movement in DS and set new UV
2508     // ---------------------------------------
2509     nodeToMove = setMovableNodes.begin();
2510     for ( ; nodeToMove != setMovableNodes.end(); nodeToMove++ ) {
2511       SMDS_MeshNode* node = const_cast< SMDS_MeshNode* > (*nodeToMove);
2512       aMesh->MoveNode( node, node->X(), node->Y(), node->Z() );
2513       map< const SMDS_MeshNode*, gp_XY* >::iterator node_uv = uvMap.find( node );
2514       if ( node_uv != uvMap.end() ) {
2515         gp_XY* uv = node_uv->second;
2516         node->SetPosition
2517           ( SMDS_PositionPtr( new SMDS_FacePosition( *fId, uv->X(), uv->Y() )));
2518       }
2519     }
2520
2521     // move medium nodes of quadratic elements
2522     if ( isQuadratic )
2523     {
2524       SMESH_MesherHelper helper( *GetMesh() );
2525       if ( !face.IsNull() )
2526         helper.SetSubShape( face );
2527       list< const SMDS_MeshElement* >::iterator elemIt = elemsOnFace.begin();
2528       for ( ; elemIt != elemsOnFace.end(); ++elemIt ) {
2529         const SMDS_QuadraticFaceOfNodes* QF =
2530           dynamic_cast<const SMDS_QuadraticFaceOfNodes*> (*elemIt);
2531         if(QF) {
2532           vector<const SMDS_MeshNode*> Ns;
2533           Ns.reserve(QF->NbNodes()+1);
2534           SMDS_NodeIteratorPtr anIter = QF->interlacedNodesIterator();
2535           while ( anIter->more() )
2536             Ns.push_back( anIter->next() );
2537           Ns.push_back( Ns[0] );
2538           double x, y, z;
2539           for(int i=0; i<QF->NbNodes(); i=i+2) {
2540             if ( !surface.IsNull() ) {
2541               gp_XY uv1 = helper.GetNodeUV( face, Ns[i], Ns[i+2] );
2542               gp_XY uv2 = helper.GetNodeUV( face, Ns[i+2], Ns[i] );
2543               gp_XY uv = ( uv1 + uv2 ) / 2.;
2544               gp_Pnt xyz = surface->Value( uv.X(), uv.Y() );
2545               x = xyz.X(); y = xyz.Y(); z = xyz.Z(); 
2546             }
2547             else {
2548               x = (Ns[i]->X() + Ns[i+2]->X())/2;
2549               y = (Ns[i]->Y() + Ns[i+2]->Y())/2;
2550               z = (Ns[i]->Z() + Ns[i+2]->Z())/2;
2551             }
2552             if( fabs( Ns[i+1]->X() - x ) > disttol ||
2553                 fabs( Ns[i+1]->Y() - y ) > disttol ||
2554                 fabs( Ns[i+1]->Z() - z ) > disttol ) {
2555               // we have to move i+1 node
2556               aMesh->MoveNode( Ns[i+1], x, y, z );
2557             }
2558           }
2559         }
2560       }
2561     }
2562     
2563   } // loop on face ids
2564
2565 }
2566
2567 //=======================================================================
2568 //function : isReverse
2569 //purpose  : Return true if normal of prevNodes is not co-directied with
2570 //           gp_Vec(prevNodes[iNotSame],nextNodes[iNotSame]).
2571 //           iNotSame is where prevNodes and nextNodes are different
2572 //=======================================================================
2573
2574 static bool isReverse(const SMDS_MeshNode* prevNodes[],
2575                       const SMDS_MeshNode* nextNodes[],
2576                       const int            nbNodes,
2577                       const int            iNotSame)
2578 {
2579   int iBeforeNotSame = ( iNotSame == 0 ? nbNodes - 1 : iNotSame - 1 );
2580   int iAfterNotSame  = ( iNotSame + 1 == nbNodes ? 0 : iNotSame + 1 );
2581
2582   const SMDS_MeshNode* nB = prevNodes[ iBeforeNotSame ];
2583   const SMDS_MeshNode* nA = prevNodes[ iAfterNotSame ];
2584   const SMDS_MeshNode* nP = prevNodes[ iNotSame ];
2585   const SMDS_MeshNode* nN = nextNodes[ iNotSame ];
2586
2587   gp_Pnt pB ( nB->X(), nB->Y(), nB->Z() );
2588   gp_Pnt pA ( nA->X(), nA->Y(), nA->Z() );
2589   gp_Pnt pP ( nP->X(), nP->Y(), nP->Z() );
2590   gp_Pnt pN ( nN->X(), nN->Y(), nN->Z() );
2591
2592   gp_Vec vB ( pP, pB ), vA ( pP, pA ), vN ( pP, pN );
2593
2594   return (vA ^ vB) * vN < 0.0;
2595 }
2596
2597 //=======================================================================
2598 //function : sweepElement
2599 //purpose  :
2600 //=======================================================================
2601
2602 static void sweepElement(SMESHDS_Mesh*                         aMesh,
2603                          const SMDS_MeshElement*               elem,
2604                          const vector<TNodeOfNodeListMapItr> & newNodesItVec,
2605                          list<const SMDS_MeshElement*>&        newElems,
2606                          const int nbSteps,
2607                          SMESH_SequenceOfElemPtr& myLastCreatedElems)
2608 {
2609   // Loop on elem nodes:
2610   // find new nodes and detect same nodes indices
2611   int nbNodes = elem->NbNodes();
2612   list<const SMDS_MeshNode*>::const_iterator itNN[ nbNodes ];
2613   const SMDS_MeshNode* prevNod[ nbNodes ], *nextNod[ nbNodes ], *midlNod[ nbNodes ];
2614   int iNode, nbSame = 0, iNotSameNode = 0, iSameNode = 0;
2615   vector<int> sames(nbNodes);
2616
2617   bool issimple[nbNodes];
2618
2619   for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2620     TNodeOfNodeListMapItr nnIt = newNodesItVec[ iNode ];
2621     const SMDS_MeshNode*                 node         = nnIt->first;
2622     const list< const SMDS_MeshNode* > & listNewNodes = nnIt->second;
2623     if ( listNewNodes.empty() )
2624       return;
2625
2626     if(listNewNodes.size()==nbSteps) {
2627       issimple[iNode] = true;
2628     }
2629     else {
2630       issimple[iNode] = false;
2631     }
2632
2633     itNN[ iNode ] = listNewNodes.begin();
2634     prevNod[ iNode ] = node;
2635     nextNod[ iNode ] = listNewNodes.front();
2636 //cout<<"iNode="<<iNode<<endl;
2637 //cout<<" prevNod[iNode]="<< prevNod[iNode]<<" nextNod[iNode]="<< nextNod[iNode]<<endl;
2638     if ( prevNod[ iNode ] != nextNod [ iNode ])
2639       iNotSameNode = iNode;
2640     else {
2641       iSameNode = iNode;
2642       //nbSame++;
2643       sames[nbSame++] = iNode;
2644     }
2645   }
2646 //cout<<"1 nbSame="<<nbSame<<endl;
2647   if ( nbSame == nbNodes || nbSame > 2) {
2648     MESSAGE( " Too many same nodes of element " << elem->GetID() );
2649     return;
2650   }
2651
2652 //  if( elem->IsQuadratic() && nbSame>0 ) {
2653 //    MESSAGE( "Can not rotate quadratic element " << elem->GetID() );
2654 //    return;
2655 //  }
2656
2657   int iBeforeSame = 0, iAfterSame = 0, iOpposSame = 0;
2658   if ( nbSame > 0 ) {
2659     iBeforeSame = ( iSameNode == 0 ? nbNodes - 1 : iSameNode - 1 );
2660     iAfterSame  = ( iSameNode + 1 == nbNodes ? 0 : iSameNode + 1 );
2661     iOpposSame  = ( iSameNode - 2 < 0  ? iSameNode + 2 : iSameNode - 2 );
2662   }
2663
2664 //if(nbNodes==8)
2665 //cout<<" prevNod[0]="<< prevNod[0]<<" prevNod[1]="<< prevNod[1]
2666 //    <<" prevNod[2]="<< prevNod[2]<<" prevNod[3]="<< prevNod[4]
2667 //    <<" prevNod[4]="<< prevNod[4]<<" prevNod[5]="<< prevNod[5]
2668 //    <<" prevNod[6]="<< prevNod[6]<<" prevNod[7]="<< prevNod[7]<<endl;
2669
2670   // check element orientation
2671   int i0 = 0, i2 = 2;
2672   if ( nbNodes > 2 && !isReverse( prevNod, nextNod, nbNodes, iNotSameNode )) {
2673     //MESSAGE("Reversed elem " << elem );
2674     i0 = 2;
2675     i2 = 0;
2676     if ( nbSame > 0 ) {
2677       int iAB = iAfterSame + iBeforeSame;
2678       iBeforeSame = iAB - iBeforeSame;
2679       iAfterSame  = iAB - iAfterSame;
2680     }
2681   }
2682
2683   // make new elements
2684   int iStep;//, nbSteps = newNodesItVec[ 0 ]->second.size();
2685   for (iStep = 0; iStep < nbSteps; iStep++ ) {
2686     // get next nodes
2687     for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2688       if(issimple[iNode]) {
2689         nextNod[ iNode ] = *itNN[ iNode ];
2690         itNN[ iNode ]++;
2691       }
2692       else {
2693         if( elem->GetType()==SMDSAbs_Node ) {
2694           // we have to use two nodes
2695           midlNod[ iNode ] = *itNN[ iNode ];
2696           itNN[ iNode ]++;
2697           nextNod[ iNode ] = *itNN[ iNode ];
2698           itNN[ iNode ]++;
2699         }
2700         else if(!elem->IsQuadratic() ||
2701            elem->IsQuadratic() && elem->IsMediumNode(prevNod[iNode]) ) {
2702           // we have to use each second node
2703           itNN[ iNode ]++;
2704           nextNod[ iNode ] = *itNN[ iNode ];
2705           itNN[ iNode ]++;
2706         }
2707         else {
2708           // we have to use two nodes
2709           midlNod[ iNode ] = *itNN[ iNode ];
2710           itNN[ iNode ]++;
2711           nextNod[ iNode ] = *itNN[ iNode ];
2712           itNN[ iNode ]++;
2713         }
2714       }
2715     }
2716     SMDS_MeshElement* aNewElem = 0;
2717     if(!elem->IsPoly()) {
2718       switch ( nbNodes ) {
2719       case 0:
2720         return;
2721       case 1: { // NODE
2722         if ( nbSame == 0 ) {
2723           if(issimple[0])
2724             aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ] );
2725           else
2726             aNewElem = aMesh->AddEdge( prevNod[ 0 ], nextNod[ 0 ], midlNod[ 0 ] );
2727         }
2728         break;
2729       }
2730       case 2: { // EDGE
2731         if ( nbSame == 0 )
2732           aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2733                                     nextNod[ 1 ], nextNod[ 0 ] );
2734         else
2735           aNewElem = aMesh->AddFace(prevNod[ 0 ], prevNod[ 1 ],
2736                                     nextNod[ iNotSameNode ] );
2737         break;
2738       }
2739
2740       case 3: { // TRIANGLE or quadratic edge
2741         if(elem->GetType() == SMDSAbs_Face) { // TRIANGLE
2742
2743           if ( nbSame == 0 )       // --- pentahedron
2744             aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2745                                          nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ] );
2746
2747           else if ( nbSame == 1 )  // --- pyramid
2748             aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ],  prevNod[ iAfterSame ],
2749                                          nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2750                                          nextNod[ iSameNode ]);
2751
2752           else // 2 same nodes:      --- tetrahedron
2753             aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ],
2754                                          nextNod[ iNotSameNode ]);
2755         }
2756         else { // quadratic edge
2757           if(nbSame==0) {     // quadratic quadrangle
2758             aNewElem = aMesh->AddFace(prevNod[0], nextNod[0], nextNod[1], prevNod[1],
2759                                       midlNod[0], nextNod[2], midlNod[1], prevNod[2]);
2760           }
2761           else if(nbSame==1) { // quadratic triangle
2762             if(sames[0]==2)
2763               return; // medium node on axis
2764             else if(sames[0]==0) {
2765               aNewElem = aMesh->AddFace(prevNod[0], nextNod[1], prevNod[1],
2766                                         nextNod[2], midlNod[1], prevNod[2]);
2767             }
2768             else { // sames[0]==1
2769               aNewElem = aMesh->AddFace(prevNod[0], nextNod[0], prevNod[1],
2770                                         midlNod[0], nextNod[2], prevNod[2]);
2771             }
2772           }
2773           else
2774             return;
2775         }
2776         break;
2777       }
2778       case 4: { // QUADRANGLE
2779
2780         if ( nbSame == 0 )       // --- hexahedron
2781           aNewElem = aMesh->AddVolume (prevNod[ i0 ], prevNod[ 1 ], prevNod[ i2 ], prevNod[ 3 ],
2782                                        nextNod[ i0 ], nextNod[ 1 ], nextNod[ i2 ], nextNod[ 3 ]);
2783         
2784         else if ( nbSame == 1 ) { // --- pyramid + pentahedron
2785           aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ],  prevNod[ iAfterSame ],
2786                                        nextNod[ iAfterSame ], nextNod[ iBeforeSame ],
2787                                        nextNod[ iSameNode ]);
2788           newElems.push_back( aNewElem );
2789           aNewElem = aMesh->AddVolume (prevNod[ iAfterSame ], prevNod[ iOpposSame ],
2790                                        prevNod[ iBeforeSame ],  nextNod[ iAfterSame ],
2791                                        nextNod[ iOpposSame ],  nextNod[ iBeforeSame ] );
2792         }
2793         else if ( nbSame == 2 ) { // pentahedron
2794           if ( prevNod[ iBeforeSame ] == nextNod[ iBeforeSame ] )
2795             // iBeforeSame is same too
2796             aNewElem = aMesh->AddVolume (prevNod[ iBeforeSame ], prevNod[ iOpposSame ],
2797                                          nextNod[ iOpposSame ], prevNod[ iSameNode ],
2798                                          prevNod[ iAfterSame ],  nextNod[ iAfterSame ]);
2799           else
2800             // iAfterSame is same too
2801             aNewElem = aMesh->AddVolume (prevNod[ iSameNode ], prevNod[ iBeforeSame ],
2802                                          nextNod[ iBeforeSame ], prevNod[ iAfterSame ],
2803                                          prevNod[ iOpposSame ],  nextNod[ iOpposSame ]);
2804         }
2805         break;
2806       }
2807       case 6: { // quadratic triangle
2808         // create pentahedron with 15 nodes
2809         if(i0>0) { // reversed case
2810           aNewElem = aMesh->AddVolume (prevNod[0], prevNod[2], prevNod[1],
2811                                        nextNod[0], nextNod[2], nextNod[1],
2812                                        prevNod[5], prevNod[4], prevNod[3],
2813                                        nextNod[5], nextNod[4], nextNod[3],
2814                                        midlNod[0], midlNod[2], midlNod[1]);
2815         }
2816         else { // not reversed case
2817           aNewElem = aMesh->AddVolume (prevNod[0], prevNod[1], prevNod[2],
2818                                        nextNod[0], nextNod[1], nextNod[2],
2819                                        prevNod[3], prevNod[4], prevNod[5],
2820                                        nextNod[3], nextNod[4], nextNod[5],
2821                                        midlNod[0], midlNod[1], midlNod[2]);
2822         }
2823         break;
2824       }
2825       case 8: { // quadratic quadrangle
2826         // create hexahedron with 20 nodes
2827         if(i0>0) { // reversed case
2828           aNewElem = aMesh->AddVolume (prevNod[0], prevNod[3], prevNod[2], prevNod[1],
2829                                        nextNod[0], nextNod[3], nextNod[2], nextNod[1],
2830                                        prevNod[7], prevNod[6], prevNod[5], prevNod[4],
2831                                        nextNod[7], nextNod[6], nextNod[5], nextNod[4],
2832                                        midlNod[0], midlNod[3], midlNod[2], midlNod[1]);
2833         }
2834         else { // not reversed case
2835           aNewElem = aMesh->AddVolume (prevNod[0], prevNod[1], prevNod[2], prevNod[3],
2836                                        nextNod[0], nextNod[1], nextNod[2], nextNod[3],
2837                                        prevNod[4], prevNod[5], prevNod[6], prevNod[7],
2838                                        nextNod[4], nextNod[5], nextNod[6], nextNod[7],
2839                                        midlNod[0], midlNod[1], midlNod[2], midlNod[3]);
2840         }
2841         break;
2842       }
2843       default: {
2844         // realized for extrusion only
2845         //vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2846         //vector<int> quantities (nbNodes + 2);
2847         
2848         //quantities[0] = nbNodes; // bottom of prism
2849         //for (int inode = 0; inode < nbNodes; inode++) {
2850         //  polyedre_nodes[inode] = prevNod[inode];
2851         //}
2852
2853         //quantities[1] = nbNodes; // top of prism
2854         //for (int inode = 0; inode < nbNodes; inode++) {
2855         //  polyedre_nodes[nbNodes + inode] = nextNod[inode];
2856         //}
2857         
2858         //for (int iface = 0; iface < nbNodes; iface++) {
2859         //  quantities[iface + 2] = 4;
2860         //  int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2861         //  polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2862         //  polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2863         //  polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2864         //  polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2865         //}
2866         //aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2867         break;
2868       }
2869       }
2870     }
2871
2872     if(!aNewElem) {
2873       // realized for extrusion only
2874       vector<const SMDS_MeshNode*> polyedre_nodes (nbNodes*2 + 4*nbNodes);
2875       vector<int> quantities (nbNodes + 2);
2876
2877       quantities[0] = nbNodes; // bottom of prism
2878       for (int inode = 0; inode < nbNodes; inode++) {
2879         polyedre_nodes[inode] = prevNod[inode];
2880       }
2881
2882       quantities[1] = nbNodes; // top of prism
2883       for (int inode = 0; inode < nbNodes; inode++) {
2884         polyedre_nodes[nbNodes + inode] = nextNod[inode];
2885       }
2886
2887       for (int iface = 0; iface < nbNodes; iface++) {
2888         quantities[iface + 2] = 4;
2889         int inextface = (iface == nbNodes - 1) ? 0 : iface + 1;
2890         polyedre_nodes[2*nbNodes + 4*iface + 0] = prevNod[iface];
2891         polyedre_nodes[2*nbNodes + 4*iface + 1] = prevNod[inextface];
2892         polyedre_nodes[2*nbNodes + 4*iface + 2] = nextNod[inextface];
2893         polyedre_nodes[2*nbNodes + 4*iface + 3] = nextNod[iface];
2894       }
2895       aNewElem = aMesh->AddPolyhedralVolume (polyedre_nodes, quantities);
2896     }
2897
2898     if ( aNewElem ) {
2899       newElems.push_back( aNewElem );
2900       myLastCreatedElems.Append(aNewElem);
2901     }
2902
2903     // set new prev nodes
2904     for ( iNode = 0; iNode < nbNodes; iNode++ )
2905       prevNod[ iNode ] = nextNod[ iNode ];
2906
2907   } // for steps
2908 }
2909
2910 //=======================================================================
2911 //function : makeWalls
2912 //purpose  : create 1D and 2D elements around swept elements
2913 //=======================================================================
2914
2915 static void makeWalls (SMESHDS_Mesh*            aMesh,
2916                        TNodeOfNodeListMap &     mapNewNodes,
2917                        TElemOfElemListMap &     newElemsMap,
2918                        TElemOfVecOfNnlmiMap &   elemNewNodesMap,
2919                        TIDSortedElemSet&        elemSet,
2920                        const int                nbSteps,
2921                        SMESH_SequenceOfElemPtr& myLastCreatedElems)
2922 {
2923   ASSERT( newElemsMap.size() == elemNewNodesMap.size() );
2924
2925   // Find nodes belonging to only one initial element - sweep them to get edges.
2926
2927   TNodeOfNodeListMapItr nList = mapNewNodes.begin();
2928   for ( ; nList != mapNewNodes.end(); nList++ ) {
2929     const SMDS_MeshNode* node =
2930       static_cast<const SMDS_MeshNode*>( nList->first );
2931     SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2932     int nbInitElems = 0;
2933     const SMDS_MeshElement* el = 0;
2934     SMDSAbs_ElementType highType = SMDSAbs_Edge; // count most complex elements only
2935     while ( eIt->more() && nbInitElems < 2 ) {
2936       el = eIt->next();
2937       SMDSAbs_ElementType type = el->GetType();
2938       if ( type == SMDSAbs_Volume || type < highType ) continue;
2939       if ( type > highType ) {
2940         nbInitElems = 0;
2941         highType = type;
2942       }
2943       if ( elemSet.find(el) != elemSet.end() )
2944         nbInitElems++;
2945     }
2946     if ( nbInitElems < 2 ) {
2947       bool NotCreateEdge = el && el->IsQuadratic() && el->IsMediumNode(node);
2948       if(!NotCreateEdge) {
2949         vector<TNodeOfNodeListMapItr> newNodesItVec( 1, nList );
2950         list<const SMDS_MeshElement*> newEdges;
2951         sweepElement( aMesh, node, newNodesItVec, newEdges, nbSteps, myLastCreatedElems );
2952       }
2953     }
2954   }
2955
2956   // Make a ceiling for each element ie an equal element of last new nodes.
2957   // Find free links of faces - make edges and sweep them into faces.
2958
2959   TElemOfElemListMap::iterator   itElem      = newElemsMap.begin();
2960   TElemOfVecOfNnlmiMap::iterator itElemNodes = elemNewNodesMap.begin();
2961   for ( ; itElem != newElemsMap.end(); itElem++, itElemNodes++ ) {
2962     const SMDS_MeshElement* elem = itElem->first;
2963     vector<TNodeOfNodeListMapItr>& vecNewNodes = itElemNodes->second;
2964
2965     if ( elem->GetType() == SMDSAbs_Edge ) {
2966       // create a ceiling edge
2967       if (!elem->IsQuadratic()) {
2968         if ( !aMesh->FindEdge( vecNewNodes[ 0 ]->second.back(),
2969                                vecNewNodes[ 1 ]->second.back()))
2970           myLastCreatedElems.Append(aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2971                                                    vecNewNodes[ 1 ]->second.back()));
2972       }
2973       else {
2974         if ( !aMesh->FindEdge( vecNewNodes[ 0 ]->second.back(),
2975                                vecNewNodes[ 1 ]->second.back(),
2976                                vecNewNodes[ 2 ]->second.back()))
2977           myLastCreatedElems.Append(aMesh->AddEdge(vecNewNodes[ 0 ]->second.back(),
2978                                                    vecNewNodes[ 1 ]->second.back(),
2979                                                    vecNewNodes[ 2 ]->second.back()));
2980       }
2981     }
2982     if ( elem->GetType() != SMDSAbs_Face )
2983       continue;
2984
2985     if(itElem->second.size()==0) continue;
2986
2987     bool hasFreeLinks = false;
2988
2989     TIDSortedElemSet avoidSet;
2990     avoidSet.insert( elem );
2991
2992     set<const SMDS_MeshNode*> aFaceLastNodes;
2993     int iNode, nbNodes = vecNewNodes.size();
2994     if(!elem->IsQuadratic()) {
2995       // loop on the face nodes
2996       for ( iNode = 0; iNode < nbNodes; iNode++ ) {
2997         aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
2998         // look for free links of the face
2999         int iNext = ( iNode + 1 == nbNodes ) ? 0 : iNode + 1;
3000         const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
3001         const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
3002         // check if a link is free
3003         if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet )) {
3004           hasFreeLinks = true;
3005           // make an edge and a ceiling for a new edge
3006           if ( !aMesh->FindEdge( n1, n2 )) {
3007             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2 ));
3008           }
3009           n1 = vecNewNodes[ iNode ]->second.back();
3010           n2 = vecNewNodes[ iNext ]->second.back();
3011           if ( !aMesh->FindEdge( n1, n2 )) {
3012             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2 ));
3013           }
3014         }
3015       }
3016     }
3017     else { // elem is quadratic face
3018       int nbn = nbNodes/2;
3019       for ( iNode = 0; iNode < nbn; iNode++ ) {
3020         aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
3021         int iNext = ( iNode + 1 == nbn ) ? 0 : iNode + 1;
3022         const SMDS_MeshNode* n1 = vecNewNodes[ iNode ]->first;
3023         const SMDS_MeshNode* n2 = vecNewNodes[ iNext ]->first;
3024         // check if a link is free
3025         if ( ! SMESH_MeshEditor::FindFaceInSet ( n1, n2, elemSet, avoidSet )) {
3026           hasFreeLinks = true;
3027           // make an edge and a ceiling for a new edge
3028           // find medium node
3029           const SMDS_MeshNode* n3 = vecNewNodes[ iNode+nbn ]->first;
3030           if ( !aMesh->FindEdge( n1, n2, n3 )) {
3031             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2, n3 ));
3032           }
3033           n1 = vecNewNodes[ iNode ]->second.back();
3034           n2 = vecNewNodes[ iNext ]->second.back();
3035           n3 = vecNewNodes[ iNode+nbn ]->second.back();
3036           if ( !aMesh->FindEdge( n1, n2, n3 )) {
3037             myLastCreatedElems.Append(aMesh->AddEdge( n1, n2, n3 ));
3038           }
3039         }
3040       }
3041       for ( iNode = nbn; iNode < 2*nbn; iNode++ ) {
3042         aFaceLastNodes.insert( vecNewNodes[ iNode ]->second.back() );
3043       }
3044     }
3045
3046     // sweep free links into faces
3047
3048     if ( hasFreeLinks )  {
3049       list<const SMDS_MeshElement*> & newVolumes = itElem->second;
3050       int iStep; //, nbSteps = vecNewNodes[0]->second.size();
3051       int iVol, volNb, nbVolumesByStep = newVolumes.size() / nbSteps;
3052
3053       set<const SMDS_MeshNode*> initNodeSet, faceNodeSet;
3054       for ( iNode = 0; iNode < nbNodes; iNode++ )
3055         initNodeSet.insert( vecNewNodes[ iNode ]->first );
3056
3057       for ( volNb = 0; volNb < nbVolumesByStep; volNb++ ) {
3058         list<const SMDS_MeshElement*>::iterator v = newVolumes.begin();
3059         iVol = 0;
3060         while ( iVol++ < volNb ) v++;
3061         // find indices of free faces of a volume
3062         list< int > fInd;
3063         SMDS_VolumeTool vTool( *v );
3064         int iF, nbF = vTool.NbFaces();
3065         for ( iF = 0; iF < nbF; iF ++ ) {
3066           if (vTool.IsFreeFace( iF ) &&
3067               vTool.GetFaceNodes( iF, faceNodeSet ) &&
3068               initNodeSet != faceNodeSet) // except an initial face
3069             fInd.push_back( iF );
3070         }
3071         if ( fInd.empty() )
3072           continue;
3073
3074         // create faces for all steps
3075         // if such a face has been already created by sweep of edge, assure that its orientation is OK
3076         for ( iStep = 0; iStep < nbSteps; iStep++ )  {
3077           vTool.Set( *v );
3078           vTool.SetExternalNormal();
3079           list< int >::iterator ind = fInd.begin();
3080           for ( ; ind != fInd.end(); ind++ ) {
3081             const SMDS_MeshNode** nodes = vTool.GetFaceNodes( *ind );
3082             int nbn = vTool.NbFaceNodes( *ind );
3083             switch ( nbn ) {
3084             case 3: { ///// triangle
3085               const SMDS_MeshFace * f = aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]);
3086               if ( !f )
3087                 myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
3088               else if ( nodes[ 1 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3089                 aMesh->ChangeElementNodes( f, nodes, nbn );
3090               break;
3091             }
3092             case 4: { ///// quadrangle
3093               const SMDS_MeshFace * f = aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]);
3094               if ( !f )
3095                 myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ));
3096               else if ( nodes[ 1 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3097                 aMesh->ChangeElementNodes( f, nodes, nbn );
3098               break;
3099             }
3100             default:
3101               if( (*v)->IsQuadratic() ) {
3102                 if(nbn==6) { /////// quadratic triangle
3103                   const SMDS_MeshFace * f = aMesh->FindFace( nodes[0], nodes[2], nodes[4],
3104                                                              nodes[1], nodes[3], nodes[5] );
3105                   if ( !f )
3106                     myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4],
3107                                                              nodes[1], nodes[3], nodes[5]));
3108                   else if ( nodes[ 2 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3109                     aMesh->ChangeElementNodes( f, nodes, nbn );
3110                 }
3111                 else {       /////// quadratic quadrangle
3112                   const SMDS_MeshFace * f = aMesh->FindFace( nodes[0], nodes[2], nodes[4], nodes[6],
3113                                                              nodes[1], nodes[3], nodes[5], nodes[7] );
3114                   if ( !f )
3115                     myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4], nodes[6],
3116                                                              nodes[1], nodes[3], nodes[5], nodes[7]));
3117                   else if ( nodes[ 2 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3118                     aMesh->ChangeElementNodes( f, nodes, nbn );
3119                 }
3120               }
3121               else { //////// polygon
3122                 vector<const SMDS_MeshNode*> polygon_nodes ( nodes, &nodes[nbn] );
3123                 const SMDS_MeshFace * f = aMesh->FindFace( polygon_nodes );
3124                 if ( !f )
3125                   myLastCreatedElems.Append(aMesh->AddPolygonalFace(polygon_nodes));
3126                 else if ( nodes[ 1 ] != f->GetNode( f->GetNodeIndex( nodes[ 0 ] ) + 1 ))
3127                   aMesh->ChangeElementNodes( f, nodes, nbn );
3128               }
3129             }
3130           }
3131           // go to the next volume
3132           iVol = 0;
3133           while ( iVol++ < nbVolumesByStep ) v++;
3134         }
3135       }
3136     } // sweep free links into faces
3137
3138     // make a ceiling face with a normal external to a volume
3139
3140     SMDS_VolumeTool lastVol( itElem->second.back() );
3141
3142     int iF = lastVol.GetFaceIndex( aFaceLastNodes );
3143     if ( iF >= 0 ) {
3144       lastVol.SetExternalNormal();
3145       const SMDS_MeshNode** nodes = lastVol.GetFaceNodes( iF );
3146       int nbn = lastVol.NbFaceNodes( iF );
3147       switch ( nbn ) {
3148       case 3:
3149         if (!hasFreeLinks ||
3150             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ]))
3151           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
3152         break;
3153       case 4:
3154         if (!hasFreeLinks ||
3155             !aMesh->FindFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ]))
3156           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ], nodes[ 3 ] ));
3157         break;
3158       default:
3159         if(itElem->second.back()->IsQuadratic()) {
3160           if(nbn==6) {
3161             if (!hasFreeLinks ||
3162                 !aMesh->FindFace(nodes[0], nodes[2], nodes[4],
3163                                  nodes[1], nodes[3], nodes[5]) ) {
3164               myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4],
3165                                                        nodes[1], nodes[3], nodes[5]));
3166             }
3167           }
3168           else { // nbn==8
3169             if (!hasFreeLinks ||
3170                 !aMesh->FindFace(nodes[0], nodes[2], nodes[4], nodes[6],
3171                                  nodes[1], nodes[3], nodes[5], nodes[7]) )
3172               myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[2], nodes[4], nodes[6],
3173                                                        nodes[1], nodes[3], nodes[5], nodes[7]));
3174           }
3175         }
3176         else {
3177           vector<const SMDS_MeshNode*> polygon_nodes ( nodes, &nodes[nbn] );
3178           if (!hasFreeLinks || !aMesh->FindFace(polygon_nodes))
3179             myLastCreatedElems.Append(aMesh->AddPolygonalFace(polygon_nodes));
3180         }
3181       } // switch
3182     }
3183   } // loop on swept elements
3184 }
3185
3186 //=======================================================================
3187 //function : RotationSweep
3188 //purpose  :
3189 //=======================================================================
3190
3191 void SMESH_MeshEditor::RotationSweep(TIDSortedElemSet & theElems,
3192                                      const gp_Ax1&      theAxis,
3193                                      const double       theAngle,
3194                                      const int          theNbSteps,
3195                                      const double       theTol)
3196 {
3197   myLastCreatedElems.Clear();
3198   myLastCreatedNodes.Clear();
3199
3200   MESSAGE( "RotationSweep()");
3201   gp_Trsf aTrsf;
3202   aTrsf.SetRotation( theAxis, theAngle );
3203   gp_Trsf aTrsf2;
3204   aTrsf2.SetRotation( theAxis, theAngle/2. );
3205
3206   gp_Lin aLine( theAxis );
3207   double aSqTol = theTol * theTol;
3208
3209   SMESHDS_Mesh* aMesh = GetMeshDS();
3210
3211   TNodeOfNodeListMap mapNewNodes;
3212   TElemOfVecOfNnlmiMap mapElemNewNodes;
3213   TElemOfElemListMap newElemsMap;
3214
3215   // loop on theElems
3216   TIDSortedElemSet::iterator itElem;
3217   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
3218     const SMDS_MeshElement* elem = *itElem;
3219     if ( !elem )
3220       continue;
3221     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3222     newNodesItVec.reserve( elem->NbNodes() );
3223
3224     // loop on elem nodes
3225     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3226     while ( itN->more() ) {
3227
3228       // check if a node has been already sweeped
3229       const SMDS_MeshNode* node =
3230         static_cast<const SMDS_MeshNode*>( itN->next() );
3231       TNodeOfNodeListMapItr nIt = mapNewNodes.find( node );
3232       if ( nIt == mapNewNodes.end() ) {
3233         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
3234         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
3235
3236         // make new nodes
3237         gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
3238         double coord[3];
3239         aXYZ.Coord( coord[0], coord[1], coord[2] );
3240         bool isOnAxis = ( aLine.SquareDistance( aXYZ ) <= aSqTol );
3241         const SMDS_MeshNode * newNode = node;
3242         for ( int i = 0; i < theNbSteps; i++ ) {
3243           if ( !isOnAxis ) {
3244             if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3245               // create two nodes
3246               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3247               //aTrsf.Transforms( coord[0], coord[1], coord[2] );
3248               newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3249               myLastCreatedNodes.Append(newNode);
3250               listNewNodes.push_back( newNode );
3251               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3252               //aTrsf.Transforms( coord[0], coord[1], coord[2] );
3253             }
3254             else {
3255               aTrsf.Transforms( coord[0], coord[1], coord[2] );
3256             }
3257             newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3258             myLastCreatedNodes.Append(newNode);
3259           }
3260           listNewNodes.push_back( newNode );
3261         }
3262       }
3263       else {
3264         // if current elem is quadratic and current node is not medium
3265         // we have to check - may be it is needed to insert additional nodes
3266         if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3267           list< const SMDS_MeshNode* > & listNewNodes = nIt->second;
3268           if(listNewNodes.size()==theNbSteps) {
3269             listNewNodes.clear();
3270             // make new nodes
3271             gp_XYZ aXYZ( node->X(), node->Y(), node->Z() );
3272             double coord[3];
3273             aXYZ.Coord( coord[0], coord[1], coord[2] );
3274             const SMDS_MeshNode * newNode = node;
3275             for(int i = 0; i<theNbSteps; i++) {
3276               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3277               newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3278               myLastCreatedNodes.Append(newNode);
3279               listNewNodes.push_back( newNode );
3280               aTrsf2.Transforms( coord[0], coord[1], coord[2] );
3281               newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3282               myLastCreatedNodes.Append(newNode);
3283               listNewNodes.push_back( newNode );
3284             }
3285           }
3286         }
3287       }
3288       newNodesItVec.push_back( nIt );
3289     }
3290     // make new elements
3291     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem], theNbSteps, myLastCreatedElems );
3292   }
3293
3294   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems, theNbSteps, myLastCreatedElems );
3295
3296 }
3297
3298
3299 //=======================================================================
3300 //function : CreateNode
3301 //purpose  : 
3302 //=======================================================================
3303 const SMDS_MeshNode* SMESH_MeshEditor::CreateNode(const double x,
3304                                                   const double y,
3305                                                   const double z,
3306                                                   const double tolnode,
3307                                                   SMESH_SequenceOfNode& aNodes)
3308 {
3309   myLastCreatedElems.Clear();
3310   myLastCreatedNodes.Clear();
3311
3312   gp_Pnt P1(x,y,z);
3313   SMESHDS_Mesh * aMesh = myMesh->GetMeshDS();
3314
3315   // try to search in sequence of existing nodes
3316   // if aNodes.Length()>0 we 'nave to use given sequence
3317   // else - use all nodes of mesh
3318   if(aNodes.Length()>0) {
3319     int i;
3320     for(i=1; i<=aNodes.Length(); i++) {
3321       gp_Pnt P2(aNodes.Value(i)->X(),aNodes.Value(i)->Y(),aNodes.Value(i)->Z());
3322       if(P1.Distance(P2)<tolnode)
3323         return aNodes.Value(i);
3324     }
3325   }
3326   else {
3327     SMDS_NodeIteratorPtr itn = aMesh->nodesIterator();
3328     while(itn->more()) {
3329       const SMDS_MeshNode* aN = static_cast<const SMDS_MeshNode*> (itn->next());
3330       gp_Pnt P2(aN->X(),aN->Y(),aN->Z());
3331       if(P1.Distance(P2)<tolnode)
3332         return aN;
3333     }    
3334   }
3335
3336   // create new node and return it
3337   const SMDS_MeshNode* NewNode = aMesh->AddNode(x,y,z);
3338   myLastCreatedNodes.Append(NewNode);
3339   return NewNode;
3340 }
3341
3342
3343 //=======================================================================
3344 //function : ExtrusionSweep
3345 //purpose  :
3346 //=======================================================================
3347
3348 void SMESH_MeshEditor::ExtrusionSweep (TIDSortedElemSet &  theElems,
3349                                        const gp_Vec&       theStep,
3350                                        const int           theNbSteps,
3351                                        TElemOfElemListMap& newElemsMap,
3352                                        const int           theFlags,
3353                                        const double        theTolerance)
3354 {
3355   ExtrusParam aParams;
3356   aParams.myDir = gp_Dir(theStep);
3357   aParams.myNodes.Clear();
3358   aParams.mySteps = new TColStd_HSequenceOfReal;
3359   int i;
3360   for(i=1; i<=theNbSteps; i++)
3361     aParams.mySteps->Append(theStep.Magnitude());
3362
3363   ExtrusionSweep(theElems,aParams,newElemsMap,theFlags,theTolerance);
3364
3365 }
3366
3367
3368 //=======================================================================
3369 //function : ExtrusionSweep
3370 //purpose  :
3371 //=======================================================================
3372
3373 void SMESH_MeshEditor::ExtrusionSweep (TIDSortedElemSet &  theElems,
3374                                        ExtrusParam&        theParams,
3375                                        TElemOfElemListMap& newElemsMap,
3376                                        const int           theFlags,
3377                                        const double        theTolerance)
3378 {
3379   myLastCreatedElems.Clear();
3380   myLastCreatedNodes.Clear();
3381
3382   SMESHDS_Mesh* aMesh = GetMeshDS();
3383
3384   int nbsteps = theParams.mySteps->Length();
3385
3386   TNodeOfNodeListMap mapNewNodes;
3387   //TNodeOfNodeVecMap mapNewNodes;
3388   TElemOfVecOfNnlmiMap mapElemNewNodes;
3389   //TElemOfVecOfMapNodesMap mapElemNewNodes;
3390
3391   // loop on theElems
3392   TIDSortedElemSet::iterator itElem;
3393   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
3394     // check element type
3395     const SMDS_MeshElement* elem = *itElem;
3396     if ( !elem )
3397       continue;
3398
3399     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3400     //vector<TNodeOfNodeVecMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3401     newNodesItVec.reserve( elem->NbNodes() );
3402
3403     // loop on elem nodes
3404     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3405     while ( itN->more() ) {
3406
3407       // check if a node has been already sweeped
3408       const SMDS_MeshNode* node =
3409         static_cast<const SMDS_MeshNode*>( itN->next() );
3410       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
3411       //TNodeOfNodeVecMap::iterator nIt = mapNewNodes.find( node );
3412       if ( nIt == mapNewNodes.end() ) {
3413         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
3414         //nIt = mapNewNodes.insert( make_pair( node, vector<const SMDS_MeshNode*>() )).first;
3415         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
3416         //vector<const SMDS_MeshNode*>& vecNewNodes = nIt->second;
3417         //vecNewNodes.reserve(nbsteps);
3418
3419         // make new nodes
3420         double coord[] = { node->X(), node->Y(), node->Z() };
3421         //int nbsteps = theParams.mySteps->Length();
3422         for ( int i = 0; i < nbsteps; i++ ) {
3423           if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3424             // create additional node
3425             double x = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1)/2.;
3426             double y = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1)/2.;
3427             double z = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1)/2.;
3428             if( theFlags & EXTRUSION_FLAG_SEW ) {
3429               const SMDS_MeshNode * newNode = CreateNode(x, y, z,
3430                                                          theTolerance, theParams.myNodes);
3431               listNewNodes.push_back( newNode );
3432             }
3433             else {
3434               const SMDS_MeshNode * newNode = aMesh->AddNode(x, y, z);
3435               myLastCreatedNodes.Append(newNode);
3436               listNewNodes.push_back( newNode );
3437             }
3438           }
3439           //aTrsf.Transforms( coord[0], coord[1], coord[2] );
3440           coord[0] = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
3441           coord[1] = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
3442           coord[2] = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
3443           if( theFlags & EXTRUSION_FLAG_SEW ) {
3444             const SMDS_MeshNode * newNode = CreateNode(coord[0], coord[1], coord[2],
3445                                                        theTolerance, theParams.myNodes);
3446             listNewNodes.push_back( newNode );
3447             //vecNewNodes[i]=newNode;
3448           }
3449           else {
3450             const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3451             myLastCreatedNodes.Append(newNode);
3452             listNewNodes.push_back( newNode );
3453             //vecNewNodes[i]=newNode;
3454           }
3455         }
3456       }
3457       else {
3458         // if current elem is quadratic and current node is not medium
3459         // we have to check - may be it is needed to insert additional nodes
3460         if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3461           list< const SMDS_MeshNode* > & listNewNodes = nIt->second;
3462           if(listNewNodes.size()==nbsteps) {
3463             listNewNodes.clear();
3464             double coord[] = { node->X(), node->Y(), node->Z() };
3465             for ( int i = 0; i < nbsteps; i++ ) {
3466               double x = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
3467               double y = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
3468               double z = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
3469               if( theFlags & EXTRUSION_FLAG_SEW ) {
3470                 const SMDS_MeshNode * newNode = CreateNode(x, y, z,
3471                                                            theTolerance, theParams.myNodes);
3472                 listNewNodes.push_back( newNode );
3473               }
3474               else {
3475                 const SMDS_MeshNode * newNode = aMesh->AddNode(x, y, z);
3476                 myLastCreatedNodes.Append(newNode);
3477                 listNewNodes.push_back( newNode );
3478               }
3479               coord[0] = coord[0] + theParams.myDir.X()*theParams.mySteps->Value(i+1);
3480               coord[1] = coord[1] + theParams.myDir.Y()*theParams.mySteps->Value(i+1);
3481               coord[2] = coord[2] + theParams.myDir.Z()*theParams.mySteps->Value(i+1);
3482               if( theFlags & EXTRUSION_FLAG_SEW ) {
3483                 const SMDS_MeshNode * newNode = CreateNode(coord[0], coord[1], coord[2],
3484                                                            theTolerance, theParams.myNodes);
3485                 listNewNodes.push_back( newNode );
3486               }
3487               else {
3488                 const SMDS_MeshNode * newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3489                 myLastCreatedNodes.Append(newNode);
3490                 listNewNodes.push_back( newNode );
3491               }
3492             }
3493           }
3494         }
3495       }
3496       newNodesItVec.push_back( nIt );
3497     }
3498     // make new elements
3499     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem], nbsteps, myLastCreatedElems );
3500   }
3501
3502   if( theFlags & EXTRUSION_FLAG_BOUNDARY ) {
3503     makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElems, nbsteps, myLastCreatedElems );
3504   }
3505 }
3506
3507
3508 //=======================================================================
3509 //class    : SMESH_MeshEditor_PathPoint
3510 //purpose  : auxiliary class
3511 //=======================================================================
3512 class SMESH_MeshEditor_PathPoint {
3513 public:
3514   SMESH_MeshEditor_PathPoint() {
3515     myPnt.SetCoord(99., 99., 99.);
3516     myTgt.SetCoord(1.,0.,0.);
3517     myAngle=0.;
3518     myPrm=0.;
3519   }
3520   void SetPnt(const gp_Pnt& aP3D){
3521     myPnt=aP3D;
3522   }
3523   void SetTangent(const gp_Dir& aTgt){
3524     myTgt=aTgt;
3525   }
3526   void SetAngle(const double& aBeta){
3527     myAngle=aBeta;
3528   }
3529   void SetParameter(const double& aPrm){
3530     myPrm=aPrm;
3531   }
3532   const gp_Pnt& Pnt()const{
3533     return myPnt;
3534   }
3535   const gp_Dir& Tangent()const{
3536     return myTgt;
3537   }
3538   double Angle()const{
3539     return myAngle;
3540   }
3541   double Parameter()const{
3542     return myPrm;
3543   }
3544
3545 protected:
3546   gp_Pnt myPnt;
3547   gp_Dir myTgt;
3548   double myAngle;
3549   double myPrm;
3550 };
3551
3552 //=======================================================================
3553 //function : ExtrusionAlongTrack
3554 //purpose  :
3555 //=======================================================================
3556 SMESH_MeshEditor::Extrusion_Error
3557   SMESH_MeshEditor::ExtrusionAlongTrack (TIDSortedElemSet &   theElements,
3558                                          SMESH_subMesh*       theTrack,
3559                                          const SMDS_MeshNode* theN1,
3560                                          const bool           theHasAngles,
3561                                          list<double>&        theAngles,
3562                                          const bool           theHasRefPoint,
3563                                          const gp_Pnt&        theRefPoint)
3564 {
3565   myLastCreatedElems.Clear();
3566   myLastCreatedNodes.Clear();
3567
3568   MESSAGE("SMESH_MeshEditor::ExtrusionAlongTrack")
3569   int j, aNbTP, aNbE, aNb;
3570   double aT1, aT2, aT, aAngle, aX, aY, aZ;
3571   std::list<double> aPrms;
3572   std::list<double>::iterator aItD;
3573   TIDSortedElemSet::iterator itElem;
3574
3575   Standard_Real aTx1, aTx2, aL2, aTolVec, aTolVec2;
3576   gp_Pnt aP3D, aV0;
3577   gp_Vec aVec;
3578   gp_XYZ aGC;
3579   Handle(Geom_Curve) aC3D;
3580   TopoDS_Edge aTrackEdge;
3581   TopoDS_Vertex aV1, aV2;
3582
3583   SMDS_ElemIteratorPtr aItE;
3584   SMDS_NodeIteratorPtr aItN;
3585   SMDSAbs_ElementType aTypeE;
3586
3587   TNodeOfNodeListMap mapNewNodes;
3588   TElemOfVecOfNnlmiMap mapElemNewNodes;
3589   TElemOfElemListMap newElemsMap;
3590
3591   aTolVec=1.e-7;
3592   aTolVec2=aTolVec*aTolVec;
3593
3594   // 1. Check data
3595   aNbE = theElements.size();
3596   // nothing to do
3597   if ( !aNbE )
3598     return EXTR_NO_ELEMENTS;
3599
3600   // 1.1 Track Pattern
3601   ASSERT( theTrack );
3602
3603   SMESHDS_SubMesh* pSubMeshDS=theTrack->GetSubMeshDS();
3604
3605   aItE = pSubMeshDS->GetElements();
3606   while ( aItE->more() ) {
3607     const SMDS_MeshElement* pE = aItE->next();
3608     aTypeE = pE->GetType();
3609     // Pattern must contain links only
3610     if ( aTypeE != SMDSAbs_Edge )
3611       return EXTR_PATH_NOT_EDGE;
3612   }
3613
3614   const TopoDS_Shape& aS = theTrack->GetSubShape();
3615   // Sub shape for the Pattern must be an Edge
3616   if ( aS.ShapeType() != TopAbs_EDGE )
3617     return EXTR_BAD_PATH_SHAPE;
3618
3619   aTrackEdge = TopoDS::Edge( aS );
3620   // the Edge must not be degenerated
3621   if ( BRep_Tool::Degenerated( aTrackEdge ) )
3622     return EXTR_BAD_PATH_SHAPE;
3623
3624   TopExp::Vertices( aTrackEdge, aV1, aV2 );
3625   aT1=BRep_Tool::Parameter( aV1, aTrackEdge );
3626   aT2=BRep_Tool::Parameter( aV2, aTrackEdge );
3627
3628   aItN = theTrack->GetFather()->GetSubMesh( aV1 )->GetSubMeshDS()->GetNodes();
3629   const SMDS_MeshNode* aN1 = aItN->next();
3630
3631   aItN = theTrack->GetFather()->GetSubMesh( aV2 )->GetSubMeshDS()->GetNodes();
3632   const SMDS_MeshNode* aN2 = aItN->next();
3633
3634   // starting node must be aN1 or aN2
3635   if ( !( aN1 == theN1 || aN2 == theN1 ) )
3636     return EXTR_BAD_STARTING_NODE;
3637
3638   aNbTP = pSubMeshDS->NbNodes() + 2;
3639
3640   // 1.2. Angles
3641   vector<double> aAngles( aNbTP );
3642
3643   for ( j=0; j < aNbTP; ++j ) {
3644     aAngles[j] = 0.;
3645   }
3646
3647   if ( theHasAngles ) {
3648     aItD = theAngles.begin();
3649     for ( j=1; (aItD != theAngles.end()) && (j<aNbTP); ++aItD, ++j ) {
3650       aAngle = *aItD;
3651       aAngles[j] = aAngle;
3652     }
3653   }
3654
3655   // 2. Collect parameters on the track edge
3656   aPrms.push_back( aT1 );
3657   aPrms.push_back( aT2 );
3658
3659   aItN = pSubMeshDS->GetNodes();
3660   while ( aItN->more() ) {
3661     const SMDS_MeshNode* pNode = aItN->next();
3662     const SMDS_EdgePosition* pEPos =
3663       static_cast<const SMDS_EdgePosition*>( pNode->GetPosition().get() );
3664     aT = pEPos->GetUParameter();
3665     aPrms.push_back( aT );
3666   }
3667
3668   // sort parameters
3669   aPrms.sort();
3670   if ( aN1 == theN1 ) {
3671     if ( aT1 > aT2 ) {
3672       aPrms.reverse();
3673     }
3674   }
3675   else {
3676     if ( aT2 > aT1 ) {
3677       aPrms.reverse();
3678     }
3679   }
3680
3681   // 3. Path Points
3682   SMESH_MeshEditor_PathPoint aPP;
3683   vector<SMESH_MeshEditor_PathPoint> aPPs( aNbTP );
3684   //
3685   aC3D = BRep_Tool::Curve( aTrackEdge, aTx1, aTx2 );
3686   //
3687   aItD = aPrms.begin();
3688   for ( j=0; aItD != aPrms.end(); ++aItD, ++j ) {
3689     aT = *aItD;
3690     aC3D->D1( aT, aP3D, aVec );
3691     aL2 = aVec.SquareMagnitude();
3692     if ( aL2 < aTolVec2 )
3693       return EXTR_CANT_GET_TANGENT;
3694
3695     gp_Dir aTgt( aVec );
3696     aAngle = aAngles[j];
3697
3698     aPP.SetPnt( aP3D );
3699     aPP.SetTangent( aTgt );
3700     aPP.SetAngle( aAngle );
3701     aPP.SetParameter( aT );
3702     aPPs[j]=aPP;
3703   }
3704
3705   // 3. Center of rotation aV0
3706   aV0 = theRefPoint;
3707   if ( !theHasRefPoint ) {
3708     aNb = 0;
3709     aGC.SetCoord( 0.,0.,0. );
3710
3711     itElem = theElements.begin();
3712     for ( ; itElem != theElements.end(); itElem++ ) {
3713       const SMDS_MeshElement* elem = *itElem;
3714
3715       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3716       while ( itN->more() ) {
3717         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( itN->next() );
3718         aX = node->X();
3719         aY = node->Y();
3720         aZ = node->Z();
3721
3722         if ( mapNewNodes.find( node ) == mapNewNodes.end() ) {
3723           list<const SMDS_MeshNode*> aLNx;
3724           mapNewNodes[node] = aLNx;
3725           //
3726           gp_XYZ aXYZ( aX, aY, aZ );
3727           aGC += aXYZ;
3728           ++aNb;
3729         }
3730       }
3731     }
3732     aGC /= aNb;
3733     aV0.SetXYZ( aGC );
3734   } // if (!theHasRefPoint) {
3735   mapNewNodes.clear();
3736
3737   // 4. Processing the elements
3738   SMESHDS_Mesh* aMesh = GetMeshDS();
3739
3740   for ( itElem = theElements.begin(); itElem != theElements.end(); itElem++ ) {
3741     // check element type
3742     const SMDS_MeshElement* elem = *itElem;
3743     aTypeE = elem->GetType();
3744     if ( !elem || ( aTypeE != SMDSAbs_Face && aTypeE != SMDSAbs_Edge ) )
3745       continue;
3746
3747     vector<TNodeOfNodeListMapItr> & newNodesItVec = mapElemNewNodes[ elem ];
3748     newNodesItVec.reserve( elem->NbNodes() );
3749
3750     // loop on elem nodes
3751     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3752     while ( itN->more() ) {
3753
3754       // check if a node has been already processed
3755       const SMDS_MeshNode* node =
3756         static_cast<const SMDS_MeshNode*>( itN->next() );
3757       TNodeOfNodeListMap::iterator nIt = mapNewNodes.find( node );
3758       if ( nIt == mapNewNodes.end() ) {
3759         nIt = mapNewNodes.insert( make_pair( node, list<const SMDS_MeshNode*>() )).first;
3760         list<const SMDS_MeshNode*>& listNewNodes = nIt->second;
3761
3762         // make new nodes
3763         aX = node->X();  aY = node->Y(); aZ = node->Z();
3764
3765         Standard_Real aAngle1x, aAngleT1T0, aTolAng;
3766         gp_Pnt aP0x, aP1x, aPN0, aPN1, aV0x, aV1x;
3767         gp_Ax1 anAx1, anAxT1T0;
3768         gp_Dir aDT1x, aDT0x, aDT1T0;
3769
3770         aTolAng=1.e-4;
3771
3772         aV0x = aV0;
3773         aPN0.SetCoord(aX, aY, aZ);
3774
3775         const SMESH_MeshEditor_PathPoint& aPP0 = aPPs[0];
3776         aP0x = aPP0.Pnt();
3777         aDT0x= aPP0.Tangent();
3778
3779         for ( j = 1; j < aNbTP; ++j ) {
3780           const SMESH_MeshEditor_PathPoint& aPP1 = aPPs[j];
3781           aP1x = aPP1.Pnt();
3782           aDT1x = aPP1.Tangent();
3783           aAngle1x = aPP1.Angle();
3784
3785           gp_Trsf aTrsf, aTrsfRot, aTrsfRotT1T0;
3786           // Translation
3787           gp_Vec aV01x( aP0x, aP1x );
3788           aTrsf.SetTranslation( aV01x );
3789
3790           // traslated point
3791           aV1x = aV0x.Transformed( aTrsf );
3792           aPN1 = aPN0.Transformed( aTrsf );
3793
3794           // rotation 1 [ T1,T0 ]
3795           aAngleT1T0=-aDT1x.Angle( aDT0x );
3796           if (fabs(aAngleT1T0) > aTolAng) {
3797             aDT1T0=aDT1x^aDT0x;
3798             anAxT1T0.SetLocation( aV1x );
3799             anAxT1T0.SetDirection( aDT1T0 );
3800             aTrsfRotT1T0.SetRotation( anAxT1T0, aAngleT1T0 );
3801
3802             aPN1 = aPN1.Transformed( aTrsfRotT1T0 );
3803           }
3804
3805           // rotation 2
3806           if ( theHasAngles ) {
3807             anAx1.SetLocation( aV1x );
3808             anAx1.SetDirection( aDT1x );
3809             aTrsfRot.SetRotation( anAx1, aAngle1x );
3810
3811             aPN1 = aPN1.Transformed( aTrsfRot );
3812           }
3813
3814           // make new node
3815           if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3816             // create additional node
3817             double x = ( aPN1.X() + aPN0.X() )/2.;
3818             double y = ( aPN1.Y() + aPN0.Y() )/2.;
3819             double z = ( aPN1.Z() + aPN0.Z() )/2.;
3820             const SMDS_MeshNode* newNode = aMesh->AddNode(x,y,z);
3821             myLastCreatedNodes.Append(newNode);
3822             listNewNodes.push_back( newNode );
3823           }
3824           aX = aPN1.X();
3825           aY = aPN1.Y();
3826           aZ = aPN1.Z();
3827           const SMDS_MeshNode* newNode = aMesh->AddNode( aX, aY, aZ );
3828           myLastCreatedNodes.Append(newNode);
3829           listNewNodes.push_back( newNode );
3830
3831           aPN0 = aPN1;
3832           aP0x = aP1x;
3833           aV0x = aV1x;
3834           aDT0x = aDT1x;
3835         }
3836       }
3837
3838       else {
3839         // if current elem is quadratic and current node is not medium
3840         // we have to check - may be it is needed to insert additional nodes
3841         if( elem->IsQuadratic() && !elem->IsMediumNode(node) ) {
3842           list< const SMDS_MeshNode* > & listNewNodes = nIt->second;
3843           if(listNewNodes.size()==aNbTP-1) {
3844             vector<const SMDS_MeshNode*> aNodes(2*(aNbTP-1));
3845             gp_XYZ P(node->X(), node->Y(), node->Z());
3846             list< const SMDS_MeshNode* >::iterator it = listNewNodes.begin();
3847             int i;
3848             for(i=0; i<aNbTP-1; i++) {
3849               const SMDS_MeshNode* N = *it;
3850               double x = ( N->X() + P.X() )/2.;
3851               double y = ( N->Y() + P.Y() )/2.;
3852               double z = ( N->Z() + P.Z() )/2.;
3853               const SMDS_MeshNode* newN = aMesh->AddNode(x,y,z);
3854               myLastCreatedNodes.Append(newN);
3855               aNodes[2*i] = newN;
3856               aNodes[2*i+1] = N;
3857               P = gp_XYZ(N->X(),N->Y(),N->Z());
3858             }
3859             listNewNodes.clear();
3860             for(i=0; i<2*(aNbTP-1); i++) {
3861               listNewNodes.push_back(aNodes[i]);
3862             }
3863           }
3864         }
3865       }
3866
3867       newNodesItVec.push_back( nIt );
3868     }
3869     // make new elements
3870     //sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem],
3871     //              newNodesItVec[0]->second.size(), myLastCreatedElems );
3872     sweepElement( aMesh, elem, newNodesItVec, newElemsMap[elem],
3873                   aNbTP-1, myLastCreatedElems );
3874   }
3875
3876   makeWalls( aMesh, mapNewNodes, newElemsMap, mapElemNewNodes, theElements,
3877              aNbTP-1, myLastCreatedElems );
3878
3879   return EXTR_OK;
3880 }
3881
3882 //=======================================================================
3883 //function : Transform
3884 //purpose  :
3885 //=======================================================================
3886
3887 void SMESH_MeshEditor::Transform (TIDSortedElemSet & theElems,
3888                                   const gp_Trsf&     theTrsf,
3889                                   const bool         theCopy)
3890 {
3891   myLastCreatedElems.Clear();
3892   myLastCreatedNodes.Clear();
3893
3894   bool needReverse;
3895   switch ( theTrsf.Form() ) {
3896   case gp_PntMirror:
3897   case gp_Ax2Mirror:
3898     needReverse = true;
3899     break;
3900   default:
3901     needReverse = false;
3902   }
3903
3904   SMESHDS_Mesh* aMesh = GetMeshDS();
3905
3906   // map old node to new one
3907   TNodeNodeMap nodeMap;
3908
3909   // elements sharing moved nodes; those of them which have all
3910   // nodes mirrored but are not in theElems are to be reversed
3911   TIDSortedElemSet inverseElemSet;
3912
3913   // loop on theElems
3914   TIDSortedElemSet::iterator itElem;
3915   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
3916     const SMDS_MeshElement* elem = *itElem;
3917     if ( !elem )
3918       continue;
3919
3920     // loop on elem nodes
3921     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
3922     while ( itN->more() ) {
3923
3924       // check if a node has been already transformed
3925       const SMDS_MeshNode* node =
3926         static_cast<const SMDS_MeshNode*>( itN->next() );
3927       if (nodeMap.find( node ) != nodeMap.end() )
3928         continue;
3929
3930       double coord[3];
3931       coord[0] = node->X();
3932       coord[1] = node->Y();
3933       coord[2] = node->Z();
3934       theTrsf.Transforms( coord[0], coord[1], coord[2] );
3935       const SMDS_MeshNode * newNode = node;
3936       if ( theCopy ) {
3937         newNode = aMesh->AddNode( coord[0], coord[1], coord[2] );
3938         myLastCreatedNodes.Append(newNode);
3939       }
3940       else {
3941         aMesh->MoveNode( node, coord[0], coord[1], coord[2] );
3942         // node position on shape becomes invalid
3943         const_cast< SMDS_MeshNode* > ( node )->SetPosition
3944           ( SMDS_SpacePosition::originSpacePosition() );
3945       }
3946       nodeMap.insert( TNodeNodeMap::value_type( node, newNode ));
3947
3948       // keep inverse elements
3949       if ( !theCopy && needReverse ) {
3950         SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
3951         while ( invElemIt->more() ) {
3952           const SMDS_MeshElement* iel = invElemIt->next(); 
3953           inverseElemSet.insert( iel );
3954         }
3955       }
3956     }
3957   }
3958
3959   // either new elements are to be created
3960   // or a mirrored element are to be reversed
3961   if ( !theCopy && !needReverse)
3962     return;
3963
3964   if ( !inverseElemSet.empty()) {
3965     TIDSortedElemSet::iterator invElemIt = inverseElemSet.begin();
3966     for ( ; invElemIt != inverseElemSet.end(); invElemIt++ )
3967       theElems.insert( *invElemIt );
3968   }
3969
3970   // replicate or reverse elements
3971
3972   enum {
3973     REV_TETRA   = 0,  //  = nbNodes - 4
3974     REV_PYRAMID = 1,  //  = nbNodes - 4
3975     REV_PENTA   = 2,  //  = nbNodes - 4
3976     REV_FACE    = 3,
3977     REV_HEXA    = 4,  //  = nbNodes - 4
3978     FORWARD     = 5
3979     };
3980   int index[][8] = {
3981     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_TETRA
3982     { 2, 1, 0, 3, 4, 0, 0, 0 },  // REV_PYRAMID
3983     { 2, 1, 0, 5, 4, 3, 0, 0 },  // REV_PENTA
3984     { 2, 1, 0, 3, 0, 0, 0, 0 },  // REV_FACE
3985     { 2, 1, 0, 3, 6, 5, 4, 7 },  // REV_HEXA
3986     { 0, 1, 2, 3, 4, 5, 6, 7 }   // FORWARD
3987   };
3988
3989   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ ) {
3990     const SMDS_MeshElement* elem = *itElem;
3991     if ( !elem || elem->GetType() == SMDSAbs_Node )
3992       continue;
3993
3994     int nbNodes = elem->NbNodes();
3995     int elemType = elem->GetType();
3996
3997     if (elem->IsPoly()) {
3998       // Polygon or Polyhedral Volume
3999       switch ( elemType ) {
4000       case SMDSAbs_Face:
4001         {
4002           vector<const SMDS_MeshNode*> poly_nodes (nbNodes);
4003           int iNode = 0;
4004           SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4005           while (itN->more()) {
4006             const SMDS_MeshNode* node =
4007               static_cast<const SMDS_MeshNode*>(itN->next());
4008             TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
4009             if (nodeMapIt == nodeMap.end())
4010               break; // not all nodes transformed
4011             if (needReverse) {
4012               // reverse mirrored faces and volumes
4013               poly_nodes[nbNodes - iNode - 1] = (*nodeMapIt).second;
4014             } else {
4015               poly_nodes[iNode] = (*nodeMapIt).second;
4016             }
4017             iNode++;
4018           }
4019           if ( iNode != nbNodes )
4020             continue; // not all nodes transformed
4021
4022           if ( theCopy ) {
4023             myLastCreatedElems.Append(aMesh->AddPolygonalFace(poly_nodes));
4024           }
4025           else {
4026             aMesh->ChangePolygonNodes(elem, poly_nodes);
4027           }
4028         }
4029         break;
4030       case SMDSAbs_Volume:
4031         {
4032           // ATTENTION: Reversing is not yet done!!!
4033           const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
4034             (const SMDS_PolyhedralVolumeOfNodes*) elem;
4035           if (!aPolyedre) {
4036             MESSAGE("Warning: bad volumic element");
4037             continue;
4038           }
4039
4040           vector<const SMDS_MeshNode*> poly_nodes;
4041           vector<int> quantities;
4042
4043           bool allTransformed = true;
4044           int nbFaces = aPolyedre->NbFaces();
4045           for (int iface = 1; iface <= nbFaces && allTransformed; iface++) {
4046             int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
4047             for (int inode = 1; inode <= nbFaceNodes && allTransformed; inode++) {
4048               const SMDS_MeshNode* node = aPolyedre->GetFaceNode(iface, inode);
4049               TNodeNodeMap::iterator nodeMapIt = nodeMap.find(node);
4050               if (nodeMapIt == nodeMap.end()) {
4051                 allTransformed = false; // not all nodes transformed
4052               } else {
4053                 poly_nodes.push_back((*nodeMapIt).second);
4054               }
4055             }
4056             quantities.push_back(nbFaceNodes);
4057           }
4058           if ( !allTransformed )
4059             continue; // not all nodes transformed
4060
4061           if ( theCopy ) {
4062             myLastCreatedElems.Append(aMesh->AddPolyhedralVolume(poly_nodes, quantities));
4063           }
4064           else {
4065             aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4066           }
4067         }
4068         break;
4069       default:;
4070       }
4071       continue;
4072     }
4073
4074     // Regular elements
4075     int* i = index[ FORWARD ];
4076     if ( needReverse && nbNodes > 2) // reverse mirrored faces and volumes
4077       if ( elemType == SMDSAbs_Face )
4078         i = index[ REV_FACE ];
4079       else
4080         i = index[ nbNodes - 4 ];
4081
4082     if(elem->IsQuadratic()) {
4083       static int anIds[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
4084       i = anIds;
4085       if(needReverse) {
4086         if(nbNodes==3) { // quadratic edge
4087           static int anIds[] = {1,0,2};
4088           i = anIds;
4089         }
4090         else if(nbNodes==6) { // quadratic triangle
4091           static int anIds[] = {0,2,1,5,4,3};
4092           i = anIds;
4093         }
4094         else if(nbNodes==8) { // quadratic quadrangle
4095           static int anIds[] = {0,3,2,1,7,6,5,4};
4096           i = anIds;
4097         }
4098         else if(nbNodes==10) { // quadratic tetrahedron of 10 nodes
4099           static int anIds[] = {0,2,1,3,6,5,4,7,9,8};
4100           i = anIds;
4101         }
4102         else if(nbNodes==13) { // quadratic pyramid of 13 nodes
4103           static int anIds[] = {0,3,2,1,4,8,7,6,5,9,12,11,10};
4104           i = anIds;
4105         }
4106         else if(nbNodes==15) { // quadratic pentahedron with 15 nodes
4107           static int anIds[] = {0,2,1,3,5,4,8,7,6,11,10,9,12,14,13};
4108           i = anIds;
4109         }
4110         else { // nbNodes==20 - quadratic hexahedron with 20 nodes
4111           static int anIds[] = {0,3,2,1,4,7,6,5,11,10,9,8,15,14,13,12,16,19,18,17};
4112           i = anIds;
4113         }
4114       }
4115     }
4116
4117     // find transformed nodes
4118     const SMDS_MeshNode* nodes[8];
4119     int iNode = 0;
4120     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4121     while ( itN->more() ) {
4122       const SMDS_MeshNode* node =
4123         static_cast<const SMDS_MeshNode*>( itN->next() );
4124       TNodeNodeMap::iterator nodeMapIt = nodeMap.find( node );
4125       if ( nodeMapIt == nodeMap.end() )
4126         break; // not all nodes transformed
4127       nodes[ i [ iNode++ ]] = (*nodeMapIt).second;
4128     }
4129     if ( iNode != nbNodes )
4130       continue; // not all nodes transformed
4131
4132     if ( theCopy ) {
4133       // add a new element
4134       switch ( elemType ) {
4135       case SMDSAbs_Edge:
4136         if ( nbNodes == 2 )
4137           myLastCreatedElems.Append(aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ] ));
4138         else
4139           myLastCreatedElems.Append(aMesh->AddEdge( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
4140         break;
4141       case SMDSAbs_Face:
4142         if ( nbNodes == 3 )
4143           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] ));
4144         else if(nbNodes==4)
4145           myLastCreatedElems.Append(aMesh->AddFace( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ]));
4146         else if(nbNodes==6)
4147           myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[1], nodes[2], nodes[3],
4148                                              nodes[4], nodes[5]));
4149         else // nbNodes==8
4150           myLastCreatedElems.Append(aMesh->AddFace(nodes[0], nodes[1], nodes[2], nodes[3],
4151                                              nodes[4], nodes[5], nodes[6], nodes[7]));
4152         break;
4153       case SMDSAbs_Volume:
4154         if ( nbNodes == 4 )
4155           myLastCreatedElems.Append(aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ] ));
4156         else if ( nbNodes == 8 )
4157           myLastCreatedElems.Append(aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
4158                                                nodes[ 4 ], nodes[ 5 ], nodes[ 6 ] , nodes[ 7 ]));
4159         else if ( nbNodes == 6 )
4160           myLastCreatedElems.Append(aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
4161                                                nodes[ 4 ], nodes[ 5 ]));
4162         else if ( nbNodes == 5 )
4163           myLastCreatedElems.Append(aMesh->AddVolume( nodes[ 0 ], nodes[ 1 ], nodes[ 2 ] , nodes[ 3 ],
4164                                                nodes[ 4 ]));
4165         else if(nbNodes==10)
4166           myLastCreatedElems.Append(aMesh->AddVolume(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4],
4167                                                nodes[5], nodes[6], nodes[7], nodes[8], nodes[9]));
4168         else if(nbNodes==13)
4169           myLastCreatedElems.Append(aMesh->AddVolume(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4],
4170                                                nodes[5], nodes[6], nodes[7], nodes[8], nodes[9],
4171                                                nodes[10], nodes[11], nodes[12]));
4172         else if(nbNodes==15)
4173           myLastCreatedElems.Append(aMesh->AddVolume(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4],
4174                                                nodes[5], nodes[6], nodes[7], nodes[8], nodes[9],
4175                                                nodes[10], nodes[11], nodes[12], nodes[13], nodes[14]));
4176         else // nbNodes==20
4177           myLastCreatedElems.Append(aMesh->AddVolume(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4],
4178                                                nodes[5], nodes[6], nodes[7], nodes[8], nodes[9],
4179                                                nodes[10], nodes[11], nodes[12], nodes[13], nodes[14],
4180                                                nodes[15], nodes[16], nodes[17], nodes[18], nodes[19]));
4181         break;
4182       default:;
4183       }
4184     }
4185     else
4186     {
4187       // reverse element as it was reversed by transformation
4188       if ( nbNodes > 2 )
4189         aMesh->ChangeElementNodes( elem, nodes, nbNodes );
4190     }
4191   }
4192 }
4193
4194 //=======================================================================
4195 //function : FindCoincidentNodes
4196 //purpose  : Return list of group of nodes close to each other within theTolerance
4197 //           Search among theNodes or in the whole mesh if theNodes is empty.
4198 //=======================================================================
4199
4200 void SMESH_MeshEditor::FindCoincidentNodes (set<const SMDS_MeshNode*> & theNodes,
4201                                             const double                theTolerance,
4202                                             TListOfListOfNodes &        theGroupsOfNodes)
4203 {
4204   myLastCreatedElems.Clear();
4205   myLastCreatedNodes.Clear();
4206
4207   double tol2 = theTolerance * theTolerance;
4208
4209   list<const SMDS_MeshNode*> nodes;
4210   if ( theNodes.empty() )
4211   { // get all nodes in the mesh
4212     SMDS_NodeIteratorPtr nIt = GetMeshDS()->nodesIterator();
4213     while ( nIt->more() )
4214       nodes.push_back( nIt->next() );
4215   }
4216   else
4217   {
4218     nodes.insert( nodes.end(), theNodes.begin(), theNodes.end() );
4219   }
4220
4221   list<const SMDS_MeshNode*>::iterator it2, it1 = nodes.begin();
4222   for ( ; it1 != nodes.end(); it1++ )
4223   {
4224     const SMDS_MeshNode* n1 = *it1;
4225     gp_Pnt p1( n1->X(), n1->Y(), n1->Z() );
4226
4227     list<const SMDS_MeshNode*> * groupPtr = 0;
4228     it2 = it1;
4229     for ( it2++; it2 != nodes.end(); it2++ )
4230     {
4231       const SMDS_MeshNode* n2 = *it2;
4232       gp_Pnt p2( n2->X(), n2->Y(), n2->Z() );
4233       if ( p1.SquareDistance( p2 ) <= tol2 )
4234       {
4235         if ( !groupPtr ) {
4236           theGroupsOfNodes.push_back( list<const SMDS_MeshNode*>() );
4237           groupPtr = & theGroupsOfNodes.back();
4238           groupPtr->push_back( n1 );
4239         }
4240         if(groupPtr->front()>n2)
4241           groupPtr->push_front( n2 );
4242         else
4243           groupPtr->push_back( n2 );
4244         it2 = nodes.erase( it2 );
4245         it2--;
4246       }
4247     }
4248   }
4249 }
4250
4251 //=======================================================================
4252 //function : SimplifyFace
4253 //purpose  :
4254 //=======================================================================
4255 int SMESH_MeshEditor::SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
4256                                     vector<const SMDS_MeshNode *>&      poly_nodes,
4257                                     vector<int>&                        quantities) const
4258 {
4259   int nbNodes = faceNodes.size();
4260
4261   if (nbNodes < 3)
4262     return 0;
4263
4264   set<const SMDS_MeshNode*> nodeSet;
4265
4266   // get simple seq of nodes
4267   const SMDS_MeshNode* simpleNodes[ nbNodes ];
4268   int iSimple = 0, nbUnique = 0;
4269
4270   simpleNodes[iSimple++] = faceNodes[0];
4271   nbUnique++;
4272   for (int iCur = 1; iCur < nbNodes; iCur++) {
4273     if (faceNodes[iCur] != simpleNodes[iSimple - 1]) {
4274       simpleNodes[iSimple++] = faceNodes[iCur];
4275       if (nodeSet.insert( faceNodes[iCur] ).second)
4276         nbUnique++;
4277     }
4278   }
4279   int nbSimple = iSimple;
4280   if (simpleNodes[nbSimple - 1] == simpleNodes[0]) {
4281     nbSimple--;
4282     iSimple--;
4283   }
4284
4285   if (nbUnique < 3)
4286     return 0;
4287
4288   // separate loops
4289   int nbNew = 0;
4290   bool foundLoop = (nbSimple > nbUnique);
4291   while (foundLoop) {
4292     foundLoop = false;
4293     set<const SMDS_MeshNode*> loopSet;
4294     for (iSimple = 0; iSimple < nbSimple && !foundLoop; iSimple++) {
4295       const SMDS_MeshNode* n = simpleNodes[iSimple];
4296       if (!loopSet.insert( n ).second) {
4297         foundLoop = true;
4298
4299         // separate loop
4300         int iC = 0, curLast = iSimple;
4301         for (; iC < curLast; iC++) {
4302           if (simpleNodes[iC] == n) break;
4303         }
4304         int loopLen = curLast - iC;
4305         if (loopLen > 2) {
4306           // create sub-element
4307           nbNew++;
4308           quantities.push_back(loopLen);
4309           for (; iC < curLast; iC++) {
4310             poly_nodes.push_back(simpleNodes[iC]);
4311           }
4312         }
4313         // shift the rest nodes (place from the first loop position)
4314         for (iC = curLast + 1; iC < nbSimple; iC++) {
4315           simpleNodes[iC - loopLen] = simpleNodes[iC];
4316         }
4317         nbSimple -= loopLen;
4318         iSimple -= loopLen;
4319       }
4320     } // for (iSimple = 0; iSimple < nbSimple; iSimple++)
4321   } // while (foundLoop)
4322
4323   if (iSimple > 2) {
4324     nbNew++;
4325     quantities.push_back(iSimple);
4326     for (int i = 0; i < iSimple; i++)
4327       poly_nodes.push_back(simpleNodes[i]);
4328   }
4329
4330   return nbNew;
4331 }
4332
4333 //=======================================================================
4334 //function : MergeNodes
4335 //purpose  : In each group, the cdr of nodes are substituted by the first one
4336 //           in all elements.
4337 //=======================================================================
4338
4339 void SMESH_MeshEditor::MergeNodes (TListOfListOfNodes & theGroupsOfNodes)
4340 {
4341   myLastCreatedElems.Clear();
4342   myLastCreatedNodes.Clear();
4343
4344   SMESHDS_Mesh* aMesh = GetMeshDS();
4345
4346   TNodeNodeMap nodeNodeMap; // node to replace - new node
4347   set<const SMDS_MeshElement*> elems; // all elements with changed nodes
4348   list< int > rmElemIds, rmNodeIds;
4349
4350   // Fill nodeNodeMap and elems
4351
4352   TListOfListOfNodes::iterator grIt = theGroupsOfNodes.begin();
4353   for ( ; grIt != theGroupsOfNodes.end(); grIt++ ) {
4354     list<const SMDS_MeshNode*>& nodes = *grIt;
4355     list<const SMDS_MeshNode*>::iterator nIt = nodes.begin();
4356     const SMDS_MeshNode* nToKeep = *nIt;
4357     for ( ++nIt; nIt != nodes.end(); nIt++ ) {
4358       const SMDS_MeshNode* nToRemove = *nIt;
4359       nodeNodeMap.insert( TNodeNodeMap::value_type( nToRemove, nToKeep ));
4360       if ( nToRemove != nToKeep ) {
4361         rmNodeIds.push_back( nToRemove->GetID() );
4362         AddToSameGroups( nToKeep, nToRemove, aMesh );
4363       }
4364
4365       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
4366       while ( invElemIt->more() ) {
4367         const SMDS_MeshElement* elem = invElemIt->next();
4368           elems.insert(elem);
4369       }
4370     }
4371   }
4372   // Change element nodes or remove an element
4373
4374   set<const SMDS_MeshElement*>::iterator eIt = elems.begin();
4375   for ( ; eIt != elems.end(); eIt++ ) {
4376     const SMDS_MeshElement* elem = *eIt;
4377     int nbNodes = elem->NbNodes();
4378     int aShapeId = FindShape( elem );
4379
4380     set<const SMDS_MeshNode*> nodeSet;
4381     const SMDS_MeshNode* curNodes[ nbNodes ], *uniqueNodes[ nbNodes ];
4382     int iUnique = 0, iCur = 0, nbRepl = 0, iRepl [ nbNodes ];
4383
4384     // get new seq of nodes
4385     SMDS_ElemIteratorPtr itN = elem->nodesIterator();
4386     while ( itN->more() ) {
4387       const SMDS_MeshNode* n =
4388         static_cast<const SMDS_MeshNode*>( itN->next() );
4389
4390       TNodeNodeMap::iterator nnIt = nodeNodeMap.find( n );
4391       if ( nnIt != nodeNodeMap.end() ) { // n sticks
4392         n = (*nnIt).second;
4393         iRepl[ nbRepl++ ] = iCur;
4394       }
4395       curNodes[ iCur ] = n;
4396       bool isUnique = nodeSet.insert( n ).second;
4397       if ( isUnique )
4398         uniqueNodes[ iUnique++ ] = n;
4399       iCur++;
4400     }
4401
4402     // Analyse element topology after replacement
4403
4404     bool isOk = true;
4405     int nbUniqueNodes = nodeSet.size();
4406     if ( nbNodes != nbUniqueNodes ) { // some nodes stick
4407       // Polygons and Polyhedral volumes
4408       if (elem->IsPoly()) {
4409
4410         if (elem->GetType() == SMDSAbs_Face) {
4411           // Polygon
4412           vector<const SMDS_MeshNode *> face_nodes (nbNodes);
4413           int inode = 0;
4414           for (; inode < nbNodes; inode++) {
4415             face_nodes[inode] = curNodes[inode];
4416           }
4417
4418           vector<const SMDS_MeshNode *> polygons_nodes;
4419           vector<int> quantities;
4420           int nbNew = SimplifyFace(face_nodes, polygons_nodes, quantities);
4421
4422           if (nbNew > 0) {
4423             inode = 0;
4424             for (int iface = 0; iface < nbNew - 1; iface++) {
4425               int nbNodes = quantities[iface];
4426               vector<const SMDS_MeshNode *> poly_nodes (nbNodes);
4427               for (int ii = 0; ii < nbNodes; ii++, inode++) {
4428                 poly_nodes[ii] = polygons_nodes[inode];
4429               }
4430               SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
4431               myLastCreatedElems.Append(newElem);
4432               if (aShapeId)
4433                 aMesh->SetMeshElementOnShape(newElem, aShapeId);
4434             }
4435             aMesh->ChangeElementNodes(elem, &polygons_nodes[inode], quantities[nbNew - 1]);
4436           }
4437           else {
4438             rmElemIds.push_back(elem->GetID());
4439           }
4440
4441         }
4442         else if (elem->GetType() == SMDSAbs_Volume) {
4443           // Polyhedral volume
4444           if (nbUniqueNodes < 4) {
4445             rmElemIds.push_back(elem->GetID());
4446           }
4447           else {
4448             // each face has to be analized in order to check volume validity
4449             const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
4450               static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
4451             if (aPolyedre) {
4452               int nbFaces = aPolyedre->NbFaces();
4453
4454               vector<const SMDS_MeshNode *> poly_nodes;
4455               vector<int> quantities;
4456
4457               for (int iface = 1; iface <= nbFaces; iface++) {
4458                 int nbFaceNodes = aPolyedre->NbFaceNodes(iface);
4459                 vector<const SMDS_MeshNode *> faceNodes (nbFaceNodes);
4460
4461                 for (int inode = 1; inode <= nbFaceNodes; inode++) {
4462                   const SMDS_MeshNode * faceNode = aPolyedre->GetFaceNode(iface, inode);
4463                   TNodeNodeMap::iterator nnIt = nodeNodeMap.find(faceNode);
4464                   if (nnIt != nodeNodeMap.end()) { // faceNode sticks
4465                     faceNode = (*nnIt).second;
4466                   }
4467                   faceNodes[inode - 1] = faceNode;
4468                 }
4469
4470                 SimplifyFace(faceNodes, poly_nodes, quantities);
4471               }
4472
4473               if (quantities.size() > 3) {
4474                 // to be done: remove coincident faces
4475               }
4476
4477               if (quantities.size() > 3)
4478                 aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
4479               else
4480                 rmElemIds.push_back(elem->GetID());
4481
4482             }
4483             else {
4484               rmElemIds.push_back(elem->GetID());
4485             }
4486           }
4487         }
4488         else {
4489         }
4490
4491         continue;
4492       }
4493
4494       // Regular elements
4495       switch ( nbNodes ) {
4496       case 2: ///////////////////////////////////// EDGE
4497         isOk = false; break;
4498       case 3: ///////////////////////////////////// TRIANGLE
4499         isOk = false; break;
4500       case 4:
4501         if ( elem->GetType() == SMDSAbs_Volume ) // TETRAHEDRON
4502           isOk = false;
4503         else { //////////////////////////////////// QUADRANGLE
4504           if ( nbUniqueNodes < 3 )
4505             isOk = false;
4506           else if ( nbRepl == 2 && iRepl[ 1 ] - iRepl[ 0 ] == 2 )
4507             isOk = false; // opposite nodes stick
4508         }
4509         break;
4510       case 6: ///////////////////////////////////// PENTAHEDRON
4511         if ( nbUniqueNodes == 4 ) {
4512           // ---------------------------------> tetrahedron
4513           if (nbRepl == 3 &&
4514               iRepl[ 0 ] > 2 && iRepl[ 1 ] > 2 && iRepl[ 2 ] > 2 ) {
4515             // all top nodes stick: reverse a bottom
4516             uniqueNodes[ 0 ] = curNodes [ 1 ];
4517             uniqueNodes[ 1 ] = curNodes [ 0 ];
4518           }
4519           else if (nbRepl == 3 &&
4520                    iRepl[ 0 ] < 3 && iRepl[ 1 ] < 3 && iRepl[ 2 ] < 3 ) {
4521             // all bottom nodes stick: set a top before
4522             uniqueNodes[ 3 ] = uniqueNodes [ 0 ];
4523             uniqueNodes[ 0 ] = curNodes [ 3 ];
4524             uniqueNodes[ 1 ] = curNodes [ 4 ];
4525             uniqueNodes[ 2 ] = curNodes [ 5 ];
4526           }
4527           else if (nbRepl == 4 &&
4528                    iRepl[ 2 ] - iRepl [ 0 ] == 3 && iRepl[ 3 ] - iRepl [ 1 ] == 3 ) {
4529             // a lateral face turns into a line: reverse a bottom
4530             uniqueNodes[ 0 ] = curNodes [ 1 ];
4531             uniqueNodes[ 1 ] = curNodes [ 0 ];
4532           }
4533           else
4534             isOk = false;
4535         }
4536         else if ( nbUniqueNodes == 5 ) {
4537           // PENTAHEDRON --------------------> 2 tetrahedrons
4538           if ( nbRepl == 2 && iRepl[ 1 ] - iRepl [ 0 ] == 3 ) {
4539             // a bottom node sticks with a linked top one
4540             // 1.
4541             SMDS_MeshElement* newElem =
4542               aMesh->AddVolume(curNodes[ 3 ],
4543                                curNodes[ 4 ],
4544                                curNodes[ 5 ],
4545                                curNodes[ iRepl[ 0 ] == 2 ? 1 : 2 ]);
4546             myLastCreatedElems.Append(newElem);
4547             if ( aShapeId )
4548               aMesh->SetMeshElementOnShape( newElem, aShapeId );
4549             // 2. : reverse a bottom
4550             uniqueNodes[ 0 ] = curNodes [ 1 ];
4551             uniqueNodes[ 1 ] = curNodes [ 0 ];
4552             nbUniqueNodes = 4;
4553           }
4554           else
4555             isOk = false;
4556         }
4557         else
4558           isOk = false;
4559         break;
4560       case 8: { 
4561         if(elem->IsQuadratic()) { // Quadratic quadrangle
4562           //   1    5    2
4563           //    +---+---+
4564           //    |       |
4565           //    |       |
4566           //   4+       +6
4567           //    |       |
4568           //    |       |
4569           //    +---+---+
4570           //   0    7    3
4571           isOk = false;
4572           if(nbRepl==3) {
4573             nbUniqueNodes = 6;
4574             if( iRepl[0]==0 && iRepl[1]==1 && iRepl[2]==4 ) {
4575               uniqueNodes[0] = curNodes[0];
4576               uniqueNodes[1] = curNodes[2];
4577               uniqueNodes[2] = curNodes[3];
4578               uniqueNodes[3] = curNodes[5];
4579               uniqueNodes[4] = curNodes[6];
4580               uniqueNodes[5] = curNodes[7];
4581               isOk = true;
4582             }
4583             if( iRepl[0]==0 && iRepl[1]==3 && iRepl[2]==7 ) {
4584               uniqueNodes[0] = curNodes[0];
4585               uniqueNodes[1] = curNodes[1];
4586               uniqueNodes[2] = curNodes[2];
4587               uniqueNodes[3] = curNodes[4];
4588               uniqueNodes[4] = curNodes[5];
4589               uniqueNodes[5] = curNodes[6];
4590               isOk = true;
4591             }
4592             if( iRepl[0]==0 && iRepl[1]==4 && iRepl[2]==7 ) {
4593               uniqueNodes[0] = curNodes[1];
4594               uniqueNodes[1] = curNodes[2];
4595               uniqueNodes[2] = curNodes[3];
4596               uniqueNodes[3] = curNodes[5];
4597               uniqueNodes[4] = curNodes[6];
4598               uniqueNodes[5] = curNodes[0];
4599               isOk = true;
4600             }
4601             if( iRepl[0]==1 && iRepl[1]==2 && iRepl[2]==5 ) {
4602               uniqueNodes[0] = curNodes[0];
4603               uniqueNodes[1] = curNodes[1];
4604               uniqueNodes[2] = curNodes[3];
4605               uniqueNodes[3] = curNodes[4];
4606               uniqueNodes[4] = curNodes[6];
4607               uniqueNodes[5] = curNodes[7];
4608               isOk = true;
4609             }
4610             if( iRepl[0]==1 && iRepl[1]==4 && iRepl[2]==5 ) {
4611               uniqueNodes[0] = curNodes[0];
4612               uniqueNodes[1] = curNodes[2];
4613               uniqueNodes[2] = curNodes[3];
4614               uniqueNodes[3] = curNodes[1];
4615               uniqueNodes[4] = curNodes[6];
4616               uniqueNodes[5] = curNodes[7];
4617               isOk = true;
4618             }
4619             if( iRepl[0]==2 && iRepl[1]==3 && iRepl[2]==6 ) {
4620               uniqueNodes[0] = curNodes[0];
4621               uniqueNodes[1] = curNodes[1];
4622               uniqueNodes[2] = curNodes[2];
4623               uniqueNodes[3] = curNodes[4];
4624               uniqueNodes[4] = curNodes[5];
4625               uniqueNodes[5] = curNodes[7];
4626               isOk = true;
4627             }
4628             if( iRepl[0]==2 && iRepl[1]==5 && iRepl[2]==6 ) {
4629               uniqueNodes[0] = curNodes[0];
4630               uniqueNodes[1] = curNodes[1];
4631               uniqueNodes[2] = curNodes[3];
4632               uniqueNodes[3] = curNodes[4];
4633               uniqueNodes[4] = curNodes[2];
4634               uniqueNodes[5] = curNodes[7];
4635               isOk = true;
4636             }
4637             if( iRepl[0]==3 && iRepl[1]==6 && iRepl[2]==7 ) {
4638               uniqueNodes[0] = curNodes[0];
4639               uniqueNodes[1] = curNodes[1];
4640               uniqueNodes[2] = curNodes[2];
4641               uniqueNodes[3] = curNodes[4];
4642               uniqueNodes[4] = curNodes[5];
4643               uniqueNodes[5] = curNodes[3];
4644               isOk = true;
4645             }
4646           }
4647           break;
4648         }
4649         //////////////////////////////////// HEXAHEDRON
4650         isOk = false;
4651         SMDS_VolumeTool hexa (elem);
4652         hexa.SetExternalNormal();
4653         if ( nbUniqueNodes == 4 && nbRepl == 6 ) {
4654           //////////////////////// ---> tetrahedron
4655           for ( int iFace = 0; iFace < 6; iFace++ ) {
4656             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
4657             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
4658                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
4659                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
4660               // one face turns into a point ...
4661               int iOppFace = hexa.GetOppFaceIndex( iFace );
4662               ind = hexa.GetFaceNodesIndices( iOppFace );
4663               int nbStick = 0;
4664               iUnique = 2; // reverse a tetrahedron bottom
4665               for ( iCur = 0; iCur < 4 && nbStick < 2; iCur++ ) {
4666                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
4667                   nbStick++;
4668                 else if ( iUnique >= 0 )
4669                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
4670               }
4671               if ( nbStick == 1 ) {
4672                 // ... and the opposite one - into a triangle.
4673                 // set a top node
4674                 ind = hexa.GetFaceNodesIndices( iFace );
4675                 uniqueNodes[ 3 ] = curNodes[ind[ 0 ]];
4676                 isOk = true;
4677               }
4678               break;
4679             }
4680           }
4681         }
4682         else if (nbUniqueNodes == 5 && nbRepl == 4 ) {
4683           //////////////////// HEXAHEDRON ---> 2 tetrahedrons
4684           for ( int iFace = 0; iFace < 6; iFace++ ) {
4685             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
4686             if (curNodes[ind[ 0 ]] == curNodes[ind[ 1 ]] &&
4687                 curNodes[ind[ 0 ]] == curNodes[ind[ 2 ]] &&
4688                 curNodes[ind[ 0 ]] == curNodes[ind[ 3 ]] ) {
4689               // one face turns into a point ...
4690               int iOppFace = hexa.GetOppFaceIndex( iFace );
4691               ind = hexa.GetFaceNodesIndices( iOppFace );
4692               int nbStick = 0;
4693               iUnique = 2;  // reverse a tetrahedron 1 bottom
4694               for ( iCur = 0; iCur < 4 && nbStick == 0; iCur++ ) {
4695                 if ( curNodes[ind[ iCur ]] == curNodes[ind[ iCur + 1 ]] )
4696                   nbStick++;
4697                 else if ( iUnique >= 0 )
4698                   uniqueNodes[ iUnique-- ] = curNodes[ind[ iCur ]];
4699               }
4700               if ( nbStick == 0 ) {
4701                 // ... and the opposite one is a quadrangle
4702                 // set a top node
4703                 const int* indTop = hexa.GetFaceNodesIndices( iFace );
4704                 uniqueNodes[ 3 ] = curNodes[indTop[ 0 ]];
4705                 nbUniqueNodes = 4;
4706                 // tetrahedron 2
4707                 SMDS_MeshElement* newElem =
4708                   aMesh->AddVolume(curNodes[ind[ 0 ]],
4709                                    curNodes[ind[ 3 ]],
4710                                    curNodes[ind[ 2 ]],
4711                                    curNodes[indTop[ 0 ]]);
4712                 myLastCreatedElems.Append(newElem);
4713                 if ( aShapeId )
4714                   aMesh->SetMeshElementOnShape( newElem, aShapeId );
4715                 isOk = true;
4716               }
4717               break;
4718             }
4719           }
4720         }
4721         else if ( nbUniqueNodes == 6 && nbRepl == 4 ) {
4722           ////////////////// HEXAHEDRON ---> 2 tetrahedrons or 1 prism
4723           // find indices of quad and tri faces
4724           int iQuadFace[ 6 ], iTriFace[ 6 ], nbQuad = 0, nbTri = 0, iFace;
4725           for ( iFace = 0; iFace < 6; iFace++ ) {
4726             const int *ind = hexa.GetFaceNodesIndices( iFace ); // indices of face nodes
4727             nodeSet.clear();
4728             for ( iCur = 0; iCur < 4; iCur++ )
4729               nodeSet.insert( curNodes[ind[ iCur ]] );
4730             nbUniqueNodes = nodeSet.size();
4731             if ( nbUniqueNodes == 3 )
4732               iTriFace[ nbTri++ ] = iFace;
4733             else if ( nbUniqueNodes == 4 )
4734               iQuadFace[ nbQuad++ ] = iFace;
4735           }
4736           if (nbQuad == 2 && nbTri == 4 &&
4737               hexa.GetOppFaceIndex( iQuadFace[ 0 ] ) == iQuadFace[ 1 ]) {
4738             // 2 opposite quadrangles stuck with a diagonal;
4739             // sample groups of merged indices: (0-4)(2-6)
4740             // --------------------------------------------> 2 tetrahedrons
4741             const int *ind1 = hexa.GetFaceNodesIndices( iQuadFace[ 0 ]); // indices of quad1 nodes
4742             const int *ind2 = hexa.GetFaceNodesIndices( iQuadFace[ 1 ]);
4743             int i0, i1d, i2, i3d, i0t, i2t; // d-daigonal, t-top
4744             if (curNodes[ind1[ 0 ]] == curNodes[ind2[ 0 ]] &&
4745                 curNodes[ind1[ 2 ]] == curNodes[ind2[ 2 ]]) {
4746               // stuck with 0-2 diagonal
4747               i0  = ind1[ 3 ];
4748               i1d = ind1[ 0 ];
4749               i2  = ind1[ 1 ];
4750               i3d = ind1[ 2 ];
4751               i0t = ind2[ 1 ];
4752               i2t = ind2[ 3 ];
4753             }
4754             else if (curNodes[ind1[ 1 ]] == curNodes[ind2[ 3 ]] &&
4755                      curNodes[ind1[ 3 ]] == curNodes[ind2[ 1 ]]) {
4756               // stuck with 1-3 diagonal
4757               i0  = ind1[ 0 ];
4758               i1d = ind1[ 1 ];
4759               i2  = ind1[ 2 ];
4760               i3d = ind1[ 3 ];
4761               i0t = ind2[ 0 ];
4762               i2t = ind2[ 1 ];
4763             }
4764             else {
4765               ASSERT(0);
4766             }
4767             // tetrahedron 1
4768             uniqueNodes[ 0 ] = curNodes [ i0 ];
4769             uniqueNodes[ 1 ] = curNodes [ i1d ];
4770             uniqueNodes[ 2 ] = curNodes [ i3d ];
4771             uniqueNodes[ 3 ] = curNodes [ i0t ];
4772             nbUniqueNodes = 4;
4773             // tetrahedron 2
4774             SMDS_MeshElement* newElem = aMesh->AddVolume(curNodes[ i1d ],
4775                                                          curNodes[ i2 ],
4776                                                          curNodes[ i3d ],
4777                                                          curNodes[ i2t ]);
4778             myLastCreatedElems.Append(newElem);
4779             if ( aShapeId )
4780               aMesh->SetMeshElementOnShape( newElem, aShapeId );
4781             isOk = true;
4782           }
4783           else if (( nbTri == 2 && nbQuad == 3 ) || // merged (0-4)(1-5)
4784                    ( nbTri == 4 && nbQuad == 2 )) { // merged (7-4)(1-5)
4785             // --------------------------------------------> prism
4786             // find 2 opposite triangles
4787             nbUniqueNodes = 6;
4788             for ( iFace = 0; iFace + 1 < nbTri; iFace++ ) {
4789               if ( hexa.GetOppFaceIndex( iTriFace[ iFace ] ) == iTriFace[ iFace + 1 ]) {
4790                 // find indices of kept and replaced nodes
4791                 // and fill unique nodes of 2 opposite triangles
4792                 const int *ind1 = hexa.GetFaceNodesIndices( iTriFace[ iFace ]);
4793                 const int *ind2 = hexa.GetFaceNodesIndices( iTriFace[ iFace + 1 ]);
4794                 const SMDS_MeshNode** hexanodes = hexa.GetNodes();
4795                 // fill unique nodes
4796                 iUnique = 0;
4797                 isOk = true;
4798                 for ( iCur = 0; iCur < 4 && isOk; iCur++ ) {
4799                   const SMDS_MeshNode* n     = curNodes[ind1[ iCur ]];
4800                   const SMDS_MeshNode* nInit = hexanodes[ind1[ iCur ]];
4801                   if ( n == nInit ) {
4802                     // iCur of a linked node of the opposite face (make normals co-directed):
4803                     int iCurOpp = ( iCur == 1 || iCur == 3 ) ? 4 - iCur : iCur;
4804                     // check that correspondent corners of triangles are linked
4805                     if ( !hexa.IsLinked( ind1[ iCur ], ind2[ iCurOpp ] ))
4806                       isOk = false;
4807                     else {
4808                       uniqueNodes[ iUnique ] = n;
4809                       uniqueNodes[ iUnique + 3 ] = curNodes[ind2[ iCurOpp ]];
4810                       iUnique++;
4811                     }
4812                   }
4813                 }
4814                 break;
4815               }
4816             }
4817           }
4818         } // if ( nbUniqueNodes == 6 && nbRepl == 4 )
4819         break;
4820       } // HEXAHEDRON
4821
4822       default:
4823         isOk = false;
4824       } // switch ( nbNodes )
4825
4826     } // if ( nbNodes != nbUniqueNodes ) // some nodes stick
4827
4828     if ( isOk ) {
4829       if (elem->IsPoly() && elem->GetType() == SMDSAbs_Volume) {
4830         // Change nodes of polyedre
4831         const SMDS_PolyhedralVolumeOfNodes* aPolyedre =
4832           static_cast<const SMDS_PolyhedralVolumeOfNodes*>( elem );
4833         if (aPolyedre) {
4834           int nbFaces = aPolyedre->NbFaces();
4835
4836           vector<const SMDS_MeshNode *> poly_nodes;
4837           vector<int> quantities (nbFaces);
4838
4839           for (int iface = 1; iface <= nbFaces; iface++) {
4840             int inode, nbFaceNodes = aPolyedre->NbFaceNodes(iface);
4841             quantities[iface - 1] = nbFaceNodes;
4842
4843             for (inode = 1; inode <= nbFaceNodes; inode++) {
4844               const SMDS_MeshNode* curNode = aPolyedre->GetFaceNode(iface, inode);
4845
4846               TNodeNodeMap::iterator nnIt = nodeNodeMap.find( curNode );
4847               if (nnIt != nodeNodeMap.end()) { // curNode sticks
4848                 curNode = (*nnIt).second;
4849               }
4850               poly_nodes.push_back(curNode);
4851             }
4852           }
4853           aMesh->ChangePolyhedronNodes( elem, poly_nodes, quantities );
4854         }
4855       }
4856       else {
4857         // Change regular element or polygon
4858         aMesh->ChangeElementNodes( elem, uniqueNodes, nbUniqueNodes );
4859       }
4860     }
4861     else {
4862       // Remove invalid regular element or invalid polygon
4863       rmElemIds.push_back( elem->GetID() );
4864     }
4865
4866   } // loop on elements
4867
4868   // Remove equal nodes and bad elements
4869
4870   Remove( rmNodeIds, true );
4871   Remove( rmElemIds, false );
4872
4873 }
4874
4875
4876 // =================================================
4877 // class   : SortableElement
4878 // purpose : auxilary
4879 // =================================================
4880 class SortableElement : public set <const SMDS_MeshElement*>
4881 {
4882  public:
4883
4884   SortableElement( const SMDS_MeshElement* theElem )
4885     {
4886       myID = theElem->GetID();
4887       SMDS_ElemIteratorPtr nodeIt = theElem->nodesIterator();
4888       while ( nodeIt->more() )
4889         this->insert( nodeIt->next() );
4890     }
4891
4892   const long GetID() const
4893     { return myID; }
4894
4895   void SetID(const long anID) const
4896     { myID = anID; }
4897
4898
4899  private:
4900   mutable long myID;
4901 };
4902
4903
4904 //=======================================================================
4905 //function : MergeEqualElements
4906 //purpose  : Remove all but one of elements built on the same nodes.
4907 //=======================================================================
4908
4909 void SMESH_MeshEditor::MergeEqualElements()
4910 {
4911   myLastCreatedElems.Clear();
4912   myLastCreatedNodes.Clear();
4913
4914   SMESHDS_Mesh* aMesh = GetMeshDS();
4915
4916   SMDS_EdgeIteratorPtr   eIt = aMesh->edgesIterator();
4917   SMDS_FaceIteratorPtr   fIt = aMesh->facesIterator();
4918   SMDS_VolumeIteratorPtr vIt = aMesh->volumesIterator();
4919
4920   list< int > rmElemIds; // IDs of elems to remove
4921
4922   for ( int iDim = 1; iDim <= 3; iDim++ ) {
4923
4924     set< SortableElement > setOfNodeSet;
4925     while ( 1 ) {
4926       // get next element
4927       const SMDS_MeshElement* elem = 0;
4928       if ( iDim == 1 ) {
4929         if ( eIt->more() ) elem = eIt->next();
4930       } else if ( iDim == 2 ) {
4931         if ( fIt->more() ) elem = fIt->next();
4932       } else {
4933         if ( vIt->more() ) elem = vIt->next();
4934       }
4935       if ( !elem ) break;
4936
4937       SortableElement SE(elem);
4938
4939       // check uniqueness
4940       pair< set<SortableElement>::iterator, bool> pp = setOfNodeSet.insert(SE);
4941       if( !(pp.second) ) {
4942         set<SortableElement>::iterator itSE = pp.first;
4943         SortableElement SEold = *itSE;
4944         if( SEold.GetID() > SE.GetID() ) {
4945           rmElemIds.push_back( SEold.GetID() );
4946           (*itSE).SetID(SE.GetID());
4947         }
4948         else {
4949           rmElemIds.push_back( SE.GetID() );
4950         }
4951       }
4952     }
4953   }
4954
4955   Remove( rmElemIds, false );
4956 }
4957
4958 //=======================================================================
4959 //function : FindFaceInSet
4960 //purpose  : Return a face having linked nodes n1 and n2 and which is
4961 //           - not in avoidSet,
4962 //           - in elemSet provided that !elemSet.empty()
4963 //=======================================================================
4964
4965 const SMDS_MeshElement*
4966   SMESH_MeshEditor::FindFaceInSet(const SMDS_MeshNode*    n1,
4967                                   const SMDS_MeshNode*    n2,
4968                                   const TIDSortedElemSet& elemSet,
4969                                   const TIDSortedElemSet& avoidSet)
4970
4971 {
4972   SMDS_ElemIteratorPtr invElemIt = n1->GetInverseElementIterator(SMDSAbs_Face);
4973   while ( invElemIt->more() ) { // loop on inverse elements of n1
4974     const SMDS_MeshElement* elem = invElemIt->next();
4975     if (avoidSet.find( elem ) != avoidSet.end() )
4976       continue;
4977     if ( !elemSet.empty() && elemSet.find( elem ) == elemSet.end())
4978       continue;
4979     // get face nodes and find index of n1
4980     int i1, nbN = elem->NbNodes(), iNode = 0;
4981     const SMDS_MeshNode* faceNodes[ nbN ], *n;
4982     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
4983     while ( nIt->more() ) {
4984       faceNodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
4985       if ( faceNodes[ iNode++ ] == n1 )
4986         i1 = iNode - 1;
4987     }
4988     // find a n2 linked to n1
4989     if(!elem->IsQuadratic()) {
4990       for ( iNode = 0; iNode < 2; iNode++ ) {
4991         if ( iNode ) // node before n1
4992           n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
4993         else         // node after n1
4994           n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
4995         if ( n == n2 )
4996           return elem;
4997       }
4998     }
4999     else { // analysis for quadratic elements
5000       bool IsFind = false;
5001       // check using only corner nodes
5002       for ( iNode = 0; iNode < 2; iNode++ ) {
5003         if ( iNode ) // node before n1
5004           n = faceNodes[ i1 == 0 ? nbN/2 - 1 : i1 - 1 ];
5005         else         // node after n1
5006           n = faceNodes[ i1 + 1 == nbN/2 ? 0 : i1 + 1 ];
5007         if ( n == n2 )
5008           IsFind = true;
5009       }
5010       if(IsFind) {
5011         return elem;
5012       }
5013       else {
5014         // check using all nodes
5015         const SMDS_QuadraticFaceOfNodes* F =
5016           static_cast<const SMDS_QuadraticFaceOfNodes*>(elem);
5017         // use special nodes iterator
5018         iNode = 0;
5019         SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5020         while ( anIter->more() ) {
5021           faceNodes[iNode] = static_cast<const SMDS_MeshNode*>(anIter->next());
5022           if ( faceNodes[ iNode++ ] == n1 )
5023             i1 = iNode - 1;
5024         }
5025         for ( iNode = 0; iNode < 2; iNode++ ) {
5026           if ( iNode ) // node before n1
5027             n = faceNodes[ i1 == 0 ? nbN - 1 : i1 - 1 ];
5028           else         // node after n1
5029             n = faceNodes[ i1 + 1 == nbN ? 0 : i1 + 1 ];
5030           if ( n == n2 ) {
5031             return elem;
5032           }
5033         }
5034       }
5035     } // end analysis for quadratic elements
5036   }
5037   return 0;
5038 }
5039
5040 //=======================================================================
5041 //function : findAdjacentFace
5042 //purpose  :
5043 //=======================================================================
5044
5045 static const SMDS_MeshElement* findAdjacentFace(const SMDS_MeshNode* n1,
5046                                                 const SMDS_MeshNode* n2,
5047                                                 const SMDS_MeshElement* elem)
5048 {
5049   TIDSortedElemSet elemSet, avoidSet;
5050   if ( elem )
5051     avoidSet.insert ( elem );
5052   return SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
5053 }
5054
5055 //=======================================================================
5056 //function : FindFreeBorder
5057 //purpose  :
5058 //=======================================================================
5059
5060 #define ControlFreeBorder SMESH::Controls::FreeEdges::IsFreeEdge
5061
5062 bool SMESH_MeshEditor::FindFreeBorder (const SMDS_MeshNode*             theFirstNode,
5063                                        const SMDS_MeshNode*             theSecondNode,
5064                                        const SMDS_MeshNode*             theLastNode,
5065                                        list< const SMDS_MeshNode* > &   theNodes,
5066                                        list< const SMDS_MeshElement* >& theFaces)
5067 {
5068   if ( !theFirstNode || !theSecondNode )
5069     return false;
5070   // find border face between theFirstNode and theSecondNode
5071   const SMDS_MeshElement* curElem = findAdjacentFace( theFirstNode, theSecondNode, 0 );
5072   if ( !curElem )
5073     return false;
5074
5075   theFaces.push_back( curElem );
5076   theNodes.push_back( theFirstNode );
5077   theNodes.push_back( theSecondNode );
5078
5079   //vector<const SMDS_MeshNode*> nodes;
5080   const SMDS_MeshNode *nIgnore = theFirstNode, *nStart = theSecondNode;
5081   set < const SMDS_MeshElement* > foundElems;
5082   bool needTheLast = ( theLastNode != 0 );
5083
5084   while ( nStart != theLastNode ) {
5085     if ( nStart == theFirstNode )
5086       return !needTheLast;
5087
5088     // find all free border faces sharing form nStart
5089
5090     list< const SMDS_MeshElement* > curElemList;
5091     list< const SMDS_MeshNode* > nStartList;
5092     SMDS_ElemIteratorPtr invElemIt = nStart->GetInverseElementIterator(SMDSAbs_Face);
5093     while ( invElemIt->more() ) {
5094       const SMDS_MeshElement* e = invElemIt->next();
5095       if ( e == curElem || foundElems.insert( e ).second ) {
5096         // get nodes
5097         int iNode = 0, nbNodes = e->NbNodes();
5098         const SMDS_MeshNode* nodes[nbNodes+1];
5099         if(e->IsQuadratic()) {
5100           const SMDS_QuadraticFaceOfNodes* F =
5101             static_cast<const SMDS_QuadraticFaceOfNodes*>(e);
5102           // use special nodes iterator
5103           SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5104           while( anIter->more() ) {
5105             nodes[ iNode++ ] = anIter->next();
5106           }
5107         }
5108         else {
5109           SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5110           while ( nIt->more() )
5111             nodes[ iNode++ ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
5112         }
5113         nodes[ iNode ] = nodes[ 0 ];
5114         // check 2 links
5115         for ( iNode = 0; iNode < nbNodes; iNode++ )
5116           if (((nodes[ iNode ] == nStart && nodes[ iNode + 1] != nIgnore ) ||
5117                (nodes[ iNode + 1] == nStart && nodes[ iNode ] != nIgnore )) &&
5118               ControlFreeBorder( &nodes[ iNode ], e->GetID() ))
5119           {
5120             nStartList.push_back( nodes[ iNode + ( nodes[ iNode ] == nStart ? 1 : 0 )]);
5121             curElemList.push_back( e );
5122           }
5123       }
5124     }
5125     // analyse the found
5126
5127     int nbNewBorders = curElemList.size();
5128     if ( nbNewBorders == 0 ) {
5129       // no free border furthermore
5130       return !needTheLast;
5131     }
5132     else if ( nbNewBorders == 1 ) {
5133       // one more element found
5134       nIgnore = nStart;
5135       nStart = nStartList.front();
5136       curElem = curElemList.front();
5137       theFaces.push_back( curElem );
5138       theNodes.push_back( nStart );
5139     }
5140     else {
5141       // several continuations found
5142       list< const SMDS_MeshElement* >::iterator curElemIt;
5143       list< const SMDS_MeshNode* >::iterator nStartIt;
5144       // check if one of them reached the last node
5145       if ( needTheLast ) {
5146         for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
5147              curElemIt!= curElemList.end();
5148              curElemIt++, nStartIt++ )
5149           if ( *nStartIt == theLastNode ) {
5150             theFaces.push_back( *curElemIt );
5151             theNodes.push_back( *nStartIt );
5152             return true;
5153           }
5154       }
5155       // find the best free border by the continuations
5156       list<const SMDS_MeshNode*>    contNodes[ 2 ], *cNL;
5157       list<const SMDS_MeshElement*> contFaces[ 2 ], *cFL;
5158       for (curElemIt = curElemList.begin(), nStartIt = nStartList.begin();
5159            curElemIt!= curElemList.end();
5160            curElemIt++, nStartIt++ )
5161       {
5162         cNL = & contNodes[ contNodes[0].empty() ? 0 : 1 ];
5163         cFL = & contFaces[ contFaces[0].empty() ? 0 : 1 ];
5164         // find one more free border
5165         if ( ! FindFreeBorder( nStart, *nStartIt, theLastNode, *cNL, *cFL )) {
5166           cNL->clear();
5167           cFL->clear();
5168         }
5169         else if ( !contNodes[0].empty() && !contNodes[1].empty() ) {
5170           // choice: clear a worse one
5171           int iLongest = ( contNodes[0].size() < contNodes[1].size() ? 1 : 0 );
5172           int iWorse = ( needTheLast ? 1 - iLongest : iLongest );
5173           contNodes[ iWorse ].clear();
5174           contFaces[ iWorse ].clear();
5175         }
5176       }
5177       if ( contNodes[0].empty() && contNodes[1].empty() )
5178         return false;
5179
5180       // append the best free border
5181       cNL = & contNodes[ contNodes[0].empty() ? 1 : 0 ];
5182       cFL = & contFaces[ contFaces[0].empty() ? 1 : 0 ];
5183       theNodes.pop_back(); // remove nIgnore
5184       theNodes.pop_back(); // remove nStart
5185       theFaces.pop_back(); // remove curElem
5186       list< const SMDS_MeshNode* >::iterator nIt = cNL->begin();
5187       list< const SMDS_MeshElement* >::iterator fIt = cFL->begin();
5188       for ( ; nIt != cNL->end(); nIt++ ) theNodes.push_back( *nIt );
5189       for ( ; fIt != cFL->end(); fIt++ ) theFaces.push_back( *fIt );
5190       return true;
5191
5192     } // several continuations found
5193   } // while ( nStart != theLastNode )
5194
5195   return true;
5196 }
5197
5198 //=======================================================================
5199 //function : CheckFreeBorderNodes
5200 //purpose  : Return true if the tree nodes are on a free border
5201 //=======================================================================
5202
5203 bool SMESH_MeshEditor::CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
5204                                             const SMDS_MeshNode* theNode2,
5205                                             const SMDS_MeshNode* theNode3)
5206 {
5207   list< const SMDS_MeshNode* > nodes;
5208   list< const SMDS_MeshElement* > faces;
5209   return FindFreeBorder( theNode1, theNode2, theNode3, nodes, faces);
5210 }
5211
5212 //=======================================================================
5213 //function : SewFreeBorder
5214 //purpose  :
5215 //=======================================================================
5216
5217 SMESH_MeshEditor::Sew_Error
5218   SMESH_MeshEditor::SewFreeBorder (const SMDS_MeshNode* theBordFirstNode,
5219                                    const SMDS_MeshNode* theBordSecondNode,
5220                                    const SMDS_MeshNode* theBordLastNode,
5221                                    const SMDS_MeshNode* theSideFirstNode,
5222                                    const SMDS_MeshNode* theSideSecondNode,
5223                                    const SMDS_MeshNode* theSideThirdNode,
5224                                    const bool           theSideIsFreeBorder,
5225                                    const bool           toCreatePolygons,
5226                                    const bool           toCreatePolyedrs)
5227 {
5228   myLastCreatedElems.Clear();
5229   myLastCreatedNodes.Clear();
5230
5231   MESSAGE("::SewFreeBorder()");
5232   Sew_Error aResult = SEW_OK;
5233
5234   // ====================================
5235   //    find side nodes and elements
5236   // ====================================
5237
5238   list< const SMDS_MeshNode* > nSide[ 2 ];
5239   list< const SMDS_MeshElement* > eSide[ 2 ];
5240   list< const SMDS_MeshNode* >::iterator nIt[ 2 ];
5241   list< const SMDS_MeshElement* >::iterator eIt[ 2 ];
5242
5243   // Free border 1
5244   // --------------
5245   if (!FindFreeBorder(theBordFirstNode,theBordSecondNode,theBordLastNode,
5246                       nSide[0], eSide[0])) {
5247     MESSAGE(" Free Border 1 not found " );
5248     aResult = SEW_BORDER1_NOT_FOUND;
5249   }
5250   if (theSideIsFreeBorder) {
5251     // Free border 2
5252     // --------------
5253     if (!FindFreeBorder(theSideFirstNode, theSideSecondNode, theSideThirdNode,
5254                         nSide[1], eSide[1])) {
5255       MESSAGE(" Free Border 2 not found " );
5256       aResult = ( aResult != SEW_OK ? SEW_BOTH_BORDERS_NOT_FOUND : SEW_BORDER2_NOT_FOUND );
5257     }
5258   }
5259   if ( aResult != SEW_OK )
5260     return aResult;
5261
5262   if (!theSideIsFreeBorder) {
5263     // Side 2
5264     // --------------
5265
5266     // -------------------------------------------------------------------------
5267     // Algo:
5268     // 1. If nodes to merge are not coincident, move nodes of the free border
5269     //    from the coord sys defined by the direction from the first to last
5270     //    nodes of the border to the correspondent sys of the side 2
5271     // 2. On the side 2, find the links most co-directed with the correspondent
5272     //    links of the free border
5273     // -------------------------------------------------------------------------
5274
5275     // 1. Since sewing may brake if there are volumes to split on the side 2,
5276     //    we wont move nodes but just compute new coordinates for them
5277     typedef map<const SMDS_MeshNode*, gp_XYZ> TNodeXYZMap;
5278     TNodeXYZMap nBordXYZ;
5279     list< const SMDS_MeshNode* >& bordNodes = nSide[ 0 ];
5280     list< const SMDS_MeshNode* >::iterator nBordIt;
5281
5282     gp_XYZ Pb1( theBordFirstNode->X(), theBordFirstNode->Y(), theBordFirstNode->Z() );
5283     gp_XYZ Pb2( theBordLastNode->X(), theBordLastNode->Y(), theBordLastNode->Z() );
5284     gp_XYZ Ps1( theSideFirstNode->X(), theSideFirstNode->Y(), theSideFirstNode->Z() );
5285     gp_XYZ Ps2( theSideSecondNode->X(), theSideSecondNode->Y(), theSideSecondNode->Z() );
5286     double tol2 = 1.e-8;
5287     gp_Vec Vbs1( Pb1 - Ps1 ),Vbs2( Pb2 - Ps2 );
5288     if ( Vbs1.SquareMagnitude() > tol2 || Vbs2.SquareMagnitude() > tol2 ) {
5289       // Need node movement.
5290
5291       // find X and Z axes to create trsf
5292       gp_Vec Zb( Pb1 - Pb2 ), Zs( Ps1 - Ps2 );
5293       gp_Vec X = Zs ^ Zb;
5294       if ( X.SquareMagnitude() <= gp::Resolution() * gp::Resolution() )
5295         // Zb || Zs
5296         X = gp_Ax2( gp::Origin(), Zb ).XDirection();
5297
5298       // coord systems
5299       gp_Ax3 toBordAx( Pb1, Zb, X );
5300       gp_Ax3 fromSideAx( Ps1, Zs, X );
5301       gp_Ax3 toGlobalAx( gp::Origin(), gp::DZ(), gp::DX() );
5302       // set trsf
5303       gp_Trsf toBordSys, fromSide2Sys;
5304       toBordSys.SetTransformation( toBordAx );
5305       fromSide2Sys.SetTransformation( fromSideAx, toGlobalAx );
5306       fromSide2Sys.SetScaleFactor( Zs.Magnitude() / Zb.Magnitude() );
5307
5308       // move
5309       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
5310         const SMDS_MeshNode* n = *nBordIt;
5311         gp_XYZ xyz( n->X(),n->Y(),n->Z() );
5312         toBordSys.Transforms( xyz );
5313         fromSide2Sys.Transforms( xyz );
5314         nBordXYZ.insert( TNodeXYZMap::value_type( n, xyz ));
5315       }
5316     }
5317     else {
5318       // just insert nodes XYZ in the nBordXYZ map
5319       for ( nBordIt = bordNodes.begin(); nBordIt != bordNodes.end(); nBordIt++ ) {
5320         const SMDS_MeshNode* n = *nBordIt;
5321         nBordXYZ.insert( TNodeXYZMap::value_type( n, gp_XYZ( n->X(),n->Y(),n->Z() )));
5322       }
5323     }
5324
5325     // 2. On the side 2, find the links most co-directed with the correspondent
5326     //    links of the free border
5327
5328     list< const SMDS_MeshElement* >& sideElems = eSide[ 1 ];
5329     list< const SMDS_MeshNode* >& sideNodes = nSide[ 1 ];
5330     sideNodes.push_back( theSideFirstNode );
5331
5332     bool hasVolumes = false;
5333     LinkID_Gen aLinkID_Gen( GetMeshDS() );
5334     set<long> foundSideLinkIDs, checkedLinkIDs;
5335     SMDS_VolumeTool volume;
5336     //const SMDS_MeshNode* faceNodes[ 4 ];
5337
5338     const SMDS_MeshNode*    sideNode;
5339     const SMDS_MeshElement* sideElem;
5340     const SMDS_MeshNode* prevSideNode = theSideFirstNode;
5341     const SMDS_MeshNode* prevBordNode = theBordFirstNode;
5342     nBordIt = bordNodes.begin();
5343     nBordIt++;
5344     // border node position and border link direction to compare with
5345     gp_XYZ bordPos = nBordXYZ[ *nBordIt ];
5346     gp_XYZ bordDir = bordPos - nBordXYZ[ prevBordNode ];
5347     // choose next side node by link direction or by closeness to
5348     // the current border node:
5349     bool searchByDir = ( *nBordIt != theBordLastNode );
5350     do {
5351       // find the next node on the Side 2
5352       sideNode = 0;
5353       double maxDot = -DBL_MAX, minDist = DBL_MAX;
5354       long linkID;
5355       checkedLinkIDs.clear();
5356       gp_XYZ prevXYZ( prevSideNode->X(), prevSideNode->Y(), prevSideNode->Z() );
5357
5358       // loop on inverse elements of current node (prevSideNode) on the Side 2
5359       SMDS_ElemIteratorPtr invElemIt = prevSideNode->GetInverseElementIterator();
5360       while ( invElemIt->more() )
5361       {
5362         const SMDS_MeshElement* elem = invElemIt->next();
5363         // prepare data for a loop on links coming to prevSideNode, of a face or a volume
5364         int iPrevNode, iNode = 0, nbNodes = elem->NbNodes();
5365         const SMDS_MeshNode* faceNodes[ nbNodes ];
5366         bool isVolume = volume.Set( elem );
5367         const SMDS_MeshNode** nodes = isVolume ? volume.GetNodes() : faceNodes;
5368         if ( isVolume ) // --volume
5369           hasVolumes = true;
5370         //else if ( nbNodes > 2 ) { // --face
5371         else if ( elem->GetType()==SMDSAbs_Face ) { // --face
5372           // retrieve all face nodes and find iPrevNode - an index of the prevSideNode
5373           if(elem->IsQuadratic()) {
5374             const SMDS_QuadraticFaceOfNodes* F =
5375               static_cast<const SMDS_QuadraticFaceOfNodes*>(elem);
5376             // use special nodes iterator
5377             SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5378             while( anIter->more() ) {
5379               nodes[ iNode ] = anIter->next();
5380               if ( nodes[ iNode++ ] == prevSideNode )
5381                 iPrevNode = iNode - 1;
5382             }
5383           }
5384           else {
5385             SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
5386             while ( nIt->more() ) {
5387               nodes[ iNode ] = static_cast<const SMDS_MeshNode*>( nIt->next() );
5388               if ( nodes[ iNode++ ] == prevSideNode )
5389                 iPrevNode = iNode - 1;
5390             }
5391           }
5392           // there are 2 links to check
5393           nbNodes = 2;
5394         }
5395         else // --edge
5396           continue;
5397         // loop on links, to be precise, on the second node of links
5398         for ( iNode = 0; iNode < nbNodes; iNode++ ) {
5399           const SMDS_MeshNode* n = nodes[ iNode ];
5400           if ( isVolume ) {
5401             if ( !volume.IsLinked( n, prevSideNode ))
5402               continue;
5403           }
5404           else {
5405             if ( iNode ) // a node before prevSideNode
5406               n = nodes[ iPrevNode == 0 ? elem->NbNodes() - 1 : iPrevNode - 1 ];
5407             else         // a node after prevSideNode
5408               n = nodes[ iPrevNode + 1 == elem->NbNodes() ? 0 : iPrevNode + 1 ];
5409           }
5410           // check if this link was already used
5411           long iLink = aLinkID_Gen.GetLinkID( prevSideNode, n );
5412           bool isJustChecked = !checkedLinkIDs.insert( iLink ).second;
5413           if (!isJustChecked &&
5414               foundSideLinkIDs.find( iLink ) == foundSideLinkIDs.end() )
5415           {
5416             // test a link geometrically
5417             gp_XYZ nextXYZ ( n->X(), n->Y(), n->Z() );
5418             bool linkIsBetter = false;
5419             double dot, dist;
5420             if ( searchByDir ) { // choose most co-directed link
5421               dot = bordDir * ( nextXYZ - prevXYZ ).Normalized();
5422               linkIsBetter = ( dot > maxDot );
5423             }
5424             else { // choose link with the node closest to bordPos
5425               dist = ( nextXYZ - bordPos ).SquareModulus();
5426               linkIsBetter = ( dist < minDist );
5427             }
5428             if ( linkIsBetter ) {
5429               maxDot = dot;
5430               minDist = dist;
5431               linkID = iLink;
5432               sideNode = n;
5433               sideElem = elem;
5434             }
5435           }
5436         }
5437       } // loop on inverse elements of prevSideNode
5438
5439       if ( !sideNode ) {
5440         MESSAGE(" Cant find path by links of the Side 2 ");
5441         return SEW_BAD_SIDE_NODES;
5442       }
5443       sideNodes.push_back( sideNode );
5444       sideElems.push_back( sideElem );
5445       foundSideLinkIDs.insert ( linkID );
5446       prevSideNode = sideNode;
5447
5448       if ( *nBordIt == theBordLastNode )
5449         searchByDir = false;
5450       else {
5451         // find the next border link to compare with
5452         gp_XYZ sidePos( sideNode->X(), sideNode->Y(), sideNode->Z() );
5453         searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
5454         // move to next border node if sideNode is before forward border node (bordPos)
5455         while ( *nBordIt != theBordLastNode && !searchByDir ) {
5456           prevBordNode = *nBordIt;
5457           nBordIt++;
5458           bordPos = nBordXYZ[ *nBordIt ];
5459           bordDir = bordPos - nBordXYZ[ prevBordNode ];
5460           searchByDir = ( bordDir * ( sidePos - bordPos ) <= 0 );
5461         }
5462       }
5463     }
5464     while ( sideNode != theSideSecondNode );
5465
5466     if ( hasVolumes && sideNodes.size () != bordNodes.size() && !toCreatePolyedrs) {
5467       MESSAGE("VOLUME SPLITTING IS FORBIDDEN");
5468       return SEW_VOLUMES_TO_SPLIT; // volume splitting is forbidden
5469     }
5470   } // end nodes search on the side 2
5471
5472   // ============================
5473   // sew the border to the side 2
5474   // ============================
5475
5476   int nbNodes[]  = { nSide[0].size(), nSide[1].size() };
5477   int maxNbNodes = Max( nbNodes[0], nbNodes[1] );
5478
5479   TListOfListOfNodes nodeGroupsToMerge;
5480   if ( nbNodes[0] == nbNodes[1] ||
5481       ( theSideIsFreeBorder && !theSideThirdNode)) {
5482
5483     // all nodes are to be merged
5484
5485     for (nIt[0] = nSide[0].begin(), nIt[1] = nSide[1].begin();
5486          nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end();
5487          nIt[0]++, nIt[1]++ )
5488     {
5489       nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
5490       nodeGroupsToMerge.back().push_back( *nIt[1] ); // to keep
5491       nodeGroupsToMerge.back().push_back( *nIt[0] ); // tp remove
5492     }
5493   }
5494   else {
5495
5496     // insert new nodes into the border and the side to get equal nb of segments
5497
5498     // get normalized parameters of nodes on the borders
5499     double param[ 2 ][ maxNbNodes ];
5500     int iNode, iBord;
5501     for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
5502       list< const SMDS_MeshNode* >& nodes = nSide[ iBord ];
5503       list< const SMDS_MeshNode* >::iterator nIt = nodes.begin();
5504       const SMDS_MeshNode* nPrev = *nIt;
5505       double bordLength = 0;
5506       for ( iNode = 0; nIt != nodes.end(); nIt++, iNode++ ) { // loop on border nodes
5507         const SMDS_MeshNode* nCur = *nIt;
5508         gp_XYZ segment (nCur->X() - nPrev->X(),
5509                         nCur->Y() - nPrev->Y(),
5510                         nCur->Z() - nPrev->Z());
5511         double segmentLen = segment.Modulus();
5512         bordLength += segmentLen;
5513         param[ iBord ][ iNode ] = bordLength;
5514         nPrev = nCur;
5515       }
5516       // normalize within [0,1]
5517       for ( iNode = 0; iNode < nbNodes[ iBord ]; iNode++ ) {
5518         param[ iBord ][ iNode ] /= bordLength;
5519       }
5520     }
5521
5522     // loop on border segments
5523     const SMDS_MeshNode *nPrev[ 2 ] = { 0, 0 };
5524     int i[ 2 ] = { 0, 0 };
5525     nIt[0] = nSide[0].begin(); eIt[0] = eSide[0].begin();
5526     nIt[1] = nSide[1].begin(); eIt[1] = eSide[1].begin();
5527
5528     TElemOfNodeListMap insertMap;
5529     TElemOfNodeListMap::iterator insertMapIt;
5530     // insertMap is
5531     // key:   elem to insert nodes into
5532     // value: 2 nodes to insert between + nodes to be inserted
5533     do {
5534       bool next[ 2 ] = { false, false };
5535
5536       // find min adjacent segment length after sewing
5537       double nextParam = 10., prevParam = 0;
5538       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
5539         if ( i[ iBord ] + 1 < nbNodes[ iBord ])
5540           nextParam = Min( nextParam, param[iBord][ i[iBord] + 1 ]);
5541         if ( i[ iBord ] > 0 )
5542           prevParam = Max( prevParam, param[iBord][ i[iBord] - 1 ]);
5543       }
5544       double minParam = Min( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
5545       double maxParam = Max( param[ 0 ][ i[0] ], param[ 1 ][ i[1] ]);
5546       double minSegLen = Min( nextParam - minParam, maxParam - prevParam );
5547
5548       // choose to insert or to merge nodes
5549       double du = param[ 1 ][ i[1] ] - param[ 0 ][ i[0] ];
5550       if ( Abs( du ) <= minSegLen * 0.2 ) {
5551         // merge
5552         // ------
5553         nodeGroupsToMerge.push_back( list<const SMDS_MeshNode*>() );
5554         const SMDS_MeshNode* n0 = *nIt[0];
5555         const SMDS_MeshNode* n1 = *nIt[1];
5556         nodeGroupsToMerge.back().push_back( n1 );
5557         nodeGroupsToMerge.back().push_back( n0 );
5558         // position of node of the border changes due to merge
5559         param[ 0 ][ i[0] ] += du;
5560         // move n1 for the sake of elem shape evaluation during insertion.
5561         // n1 will be removed by MergeNodes() anyway
5562         const_cast<SMDS_MeshNode*>( n0 )->setXYZ( n1->X(), n1->Y(), n1->Z() );
5563         next[0] = next[1] = true;
5564       }
5565       else {
5566         // insert
5567         // ------
5568         int intoBord = ( du < 0 ) ? 0 : 1;
5569         const SMDS_MeshElement* elem = *eIt[ intoBord ];
5570         const SMDS_MeshNode*    n1   = nPrev[ intoBord ];
5571         const SMDS_MeshNode*    n2   = *nIt[ intoBord ];
5572         const SMDS_MeshNode*    nIns = *nIt[ 1 - intoBord ];
5573         if ( intoBord == 1 ) {
5574           // move node of the border to be on a link of elem of the side
5575           gp_XYZ p1 (n1->X(), n1->Y(), n1->Z());
5576           gp_XYZ p2 (n2->X(), n2->Y(), n2->Z());
5577           double ratio = du / ( param[ 1 ][ i[1] ] - param[ 1 ][ i[1]-1 ]);
5578           gp_XYZ p = p2 * ( 1 - ratio ) + p1 * ratio;
5579           GetMeshDS()->MoveNode( nIns, p.X(), p.Y(), p.Z() );
5580         }
5581         insertMapIt = insertMap.find( elem );
5582         bool notFound = ( insertMapIt == insertMap.end() );
5583         bool otherLink = ( !notFound && (*insertMapIt).second.front() != n1 );
5584         if ( otherLink ) {
5585           // insert into another link of the same element:
5586           // 1. perform insertion into the other link of the elem
5587           list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
5588           const SMDS_MeshNode* n12 = nodeList.front(); nodeList.pop_front();
5589           const SMDS_MeshNode* n22 = nodeList.front(); nodeList.pop_front();
5590           InsertNodesIntoLink( elem, n12, n22, nodeList, toCreatePolygons );
5591           // 2. perform insertion into the link of adjacent faces
5592           while (true) {
5593             const SMDS_MeshElement* adjElem = findAdjacentFace( n12, n22, elem );
5594             if ( adjElem )
5595               InsertNodesIntoLink( adjElem, n12, n22, nodeList, toCreatePolygons );
5596             else
5597               break;
5598           }
5599           if (toCreatePolyedrs) {
5600             // perform insertion into the links of adjacent volumes
5601             UpdateVolumes(n12, n22, nodeList);
5602           }
5603           // 3. find an element appeared on n1 and n2 after the insertion
5604           insertMap.erase( elem );
5605           elem = findAdjacentFace( n1, n2, 0 );
5606         }
5607         if ( notFound || otherLink ) {
5608           // add element and nodes of the side into the insertMap
5609           insertMapIt = insertMap.insert
5610             ( TElemOfNodeListMap::value_type( elem, list<const SMDS_MeshNode*>() )).first;
5611           (*insertMapIt).second.push_back( n1 );
5612           (*insertMapIt).second.push_back( n2 );
5613         }
5614         // add node to be inserted into elem
5615         (*insertMapIt).second.push_back( nIns );
5616         next[ 1 - intoBord ] = true;
5617       }
5618
5619       // go to the next segment
5620       for ( iBord = 0; iBord < 2; iBord++ ) { // loop on 2 borders
5621         if ( next[ iBord ] ) {
5622           if ( i[ iBord ] != 0 && eIt[ iBord ] != eSide[ iBord ].end())
5623             eIt[ iBord ]++;
5624           nPrev[ iBord ] = *nIt[ iBord ];
5625           nIt[ iBord ]++; i[ iBord ]++;
5626         }
5627       }
5628     }
5629     while ( nIt[0] != nSide[0].end() && nIt[1] != nSide[1].end());
5630
5631     // perform insertion of nodes into elements
5632
5633     for (insertMapIt = insertMap.begin();
5634          insertMapIt != insertMap.end();
5635          insertMapIt++ )
5636     {
5637       const SMDS_MeshElement* elem = (*insertMapIt).first;
5638       list<const SMDS_MeshNode*> & nodeList = (*insertMapIt).second;
5639       const SMDS_MeshNode* n1 = nodeList.front(); nodeList.pop_front();
5640       const SMDS_MeshNode* n2 = nodeList.front(); nodeList.pop_front();
5641
5642       InsertNodesIntoLink( elem, n1, n2, nodeList, toCreatePolygons );
5643
5644       if ( !theSideIsFreeBorder ) {
5645         // look for and insert nodes into the faces adjacent to elem
5646         while (true) {
5647           const SMDS_MeshElement* adjElem = findAdjacentFace( n1, n2, elem );
5648           if ( adjElem )
5649             InsertNodesIntoLink( adjElem, n1, n2, nodeList, toCreatePolygons );
5650           else
5651             break;
5652         }
5653       }
5654       if (toCreatePolyedrs) {
5655         // perform insertion into the links of adjacent volumes
5656         UpdateVolumes(n1, n2, nodeList);
5657       }
5658     }
5659
5660   } // end: insert new nodes
5661
5662   MergeNodes ( nodeGroupsToMerge );
5663
5664   return aResult;
5665 }
5666
5667 //=======================================================================
5668 //function : InsertNodesIntoLink
5669 //purpose  : insert theNodesToInsert into theFace between theBetweenNode1
5670 //           and theBetweenNode2 and split theElement
5671 //=======================================================================
5672
5673 void SMESH_MeshEditor::InsertNodesIntoLink(const SMDS_MeshElement*     theFace,
5674                                            const SMDS_MeshNode*        theBetweenNode1,
5675                                            const SMDS_MeshNode*        theBetweenNode2,
5676                                            list<const SMDS_MeshNode*>& theNodesToInsert,
5677                                            const bool                  toCreatePoly)
5678 {
5679   if ( theFace->GetType() != SMDSAbs_Face ) return;
5680
5681   // find indices of 2 link nodes and of the rest nodes
5682   int iNode = 0, il1, il2, i3, i4;
5683   il1 = il2 = i3 = i4 = -1;
5684   const SMDS_MeshNode* nodes[ theFace->NbNodes() ];
5685
5686   if(theFace->IsQuadratic()) {
5687     const SMDS_QuadraticFaceOfNodes* F =
5688       static_cast<const SMDS_QuadraticFaceOfNodes*>(theFace);
5689     // use special nodes iterator
5690     SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5691     while( anIter->more() ) {
5692       const SMDS_MeshNode* n = anIter->next();
5693       if ( n == theBetweenNode1 )
5694         il1 = iNode;
5695       else if ( n == theBetweenNode2 )
5696         il2 = iNode;
5697       else if ( i3 < 0 )
5698         i3 = iNode;
5699       else
5700         i4 = iNode;
5701       nodes[ iNode++ ] = n;
5702     }
5703   }
5704   else {
5705     SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
5706     while ( nodeIt->more() ) {
5707       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
5708       if ( n == theBetweenNode1 )
5709         il1 = iNode;
5710       else if ( n == theBetweenNode2 )
5711         il2 = iNode;
5712       else if ( i3 < 0 )
5713         i3 = iNode;
5714       else
5715         i4 = iNode;
5716       nodes[ iNode++ ] = n;
5717     }
5718   }
5719   if ( il1 < 0 || il2 < 0 || i3 < 0 )
5720     return ;
5721
5722   // arrange link nodes to go one after another regarding the face orientation
5723   bool reverse = ( Abs( il2 - il1 ) == 1 ? il2 < il1 : il1 < il2 );
5724   list<const SMDS_MeshNode *> aNodesToInsert = theNodesToInsert;
5725   if ( reverse ) {
5726     iNode = il1;
5727     il1 = il2;
5728     il2 = iNode;
5729     aNodesToInsert.reverse();
5730   }
5731   // check that not link nodes of a quadrangles are in good order
5732   int nbFaceNodes = theFace->NbNodes();
5733   if ( nbFaceNodes == 4 && i4 - i3 != 1 ) {
5734     iNode = i3;
5735     i3 = i4;
5736     i4 = iNode;
5737   }
5738
5739   if (toCreatePoly || theFace->IsPoly()) {
5740
5741     iNode = 0;
5742     vector<const SMDS_MeshNode *> poly_nodes (nbFaceNodes + aNodesToInsert.size());
5743
5744     // add nodes of face up to first node of link
5745     bool isFLN = false;
5746
5747     if(theFace->IsQuadratic()) {
5748       const SMDS_QuadraticFaceOfNodes* F =
5749         static_cast<const SMDS_QuadraticFaceOfNodes*>(theFace);
5750       // use special nodes iterator
5751       SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
5752       while( anIter->more()  && !isFLN ) {
5753         const SMDS_MeshNode* n = anIter->next();
5754         poly_nodes[iNode++] = n;
5755         if (n == nodes[il1]) {
5756           isFLN = true;
5757         }
5758       }
5759       // add nodes to insert
5760       list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
5761       for (; nIt != aNodesToInsert.end(); nIt++) {
5762         poly_nodes[iNode++] = *nIt;
5763       }
5764       // add nodes of face starting from last node of link
5765       while ( anIter->more() ) {
5766         poly_nodes[iNode++] = anIter->next();
5767       }
5768     }
5769     else {
5770       SMDS_ElemIteratorPtr nodeIt = theFace->nodesIterator();
5771       while ( nodeIt->more() && !isFLN ) {
5772         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
5773         poly_nodes[iNode++] = n;
5774         if (n == nodes[il1]) {
5775           isFLN = true;
5776         }
5777       }
5778       // add nodes to insert
5779       list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
5780       for (; nIt != aNodesToInsert.end(); nIt++) {
5781         poly_nodes[iNode++] = *nIt;
5782       }
5783       // add nodes of face starting from last node of link
5784       while ( nodeIt->more() ) {
5785         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
5786         poly_nodes[iNode++] = n;
5787       }
5788     }
5789
5790     // edit or replace the face
5791     SMESHDS_Mesh *aMesh = GetMeshDS();
5792
5793     if (theFace->IsPoly()) {
5794       aMesh->ChangePolygonNodes(theFace, poly_nodes);
5795     }
5796     else {
5797       int aShapeId = FindShape( theFace );
5798
5799       SMDS_MeshElement* newElem = aMesh->AddPolygonalFace(poly_nodes);
5800       myLastCreatedElems.Append(newElem);
5801       if ( aShapeId && newElem )
5802         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5803
5804       aMesh->RemoveElement(theFace);
5805     }
5806     return;
5807   }
5808
5809   if( !theFace->IsQuadratic() ) {
5810
5811     // put aNodesToInsert between theBetweenNode1 and theBetweenNode2
5812     int nbLinkNodes = 2 + aNodesToInsert.size();
5813     const SMDS_MeshNode* linkNodes[ nbLinkNodes ];
5814     linkNodes[ 0 ] = nodes[ il1 ];
5815     linkNodes[ nbLinkNodes - 1 ] = nodes[ il2 ];
5816     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
5817     for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
5818       linkNodes[ iNode++ ] = *nIt;
5819     }
5820     // decide how to split a quadrangle: compare possible variants
5821     // and choose which of splits to be a quadrangle
5822     int i1, i2, iSplit, nbSplits = nbLinkNodes - 1, iBestQuad;
5823     if ( nbFaceNodes == 3 ) {
5824       iBestQuad = nbSplits;
5825       i4 = i3;
5826     }
5827     else if ( nbFaceNodes == 4 ) {
5828       SMESH::Controls::NumericalFunctorPtr aCrit( new SMESH::Controls::AspectRatio);
5829       double aBestRate = DBL_MAX;
5830       for ( int iQuad = 0; iQuad < nbSplits; iQuad++ ) {
5831         i1 = 0; i2 = 1;
5832         double aBadRate = 0;
5833         // evaluate elements quality
5834         for ( iSplit = 0; iSplit < nbSplits; iSplit++ ) {
5835           if ( iSplit == iQuad ) {
5836             SMDS_FaceOfNodes quad (linkNodes[ i1++ ],
5837                                    linkNodes[ i2++ ],
5838                                    nodes[ i3 ],
5839                                    nodes[ i4 ]);
5840             aBadRate += getBadRate( &quad, aCrit );
5841           }
5842           else {
5843             SMDS_FaceOfNodes tria (linkNodes[ i1++ ],
5844                                    linkNodes[ i2++ ],
5845                                    nodes[ iSplit < iQuad ? i4 : i3 ]);
5846             aBadRate += getBadRate( &tria, aCrit );
5847           }
5848         }
5849         // choice
5850         if ( aBadRate < aBestRate ) {
5851           iBestQuad = iQuad;
5852           aBestRate = aBadRate;
5853         }
5854       }
5855     }
5856     
5857     // create new elements
5858     SMESHDS_Mesh *aMesh = GetMeshDS();
5859     int aShapeId = FindShape( theFace );
5860     
5861     i1 = 0; i2 = 1;
5862     for ( iSplit = 0; iSplit < nbSplits - 1; iSplit++ ) {
5863       SMDS_MeshElement* newElem = 0;
5864       if ( iSplit == iBestQuad )
5865         newElem = aMesh->AddFace (linkNodes[ i1++ ],
5866                                   linkNodes[ i2++ ],
5867                                   nodes[ i3 ],
5868                                   nodes[ i4 ]);
5869       else
5870         newElem = aMesh->AddFace (linkNodes[ i1++ ],
5871                                   linkNodes[ i2++ ],
5872                                   nodes[ iSplit < iBestQuad ? i4 : i3 ]);
5873       myLastCreatedElems.Append(newElem);
5874       if ( aShapeId && newElem )
5875         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5876     }
5877     
5878     // change nodes of theFace
5879     const SMDS_MeshNode* newNodes[ 4 ];
5880     newNodes[ 0 ] = linkNodes[ i1 ];
5881     newNodes[ 1 ] = linkNodes[ i2 ];
5882     newNodes[ 2 ] = nodes[ iSplit >= iBestQuad ? i3 : i4 ];
5883     newNodes[ 3 ] = nodes[ i4 ];
5884     aMesh->ChangeElementNodes( theFace, newNodes, iSplit == iBestQuad ? 4 : 3 );
5885   } // end if(!theFace->IsQuadratic())
5886   else { // theFace is quadratic
5887     // we have to split theFace on simple triangles and one simple quadrangle
5888     int tmp = il1/2;
5889     int nbshift = tmp*2;
5890     // shift nodes in nodes[] by nbshift
5891     int i,j;
5892     for(i=0; i<nbshift; i++) {
5893       const SMDS_MeshNode* n = nodes[0];
5894       for(j=0; j<nbFaceNodes-1; j++) {
5895         nodes[j] = nodes[j+1];
5896       }
5897       nodes[nbFaceNodes-1] = n;
5898     }
5899     il1 = il1 - nbshift;
5900     // now have to insert nodes between n0 and n1 or n1 and n2 (see below)
5901     //   n0      n1     n2    n0      n1     n2
5902     //     +-----+-----+        +-----+-----+ 
5903     //      \         /         |           |
5904     //       \       /          |           |
5905     //      n5+     +n3       n7+           +n3
5906     //         \   /            |           |
5907     //          \ /             |           |
5908     //           +              +-----+-----+
5909     //           n4           n6      n5     n4
5910
5911     // create new elements
5912     SMESHDS_Mesh *aMesh = GetMeshDS();
5913     int aShapeId = FindShape( theFace );
5914
5915     int n1,n2,n3;
5916     if(nbFaceNodes==6) { // quadratic triangle
5917       SMDS_MeshElement* newElem =
5918         aMesh->AddFace(nodes[3],nodes[4],nodes[5]);
5919       myLastCreatedElems.Append(newElem);
5920       if ( aShapeId && newElem )
5921         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5922       if(theFace->IsMediumNode(nodes[il1])) {
5923         // create quadrangle
5924         newElem = aMesh->AddFace(nodes[0],nodes[1],nodes[3],nodes[5]);
5925         myLastCreatedElems.Append(newElem);
5926         if ( aShapeId && newElem )
5927           aMesh->SetMeshElementOnShape( newElem, aShapeId );
5928         n1 = 1;
5929         n2 = 2;
5930         n3 = 3;
5931       }
5932       else {
5933         // create quadrangle
5934         newElem = aMesh->AddFace(nodes[1],nodes[2],nodes[3],nodes[5]);
5935         myLastCreatedElems.Append(newElem);
5936         if ( aShapeId && newElem )
5937           aMesh->SetMeshElementOnShape( newElem, aShapeId );
5938         n1 = 0;
5939         n2 = 1;
5940         n3 = 5;
5941       }
5942     }
5943     else { // nbFaceNodes==8 - quadratic quadrangle
5944       SMDS_MeshElement* newElem =
5945         aMesh->AddFace(nodes[3],nodes[4],nodes[5]);
5946       myLastCreatedElems.Append(newElem);
5947       if ( aShapeId && newElem )
5948         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5949       newElem = aMesh->AddFace(nodes[5],nodes[6],nodes[7]);
5950       myLastCreatedElems.Append(newElem);
5951       if ( aShapeId && newElem )
5952         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5953       newElem = aMesh->AddFace(nodes[5],nodes[7],nodes[3]);
5954       myLastCreatedElems.Append(newElem);
5955       if ( aShapeId && newElem )
5956         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5957       if(theFace->IsMediumNode(nodes[il1])) {
5958         // create quadrangle
5959         newElem = aMesh->AddFace(nodes[0],nodes[1],nodes[3],nodes[7]);
5960         myLastCreatedElems.Append(newElem);
5961         if ( aShapeId && newElem )
5962           aMesh->SetMeshElementOnShape( newElem, aShapeId );
5963         n1 = 1;
5964         n2 = 2;
5965         n3 = 3;
5966       }
5967       else {
5968         // create quadrangle
5969         newElem = aMesh->AddFace(nodes[1],nodes[2],nodes[3],nodes[7]);
5970         myLastCreatedElems.Append(newElem);
5971         if ( aShapeId && newElem )
5972           aMesh->SetMeshElementOnShape( newElem, aShapeId );
5973         n1 = 0;
5974         n2 = 1;
5975         n3 = 7;
5976       }
5977     }
5978     // create needed triangles using n1,n2,n3 and inserted nodes
5979     int nbn = 2 + aNodesToInsert.size();
5980     const SMDS_MeshNode* aNodes[nbn];
5981     aNodes[0] = nodes[n1];
5982     aNodes[nbn-1] = nodes[n2];
5983     list<const SMDS_MeshNode*>::iterator nIt = aNodesToInsert.begin();
5984     for ( iNode = 1; nIt != aNodesToInsert.end(); nIt++ ) {
5985       aNodes[iNode++] = *nIt;
5986     }
5987     for(i=1; i<nbn; i++) {
5988       SMDS_MeshElement* newElem =
5989         aMesh->AddFace(aNodes[i-1],aNodes[i],nodes[n3]);
5990       myLastCreatedElems.Append(newElem);
5991       if ( aShapeId && newElem )
5992         aMesh->SetMeshElementOnShape( newElem, aShapeId );
5993     }
5994     // remove old quadratic face
5995     aMesh->RemoveElement(theFace);
5996   }
5997 }
5998
5999 //=======================================================================
6000 //function : UpdateVolumes
6001 //purpose  :
6002 //=======================================================================
6003 void SMESH_MeshEditor::UpdateVolumes (const SMDS_MeshNode*        theBetweenNode1,
6004                                       const SMDS_MeshNode*        theBetweenNode2,
6005                                       list<const SMDS_MeshNode*>& theNodesToInsert)
6006 {
6007   myLastCreatedElems.Clear();
6008   myLastCreatedNodes.Clear();
6009
6010   SMDS_ElemIteratorPtr invElemIt = theBetweenNode1->GetInverseElementIterator(SMDSAbs_Volume);
6011   while (invElemIt->more()) { // loop on inverse elements of theBetweenNode1
6012     const SMDS_MeshElement* elem = invElemIt->next();
6013
6014     // check, if current volume has link theBetweenNode1 - theBetweenNode2
6015     SMDS_VolumeTool aVolume (elem);
6016     if (!aVolume.IsLinked(theBetweenNode1, theBetweenNode2))
6017       continue;
6018
6019     // insert new nodes in all faces of the volume, sharing link theBetweenNode1 - theBetweenNode2
6020     int iface, nbFaces = aVolume.NbFaces();
6021     vector<const SMDS_MeshNode *> poly_nodes;
6022     vector<int> quantities (nbFaces);
6023
6024     for (iface = 0; iface < nbFaces; iface++) {
6025       int nbFaceNodes = aVolume.NbFaceNodes(iface), nbInserted = 0;
6026       // faceNodes will contain (nbFaceNodes + 1) nodes, last = first
6027       const SMDS_MeshNode** faceNodes = aVolume.GetFaceNodes(iface);
6028
6029       for (int inode = 0; inode < nbFaceNodes; inode++) {
6030         poly_nodes.push_back(faceNodes[inode]);
6031
6032         if (nbInserted == 0) {
6033           if (faceNodes[inode] == theBetweenNode1) {
6034             if (faceNodes[inode + 1] == theBetweenNode2) {
6035               nbInserted = theNodesToInsert.size();
6036
6037               // add nodes to insert
6038               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.begin();
6039               for (; nIt != theNodesToInsert.end(); nIt++) {
6040                 poly_nodes.push_back(*nIt);
6041               }
6042             }
6043           }
6044           else if (faceNodes[inode] == theBetweenNode2) {
6045             if (faceNodes[inode + 1] == theBetweenNode1) {
6046               nbInserted = theNodesToInsert.size();
6047
6048               // add nodes to insert in reversed order
6049               list<const SMDS_MeshNode*>::iterator nIt = theNodesToInsert.end();
6050               nIt--;
6051               for (; nIt != theNodesToInsert.begin(); nIt--) {
6052                 poly_nodes.push_back(*nIt);
6053               }
6054               poly_nodes.push_back(*nIt);
6055             }
6056           }
6057           else {
6058           }
6059         }
6060       }
6061       quantities[iface] = nbFaceNodes + nbInserted;
6062     }
6063
6064     // Replace or update the volume
6065     SMESHDS_Mesh *aMesh = GetMeshDS();
6066
6067     if (elem->IsPoly()) {
6068       aMesh->ChangePolyhedronNodes(elem, poly_nodes, quantities);
6069
6070     }
6071     else {
6072       int aShapeId = FindShape( elem );
6073
6074       SMDS_MeshElement* newElem =
6075         aMesh->AddPolyhedralVolume(poly_nodes, quantities);
6076       myLastCreatedElems.Append(newElem);
6077       if (aShapeId && newElem)
6078         aMesh->SetMeshElementOnShape(newElem, aShapeId);
6079
6080       aMesh->RemoveElement(elem);
6081     }
6082   }
6083 }
6084
6085 //=======================================================================
6086 //function : ConvertElemToQuadratic
6087 //purpose  :
6088 //=======================================================================
6089 void SMESH_MeshEditor::ConvertElemToQuadratic(SMESHDS_SubMesh *theSm,
6090                                               SMESH_MesherHelper* theHelper,
6091                                               const bool theForce3d)
6092 {
6093   if( !theSm ) return;
6094   SMESHDS_Mesh* meshDS = GetMeshDS();
6095   SMDS_ElemIteratorPtr ElemItr = theSm->GetElements();
6096   while(ElemItr->more())
6097   {
6098     const SMDS_MeshElement* elem = ElemItr->next();
6099     if( !elem ) continue;
6100
6101     int id = elem->GetID();
6102     int nbNodes = elem->NbNodes();
6103     vector<const SMDS_MeshNode *> aNds (nbNodes);
6104     
6105     for(int i = 0; i < nbNodes; i++)
6106     {
6107       aNds[i] = elem->GetNode(i);
6108     }
6109
6110     SMDSAbs_ElementType aType = elem->GetType();
6111     const SMDS_MeshElement* NewElem = 0;
6112
6113     switch( aType )
6114     {
6115     case SMDSAbs_Edge :
6116     {
6117       meshDS->RemoveFreeElement(elem, theSm);   
6118       NewElem = theHelper->AddQuadraticEdge(aNds[0], aNds[1], id, theForce3d);
6119       break;
6120     }
6121     case SMDSAbs_Face :
6122     {
6123       if(elem->IsQuadratic()) continue;
6124
6125       meshDS->RemoveFreeElement(elem, theSm);
6126       switch(nbNodes)
6127       {
6128       case 3:
6129         NewElem = theHelper->AddFace(aNds[0], aNds[1], aNds[2], id, theForce3d);
6130         break;
6131       case 4:
6132         NewElem = theHelper->AddFace(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6133         break;
6134       default:
6135         continue;
6136       }
6137       break;  
6138     }
6139     case SMDSAbs_Volume :
6140     {
6141       if( elem->IsQuadratic() ) continue;
6142
6143       meshDS->RemoveFreeElement(elem, theSm);
6144       switch(nbNodes)
6145       {
6146       case 4:
6147         NewElem = theHelper->AddVolume(aNds[0], aNds[1], aNds[2], aNds[3], id, true);
6148         break;
6149       case 6:
6150         NewElem = theHelper->AddVolume(aNds[0], aNds[1], aNds[2], aNds[3], aNds[4], aNds[5], id, true);
6151         break;
6152       case 8:
6153         NewElem = theHelper->AddVolume(aNds[0], aNds[1], aNds[2], aNds[3],
6154                                        aNds[4], aNds[5], aNds[6], aNds[7], id, true);
6155         break;
6156       default:
6157         continue;
6158       }
6159       break;  
6160     }
6161     default :
6162       continue;
6163     }
6164     if( NewElem )
6165     {
6166       AddToSameGroups( NewElem, elem, meshDS);
6167       theSm->AddElement( NewElem );
6168     }
6169   }
6170 }
6171
6172 //=======================================================================
6173 //function : ConvertToQuadratic
6174 //purpose  :
6175 //=======================================================================
6176 void SMESH_MeshEditor::ConvertToQuadratic(const bool theForce3d)
6177 {
6178   SMESHDS_Mesh* meshDS = GetMeshDS();
6179
6180   SMESH_MesherHelper* aHelper = new SMESH_MesherHelper(*myMesh);
6181   aHelper->SetKeyIsQuadratic( true );
6182   const TopoDS_Shape& aShape = meshDS->ShapeToMesh();
6183
6184   if ( !aShape.IsNull() && GetMesh()->GetSubMeshContaining(aShape) )
6185   {
6186     SMESH_subMesh *aSubMesh = GetMesh()->GetSubMeshContaining(aShape);
6187     
6188     const map < int, SMESH_subMesh * >& aMapSM = aSubMesh->DependsOn();
6189     map < int, SMESH_subMesh * >::const_iterator itsub;
6190     for (itsub = aMapSM.begin(); itsub != aMapSM.end(); itsub++)
6191     {
6192       SMESHDS_SubMesh *sm = ((*itsub).second)->GetSubMeshDS();
6193       aHelper->SetSubShape( (*itsub).second->GetSubShape() );
6194       ConvertElemToQuadratic(sm, aHelper, theForce3d);
6195     }
6196     aHelper->SetSubShape( aSubMesh->GetSubShape() );
6197     ConvertElemToQuadratic(aSubMesh->GetSubMeshDS(), aHelper, theForce3d);
6198   }
6199   else
6200   {
6201     SMDS_EdgeIteratorPtr aEdgeItr = meshDS->edgesIterator();
6202     while(aEdgeItr->more())
6203     {
6204       const SMDS_MeshEdge* edge = aEdgeItr->next();
6205       if(edge)
6206       {
6207         int id = edge->GetID();
6208         const SMDS_MeshNode* n1 = edge->GetNode(0);
6209         const SMDS_MeshNode* n2 = edge->GetNode(1);
6210
6211         RemoveElemFromGroups (edge, meshDS);
6212         meshDS->SMDS_Mesh::RemoveFreeElement(edge);
6213
6214         const SMDS_QuadraticEdge* NewEdge = aHelper->AddQuadraticEdge(n1, n2, id, theForce3d);
6215         AddToSameGroups(NewEdge, edge, meshDS);
6216       }
6217     }
6218     SMDS_FaceIteratorPtr aFaceItr = meshDS->facesIterator();
6219     while(aFaceItr->more())
6220     {
6221       const SMDS_MeshFace* face = aFaceItr->next();
6222       if(!face || face->IsQuadratic() ) continue;
6223       
6224       int id = face->GetID();
6225       int nbNodes = face->NbNodes();
6226       vector<const SMDS_MeshNode *> aNds (nbNodes);
6227
6228       for(int i = 0; i < nbNodes; i++)
6229       {
6230         aNds[i] = face->GetNode(i);
6231       }
6232
6233       RemoveElemFromGroups (face, meshDS); 
6234       meshDS->SMDS_Mesh::RemoveFreeElement(face);
6235
6236       SMDS_MeshFace * NewFace = 0;
6237       switch(nbNodes)
6238       {
6239       case 3:
6240         NewFace = aHelper->AddFace(aNds[0], aNds[1], aNds[2], id, theForce3d);
6241         break;
6242       case 4:
6243         NewFace = aHelper->AddFace(aNds[0], aNds[1], aNds[2], aNds[3], id, theForce3d);
6244         break;
6245       default:
6246         continue;
6247       }
6248       AddToSameGroups(NewFace, face, meshDS);
6249     }
6250     SMDS_VolumeIteratorPtr aVolumeItr = meshDS->volumesIterator();
6251     while(aVolumeItr->more())
6252     {
6253       const SMDS_MeshVolume* volume = aVolumeItr->next();
6254       if(!volume || volume->IsQuadratic() ) continue;
6255       
6256       int id = volume->GetID();
6257       int nbNodes = volume->NbNodes();
6258       vector<const SMDS_MeshNode *> aNds (nbNodes);
6259
6260       for(int i = 0; i < nbNodes; i++)
6261       {
6262         aNds[i] = volume->GetNode(i);
6263       }
6264
6265       RemoveElemFromGroups (volume, meshDS);
6266       meshDS->SMDS_Mesh::RemoveFreeElement(volume);
6267
6268       SMDS_MeshVolume * NewVolume = 0;
6269       switch(nbNodes)
6270       {
6271       case 4:
6272         NewVolume = aHelper->AddVolume(aNds[0], aNds[1], aNds[2],
6273                                        aNds[3], id, true );
6274         break;
6275       case 6:
6276         NewVolume = aHelper->AddVolume(aNds[0], aNds[1], aNds[2],
6277                                        aNds[3], aNds[4], aNds[5], id, true);
6278         break;
6279       case 8:
6280         NewVolume = aHelper->AddVolume(aNds[0], aNds[1], aNds[2], aNds[3],
6281                                        aNds[4], aNds[5], aNds[6], aNds[7], id, true);
6282         break;
6283       default:
6284         continue;
6285       }
6286       AddToSameGroups(NewVolume, volume, meshDS);
6287     }
6288   }
6289   delete aHelper;
6290 }
6291
6292 //=======================================================================
6293 //function : RemoveQuadElem
6294 //purpose  :
6295 //=======================================================================
6296 void SMESH_MeshEditor::RemoveQuadElem(SMESHDS_SubMesh *theSm, 
6297                                       SMDS_ElemIteratorPtr theItr,
6298                                       RemoveQuadNodeMap& theRemoveNodeMap)
6299 {
6300   SMESHDS_Mesh* meshDS = GetMeshDS();
6301   while( theItr->more() )
6302   {
6303     const SMDS_MeshElement* elem = theItr->next();
6304     if( elem )
6305     {
6306       if( !elem->IsQuadratic() )
6307         continue;
6308       
6309       int id = elem->GetID();
6310
6311       int nbNodes = elem->NbNodes(), idx = 0;
6312       vector<const SMDS_MeshNode *> aNds; 
6313
6314       for(int i = 0; i < nbNodes; i++)
6315       {
6316         const SMDS_MeshNode* n = elem->GetNode(i);
6317
6318         if( elem->IsMediumNode( n ) )
6319         {
6320           ItRemoveQuadNodeMap itRNM = theRemoveNodeMap.find( n );
6321           if( itRNM == theRemoveNodeMap.end() )
6322           {
6323             theRemoveNodeMap.insert(RemoveQuadNodeMap::value_type( n,theSm ));
6324           }
6325         }
6326         else 
6327           aNds.push_back( n );
6328       }
6329
6330       idx = aNds.size();
6331       if( !idx ) continue;
6332       SMDSAbs_ElementType aType = elem->GetType();      
6333
6334       //remove old quadratic elements
6335       meshDS->RemoveFreeElement( elem, theSm );
6336
6337       SMDS_MeshElement * NewElem = 0;
6338       switch(aType)
6339       {
6340         case SMDSAbs_Edge:
6341           NewElem = meshDS->AddEdgeWithID( aNds[0], aNds[1] ,id );
6342           break;
6343         case SMDSAbs_Face:
6344           if( idx==3 ) NewElem = meshDS->AddFaceWithID( aNds[0],
6345                                    aNds[1], aNds[2], id );
6346           if( idx==4 ) NewElem = meshDS->AddFaceWithID( aNds[0],
6347                                    aNds[1], aNds[2], aNds[3],id );
6348           break;
6349         case SMDSAbs_Volume:
6350           if( idx==4 ) NewElem = meshDS->AddVolumeWithID( aNds[0],
6351                                    aNds[1], aNds[2], aNds[3], id );
6352           if( idx==6 ) NewElem = meshDS->AddVolumeWithID( aNds[0],
6353                                    aNds[1], aNds[2], aNds[3],
6354                                    aNds[4], aNds[5], id );
6355           if( idx==8 ) NewElem = meshDS->AddVolumeWithID(aNds[0],
6356                                    aNds[1], aNds[2], aNds[3],
6357                                    aNds[4], aNds[5], aNds[6],
6358                                    aNds[7] ,id );
6359           break;
6360         default:
6361           break;
6362       }
6363
6364       AddToSameGroups(NewElem, elem, meshDS);
6365       if( theSm )
6366         theSm->AddElement( NewElem );
6367     }
6368   }
6369 }
6370 //=======================================================================
6371 //function : ConvertFromQuadratic
6372 //purpose  :
6373 //=======================================================================
6374 bool  SMESH_MeshEditor::ConvertFromQuadratic()
6375 {
6376   SMESHDS_Mesh* meshDS = GetMeshDS();
6377   RemoveQuadNodeMap aRemoveNodeMap;
6378
6379   const TopoDS_Shape& aShape = meshDS->ShapeToMesh();
6380
6381   if ( !aShape.IsNull() && GetMesh()->GetSubMeshContaining(aShape) )
6382   {
6383     SMESH_subMesh *aSubMesh = GetMesh()->GetSubMeshContaining(aShape);
6384     
6385     const map < int, SMESH_subMesh * >& aMapSM = aSubMesh->DependsOn();
6386     map < int, SMESH_subMesh * >::const_iterator itsub;
6387     for (itsub = aMapSM.begin(); itsub != aMapSM.end(); itsub++)
6388     {
6389       SMESHDS_SubMesh *sm = ((*itsub).second)->GetSubMeshDS();
6390       if( sm )
6391         RemoveQuadElem( sm, sm->GetElements(), aRemoveNodeMap );
6392     }
6393     SMESHDS_SubMesh *Sm = aSubMesh->GetSubMeshDS();
6394     if( Sm )
6395       RemoveQuadElem( Sm, Sm->GetElements(), aRemoveNodeMap );
6396   }
6397   else
6398   {
6399     SMESHDS_SubMesh *aSM = 0;
6400     RemoveQuadElem( aSM, meshDS->elementsIterator(), aRemoveNodeMap );
6401   }
6402
6403   //remove all quadratic nodes 
6404   ItRemoveQuadNodeMap itRNM = aRemoveNodeMap.begin();
6405   for ( ; itRNM != aRemoveNodeMap.end(); itRNM++ ) 
6406   {
6407     meshDS->RemoveFreeNode( (*itRNM).first, (*itRNM).second  ); 
6408   }
6409
6410   return true;
6411 }
6412
6413 //=======================================================================
6414 //function : SewSideElements
6415 //purpose  :
6416 //=======================================================================
6417
6418 SMESH_MeshEditor::Sew_Error
6419   SMESH_MeshEditor::SewSideElements (TIDSortedElemSet&    theSide1,
6420                                      TIDSortedElemSet&    theSide2,
6421                                      const SMDS_MeshNode* theFirstNode1,
6422                                      const SMDS_MeshNode* theFirstNode2,
6423                                      const SMDS_MeshNode* theSecondNode1,
6424                                      const SMDS_MeshNode* theSecondNode2)
6425 {
6426   myLastCreatedElems.Clear();
6427   myLastCreatedNodes.Clear();
6428
6429   MESSAGE ("::::SewSideElements()");
6430   if ( theSide1.size() != theSide2.size() )
6431     return SEW_DIFF_NB_OF_ELEMENTS;
6432
6433   Sew_Error aResult = SEW_OK;
6434   // Algo:
6435   // 1. Build set of faces representing each side
6436   // 2. Find which nodes of the side 1 to merge with ones on the side 2
6437   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
6438
6439   // =======================================================================
6440   // 1. Build set of faces representing each side:
6441   // =======================================================================
6442   // a. build set of nodes belonging to faces
6443   // b. complete set of faces: find missing fices whose nodes are in set of nodes
6444   // c. create temporary faces representing side of volumes if correspondent
6445   //    face does not exist
6446
6447   SMESHDS_Mesh* aMesh = GetMeshDS();
6448   SMDS_Mesh aTmpFacesMesh;
6449   set<const SMDS_MeshElement*> faceSet1, faceSet2;
6450   set<const SMDS_MeshElement*> volSet1,  volSet2;
6451   set<const SMDS_MeshNode*>    nodeSet1, nodeSet2;
6452   set<const SMDS_MeshElement*> * faceSetPtr[] = { &faceSet1, &faceSet2 };
6453   set<const SMDS_MeshElement*>  * volSetPtr[] = { &volSet1,  &volSet2  };
6454   set<const SMDS_MeshNode*>    * nodeSetPtr[] = { &nodeSet1, &nodeSet2 };
6455   TIDSortedElemSet * elemSetPtr[] = { &theSide1, &theSide2 };
6456   int iSide, iFace, iNode;
6457
6458   for ( iSide = 0; iSide < 2; iSide++ ) {
6459     set<const SMDS_MeshNode*>    * nodeSet = nodeSetPtr[ iSide ];
6460     TIDSortedElemSet * elemSet = elemSetPtr[ iSide ];
6461     set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
6462     set<const SMDS_MeshElement*> * volSet  = volSetPtr [ iSide ];
6463     set<const SMDS_MeshElement*>::iterator vIt;
6464     TIDSortedElemSet::iterator eIt;
6465     set<const SMDS_MeshNode*>::iterator    nIt;
6466
6467     // check that given nodes belong to given elements
6468     const SMDS_MeshNode* n1 = ( iSide == 0 ) ? theFirstNode1 : theFirstNode2;
6469     const SMDS_MeshNode* n2 = ( iSide == 0 ) ? theSecondNode1 : theSecondNode2;
6470     int firstIndex = -1, secondIndex = -1;
6471     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
6472       const SMDS_MeshElement* elem = *eIt;
6473       if ( firstIndex  < 0 ) firstIndex  = elem->GetNodeIndex( n1 );
6474       if ( secondIndex < 0 ) secondIndex = elem->GetNodeIndex( n2 );
6475       if ( firstIndex > -1 && secondIndex > -1 ) break;
6476     }
6477     if ( firstIndex < 0 || secondIndex < 0 ) {
6478       // we can simply return until temporary faces created
6479       return (iSide == 0 ) ? SEW_BAD_SIDE1_NODES : SEW_BAD_SIDE2_NODES;
6480     }
6481
6482     // -----------------------------------------------------------
6483     // 1a. Collect nodes of existing faces
6484     //     and build set of face nodes in order to detect missing
6485     //     faces corresponing to sides of volumes
6486     // -----------------------------------------------------------
6487
6488     set< set <const SMDS_MeshNode*> > setOfFaceNodeSet;
6489
6490     // loop on the given element of a side
6491     for (eIt = elemSet->begin(); eIt != elemSet->end(); eIt++ ) {
6492       //const SMDS_MeshElement* elem = *eIt;
6493       const SMDS_MeshElement* elem = *eIt;
6494       if ( elem->GetType() == SMDSAbs_Face ) {
6495         faceSet->insert( elem );
6496         set <const SMDS_MeshNode*> faceNodeSet;
6497         SMDS_ElemIteratorPtr nodeIt = elem->nodesIterator();
6498         while ( nodeIt->more() ) {
6499           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6500           nodeSet->insert( n );
6501           faceNodeSet.insert( n );
6502         }
6503         setOfFaceNodeSet.insert( faceNodeSet );
6504       }
6505       else if ( elem->GetType() == SMDSAbs_Volume )
6506         volSet->insert( elem );
6507     }
6508     // ------------------------------------------------------------------------------
6509     // 1b. Complete set of faces: find missing fices whose nodes are in set of nodes
6510     // ------------------------------------------------------------------------------
6511
6512     for ( nIt = nodeSet->begin(); nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
6513       SMDS_ElemIteratorPtr fIt = (*nIt)->GetInverseElementIterator(SMDSAbs_Face);
6514       while ( fIt->more() ) { // loop on faces sharing a node
6515         const SMDS_MeshElement* f = fIt->next();
6516         if ( faceSet->find( f ) == faceSet->end() ) {
6517           // check if all nodes are in nodeSet and
6518           // complete setOfFaceNodeSet if they are
6519           set <const SMDS_MeshNode*> faceNodeSet;
6520           SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
6521           bool allInSet = true;
6522           while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
6523             const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6524             if ( nodeSet->find( n ) == nodeSet->end() )
6525               allInSet = false;
6526             else
6527               faceNodeSet.insert( n );
6528           }
6529           if ( allInSet ) {
6530             faceSet->insert( f );
6531             setOfFaceNodeSet.insert( faceNodeSet );
6532           }
6533         }
6534       }
6535     }
6536
6537     // -------------------------------------------------------------------------
6538     // 1c. Create temporary faces representing sides of volumes if correspondent
6539     //     face does not exist
6540     // -------------------------------------------------------------------------
6541
6542     if ( !volSet->empty() ) {
6543       //int nodeSetSize = nodeSet->size();
6544
6545       // loop on given volumes
6546       for ( vIt = volSet->begin(); vIt != volSet->end(); vIt++ ) {
6547         SMDS_VolumeTool vol (*vIt);
6548         // loop on volume faces: find free faces
6549         // --------------------------------------
6550         list<const SMDS_MeshElement* > freeFaceList;
6551         for ( iFace = 0; iFace < vol.NbFaces(); iFace++ ) {
6552           if ( !vol.IsFreeFace( iFace ))
6553             continue;
6554           // check if there is already a face with same nodes in a face set
6555           const SMDS_MeshElement* aFreeFace = 0;
6556           const SMDS_MeshNode** fNodes = vol.GetFaceNodes( iFace );
6557           int nbNodes = vol.NbFaceNodes( iFace );
6558           set <const SMDS_MeshNode*> faceNodeSet;
6559           vol.GetFaceNodes( iFace, faceNodeSet );
6560           bool isNewFace = setOfFaceNodeSet.insert( faceNodeSet ).second;
6561           if ( isNewFace ) {
6562             // no such a face is given but it still can exist, check it
6563             if ( nbNodes == 3 ) {
6564               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2] );
6565             }
6566             else if ( nbNodes == 4 ) {
6567               aFreeFace = aMesh->FindFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
6568             }
6569             else {
6570               vector<const SMDS_MeshNode *> poly_nodes ( fNodes, & fNodes[nbNodes]);
6571               aFreeFace = aMesh->FindFace(poly_nodes);
6572             }
6573           }
6574           if ( !aFreeFace ) {
6575             // create a temporary face
6576             if ( nbNodes == 3 ) {
6577               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2] );
6578             }
6579             else if ( nbNodes == 4 ) {
6580               aFreeFace = aTmpFacesMesh.AddFace( fNodes[0],fNodes[1],fNodes[2],fNodes[3] );
6581             }
6582             else {
6583               vector<const SMDS_MeshNode *> poly_nodes ( fNodes, & fNodes[nbNodes]);
6584               aFreeFace = aTmpFacesMesh.AddPolygonalFace(poly_nodes);
6585             }
6586           }
6587           if ( aFreeFace )
6588             freeFaceList.push_back( aFreeFace );
6589
6590         } // loop on faces of a volume
6591
6592         // choose one of several free faces
6593         // --------------------------------------
6594         if ( freeFaceList.size() > 1 ) {
6595           // choose a face having max nb of nodes shared by other elems of a side
6596           int maxNbNodes = -1/*, nbExcludedFaces = 0*/;
6597           list<const SMDS_MeshElement* >::iterator fIt = freeFaceList.begin();
6598           while ( fIt != freeFaceList.end() ) { // loop on free faces
6599             int nbSharedNodes = 0;
6600             SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
6601             while ( nodeIt->more() ) { // loop on free face nodes
6602               const SMDS_MeshNode* n =
6603                 static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6604               SMDS_ElemIteratorPtr invElemIt = n->GetInverseElementIterator();
6605               while ( invElemIt->more() ) {
6606                 const SMDS_MeshElement* e = invElemIt->next();
6607                 if ( faceSet->find( e ) != faceSet->end() )
6608                   nbSharedNodes++;
6609                 if ( elemSet->find( e ) != elemSet->end() )
6610                   nbSharedNodes++;
6611               }
6612             }
6613             if ( nbSharedNodes >= maxNbNodes ) {
6614               maxNbNodes = nbSharedNodes;
6615               fIt++;
6616             }
6617             else
6618               freeFaceList.erase( fIt++ ); // here fIt++ occures before erase
6619           }
6620           if ( freeFaceList.size() > 1 )
6621           {
6622             // could not choose one face, use another way
6623             // choose a face most close to the bary center of the opposite side
6624             gp_XYZ aBC( 0., 0., 0. );
6625             set <const SMDS_MeshNode*> addedNodes;
6626             TIDSortedElemSet * elemSet2 = elemSetPtr[ 1 - iSide ];
6627             eIt = elemSet2->begin();
6628             for ( eIt = elemSet2->begin(); eIt != elemSet2->end(); eIt++ ) {
6629               SMDS_ElemIteratorPtr nodeIt = (*eIt)->nodesIterator();
6630               while ( nodeIt->more() ) { // loop on free face nodes
6631                 const SMDS_MeshNode* n =
6632                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6633                 if ( addedNodes.insert( n ).second )
6634                   aBC += gp_XYZ( n->X(),n->Y(),n->Z() );
6635               }
6636             }
6637             aBC /= addedNodes.size();
6638             double minDist = DBL_MAX;
6639             fIt = freeFaceList.begin();
6640             while ( fIt != freeFaceList.end() ) { // loop on free faces
6641               double dist = 0;
6642               SMDS_ElemIteratorPtr nodeIt = (*fIt)->nodesIterator();
6643               while ( nodeIt->more() ) { // loop on free face nodes
6644                 const SMDS_MeshNode* n =
6645                   static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6646                 gp_XYZ p( n->X(),n->Y(),n->Z() );
6647                 dist += ( aBC - p ).SquareModulus();
6648               }
6649               if ( dist < minDist ) {
6650                 minDist = dist;
6651                 freeFaceList.erase( freeFaceList.begin(), fIt++ );
6652               }
6653               else
6654                 fIt = freeFaceList.erase( fIt++ );
6655             }
6656           }
6657         } // choose one of several free faces of a volume
6658
6659         if ( freeFaceList.size() == 1 ) {
6660           const SMDS_MeshElement* aFreeFace = freeFaceList.front();
6661           faceSet->insert( aFreeFace );
6662           // complete a node set with nodes of a found free face
6663 //           for ( iNode = 0; iNode < ; iNode++ )
6664 //             nodeSet->insert( fNodes[ iNode ] );
6665         }
6666
6667       } // loop on volumes of a side
6668
6669 //       // complete a set of faces if new nodes in a nodeSet appeared
6670 //       // ----------------------------------------------------------
6671 //       if ( nodeSetSize != nodeSet->size() ) {
6672 //         for ( ; nIt != nodeSet->end(); nIt++ ) { // loop on nodes of iSide
6673 //           SMDS_ElemIteratorPtr fIt = (*nIt)->GetInverseElementIterator(SMDSAbs_Face);
6674 //           while ( fIt->more() ) { // loop on faces sharing a node
6675 //             const SMDS_MeshElement* f = fIt->next();
6676 //             if ( faceSet->find( f ) == faceSet->end() ) {
6677 //               // check if all nodes are in nodeSet and
6678 //               // complete setOfFaceNodeSet if they are
6679 //               set <const SMDS_MeshNode*> faceNodeSet;
6680 //               SMDS_ElemIteratorPtr nodeIt = f->nodesIterator();
6681 //               bool allInSet = true;
6682 //               while ( nodeIt->more() && allInSet ) { // loop on nodes of a face
6683 //                 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
6684 //                 if ( nodeSet->find( n ) == nodeSet->end() )
6685 //                   allInSet = false;
6686 //                 else
6687 //                   faceNodeSet.insert( n );
6688 //               }
6689 //               if ( allInSet ) {
6690 //                 faceSet->insert( f );
6691 //                 setOfFaceNodeSet.insert( faceNodeSet );
6692 //               }
6693 //             }
6694 //           }
6695 //         }
6696 //       }
6697     } // Create temporary faces, if there are volumes given
6698   } // loop on sides
6699
6700   if ( faceSet1.size() != faceSet2.size() ) {
6701     // delete temporary faces: they are in reverseElements of actual nodes
6702     SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
6703     while ( tmpFaceIt->more() )
6704       aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
6705     MESSAGE("Diff nb of faces");
6706     return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
6707   }
6708
6709   // ============================================================
6710   // 2. Find nodes to merge:
6711   //              bind a node to remove to a node to put instead
6712   // ============================================================
6713
6714   TNodeNodeMap nReplaceMap; // bind a node to remove to a node to put instead
6715   if ( theFirstNode1 != theFirstNode2 )
6716     nReplaceMap.insert( TNodeNodeMap::value_type( theFirstNode1, theFirstNode2 ));
6717   if ( theSecondNode1 != theSecondNode2 )
6718     nReplaceMap.insert( TNodeNodeMap::value_type( theSecondNode1, theSecondNode2 ));
6719
6720   LinkID_Gen aLinkID_Gen( GetMeshDS() );
6721   set< long > linkIdSet; // links to process
6722   linkIdSet.insert( aLinkID_Gen.GetLinkID( theFirstNode1, theSecondNode1 ));
6723
6724   typedef pair< const SMDS_MeshNode*, const SMDS_MeshNode* > NLink;
6725   list< NLink > linkList[2];
6726   linkList[0].push_back( NLink( theFirstNode1, theSecondNode1 ));
6727   linkList[1].push_back( NLink( theFirstNode2, theSecondNode2 ));
6728   // loop on links in linkList; find faces by links and append links
6729   // of the found faces to linkList
6730   list< NLink >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
6731   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ ) {
6732     NLink link[] = { *linkIt[0], *linkIt[1] };
6733     long linkID = aLinkID_Gen.GetLinkID( link[0].first, link[0].second );
6734     if ( linkIdSet.find( linkID ) == linkIdSet.end() )
6735       continue;
6736
6737     // by links, find faces in the face sets,
6738     // and find indices of link nodes in the found faces;
6739     // in a face set, there is only one or no face sharing a link
6740     // ---------------------------------------------------------------
6741
6742     const SMDS_MeshElement* face[] = { 0, 0 };
6743     //const SMDS_MeshNode* faceNodes[ 2 ][ 5 ];
6744     vector<const SMDS_MeshNode*> fnodes1(9);
6745     vector<const SMDS_MeshNode*> fnodes2(9);
6746     //const SMDS_MeshNode* notLinkNodes[ 2 ][ 2 ] = {{ 0, 0 },{ 0, 0 }} ;
6747     vector<const SMDS_MeshNode*> notLinkNodes1(6);
6748     vector<const SMDS_MeshNode*> notLinkNodes2(6);
6749     int iLinkNode[2][2];
6750     for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
6751       const SMDS_MeshNode* n1 = link[iSide].first;
6752       const SMDS_MeshNode* n2 = link[iSide].second;
6753       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
6754       set< const SMDS_MeshElement* > fMap;
6755       for ( int i = 0; i < 2; i++ ) { // loop on 2 nodes of a link
6756         const SMDS_MeshNode* n = i ? n1 : n2; // a node of a link
6757         SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
6758         while ( fIt->more() ) { // loop on faces sharing a node
6759           const SMDS_MeshElement* f = fIt->next();
6760           if (faceSet->find( f ) != faceSet->end() && // f is in face set
6761               ! fMap.insert( f ).second ) // f encounters twice
6762           {
6763             if ( face[ iSide ] ) {
6764               MESSAGE( "2 faces per link " );
6765               aResult = iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES;
6766               break;
6767             }
6768             face[ iSide ] = f;
6769             faceSet->erase( f );
6770             // get face nodes and find ones of a link
6771             iNode = 0;
6772             int nbl = -1;
6773             if(f->IsPoly()) {
6774               if(iSide==0) {
6775                 fnodes1.resize(f->NbNodes()+1);
6776                 notLinkNodes1.resize(f->NbNodes()-2);
6777               }
6778               else {
6779                 fnodes2.resize(f->NbNodes()+1);
6780                 notLinkNodes2.resize(f->NbNodes()-2);
6781               }
6782             }
6783             if(!f->IsQuadratic()) {
6784               SMDS_ElemIteratorPtr nIt = f->nodesIterator();
6785               while ( nIt->more() ) {
6786                 const SMDS_MeshNode* n =
6787                   static_cast<const SMDS_MeshNode*>( nIt->next() );
6788                 if ( n == n1 ) {
6789                   iLinkNode[ iSide ][ 0 ] = iNode;
6790                 }
6791                 else if ( n == n2 ) {
6792                   iLinkNode[ iSide ][ 1 ] = iNode;
6793                 }
6794                 //else if ( notLinkNodes[ iSide ][ 0 ] )
6795                 //  notLinkNodes[ iSide ][ 1 ] = n;
6796                 //else
6797                 //  notLinkNodes[ iSide ][ 0 ] = n;
6798                 else {
6799                   nbl++;
6800                   if(iSide==0)
6801                     notLinkNodes1[nbl] = n;
6802                     //notLinkNodes1.push_back(n);
6803                   else
6804                     notLinkNodes2[nbl] = n;
6805                     //notLinkNodes2.push_back(n);
6806                 }
6807                 //faceNodes[ iSide ][ iNode++ ] = n;
6808                 if(iSide==0) {
6809                   fnodes1[iNode++] = n;
6810                 }
6811                 else {
6812                   fnodes2[iNode++] = n;
6813                 }
6814               }
6815             }
6816             else { // f->IsQuadratic()
6817               const SMDS_QuadraticFaceOfNodes* F =
6818                 static_cast<const SMDS_QuadraticFaceOfNodes*>(f);
6819               // use special nodes iterator
6820               SMDS_NodeIteratorPtr anIter = F->interlacedNodesIterator();
6821               while ( anIter->more() ) {
6822                 const SMDS_MeshNode* n =
6823                   static_cast<const SMDS_MeshNode*>( anIter->next() );
6824                 if ( n == n1 ) {
6825                   iLinkNode[ iSide ][ 0 ] = iNode;
6826                 }
6827                 else if ( n == n2 ) {
6828                   iLinkNode[ iSide ][ 1 ] = iNode;
6829                 }
6830                 else {
6831                   nbl++;
6832                   if(iSide==0) {
6833                     notLinkNodes1[nbl] = n;
6834                   }
6835                   else {
6836                     notLinkNodes2[nbl] = n;
6837                   }
6838                 }
6839                 if(iSide==0) {
6840                   fnodes1[iNode++] = n;
6841                 }
6842                 else {
6843                   fnodes2[iNode++] = n;
6844                 }
6845               }
6846             }
6847             //faceNodes[ iSide ][ iNode ] = faceNodes[ iSide ][ 0 ];
6848             if(iSide==0) {
6849               fnodes1[iNode] = fnodes1[0];
6850             }
6851             else {
6852               fnodes2[iNode] = fnodes1[0];
6853             }
6854           }
6855         }
6856       }
6857     }
6858
6859     // check similarity of elements of the sides
6860     if (aResult == SEW_OK && ( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
6861       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
6862       if ( nReplaceMap.size() == 2 ) { // faces on input nodes not found
6863         aResult = ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
6864       }
6865       else {
6866         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
6867       }
6868       break; // do not return because it s necessary to remove tmp faces
6869     }
6870
6871     // set nodes to merge
6872     // -------------------
6873
6874     if ( face[0] && face[1] )  {
6875       int nbNodes = face[0]->NbNodes();
6876       if ( nbNodes != face[1]->NbNodes() ) {
6877         MESSAGE("Diff nb of face nodes");
6878         aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
6879         break; // do not return because it s necessary to remove tmp faces
6880       }
6881       bool reverse[] = { false, false }; // order of notLinkNodes of quadrangle
6882       if ( nbNodes == 3 ) {
6883         //nReplaceMap.insert( TNodeNodeMap::value_type
6884         //                   ( notLinkNodes[0][0], notLinkNodes[1][0] ));
6885         nReplaceMap.insert( TNodeNodeMap::value_type
6886                            ( notLinkNodes1[0], notLinkNodes2[0] ));
6887       }
6888       else {
6889         for ( iSide = 0; iSide < 2; iSide++ ) { // loop on 2 sides
6890           // analyse link orientation in faces
6891           int i1 = iLinkNode[ iSide ][ 0 ];
6892           int i2 = iLinkNode[ iSide ][ 1 ];
6893           reverse[ iSide ] = Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1;
6894           // if notLinkNodes are the first and the last ones, then
6895           // their order does not correspond to the link orientation
6896           if (( i1 == 1 && i2 == 2 ) ||
6897               ( i1 == 2 && i2 == 1 ))
6898             reverse[ iSide ] = !reverse[ iSide ];
6899         }
6900         if ( reverse[0] == reverse[1] ) {
6901           //nReplaceMap.insert( TNodeNodeMap::value_type
6902           //                   ( notLinkNodes[0][0], notLinkNodes[1][0] ));
6903           //nReplaceMap.insert( TNodeNodeMap::value_type
6904           //                   ( notLinkNodes[0][1], notLinkNodes[1][1] ));
6905           for(int nn=0; nn<nbNodes-2; nn++) {
6906             nReplaceMap.insert( TNodeNodeMap::value_type
6907                              ( notLinkNodes1[nn], notLinkNodes2[nn] ));
6908           }
6909         }
6910         else {
6911           //nReplaceMap.insert( TNodeNodeMap::value_type
6912           //                   ( notLinkNodes[0][0], notLinkNodes[1][1] ));
6913           //nReplaceMap.insert( TNodeNodeMap::value_type
6914           //                   ( notLinkNodes[0][1], notLinkNodes[1][0] ));
6915           for(int nn=0; nn<nbNodes-2; nn++) {
6916             nReplaceMap.insert( TNodeNodeMap::value_type
6917                              ( notLinkNodes1[nn], notLinkNodes2[nbNodes-3-nn] ));
6918           }
6919         }
6920       }
6921
6922       // add other links of the faces to linkList
6923       // -----------------------------------------
6924
6925       //const SMDS_MeshNode** nodes = faceNodes[ 0 ];
6926       for ( iNode = 0; iNode < nbNodes; iNode++ )  {
6927         //linkID = aLinkID_Gen.GetLinkID( nodes[iNode], nodes[iNode+1] );
6928         linkID = aLinkID_Gen.GetLinkID( fnodes1[iNode], fnodes1[iNode+1] );
6929         pair< set<long>::iterator, bool > iter_isnew = linkIdSet.insert( linkID );
6930         if ( !iter_isnew.second ) { // already in a set: no need to process
6931           linkIdSet.erase( iter_isnew.first );
6932         }
6933         else // new in set == encountered for the first time: add
6934         {
6935           //const SMDS_MeshNode* n1 = nodes[ iNode ];
6936           //const SMDS_MeshNode* n2 = nodes[ iNode + 1];
6937           const SMDS_MeshNode* n1 = fnodes1[ iNode ];
6938           const SMDS_MeshNode* n2 = fnodes1[ iNode + 1];
6939           linkList[0].push_back ( NLink( n1, n2 ));
6940           linkList[1].push_back ( NLink( nReplaceMap[n1], nReplaceMap[n2] ));
6941         }
6942       }
6943     } // 2 faces found
6944   } // loop on link lists
6945
6946   if ( aResult == SEW_OK &&
6947       ( linkIt[0] != linkList[0].end() ||
6948        !faceSetPtr[0]->empty() || !faceSetPtr[1]->empty() )) {
6949     MESSAGE( (linkIt[0] != linkList[0].end()) <<" "<< (faceSetPtr[0]->empty()) <<
6950             " " << (faceSetPtr[1]->empty()));
6951     aResult = SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
6952   }
6953
6954   // ====================================================================
6955   // 3. Replace nodes in elements of the side 1 and remove replaced nodes
6956   // ====================================================================
6957
6958   // delete temporary faces: they are in reverseElements of actual nodes
6959   SMDS_FaceIteratorPtr tmpFaceIt = aTmpFacesMesh.facesIterator();
6960   while ( tmpFaceIt->more() )
6961     aTmpFacesMesh.RemoveElement( tmpFaceIt->next() );
6962
6963   if ( aResult != SEW_OK)
6964     return aResult;
6965
6966   list< int > nodeIDsToRemove/*, elemIDsToRemove*/;
6967   // loop on nodes replacement map
6968   TNodeNodeMap::iterator nReplaceMapIt = nReplaceMap.begin(), nnIt;
6969   for ( ; nReplaceMapIt != nReplaceMap.end(); nReplaceMapIt++ )
6970     if ( (*nReplaceMapIt).first != (*nReplaceMapIt).second ) {
6971       const SMDS_MeshNode* nToRemove = (*nReplaceMapIt).first;
6972       nodeIDsToRemove.push_back( nToRemove->GetID() );
6973       // loop on elements sharing nToRemove
6974       SMDS_ElemIteratorPtr invElemIt = nToRemove->GetInverseElementIterator();
6975       while ( invElemIt->more() ) {
6976         const SMDS_MeshElement* e = invElemIt->next();
6977         // get a new suite of nodes: make replacement
6978         int nbReplaced = 0, i = 0, nbNodes = e->NbNodes();
6979         vector< const SMDS_MeshNode*> nodes( nbNodes );
6980         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
6981         while ( nIt->more() ) {
6982           const SMDS_MeshNode* n =
6983             static_cast<const SMDS_MeshNode*>( nIt->next() );
6984           nnIt = nReplaceMap.find( n );
6985           if ( nnIt != nReplaceMap.end() ) {
6986             nbReplaced++;
6987             n = (*nnIt).second;
6988           }
6989           nodes[ i++ ] = n;
6990         }
6991         //       if ( nbReplaced == nbNodes && e->GetType() == SMDSAbs_Face )
6992         //         elemIDsToRemove.push_back( e->GetID() );
6993         //       else
6994         if ( nbReplaced )
6995           aMesh->ChangeElementNodes( e, & nodes[0], nbNodes );
6996       }
6997     }
6998
6999   Remove( nodeIDsToRemove, true );
7000
7001   return aResult;
7002 }
7003
7004 /*!
7005  * \brief A sorted pair of nodes
7006  */
7007 struct TLink: public NLink
7008 {
7009   TLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ):NLink( n1, n2 )
7010   { if ( n1 < n2 ) std::swap( first, second ); }
7011   TLink(const NLink& link ):NLink( link )
7012   { if ( first < second ) std::swap( first, second ); }
7013 };
7014
7015 //================================================================================
7016   /*!
7017    * \brief Find corresponding nodes in two sets of faces 
7018     * \param theSide1 - first face set
7019     * \param theSide2 - second first face
7020     * \param theFirstNode1 - a boundary node of set 1
7021     * \param theFirstNode2 - a node of set 2 corresponding to theFirstNode1
7022     * \param theSecondNode1 - a boundary node of set 1 linked with theFirstNode1
7023     * \param theSecondNode2 - a node of set 2 corresponding to theSecondNode1
7024     * \param nReplaceMap - output map of corresponding nodes
7025     * \retval bool  - is a success or not
7026    */
7027 //================================================================================
7028
7029 //#define DEBUG_MATCHING_NODES
7030
7031 SMESH_MeshEditor::Sew_Error
7032 SMESH_MeshEditor::FindMatchingNodes(set<const SMDS_MeshElement*>& theSide1,
7033                                     set<const SMDS_MeshElement*>& theSide2,
7034                                     const SMDS_MeshNode*          theFirstNode1,
7035                                     const SMDS_MeshNode*          theFirstNode2,
7036                                     const SMDS_MeshNode*          theSecondNode1,
7037                                     const SMDS_MeshNode*          theSecondNode2,
7038                                     TNodeNodeMap &                nReplaceMap)
7039 {
7040   set<const SMDS_MeshElement*> * faceSetPtr[] = { &theSide1, &theSide2 };
7041
7042   nReplaceMap.clear();
7043   if ( theFirstNode1 != theFirstNode2 )
7044     nReplaceMap.insert( make_pair( theFirstNode1, theFirstNode2 ));
7045   if ( theSecondNode1 != theSecondNode2 )
7046     nReplaceMap.insert( make_pair( theSecondNode1, theSecondNode2 ));
7047
7048   set< TLink > linkSet; // set of nodes where order of nodes is ignored
7049   linkSet.insert( TLink( theFirstNode1, theSecondNode1 ));
7050
7051   list< NLink > linkList[2];
7052   linkList[0].push_back( NLink( theFirstNode1, theSecondNode1 ));
7053   linkList[1].push_back( NLink( theFirstNode2, theSecondNode2 ));
7054
7055   // loop on links in linkList; find faces by links and append links
7056   // of the found faces to linkList
7057   list< NLink >::iterator linkIt[] = { linkList[0].begin(), linkList[1].begin() } ;
7058   for ( ; linkIt[0] != linkList[0].end(); linkIt[0]++, linkIt[1]++ ) {
7059     NLink link[] = { *linkIt[0], *linkIt[1] };
7060     if ( linkSet.find( link[0] ) == linkSet.end() )
7061       continue;
7062
7063     // by links, find faces in the face sets,
7064     // and find indices of link nodes in the found faces;
7065     // in a face set, there is only one or no face sharing a link
7066     // ---------------------------------------------------------------
7067
7068     const SMDS_MeshElement* face[] = { 0, 0 };
7069     list<const SMDS_MeshNode*> notLinkNodes[2];
7070     //bool reverse[] = { false, false }; // order of notLinkNodes
7071     int nbNodes[2];
7072     for ( int iSide = 0; iSide < 2; iSide++ ) // loop on 2 sides
7073     {
7074       const SMDS_MeshNode* n1 = link[iSide].first;
7075       const SMDS_MeshNode* n2 = link[iSide].second;
7076       set<const SMDS_MeshElement*> * faceSet = faceSetPtr[ iSide ];
7077       set< const SMDS_MeshElement* > facesOfNode1;
7078       for ( int iNode = 0; iNode < 2; iNode++ ) // loop on 2 nodes of a link
7079       {
7080         // during a loop of the first node, we find all faces around n1,
7081         // during a loop of the second node, we find one face sharing both n1 and n2
7082         const SMDS_MeshNode* n = iNode ? n1 : n2; // a node of a link
7083         SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
7084         while ( fIt->more() ) { // loop on faces sharing a node
7085           const SMDS_MeshElement* f = fIt->next();
7086           if (faceSet->find( f ) != faceSet->end() && // f is in face set
7087               ! facesOfNode1.insert( f ).second ) // f encounters twice
7088           {
7089             if ( face[ iSide ] ) {
7090               MESSAGE( "2 faces per link " );
7091               return ( iSide ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
7092             }
7093             face[ iSide ] = f;
7094             faceSet->erase( f );
7095
7096             // get not link nodes
7097             int nbN = f->NbNodes();
7098             if ( f->IsQuadratic() )
7099               nbN /= 2;
7100             nbNodes[ iSide ] = nbN;
7101             list< const SMDS_MeshNode* > & nodes = notLinkNodes[ iSide ];
7102             int i1 = f->GetNodeIndex( n1 );
7103             int i2 = f->GetNodeIndex( n2 );
7104             int iEnd = nbN, iBeg = -1, iDelta = 1;
7105             bool reverse = ( Abs( i1 - i2 ) == 1 ? i1 > i2 : i2 > i1 );
7106             if ( reverse ) {
7107               std::swap( iEnd, iBeg ); iDelta = -1;
7108             }
7109             int i = i2;
7110             while ( true ) {
7111               i += iDelta;
7112               if ( i == iEnd ) i = iBeg + iDelta;
7113               if ( i == i1 ) break;
7114               nodes.push_back ( f->GetNode( i ) );
7115             }
7116           }
7117         }
7118       }
7119     }
7120     // check similarity of elements of the sides
7121     if (( face[0] && !face[1] ) || ( !face[0] && face[1] )) {
7122       MESSAGE("Correspondent face not found on side " << ( face[0] ? 1 : 0 ));
7123       if ( nReplaceMap.size() == 2 ) { // faces on input nodes not found
7124         return ( face[0] ? SEW_BAD_SIDE2_NODES : SEW_BAD_SIDE1_NODES );
7125       }
7126       else {
7127         return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7128       }
7129     }
7130
7131     // set nodes to merge
7132     // -------------------
7133
7134     if ( face[0] && face[1] )  {
7135       if ( nbNodes[0] != nbNodes[1] ) {
7136         MESSAGE("Diff nb of face nodes");
7137         return SEW_TOPO_DIFF_SETS_OF_ELEMENTS;
7138       }
7139 #ifdef DEBUG_MATCHING_NODES
7140       cout << " Link 1: " << link[0].first->GetID() <<" "<< link[0].second->GetID()
7141            << " F 1: " << face[0];
7142       cout << "| Link 2: " << link[1].first->GetID() <<" "<< link[1].second->GetID()
7143            << " F 2: " << face[1] << " | Bind: "<<endl ;
7144 #endif
7145       int nbN = nbNodes[0];
7146       {
7147         list<const SMDS_MeshNode*>::iterator n1 = notLinkNodes[0].begin();
7148         list<const SMDS_MeshNode*>::iterator n2 = notLinkNodes[1].begin();
7149         for ( int i = 0 ; i < nbN - 2; ++i ) {
7150 #ifdef DEBUG_MATCHING_NODES
7151           cout << (*n1)->GetID() << " to " << (*n2)->GetID() << endl;
7152 #endif
7153           nReplaceMap.insert( make_pair( *(n1++), *(n2++) ));
7154         }
7155       }
7156
7157       // add other links of the face 1 to linkList
7158       // -----------------------------------------
7159
7160       const SMDS_MeshElement* f0 = face[0];
7161       const SMDS_MeshNode* n1 = f0->GetNode( nbN - 1 );
7162       for ( int i = 0; i < nbN; i++ )
7163       {
7164         const SMDS_MeshNode* n2 = f0->GetNode( i );
7165         pair< set< TLink >::iterator, bool > iter_isnew =
7166           linkSet.insert( TLink( n1, n2 ));
7167         if ( !iter_isnew.second ) { // already in a set: no need to process
7168           linkSet.erase( iter_isnew.first );
7169         }
7170         else // new in set == encountered for the first time: add
7171         {
7172 #ifdef DEBUG_MATCHING_NODES
7173           cout << "Add link 1: " << n1->GetID() << " " << n2->GetID() << " ";
7174           cout << " | link 2: " << nReplaceMap[n1]->GetID() << " " << nReplaceMap[n2]->GetID() << " " << endl;
7175 #endif
7176           linkList[0].push_back ( NLink( n1, n2 ));
7177           linkList[1].push_back ( NLink( nReplaceMap[n1], nReplaceMap[n2] ));
7178         }
7179         n1 = n2;
7180       }
7181     } // 2 faces found
7182   } // loop on link lists
7183
7184   return SEW_OK;
7185 }