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