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