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