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