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