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