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