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