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