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