Salome HOME
Merge from V6_main 11/02/2013
[modules/smesh.git] / src / StdMeshers / StdMeshers_Quadrangle_2D.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  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 //  File   : StdMeshers_Quadrangle_2D.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26
27 #include "StdMeshers_Quadrangle_2D.hxx"
28
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FacePosition.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshNode.hxx"
33 #include "SMESH_Block.hxx"
34 #include "SMESH_Comment.hxx"
35 #include "SMESH_Gen.hxx"
36 #include "SMESH_Mesh.hxx"
37 #include "SMESH_MesherHelper.hxx"
38 #include "SMESH_subMesh.hxx"
39 #include "StdMeshers_FaceSide.hxx"
40 #include "StdMeshers_QuadrangleParams.hxx"
41 #include "StdMeshers_ViscousLayers2D.hxx"
42
43 #include <BRep_Tool.hxx>
44 #include <Geom_Surface.hxx>
45 #include <NCollection_DefineArray2.hxx>
46 #include <Precision.hxx>
47 #include <TColStd_SequenceOfReal.hxx>
48 #include <TColStd_SequenceOfInteger.hxx>
49 #include <TColgp_SequenceOfXY.hxx>
50 #include <TopExp.hxx>
51 #include <TopExp_Explorer.hxx>
52 #include <TopTools_ListIteratorOfListOfShape.hxx>
53 #include <TopTools_MapOfShape.hxx>
54 #include <TopoDS.hxx>
55
56 #include "utilities.h"
57 #include "Utils_ExceptHandlers.hxx"
58
59 #ifndef StdMeshers_Array2OfNode_HeaderFile
60 #define StdMeshers_Array2OfNode_HeaderFile
61 typedef const SMDS_MeshNode* SMDS_MeshNodePtr;
62 DEFINE_BASECOLLECTION (StdMeshers_BaseCollectionNodePtr, SMDS_MeshNodePtr)
63 DEFINE_ARRAY2(StdMeshers_Array2OfNode,
64               StdMeshers_BaseCollectionNodePtr, SMDS_MeshNodePtr)
65 #endif
66
67 using namespace std;
68
69 typedef gp_XY gp_UV;
70 typedef SMESH_Comment TComm;
71
72 //=============================================================================
73 /*!
74  *  
75  */
76 //=============================================================================
77
78 StdMeshers_Quadrangle_2D::StdMeshers_Quadrangle_2D (int hypId, int studyId,
79                                                     SMESH_Gen* gen)
80   : SMESH_2D_Algo(hypId, studyId, gen),
81     myQuadranglePreference(false),
82     myTrianglePreference(false),
83     myTriaVertexID(-1),
84     myNeedSmooth(false),
85     myQuadType(QUAD_STANDARD),
86     myHelper( 0 )
87 {
88   MESSAGE("StdMeshers_Quadrangle_2D::StdMeshers_Quadrangle_2D");
89   _name = "Quadrangle_2D";
90   _shapeType = (1 << TopAbs_FACE);
91   _compatibleHypothesis.push_back("QuadrangleParams");
92   _compatibleHypothesis.push_back("QuadranglePreference");
93   _compatibleHypothesis.push_back("TrianglePreference");
94   _compatibleHypothesis.push_back("ViscousLayers2D");
95 }
96
97 //=============================================================================
98 /*!
99  *  
100  */
101 //=============================================================================
102
103 StdMeshers_Quadrangle_2D::~StdMeshers_Quadrangle_2D()
104 {
105   MESSAGE("StdMeshers_Quadrangle_2D::~StdMeshers_Quadrangle_2D");
106 }
107
108 //=============================================================================
109 /*!
110  *  
111  */
112 //=============================================================================
113
114 bool StdMeshers_Quadrangle_2D::CheckHypothesis
115                          (SMESH_Mesh&                          aMesh,
116                           const TopoDS_Shape&                  aShape,
117                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
118 {
119   bool isOk = true;
120   aStatus = SMESH_Hypothesis::HYP_OK;
121
122   const list <const SMESHDS_Hypothesis * >& hyps =
123     GetUsedHypothesis(aMesh, aShape, false);
124   const SMESHDS_Hypothesis * aHyp = 0;
125
126   myTriaVertexID = -1;
127   myQuadType = QUAD_STANDARD;
128   myQuadranglePreference = false;
129   myTrianglePreference = false;
130   myQuadStruct.reset();
131
132   bool isFirstParams = true;
133
134   // First assigned hypothesis (if any) is processed now
135   if (hyps.size() > 0) {
136     aHyp = hyps.front();
137     if (strcmp("QuadrangleParams", aHyp->GetName()) == 0) {
138       const StdMeshers_QuadrangleParams* aHyp1 = 
139         (const StdMeshers_QuadrangleParams*)aHyp;
140       myTriaVertexID = aHyp1->GetTriaVertex();
141       myQuadType = aHyp1->GetQuadType();
142       if (myQuadType == QUAD_QUADRANGLE_PREF ||
143           myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
144         myQuadranglePreference = true;
145       else if (myQuadType == QUAD_TRIANGLE_PREF)
146         myTrianglePreference = true;
147     }
148     else if (strcmp("QuadranglePreference", aHyp->GetName()) == 0) {
149       isFirstParams = false;
150       myQuadranglePreference = true;
151     }
152     else if (strcmp("TrianglePreference", aHyp->GetName()) == 0){
153       isFirstParams = false;
154       myTrianglePreference = true; 
155     }
156     else {
157       isFirstParams = false;
158     }
159   }
160
161   // Second(last) assigned hypothesis (if any) is processed now
162   if (hyps.size() > 1) {
163     aHyp = hyps.back();
164     if (isFirstParams) {
165       if (strcmp("QuadranglePreference", aHyp->GetName()) == 0) {
166         myQuadranglePreference = true;
167         myTrianglePreference = false; 
168         myQuadType = QUAD_STANDARD;
169       }
170       else if (strcmp("TrianglePreference", aHyp->GetName()) == 0){
171         myQuadranglePreference = false;
172         myTrianglePreference = true; 
173         myQuadType = QUAD_STANDARD;
174       }
175     }
176     else {
177       const StdMeshers_QuadrangleParams* aHyp2 = 
178         (const StdMeshers_QuadrangleParams*)aHyp;
179       myTriaVertexID = aHyp2->GetTriaVertex();
180
181       if (!myQuadranglePreference && !myTrianglePreference) { // priority of hypos
182         myQuadType = aHyp2->GetQuadType();
183         if (myQuadType == QUAD_QUADRANGLE_PREF ||
184             myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
185           myQuadranglePreference = true;
186         else if (myQuadType == QUAD_TRIANGLE_PREF)
187           myTrianglePreference = true;
188       }
189     }
190   }
191
192   return isOk;
193 }
194
195 //=============================================================================
196 /*!
197  *  
198  */
199 //=============================================================================
200
201 bool StdMeshers_Quadrangle_2D::Compute (SMESH_Mesh&         aMesh,
202                                         const TopoDS_Shape& aShape)
203 {
204   const TopoDS_Face& F = TopoDS::Face(aShape);
205   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
206
207   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
208   aMesh.GetSubMesh(aShape);
209
210   SMESH_MesherHelper helper (aMesh);
211   myHelper = &helper;
212
213   myProxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
214   if ( !myProxyMesh )
215     return false;
216
217   _quadraticMesh = myHelper->IsQuadraticSubMesh(aShape);
218   myNeedSmooth = false;
219
220   FaceQuadStruct::Ptr quad = CheckNbEdges(aMesh, aShape);
221   if (!quad)
222     return false;
223   myQuadStruct = quad;
224
225   if (myQuadranglePreference) {
226     int n1 = quad->side[0]->NbPoints();
227     int n2 = quad->side[1]->NbPoints();
228     int n3 = quad->side[2]->NbPoints();
229     int n4 = quad->side[3]->NbPoints();
230     int nfull = n1+n2+n3+n4;
231     int ntmp = nfull/2;
232     ntmp = ntmp*2;
233     if (nfull == ntmp && ((n1 != n3) || (n2 != n4))) {
234       // special path for using only quandrangle faces
235       bool ok = ComputeQuadPref(aMesh, aShape, quad);
236       if ( ok && myNeedSmooth )
237         Smooth( quad ); 
238       return ok;
239     }
240   }
241   else if (myQuadType == QUAD_REDUCED) {
242     int n1 = quad->side[0]->NbPoints();
243     int n2 = quad->side[1]->NbPoints();
244     int n3 = quad->side[2]->NbPoints();
245     int n4 = quad->side[3]->NbPoints();
246     int n13 = n1 - n3;
247     int n24 = n2 - n4;
248     int n13tmp = n13/2; n13tmp = n13tmp*2;
249     int n24tmp = n24/2; n24tmp = n24tmp*2;
250     if ((n1 == n3 && n2 != n4 && n24tmp == n24) ||
251         (n2 == n4 && n1 != n3 && n13tmp == n13)) {
252       bool ok = ComputeReduced(aMesh, aShape, quad);
253       if ( ok && myNeedSmooth )
254         Smooth( quad ); 
255       return ok;
256     }
257   }
258
259   // set normalized grid on unit square in parametric domain
260   
261   if (!SetNormalizedGrid(aMesh, aShape, quad))
262     return false;
263
264   // --- compute 3D values on points, store points & quadrangles
265
266   int nbdown  = quad->side[0]->NbPoints();
267   int nbup    = quad->side[2]->NbPoints();
268
269   int nbright = quad->side[1]->NbPoints();
270   int nbleft  = quad->side[3]->NbPoints();
271
272   int nbhoriz  = Min(nbdown, nbup);
273   int nbvertic = Min(nbright, nbleft);
274
275   // internal mesh nodes
276   int i, j, geomFaceID = meshDS->ShapeToIndex(F);
277   for (i = 1; i < nbhoriz - 1; i++) {
278     for (j = 1; j < nbvertic - 1; j++) {
279       int ij = j * nbhoriz + i;
280       double u = quad->uv_grid[ij].u;
281       double v = quad->uv_grid[ij].v;
282       gp_Pnt P = S->Value(u, v);
283       SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
284       meshDS->SetNodeOnFace(node, geomFaceID, u, v);
285       quad->uv_grid[ij].node = node;
286     }
287   }
288   
289   // mesh faces
290
291   //             [2]
292   //      --.--.--.--.--.--  nbvertic
293   //     |                 | ^
294   //     |                 | ^
295   // [3] |                 | ^ j  [1]
296   //     |                 | ^
297   //     |                 | ^
298   //      ---.----.----.---  0
299   //     0 > > > > > > > > nbhoriz
300   //              i
301   //             [0]
302   
303   i = 0;
304   int ilow = 0;
305   int iup = nbhoriz - 1;
306   if (quad->isEdgeOut[3]) { ilow++; } else { if (quad->isEdgeOut[1]) iup--; }
307   
308   int jlow = 0;
309   int jup = nbvertic - 1;
310   if (quad->isEdgeOut[0]) { jlow++; } else { if (quad->isEdgeOut[2]) jup--; }
311   
312   // regular quadrangles
313   for (i = ilow; i < iup; i++) {
314     for (j = jlow; j < jup; j++) {
315       const SMDS_MeshNode *a, *b, *c, *d;
316       a = quad->uv_grid[j       * nbhoriz + i    ].node;
317       b = quad->uv_grid[j       * nbhoriz + i + 1].node;
318       c = quad->uv_grid[(j + 1) * nbhoriz + i + 1].node;
319       d = quad->uv_grid[(j + 1) * nbhoriz + i    ].node;
320       SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
321       if (face) {
322         meshDS->SetMeshElementOnShape(face, geomFaceID);
323       }
324     }
325   }
326
327   const vector<UVPtStruct>& uv_e0 = quad->side[0]->GetUVPtStruct(true,0);
328   const vector<UVPtStruct>& uv_e1 = quad->side[1]->GetUVPtStruct(false,1);
329   const vector<UVPtStruct>& uv_e2 = quad->side[2]->GetUVPtStruct(true,1);
330   const vector<UVPtStruct>& uv_e3 = quad->side[3]->GetUVPtStruct(false,0);
331
332   if (uv_e0.empty() || uv_e1.empty() || uv_e2.empty() || uv_e3.empty())
333     return error(COMPERR_BAD_INPUT_MESH);
334
335   double eps = Precision::Confusion();
336
337   // Boundary quadrangles
338   
339   if (quad->isEdgeOut[0]) {
340     // Down edge is out
341     // 
342     // |___|___|___|___|___|___|
343     // |   |   |   |   |   |   |
344     // |___|___|___|___|___|___|
345     // |   |   |   |   |   |   |
346     // |___|___|___|___|___|___| __ first row of the regular grid
347     // .  .  .  .  .  .  .  .  . __ down edge nodes
348     // 
349     // >->->->->->->->->->->->-> -- direction of processing
350       
351     int g = 0; // number of last processed node in the regular grid
352     
353     // number of last node of the down edge to be processed
354     int stop = nbdown - 1;
355     // if right edge is out, we will stop at a node, previous to the last one
356     if (quad->isEdgeOut[1]) stop--;
357     
358     // for each node of the down edge find nearest node
359     // in the first row of the regular grid and link them
360     for (i = 0; i < stop; i++) {
361       const SMDS_MeshNode *a, *b, *c, *d;
362       a = uv_e0[i].node;
363       b = uv_e0[i + 1].node;
364       gp_Pnt pb (b->X(), b->Y(), b->Z());
365       
366       // find node c in the regular grid, which will be linked with node b
367       int near = g;
368       if (i == stop - 1) {
369         // right bound reached, link with the rightmost node
370         near = iup;
371         c = quad->uv_grid[nbhoriz + iup].node;
372       }
373       else {
374         // find in the grid node c, nearest to the b
375         double mind = RealLast();
376         for (int k = g; k <= iup; k++) {
377           
378           const SMDS_MeshNode *nk;
379           if (k < ilow) // this can be, if left edge is out
380             nk = uv_e3[1].node; // get node from the left edge
381           else
382             nk = quad->uv_grid[nbhoriz + k].node; // get one of middle nodes
383
384           gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
385           double dist = pb.Distance(pnk);
386           if (dist < mind - eps) {
387             c = nk;
388             near = k;
389             mind = dist;
390           } else {
391             break;
392           }
393         }
394       }
395
396       if (near == g) { // make triangle
397         SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
398         if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
399       }
400       else { // make quadrangle
401         if (near - 1 < ilow)
402           d = uv_e3[1].node;
403         else
404           d = quad->uv_grid[nbhoriz + near - 1].node;
405         //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
406         
407         if (!myTrianglePreference){
408           SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
409           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
410         }
411         else {
412           SplitQuad(meshDS, geomFaceID, a, b, c, d);
413         }
414
415         // if node d is not at position g - make additional triangles
416         if (near - 1 > g) {
417           for (int k = near - 1; k > g; k--) {
418             c = quad->uv_grid[nbhoriz + k].node;
419             if (k - 1 < ilow)
420               d = uv_e3[1].node;
421             else
422               d = quad->uv_grid[nbhoriz + k - 1].node;
423             SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
424             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
425           }
426         }
427         g = near;
428       }
429     }
430   } else {
431     if (quad->isEdgeOut[2]) {
432       // Up edge is out
433       // 
434       // <-<-<-<-<-<-<-<-<-<-<-<-< -- direction of processing
435       // 
436       // .  .  .  .  .  .  .  .  . __ up edge nodes
437       //  ___ ___ ___ ___ ___ ___  __ first row of the regular grid
438       // |   |   |   |   |   |   |
439       // |___|___|___|___|___|___|
440       // |   |   |   |   |   |   |
441       // |___|___|___|___|___|___|
442       // |   |   |   |   |   |   |
443
444       int g = nbhoriz - 1; // last processed node in the regular grid
445
446       int stop = 0;
447       // if left edge is out, we will stop at a second node
448       if (quad->isEdgeOut[3]) stop++;
449
450       // for each node of the up edge find nearest node
451       // in the first row of the regular grid and link them
452       for (i = nbup - 1; i > stop; i--) {
453         const SMDS_MeshNode *a, *b, *c, *d;
454         a = uv_e2[i].node;
455         b = uv_e2[i - 1].node;
456         gp_Pnt pb (b->X(), b->Y(), b->Z());
457
458         // find node c in the grid, which will be linked with node b
459         int near = g;
460         if (i == stop + 1) { // left bound reached, link with the leftmost node
461           c = quad->uv_grid[nbhoriz*(nbvertic - 2) + ilow].node;
462           near = ilow;
463         } else {
464           // find node c in the grid, nearest to the b
465           double mind = RealLast();
466           for (int k = g; k >= ilow; k--) {
467             const SMDS_MeshNode *nk;
468             if (k > iup)
469               nk = uv_e1[nbright - 2].node;
470             else
471               nk = quad->uv_grid[nbhoriz*(nbvertic - 2) + k].node;
472             gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
473             double dist = pb.Distance(pnk);
474             if (dist < mind - eps) {
475               c = nk;
476               near = k;
477               mind = dist;
478             } else {
479               break;
480             }
481           }
482         }
483
484         if (near == g) { // make triangle
485           SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
486           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
487         }
488         else { // make quadrangle
489           if (near + 1 > iup)
490             d = uv_e1[nbright - 2].node;
491           else
492             d = quad->uv_grid[nbhoriz*(nbvertic - 2) + near + 1].node;
493           //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
494           if (!myTrianglePreference){
495             SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
496             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
497           }
498           else {
499             SplitQuad(meshDS, geomFaceID, a, b, c, d);
500           }
501
502           if (near + 1 < g) { // if d not is at g - make additional triangles
503             for (int k = near + 1; k < g; k++) {
504               c = quad->uv_grid[nbhoriz*(nbvertic - 2) + k].node;
505               if (k + 1 > iup)
506                 d = uv_e1[nbright - 2].node;
507               else
508                 d = quad->uv_grid[nbhoriz*(nbvertic - 2) + k + 1].node;
509               SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
510               if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
511             }
512           }
513           g = near;
514         }
515       }
516     }
517   }
518
519   // right or left boundary quadrangles
520   if (quad->isEdgeOut[1]) {
521 //    MESSAGE("right edge is out");
522     int g = 0; // last processed node in the grid
523     int stop = nbright - 1;
524     if (quad->isEdgeOut[2]) stop--;
525     for (i = 0; i < stop; i++) {
526       const SMDS_MeshNode *a, *b, *c, *d;
527       a = uv_e1[i].node;
528       b = uv_e1[i + 1].node;
529       gp_Pnt pb (b->X(), b->Y(), b->Z());
530
531       // find node c in the grid, nearest to the b
532       int near = g;
533       if (i == stop - 1) { // up bondary reached
534         c = quad->uv_grid[nbhoriz*(jup + 1) - 2].node;
535         near = jup;
536       } else {
537         double mind = RealLast();
538         for (int k = g; k <= jup; k++) {
539           const SMDS_MeshNode *nk;
540           if (k < jlow)
541             nk = uv_e0[nbdown - 2].node;
542           else
543             nk = quad->uv_grid[nbhoriz*(k + 1) - 2].node;
544           gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
545           double dist = pb.Distance(pnk);
546           if (dist < mind - eps) {
547             c = nk;
548             near = k;
549             mind = dist;
550           } else {
551             break;
552           }
553         }
554       }
555
556       if (near == g) { // make triangle
557         SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
558         if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
559       }
560       else { // make quadrangle
561         if (near - 1 < jlow)
562           d = uv_e0[nbdown - 2].node;
563         else
564           d = quad->uv_grid[nbhoriz*near - 2].node;
565         //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
566
567         if (!myTrianglePreference){
568           SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
569           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
570         }
571         else {
572           SplitQuad(meshDS, geomFaceID, a, b, c, d);
573         }
574
575         if (near - 1 > g) { // if d not is at g - make additional triangles
576           for (int k = near - 1; k > g; k--) {
577             c = quad->uv_grid[nbhoriz*(k + 1) - 2].node;
578             if (k - 1 < jlow)
579               d = uv_e0[nbdown - 2].node;
580             else
581               d = quad->uv_grid[nbhoriz*k - 2].node;
582             SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
583             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
584           }
585         }
586         g = near;
587       }
588     }
589   } else {
590     if (quad->isEdgeOut[3]) {
591 //      MESSAGE("left edge is out");
592       int g = nbvertic - 1; // last processed node in the grid
593       int stop = 0;
594       if (quad->isEdgeOut[0]) stop++;
595       for (i = nbleft - 1; i > stop; i--) {
596         const SMDS_MeshNode *a, *b, *c, *d;
597         a = uv_e3[i].node;
598         b = uv_e3[i - 1].node;
599         gp_Pnt pb (b->X(), b->Y(), b->Z());
600
601         // find node c in the grid, nearest to the b
602         int near = g;
603         if (i == stop + 1) { // down bondary reached
604           c = quad->uv_grid[nbhoriz*jlow + 1].node;
605           near = jlow;
606         } else {
607           double mind = RealLast();
608           for (int k = g; k >= jlow; k--) {
609             const SMDS_MeshNode *nk;
610             if (k > jup)
611               nk = uv_e2[1].node;
612             else
613               nk = quad->uv_grid[nbhoriz*k + 1].node;
614             gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
615             double dist = pb.Distance(pnk);
616             if (dist < mind - eps) {
617               c = nk;
618               near = k;
619               mind = dist;
620             } else {
621               break;
622             }
623           }
624         }
625
626         if (near == g) { // make triangle
627           SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
628           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
629         }
630         else { // make quadrangle
631           if (near + 1 > jup)
632             d = uv_e2[1].node;
633           else
634             d = quad->uv_grid[nbhoriz*(near + 1) + 1].node;
635           //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
636           if (!myTrianglePreference){
637             SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
638             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
639           }
640           else {
641             SplitQuad(meshDS, geomFaceID, a, b, c, d);
642           }
643
644           if (near + 1 < g) { // if d not is at g - make additional triangles
645             for (int k = near + 1; k < g; k++) {
646               c = quad->uv_grid[nbhoriz*k + 1].node;
647               if (k + 1 > jup)
648                 d = uv_e2[1].node;
649               else
650                 d = quad->uv_grid[nbhoriz*(k + 1) + 1].node;
651               SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
652               if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
653             }
654           }
655           g = near;
656         }
657       }
658     }
659   }
660
661   if ( myNeedSmooth )
662     Smooth( quad );
663
664   bool isOk = true;
665   return isOk;
666 }
667
668
669 //=============================================================================
670 /*!
671  *  Evaluate
672  */
673 //=============================================================================
674
675 bool StdMeshers_Quadrangle_2D::Evaluate(SMESH_Mesh& aMesh,
676                                         const TopoDS_Shape& aShape,
677                                         MapShapeNbElems& aResMap)
678
679 {
680   aMesh.GetSubMesh(aShape);
681
682   std::vector<int> aNbNodes(4);
683   bool IsQuadratic = false;
684   if (!CheckNbEdgesForEvaluate(aMesh, aShape, aResMap, aNbNodes, IsQuadratic)) {
685     std::vector<int> aResVec(SMDSEntity_Last);
686     for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
687     SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
688     aResMap.insert(std::make_pair(sm,aResVec));
689     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
690     smError.reset(new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
691     return false;
692   }
693
694   if (myQuadranglePreference) {
695     int n1 = aNbNodes[0];
696     int n2 = aNbNodes[1];
697     int n3 = aNbNodes[2];
698     int n4 = aNbNodes[3];
699     int nfull = n1+n2+n3+n4;
700     int ntmp = nfull/2;
701     ntmp = ntmp*2;
702     if (nfull==ntmp && ((n1!=n3) || (n2!=n4))) {
703       // special path for using only quandrangle faces
704       return EvaluateQuadPref(aMesh, aShape, aNbNodes, aResMap, IsQuadratic);
705       //return true;
706     }
707   }
708
709   int nbdown  = aNbNodes[0];
710   int nbup    = aNbNodes[2];
711
712   int nbright = aNbNodes[1];
713   int nbleft  = aNbNodes[3];
714
715   int nbhoriz  = Min(nbdown, nbup);
716   int nbvertic = Min(nbright, nbleft);
717
718   int dh = Max(nbdown, nbup) - nbhoriz;
719   int dv = Max(nbright, nbleft) - nbvertic;
720
721   //int kdh = 0;
722   //if (dh>0) kdh = 1;
723   //int kdv = 0;
724   //if (dv>0) kdv = 1;
725
726   int nbNodes = (nbhoriz-2)*(nbvertic-2);
727   //int nbFaces3 = dh + dv + kdh*(nbvertic-1)*2 + kdv*(nbhoriz-1)*2;
728   int nbFaces3 = dh + dv;
729   //if (kdh==1 && kdv==1) nbFaces3 -= 2;
730   //if (dh>0 && dv>0) nbFaces3 -= 2;
731   //int nbFaces4 = (nbhoriz-1-kdh)*(nbvertic-1-kdv);
732   int nbFaces4 = (nbhoriz-1)*(nbvertic-1);
733
734   std::vector<int> aVec(SMDSEntity_Last);
735   for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
736   if (IsQuadratic) {
737     aVec[SMDSEntity_Quad_Triangle] = nbFaces3;
738     aVec[SMDSEntity_Quad_Quadrangle] = nbFaces4;
739     int nbbndedges = nbdown + nbup + nbright + nbleft -4;
740     int nbintedges = (nbFaces4*4 + nbFaces3*3 - nbbndedges) / 2;
741     aVec[SMDSEntity_Node] = nbNodes + nbintedges;
742     if (aNbNodes.size()==5) {
743       aVec[SMDSEntity_Quad_Triangle] = nbFaces3 + aNbNodes[3] -1;
744       aVec[SMDSEntity_Quad_Quadrangle] = nbFaces4 - aNbNodes[3] +1;
745     }
746   }
747   else {
748     aVec[SMDSEntity_Node] = nbNodes;
749     aVec[SMDSEntity_Triangle] = nbFaces3;
750     aVec[SMDSEntity_Quadrangle] = nbFaces4;
751     if (aNbNodes.size()==5) {
752       aVec[SMDSEntity_Triangle] = nbFaces3 + aNbNodes[3] - 1;
753       aVec[SMDSEntity_Quadrangle] = nbFaces4 - aNbNodes[3] + 1;
754     }
755   }
756   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
757   aResMap.insert(std::make_pair(sm,aVec));
758
759   return true;
760 }
761
762
763 //================================================================================
764 /*!
765  * \brief Return true if only two given edges meat at their common vertex
766  */
767 //================================================================================
768
769 static bool twoEdgesMeatAtVertex(const TopoDS_Edge& e1,
770                                  const TopoDS_Edge& e2,
771                                  SMESH_Mesh &       mesh)
772 {
773   TopoDS_Vertex v;
774   if (!TopExp::CommonVertex(e1, e2, v))
775     return false;
776   TopTools_ListIteratorOfListOfShape ancestIt(mesh.GetAncestors(v));
777   for (; ancestIt.More() ; ancestIt.Next())
778     if (ancestIt.Value().ShapeType() == TopAbs_EDGE)
779       if (!e1.IsSame(ancestIt.Value()) && !e2.IsSame(ancestIt.Value()))
780         return false;
781   return true;
782 }
783
784 //=============================================================================
785 /*!
786  *  
787  */
788 //=============================================================================
789
790 FaceQuadStruct::Ptr StdMeshers_Quadrangle_2D::CheckNbEdges(SMESH_Mesh &         aMesh,
791                                                            const TopoDS_Shape & aShape)
792 {
793   if ( myQuadStruct && myQuadStruct->face.IsSame( aShape ))
794     return myQuadStruct;
795
796   TopoDS_Face F = TopoDS::Face(aShape);
797   if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
798   const bool ignoreMediumNodes = _quadraticMesh;
799
800   // verify 1 wire only, with 4 edges
801   list< TopoDS_Edge > edges;
802   list< int > nbEdgesInWire;
803   int nbWire = SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
804   if (nbWire != 1) {
805     error(COMPERR_BAD_SHAPE, TComm("Wrong number of wires: ") << nbWire);
806     return FaceQuadStruct::Ptr();
807   }
808   FaceQuadStruct::Ptr quad( new FaceQuadStruct );
809   quad->uv_grid = 0;
810   quad->side.reserve(nbEdgesInWire.front());
811   quad->face = F;
812
813   int nbSides = 0;
814   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
815   if (nbEdgesInWire.front() == 3) // exactly 3 edges
816   {
817     SMESH_Comment comment;
818     SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
819     if (myTriaVertexID < 1)
820     {
821       comment << "No Base vertex parameter provided for a trilateral geometrical face";
822     }
823     else
824     {
825       TopoDS_Vertex V = TopoDS::Vertex(meshDS->IndexToShape(myTriaVertexID));
826       if (!V.IsNull()) {
827         TopoDS_Edge E1,E2,E3;
828         for (; edgeIt != edges.end(); ++edgeIt) {
829           TopoDS_Edge E =  *edgeIt;
830           TopoDS_Vertex VF, VL;
831           TopExp::Vertices(E, VF, VL, true);
832           if (VF.IsSame(V))
833             E1 = E;
834           else if (VL.IsSame(V))
835             E3 = E;
836           else
837             E2 = E;
838         }
839         if (!E1.IsNull() && !E2.IsNull() && !E3.IsNull())
840         {
841           quad->side.push_back(new StdMeshers_FaceSide(F, E1, &aMesh, true,
842                                                        ignoreMediumNodes, myProxyMesh));
843           quad->side.push_back(new StdMeshers_FaceSide(F, E2, &aMesh, true,
844                                                        ignoreMediumNodes, myProxyMesh));
845           quad->side.push_back(new StdMeshers_FaceSide(F, E3, &aMesh, false,
846                                                        ignoreMediumNodes, myProxyMesh));
847           const vector<UVPtStruct>& UVPSleft  = quad->side[0]->GetUVPtStruct(true,0);
848           /*  vector<UVPtStruct>& UVPStop   = */quad->side[1]->GetUVPtStruct(false,1);
849           /*  vector<UVPtStruct>& UVPSright = */quad->side[2]->GetUVPtStruct(true,1);
850           const SMDS_MeshNode* aNode = UVPSleft[0].node;
851           gp_Pnt2d aPnt2d(UVPSleft[0].u, UVPSleft[0].v);
852           quad->side.push_back(new StdMeshers_FaceSide(aNode, aPnt2d, quad->side[1]));
853           return quad;
854         }
855       }
856       comment << "Invalid Base vertex parameter: " << myTriaVertexID << " is not among [";
857       TopTools_MapOfShape vMap;
858       for (TopExp_Explorer v(aShape, TopAbs_VERTEX); v.More(); v.Next())
859         if (vMap.Add(v.Current()))
860           comment << meshDS->ShapeToIndex(v.Current()) << (vMap.Extent()==3 ? "]" : ", ");
861     }
862     error(comment);
863     quad.reset();
864     return quad;
865   }
866   else if (nbEdgesInWire.front() == 4) // exactly 4 edges
867   {
868     for (; edgeIt != edges.end(); ++edgeIt, nbSides++)
869       quad->side.push_back(new StdMeshers_FaceSide(F, *edgeIt, &aMesh, nbSides < QUAD_TOP_SIDE,
870                                                    ignoreMediumNodes, myProxyMesh));
871   }
872   else if (nbEdgesInWire.front() > 4) // more than 4 edges - try to unite some
873   {
874     list< TopoDS_Edge > sideEdges;
875     vector< int > degenSides;
876     while (!edges.empty()) {
877       sideEdges.clear();
878       sideEdges.splice(sideEdges.end(), edges, edges.begin()); // edges.front() -> sideEdges.end()
879       bool sameSide = true;
880       while (!edges.empty() && sameSide) {
881         sameSide = SMESH_Algo::IsContinuous(sideEdges.back(), edges.front());
882         if (sameSide)
883           sideEdges.splice(sideEdges.end(), edges, edges.begin());
884       }
885       if (nbSides == 0) { // go backward from the first edge
886         sameSide = true;
887         while (!edges.empty() && sameSide) {
888           sameSide = SMESH_Algo::IsContinuous(sideEdges.front(), edges.back());
889           if (sameSide)
890             sideEdges.splice(sideEdges.begin(), edges, --edges.end());
891         }
892       }
893       if ( sideEdges.size() == 1 && BRep_Tool::Degenerated( sideEdges.front() ))
894         degenSides.push_back( nbSides );
895
896       quad->side.push_back(new StdMeshers_FaceSide(F, sideEdges, &aMesh, nbSides < QUAD_TOP_SIDE,
897                                                    ignoreMediumNodes, myProxyMesh));
898       ++nbSides;
899     }
900     if ( !degenSides.empty() && nbSides - degenSides.size() == 4 )
901     {
902       myNeedSmooth = true;
903       for ( unsigned i = QUAD_TOP_SIDE; i < quad->side.size(); ++i )
904         quad->side[i]->Reverse();
905
906       for ( int i = degenSides.size()-1; i > -1; --i )
907       {
908         StdMeshers_FaceSide* degenSide = quad->side[ degenSides[ i ]];
909         delete degenSide;
910         quad->side.erase( quad->side.begin() + degenSides[ i ] );
911       }
912       for ( unsigned i = QUAD_TOP_SIDE; i < quad->side.size(); ++i )
913         quad->side[i]->Reverse();
914
915       nbSides -= degenSides.size();
916     }
917     // issue 20222. Try to unite only edges shared by two same faces
918     if (nbSides < 4)
919     {
920       quad.reset( new FaceQuadStruct );
921       quad->side.reserve(nbEdgesInWire.front());
922       nbSides = 0;
923
924       SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
925       while (!edges.empty()) {
926         sideEdges.clear();
927         sideEdges.splice(sideEdges.end(), edges, edges.begin());
928         bool sameSide = true;
929         while (!edges.empty() && sameSide) {
930           sameSide =
931             SMESH_Algo::IsContinuous(sideEdges.back(), edges.front()) &&
932             twoEdgesMeatAtVertex(sideEdges.back(), edges.front(), aMesh);
933           if (sameSide)
934             sideEdges.splice(sideEdges.end(), edges, edges.begin());
935         }
936         if (nbSides == 0) { // go backward from the first edge
937           sameSide = true;
938           while (!edges.empty() && sameSide) {
939             sameSide =
940               SMESH_Algo::IsContinuous(sideEdges.front(), edges.back()) &&
941               twoEdgesMeatAtVertex(sideEdges.front(), edges.back(), aMesh);
942             if (sameSide)
943               sideEdges.splice(sideEdges.begin(), edges, --edges.end());
944           }
945         }
946         quad->side.push_back(new StdMeshers_FaceSide(F, sideEdges, &aMesh,
947                                                      nbSides < QUAD_TOP_SIDE,
948                                                      ignoreMediumNodes, myProxyMesh));
949         ++nbSides;
950       }
951     }
952   }
953   if (nbSides != 4) {
954 #ifdef _DEBUG_
955     MESSAGE ("StdMeshers_Quadrangle_2D. Edge IDs of " << nbSides << " sides:\n");
956     for (int i = 0; i < nbSides; ++i) {
957       MESSAGE (" (");
958       for (int e = 0; e < quad->side[i]->NbEdges(); ++e)
959         MESSAGE (myHelper->GetMeshDS()->ShapeToIndex(quad->side[i]->Edge(e)) << " ");
960       MESSAGE (")\n");
961     }
962 #endif
963     if (!nbSides)
964       nbSides = nbEdgesInWire.front();
965     error(COMPERR_BAD_SHAPE, TComm("Face must have 4 sides but not ") << nbSides);
966     quad.reset();
967   }
968
969   return quad;
970 }
971
972
973 //=============================================================================
974 /*!
975  *  
976  */
977 //=============================================================================
978
979 bool StdMeshers_Quadrangle_2D::CheckNbEdgesForEvaluate(SMESH_Mesh& aMesh,
980                                                        const TopoDS_Shape & aShape,
981                                                        MapShapeNbElems& aResMap,
982                                                        std::vector<int>& aNbNodes,
983                                                        bool& IsQuadratic)
984
985 {
986   const TopoDS_Face & F = TopoDS::Face(aShape);
987
988   // verify 1 wire only, with 4 edges
989   list< TopoDS_Edge > edges;
990   list< int > nbEdgesInWire;
991   int nbWire = SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
992   if (nbWire != 1) {
993     return false;
994   }
995
996   aNbNodes.resize(4);
997
998   int nbSides = 0;
999   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
1000   SMESH_subMesh * sm = aMesh.GetSubMesh(*edgeIt);
1001   MapShapeNbElemsItr anIt = aResMap.find(sm);
1002   if (anIt==aResMap.end()) {
1003     return false;
1004   }
1005   std::vector<int> aVec = (*anIt).second;
1006   IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
1007   if (nbEdgesInWire.front() == 3) { // exactly 3 edges
1008     if (myTriaVertexID>0) {
1009       SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1010       TopoDS_Vertex V = TopoDS::Vertex(meshDS->IndexToShape(myTriaVertexID));
1011       if (!V.IsNull()) {
1012         TopoDS_Edge E1,E2,E3;
1013         for (; edgeIt != edges.end(); ++edgeIt) {
1014           TopoDS_Edge E =  TopoDS::Edge(*edgeIt);
1015           TopoDS_Vertex VF, VL;
1016           TopExp::Vertices(E, VF, VL, true);
1017           if (VF.IsSame(V))
1018             E1 = E;
1019           else if (VL.IsSame(V))
1020             E3 = E;
1021           else
1022             E2 = E;
1023         }
1024         SMESH_subMesh * sm = aMesh.GetSubMesh(E1);
1025         MapShapeNbElemsItr anIt = aResMap.find(sm);
1026         if (anIt==aResMap.end()) return false;
1027         std::vector<int> aVec = (*anIt).second;
1028         if (IsQuadratic)
1029           aNbNodes[0] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1030         else
1031           aNbNodes[0] = aVec[SMDSEntity_Node] + 2;
1032         sm = aMesh.GetSubMesh(E2);
1033         anIt = aResMap.find(sm);
1034         if (anIt==aResMap.end()) return false;
1035         aVec = (*anIt).second;
1036         if (IsQuadratic)
1037           aNbNodes[1] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1038         else
1039           aNbNodes[1] = aVec[SMDSEntity_Node] + 2;
1040         sm = aMesh.GetSubMesh(E3);
1041         anIt = aResMap.find(sm);
1042         if (anIt==aResMap.end()) return false;
1043         aVec = (*anIt).second;
1044         if (IsQuadratic)
1045           aNbNodes[2] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1046         else
1047           aNbNodes[2] = aVec[SMDSEntity_Node] + 2;
1048         aNbNodes[3] = aNbNodes[1];
1049         aNbNodes.resize(5);
1050         nbSides = 4;
1051       }
1052     }
1053   }
1054   if (nbEdgesInWire.front() == 4) { // exactly 4 edges
1055     for (; edgeIt != edges.end(); edgeIt++) {
1056       SMESH_subMesh * sm = aMesh.GetSubMesh(*edgeIt);
1057       MapShapeNbElemsItr anIt = aResMap.find(sm);
1058       if (anIt==aResMap.end()) {
1059         return false;
1060       }
1061       std::vector<int> aVec = (*anIt).second;
1062       if (IsQuadratic)
1063         aNbNodes[nbSides] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1064       else
1065         aNbNodes[nbSides] = aVec[SMDSEntity_Node] + 2;
1066       nbSides++;
1067     }
1068   }
1069   else if (nbEdgesInWire.front() > 4) { // more than 4 edges - try to unite some
1070     list< TopoDS_Edge > sideEdges;
1071     while (!edges.empty()) {
1072       sideEdges.clear();
1073       sideEdges.splice(sideEdges.end(), edges, edges.begin()); // edges.front() -> sideEdges.end()
1074       bool sameSide = true;
1075       while (!edges.empty() && sameSide) {
1076         sameSide = SMESH_Algo::IsContinuous(sideEdges.back(), edges.front());
1077         if (sameSide)
1078           sideEdges.splice(sideEdges.end(), edges, edges.begin());
1079       }
1080       if (nbSides == 0) { // go backward from the first edge
1081         sameSide = true;
1082         while (!edges.empty() && sameSide) {
1083           sameSide = SMESH_Algo::IsContinuous(sideEdges.front(), edges.back());
1084           if (sameSide)
1085             sideEdges.splice(sideEdges.begin(), edges, --edges.end());
1086         }
1087       }
1088       list<TopoDS_Edge>::iterator ite = sideEdges.begin();
1089       aNbNodes[nbSides] = 1;
1090       for (; ite!=sideEdges.end(); ite++) {
1091         SMESH_subMesh * sm = aMesh.GetSubMesh(*ite);
1092         MapShapeNbElemsItr anIt = aResMap.find(sm);
1093         if (anIt==aResMap.end()) {
1094           return false;
1095         }
1096         std::vector<int> aVec = (*anIt).second;
1097         if (IsQuadratic)
1098           aNbNodes[nbSides] += (aVec[SMDSEntity_Node]-1)/2 + 1;
1099         else
1100           aNbNodes[nbSides] += aVec[SMDSEntity_Node] + 1;
1101       }
1102       ++nbSides;
1103     }
1104     // issue 20222. Try to unite only edges shared by two same faces
1105     if (nbSides < 4) {
1106       nbSides = 0;
1107       SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
1108       while (!edges.empty()) {
1109         sideEdges.clear();
1110         sideEdges.splice(sideEdges.end(), edges, edges.begin());
1111         bool sameSide = true;
1112         while (!edges.empty() && sameSide) {
1113           sameSide =
1114             SMESH_Algo::IsContinuous(sideEdges.back(), edges.front()) &&
1115             twoEdgesMeatAtVertex(sideEdges.back(), edges.front(), aMesh);
1116           if (sameSide)
1117             sideEdges.splice(sideEdges.end(), edges, edges.begin());
1118         }
1119         if (nbSides == 0) { // go backward from the first edge
1120           sameSide = true;
1121           while (!edges.empty() && sameSide) {
1122             sameSide =
1123               SMESH_Algo::IsContinuous(sideEdges.front(), edges.back()) &&
1124               twoEdgesMeatAtVertex(sideEdges.front(), edges.back(), aMesh);
1125             if (sameSide)
1126               sideEdges.splice(sideEdges.begin(), edges, --edges.end());
1127           }
1128         }
1129         list<TopoDS_Edge>::iterator ite = sideEdges.begin();
1130         aNbNodes[nbSides] = 1;
1131         for (; ite!=sideEdges.end(); ite++) {
1132           SMESH_subMesh * sm = aMesh.GetSubMesh(*ite);
1133           MapShapeNbElemsItr anIt = aResMap.find(sm);
1134           if (anIt==aResMap.end()) {
1135             return false;
1136           }
1137           std::vector<int> aVec = (*anIt).second;
1138           if (IsQuadratic)
1139             aNbNodes[nbSides] += (aVec[SMDSEntity_Node]-1)/2 + 1;
1140           else
1141             aNbNodes[nbSides] += aVec[SMDSEntity_Node] + 1;
1142         }
1143         ++nbSides;
1144       }
1145     }
1146   }
1147   if (nbSides != 4) {
1148     if (!nbSides)
1149       nbSides = nbEdgesInWire.front();
1150     error(COMPERR_BAD_SHAPE, TComm("Face must have 4 sides but not ") << nbSides);
1151     return false;
1152   }
1153
1154   return true;
1155 }
1156
1157
1158 //=============================================================================
1159 /*!
1160  *  CheckAnd2Dcompute
1161  */
1162 //=============================================================================
1163
1164 FaceQuadStruct::Ptr
1165 StdMeshers_Quadrangle_2D::CheckAnd2Dcompute (SMESH_Mesh &         aMesh,
1166                                              const TopoDS_Shape & aShape,
1167                                              const bool           CreateQuadratic)
1168 {
1169   _quadraticMesh = CreateQuadratic;
1170
1171   FaceQuadStruct::Ptr quad = CheckNbEdges(aMesh, aShape);
1172   if ( quad )
1173   {
1174     // set normalized grid on unit square in parametric domain
1175     if (!SetNormalizedGrid(aMesh, aShape, quad))
1176       quad.reset();
1177   }
1178   return quad;
1179 }
1180
1181 //=============================================================================
1182 /*!
1183  *
1184  */
1185 //=============================================================================
1186
1187 faceQuadStruct::~faceQuadStruct()
1188 {
1189   for (size_t i = 0; i < side.size(); i++) {
1190     if (side[i]) {
1191       delete side[i];
1192       for (size_t j = i+1; j < side.size(); j++)
1193         if ( side[i] == side[j] )
1194           side[j] = 0;
1195     }
1196   }
1197   side.clear();
1198
1199   if (uv_grid) {
1200     delete [] uv_grid;
1201     uv_grid = 0;
1202   }
1203 }
1204
1205 namespace
1206 {
1207   inline const vector<UVPtStruct>& getUVPtStructIn(FaceQuadStruct::Ptr& quad, int i, int nbSeg)
1208   {
1209     bool   isXConst   = (i == QUAD_BOTTOM_SIDE || i == QUAD_TOP_SIDE);
1210     double constValue = (i == QUAD_BOTTOM_SIDE || i == QUAD_LEFT_SIDE) ? 0 : 1;
1211     return
1212       quad->isEdgeOut[i] ?
1213       quad->side[i]->SimulateUVPtStruct(nbSeg,isXConst,constValue) :
1214       quad->side[i]->GetUVPtStruct(isXConst,constValue);
1215   }
1216   inline gp_UV calcUV(double x, double y,
1217                       const gp_UV& a0,const gp_UV& a1,const gp_UV& a2,const gp_UV& a3,
1218                       const gp_UV& p0,const gp_UV& p1,const gp_UV& p2,const gp_UV& p3)
1219   {
1220     return
1221       ((1 - y) * p0 + x * p1 + y * p2 + (1 - x) * p3 ) -
1222       ((1 - x) * (1 - y) * a0 + x * (1 - y) * a1 + x * y * a2 + (1 - x) * y * a3);
1223   }
1224 }
1225
1226 //=============================================================================
1227 /*!
1228  *  
1229  */
1230 //=============================================================================
1231
1232 bool StdMeshers_Quadrangle_2D::SetNormalizedGrid (SMESH_Mesh &          aMesh,
1233                                                   const TopoDS_Shape&   aShape,
1234                                                   FaceQuadStruct::Ptr & quad)
1235 {
1236   // Algorithme décrit dans "Génération automatique de maillages"
1237   // P.L. GEORGE, MASSON, Â§ 6.4.1 p. 84-85
1238   // traitement dans le domaine paramétrique 2d u,v
1239   // transport - projection sur le carré unité
1240
1241 //  MESSAGE("StdMeshers_Quadrangle_2D::SetNormalizedGrid");
1242 //  const TopoDS_Face& F = TopoDS::Face(aShape);
1243
1244   // 1 --- find orientation of the 4 edges, by test on extrema
1245
1246   //      max             min                    0     x1     1
1247   //     |<----north-2-------^                a3 -------------> a2
1248   //     |                   |                   ^1          1^
1249   //    west-3            east-1 =right          |            |
1250   //     |                   |         ==>       |            |
1251   //  y0 |                   | y1                |            |
1252   //     |                   |                   |0          0|
1253   //     v----south-0-------->                a0 -------------> a1
1254   //      min             max                    0     x0     1
1255   //             =down
1256   //
1257
1258   // 3 --- 2D normalized values on unit square [0..1][0..1]
1259
1260   int nbhoriz  = Min(quad->side[0]->NbPoints(), quad->side[2]->NbPoints());
1261   int nbvertic = Min(quad->side[1]->NbPoints(), quad->side[3]->NbPoints());
1262
1263   quad->isEdgeOut[0] = (quad->side[0]->NbPoints() > quad->side[2]->NbPoints());
1264   quad->isEdgeOut[1] = (quad->side[1]->NbPoints() > quad->side[3]->NbPoints());
1265   quad->isEdgeOut[2] = (quad->side[2]->NbPoints() > quad->side[0]->NbPoints());
1266   quad->isEdgeOut[3] = (quad->side[3]->NbPoints() > quad->side[1]->NbPoints());
1267
1268   UVPtStruct *uv_grid = quad->uv_grid = new UVPtStruct[nbvertic * nbhoriz];
1269
1270   const vector<UVPtStruct>& uv_e0 = getUVPtStructIn(quad, 0, nbhoriz - 1);
1271   const vector<UVPtStruct>& uv_e1 = getUVPtStructIn(quad, 1, nbvertic - 1);
1272   const vector<UVPtStruct>& uv_e2 = getUVPtStructIn(quad, 2, nbhoriz - 1);
1273   const vector<UVPtStruct>& uv_e3 = getUVPtStructIn(quad, 3, nbvertic - 1);
1274
1275   if (uv_e0.empty() || uv_e1.empty() || uv_e2.empty() || uv_e3.empty())
1276     //return error("Can't find nodes on sides");
1277     return error(COMPERR_BAD_INPUT_MESH);
1278
1279   if ( myNeedSmooth )
1280     UpdateDegenUV( quad );
1281
1282   // copy data of face boundary
1283   /*if (! quad->isEdgeOut[0])*/ {
1284     const int j = 0;
1285     for (int i = 0; i < nbhoriz; i++)       // down
1286       uv_grid[ j * nbhoriz + i ] = uv_e0[i];
1287   }
1288   /*if (! quad->isEdgeOut[1])*/ {
1289     const int i = nbhoriz - 1;
1290     for (int j = 0; j < nbvertic; j++)      // right
1291       uv_grid[ j * nbhoriz + i ] = uv_e1[j];
1292   }
1293   /*if (! quad->isEdgeOut[2])*/ {
1294     const int j = nbvertic - 1;
1295     for (int i = 0; i < nbhoriz; i++)       // up
1296       uv_grid[ j * nbhoriz + i ] = uv_e2[i];
1297   }
1298   /*if (! quad->isEdgeOut[3])*/ {
1299     int i = 0;
1300     for (int j = 0; j < nbvertic; j++)      // left
1301       uv_grid[ j * nbhoriz + i ] = uv_e3[j];
1302   }
1303
1304   // normalized 2d parameters on grid
1305   for (int i = 0; i < nbhoriz; i++) {
1306     for (int j = 0; j < nbvertic; j++) {
1307       int ij = j * nbhoriz + i;
1308       // --- droite i cste : x = x0 + y(x1-x0)
1309       double x0 = uv_e0[i].normParam;   // bas - sud
1310       double x1 = uv_e2[i].normParam;   // haut - nord
1311       // --- droite j cste : y = y0 + x(y1-y0)
1312       double y0 = uv_e3[j].normParam;   // gauche-ouest
1313       double y1 = uv_e1[j].normParam;   // droite - est
1314       // --- intersection : x=x0+(y0+x(y1-y0))(x1-x0)
1315       double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1316       double y = y0 + x * (y1 - y0);
1317       uv_grid[ij].x = x;
1318       uv_grid[ij].y = y;
1319       //MESSAGE("-xy-01 "<<x0<<" "<<x1<<" "<<y0<<" "<<y1);
1320       //MESSAGE("-xy-norm "<<i<<" "<<j<<" "<<x<<" "<<y);
1321     }
1322   }
1323
1324   // 4 --- projection on 2d domain (u,v)
1325   gp_UV a0 (uv_e0.front().u, uv_e0.front().v);
1326   gp_UV a1 (uv_e0.back().u,  uv_e0.back().v );
1327   gp_UV a2 (uv_e2.back().u,  uv_e2.back().v );
1328   gp_UV a3 (uv_e2.front().u, uv_e2.front().v);
1329
1330   for (int i = 0; i < nbhoriz; i++)
1331   {
1332     gp_UV p0( uv_e0[i].u, uv_e0[i].v );
1333     gp_UV p2( uv_e2[i].u, uv_e2[i].v );
1334     for (int j = 0; j < nbvertic; j++)
1335     {
1336       gp_UV p1( uv_e1[j].u, uv_e1[j].v );
1337       gp_UV p3( uv_e3[j].u, uv_e3[j].v );
1338
1339       int ij = j * nbhoriz + i;
1340       double x = uv_grid[ij].x;
1341       double y = uv_grid[ij].y;
1342
1343       gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1344
1345       uv_grid[ij].u = uv.X();
1346       uv_grid[ij].v = uv.Y();
1347     }
1348   }
1349   return true;
1350 }
1351
1352 //=======================================================================
1353 //function : ShiftQuad
1354 //purpose  : auxilary function for ComputeQuadPref
1355 //=======================================================================
1356
1357 static void shiftQuad(FaceQuadStruct::Ptr& quad, const int num, bool)
1358 {
1359   quad->shift( num, /*ori=*/true );
1360 }
1361
1362 //================================================================================
1363 /*!
1364  * \brief Rotate sides of a quad by nb
1365  *  \param nb  - number of rotation quartes 
1366  *  \param ori - to keep orientation of sides as in an unit quad or not
1367  */
1368 //================================================================================
1369
1370 void FaceQuadStruct::shift( size_t nb, bool ori )
1371 {
1372   if ( nb == 0 ) return;
1373   StdMeshers_FaceSide* sideArr[4] = { side[0], side[1], side[2], side[3] };
1374   for (int i = QUAD_BOTTOM_SIDE; i < NB_QUAD_SIDES; ++i) {
1375     int id = (i + nb) % NB_QUAD_SIDES;
1376     bool wasForward = (i  < QUAD_TOP_SIDE);
1377     bool newForward = (id < QUAD_TOP_SIDE);
1378     if (ori && wasForward != newForward)
1379       sideArr[ i ]->Reverse();
1380     side[ id ] = sideArr[ i ];
1381   }
1382 }
1383
1384 //=======================================================================
1385 //function : calcUV
1386 //purpose  : auxilary function for ComputeQuadPref
1387 //=======================================================================
1388
1389 static gp_UV calcUV(double x0, double x1, double y0, double y1,
1390                     FaceQuadStruct::Ptr& quad,
1391                     const gp_UV& a0, const gp_UV& a1,
1392                     const gp_UV& a2, const gp_UV& a3)
1393 {
1394   double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1395   double y = y0 + x * (y1 - y0);
1396
1397   gp_UV p0 = quad->side[QUAD_BOTTOM_SIDE]->Value2d(x).XY();
1398   gp_UV p1 = quad->side[QUAD_RIGHT_SIDE ]->Value2d(y).XY();
1399   gp_UV p2 = quad->side[QUAD_TOP_SIDE   ]->Value2d(x).XY();
1400   gp_UV p3 = quad->side[QUAD_LEFT_SIDE  ]->Value2d(y).XY();
1401
1402   gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1403
1404   return uv;
1405 }
1406
1407 //=======================================================================
1408 //function : calcUV2
1409 //purpose  : auxilary function for ComputeQuadPref
1410 //=======================================================================
1411
1412 static gp_UV calcUV2(double x, double y,
1413                      FaceQuadStruct::Ptr& quad,
1414                      const gp_UV& a0, const gp_UV& a1,
1415                      const gp_UV& a2, const gp_UV& a3)
1416 {
1417   gp_UV p0 = quad->side[QUAD_BOTTOM_SIDE]->Value2d(x).XY();
1418   gp_UV p1 = quad->side[QUAD_RIGHT_SIDE ]->Value2d(y).XY();
1419   gp_UV p2 = quad->side[QUAD_TOP_SIDE   ]->Value2d(x).XY();
1420   gp_UV p3 = quad->side[QUAD_LEFT_SIDE  ]->Value2d(y).XY();
1421
1422   gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1423
1424   return uv;
1425 }
1426
1427
1428 //=======================================================================
1429 /*!
1430  * Create only quandrangle faces
1431  */
1432 //=======================================================================
1433
1434 bool StdMeshers_Quadrangle_2D::ComputeQuadPref (SMESH_Mesh &        aMesh,
1435                                                 const TopoDS_Shape& aShape,
1436                                                 FaceQuadStruct::Ptr quad)
1437 {
1438   // Auxilary key in order to keep old variant
1439   // of meshing after implementation new variant
1440   // for bug 0016220 from Mantis.
1441   bool OldVersion = false;
1442   if (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
1443     OldVersion = true;
1444
1445   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1446   const TopoDS_Face& F = TopoDS::Face(aShape);
1447   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
1448   bool WisF = true;
1449   int i,j,geomFaceID = meshDS->ShapeToIndex(F);
1450
1451   int nb = quad->side[0]->NbPoints();
1452   int nr = quad->side[1]->NbPoints();
1453   int nt = quad->side[2]->NbPoints();
1454   int nl = quad->side[3]->NbPoints();
1455   int dh = abs(nb-nt);
1456   int dv = abs(nr-nl);
1457
1458   if (dh>=dv) {
1459     if (nt>nb) {
1460       // it is a base case => not shift quad but me be replacement is need
1461       shiftQuad(quad,0,WisF);
1462     }
1463     else {
1464       // we have to shift quad on 2
1465       shiftQuad(quad,2,WisF);
1466     }
1467   }
1468   else {
1469     if (nr>nl) {
1470       // we have to shift quad on 1
1471       shiftQuad(quad,1,WisF);
1472     }
1473     else {
1474       // we have to shift quad on 3
1475       shiftQuad(quad,3,WisF);
1476     }
1477   }
1478
1479   nb = quad->side[0]->NbPoints();
1480   nr = quad->side[1]->NbPoints();
1481   nt = quad->side[2]->NbPoints();
1482   nl = quad->side[3]->NbPoints();
1483   dh = abs(nb-nt);
1484   dv = abs(nr-nl);
1485   int nbh  = Max(nb,nt);
1486   int nbv = Max(nr,nl);
1487   int addh = 0;
1488   int addv = 0;
1489
1490   // ----------- Old version ---------------
1491   // orientation of face and 3 main domain for future faces
1492   //       0   top    1
1493   //      1------------1
1494   //       |   |  |   |
1495   //       |   |  |   |
1496   //       | L |  | R |
1497   //  left |   |  |   | rigth
1498   //       |  /    \  |
1499   //       | /  C   \ |
1500   //       |/        \|
1501   //      0------------0
1502   //       0  bottom  1
1503
1504   // ----------- New version ---------------
1505   // orientation of face and 3 main domain for future faces
1506   //       0   top    1
1507   //      1------------1
1508   //       |  |____|  |
1509   //       |  /    \  |
1510   //       | /  C   \ |
1511   //  left |/________\| rigth
1512   //       |          |
1513   //       |          |
1514   //       |          |
1515   //      0------------0
1516   //       0  bottom  1
1517
1518   if (dh>dv) {
1519     addv = (dh-dv)/2;
1520     nbv = nbv + addv;
1521   }
1522   else { // dv>=dh
1523     addh = (dv-dh)/2;
1524     nbh = nbh + addh;
1525   }
1526
1527   const vector<UVPtStruct>& uv_eb = quad->side[0]->GetUVPtStruct(true,0);
1528   const vector<UVPtStruct>& uv_er = quad->side[1]->GetUVPtStruct(false,1);
1529   const vector<UVPtStruct>& uv_et = quad->side[2]->GetUVPtStruct(true,1);
1530   const vector<UVPtStruct>& uv_el = quad->side[3]->GetUVPtStruct(false,0);
1531
1532   if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
1533     return error(COMPERR_BAD_INPUT_MESH);
1534
1535   if ( myNeedSmooth )
1536     UpdateDegenUV( quad );
1537
1538   // arrays for normalized params
1539   TColStd_SequenceOfReal npb, npr, npt, npl;
1540   for (i=0; i<nb; i++) {
1541     npb.Append(uv_eb[i].normParam);
1542   }
1543   for (i=0; i<nr; i++) {
1544     npr.Append(uv_er[i].normParam);
1545   }
1546   for (i=0; i<nt; i++) {
1547     npt.Append(uv_et[i].normParam);
1548   }
1549   for (i=0; i<nl; i++) {
1550     npl.Append(uv_el[i].normParam);
1551   }
1552
1553   int dl,dr;
1554   if (OldVersion) {
1555     // add some params to right and left after the first param
1556     // insert to right
1557     dr = nbv - nr;
1558     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
1559     for (i=1; i<=dr; i++) {
1560       npr.InsertAfter(1,npr.Value(2)-dpr);
1561     }
1562     // insert to left
1563     dl = nbv - nl;
1564     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
1565     for (i=1; i<=dl; i++) {
1566       npl.InsertAfter(1,npl.Value(2)-dpr);
1567     }
1568   }
1569   
1570   gp_XY a0(uv_eb.front().u, uv_eb.front().v);
1571   gp_XY a1(uv_eb.back().u,  uv_eb.back().v);
1572   gp_XY a2(uv_et.back().u,  uv_et.back().v);
1573   gp_XY a3(uv_et.front().u, uv_et.front().v);
1574
1575   int nnn = Min(nr,nl);
1576   // auxilary sequence of XY for creation nodes
1577   // in the bottom part of central domain
1578   // Length of UVL and UVR must be == nbv-nnn
1579   TColgp_SequenceOfXY UVL, UVR, UVT;
1580
1581   if (OldVersion) {
1582     // step1: create faces for left domain
1583     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
1584     // add left nodes
1585     for (j=1; j<=nl; j++)
1586       NodesL.SetValue(1,j,uv_el[j-1].node);
1587     if (dl>0) {
1588       // add top nodes
1589       for (i=1; i<=dl; i++) 
1590         NodesL.SetValue(i+1,nl,uv_et[i].node);
1591       // create and add needed nodes
1592       TColgp_SequenceOfXY UVtmp;
1593       for (i=1; i<=dl; i++) {
1594         double x0 = npt.Value(i+1);
1595         double x1 = x0;
1596         // diagonal node
1597         double y0 = npl.Value(i+1);
1598         double y1 = npr.Value(i+1);
1599         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1600         gp_Pnt P = S->Value(UV.X(),UV.Y());
1601         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1602         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1603         NodesL.SetValue(i+1,1,N);
1604         if (UVL.Length()<nbv-nnn) UVL.Append(UV);
1605         // internal nodes
1606         for (j=2; j<nl; j++) {
1607           double y0 = npl.Value(dl+j);
1608           double y1 = npr.Value(dl+j);
1609           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1610           gp_Pnt P = S->Value(UV.X(),UV.Y());
1611           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1612           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1613           NodesL.SetValue(i+1,j,N);
1614           if (i==dl) UVtmp.Append(UV);
1615         }
1616       }
1617       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn; i++) {
1618         UVL.Append(UVtmp.Value(i));
1619       }
1620       // create faces
1621       for (i=1; i<=dl; i++) {
1622         for (j=1; j<nl; j++) {
1623           if (WisF) {
1624             SMDS_MeshFace* F =
1625               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
1626                               NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
1627             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1628           }
1629           else {
1630             SMDS_MeshFace* F =
1631               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i,j+1),
1632                               NodesL.Value(i+1,j+1), NodesL.Value(i+1,j));
1633             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1634           }
1635         }
1636       }
1637     }
1638     else {
1639       // fill UVL using c2d
1640       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn; i++) {
1641         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
1642       }
1643     }
1644     
1645     // step2: create faces for right domain
1646     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
1647     // add right nodes
1648     for (j=1; j<=nr; j++) 
1649       NodesR.SetValue(1,j,uv_er[nr-j].node);
1650     if (dr>0) {
1651       // add top nodes
1652       for (i=1; i<=dr; i++) 
1653         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
1654       // create and add needed nodes
1655       TColgp_SequenceOfXY UVtmp;
1656       for (i=1; i<=dr; i++) {
1657         double x0 = npt.Value(nt-i);
1658         double x1 = x0;
1659         // diagonal node
1660         double y0 = npl.Value(i+1);
1661         double y1 = npr.Value(i+1);
1662         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1663         gp_Pnt P = S->Value(UV.X(),UV.Y());
1664         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1665         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1666         NodesR.SetValue(i+1,nr,N);
1667         if (UVR.Length()<nbv-nnn) UVR.Append(UV);
1668         // internal nodes
1669         for (j=2; j<nr; j++) {
1670           double y0 = npl.Value(nbv-j+1);
1671           double y1 = npr.Value(nbv-j+1);
1672           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1673           gp_Pnt P = S->Value(UV.X(),UV.Y());
1674           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1675           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1676           NodesR.SetValue(i+1,j,N);
1677           if (i==dr) UVtmp.Prepend(UV);
1678         }
1679       }
1680       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn; i++) {
1681         UVR.Append(UVtmp.Value(i));
1682       }
1683       // create faces
1684       for (i=1; i<=dr; i++) {
1685         for (j=1; j<nr; j++) {
1686           if (WisF) {
1687             SMDS_MeshFace* F =
1688               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
1689                               NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
1690             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1691           }
1692           else {
1693             SMDS_MeshFace* F =
1694               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i,j+1),
1695                               NodesR.Value(i+1,j+1), NodesR.Value(i+1,j));
1696             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1697           }
1698         }
1699       }
1700     }
1701     else {
1702       // fill UVR using c2d
1703       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn; i++) {
1704         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
1705       }
1706     }
1707     
1708     // step3: create faces for central domain
1709     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
1710     // add first line using NodesL
1711     for (i=1; i<=dl+1; i++)
1712       NodesC.SetValue(1,i,NodesL(i,1));
1713     for (i=2; i<=nl; i++)
1714       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
1715     // add last line using NodesR
1716     for (i=1; i<=dr+1; i++)
1717       NodesC.SetValue(nb,i,NodesR(i,nr));
1718     for (i=1; i<nr; i++)
1719       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
1720     // add top nodes (last columns)
1721     for (i=dl+2; i<nbh-dr; i++) 
1722       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
1723     // add bottom nodes (first columns)
1724     for (i=2; i<nb; i++)
1725       NodesC.SetValue(i,1,uv_eb[i-1].node);
1726     
1727     // create and add needed nodes
1728     // add linear layers
1729     for (i=2; i<nb; i++) {
1730       double x0 = npt.Value(dl+i);
1731       double x1 = x0;
1732       for (j=1; j<nnn; j++) {
1733         double y0 = npl.Value(nbv-nnn+j);
1734         double y1 = npr.Value(nbv-nnn+j);
1735         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1736         gp_Pnt P = S->Value(UV.X(),UV.Y());
1737         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1738         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1739         NodesC.SetValue(i,nbv-nnn+j,N);
1740         if ( j==1 )
1741           UVT.Append( UV );
1742       }
1743     }
1744     // add diagonal layers
1745     gp_UV A2 = UVR.Value(nbv-nnn);
1746     gp_UV A3 = UVL.Value(nbv-nnn);
1747     for (i=1; i<nbv-nnn; i++) {
1748       gp_UV p1 = UVR.Value(i);
1749       gp_UV p3 = UVL.Value(i);
1750       double y = i / double(nbv-nnn);
1751       for (j=2; j<nb; j++) {
1752         double x = npb.Value(j);
1753         gp_UV p0( uv_eb[j-1].u, uv_eb[j-1].v );
1754         gp_UV p2 = UVT.Value( j-1 );
1755         gp_UV UV = calcUV(x, y, a0, a1, A2, A3, p0,p1,p2,p3 );
1756         gp_Pnt P = S->Value(UV.X(),UV.Y());
1757         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1758         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
1759         NodesC.SetValue(j,i+1,N);
1760       }
1761     }
1762     // create faces
1763     for (i=1; i<nb; i++) {
1764       for (j=1; j<nbv; j++) {
1765         if (WisF) {
1766           SMDS_MeshFace* F =
1767             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
1768                             NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
1769           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1770         }
1771         else {
1772           SMDS_MeshFace* F =
1773             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i,j+1),
1774                             NodesC.Value(i+1,j+1), NodesC.Value(i+1,j));
1775           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1776         }
1777       }
1778     }
1779   }
1780
1781   else { // New version (!OldVersion)
1782     // step1: create faces for bottom rectangle domain
1783     StdMeshers_Array2OfNode NodesBRD(1,nb,1,nnn-1);
1784     // fill UVL and UVR using c2d
1785     for (j=0; j<nb; j++) {
1786       NodesBRD.SetValue(j+1,1,uv_eb[j].node);
1787     }
1788     for (i=1; i<nnn-1; i++) {
1789       NodesBRD.SetValue(1,i+1,uv_el[i].node);
1790       NodesBRD.SetValue(nb,i+1,uv_er[i].node);
1791       for (j=2; j<nb; j++) {
1792         double x = npb.Value(j);
1793         double y = (1-x) * npl.Value(i+1) + x * npr.Value(i+1);
1794         gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
1795         gp_Pnt P = S->Value(UV.X(),UV.Y());
1796         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1797         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
1798         NodesBRD.SetValue(j,i+1,N);
1799       }
1800     }
1801     for (j=1; j<nnn-1; j++) {
1802       for (i=1; i<nb; i++) {
1803         if (WisF) {
1804           SMDS_MeshFace* F =
1805             myHelper->AddFace(NodesBRD.Value(i,j), NodesBRD.Value(i+1,j),
1806                             NodesBRD.Value(i+1,j+1), NodesBRD.Value(i,j+1));
1807           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1808         }
1809         else {
1810           SMDS_MeshFace* F =
1811             myHelper->AddFace(NodesBRD.Value(i,j), NodesBRD.Value(i,j+1),
1812                             NodesBRD.Value(i+1,j+1), NodesBRD.Value(i+1,j));
1813           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1814         }
1815       }
1816     }
1817     int drl = abs(nr-nl);
1818     // create faces for region C
1819     StdMeshers_Array2OfNode NodesC(1,nb,1,drl+1+addv);
1820     // add nodes from previous region
1821     for (j=1; j<=nb; j++) {
1822       NodesC.SetValue(j,1,NodesBRD.Value(j,nnn-1));
1823     }
1824     if ((drl+addv) > 0) {
1825       int n1,n2;
1826       if (nr>nl) {
1827         n1 = 1;
1828         n2 = drl + 1;
1829         TColgp_SequenceOfXY UVtmp;
1830         double drparam = npr.Value(nr) - npr.Value(nnn-1);
1831         double dlparam = npl.Value(nnn) - npl.Value(nnn-1);
1832         double y0,y1;
1833         for (i=1; i<=drl; i++) {
1834           // add existed nodes from right edge
1835           NodesC.SetValue(nb,i+1,uv_er[nnn+i-2].node);
1836           //double dtparam = npt.Value(i+1);
1837           y1 = npr.Value(nnn+i-1); // param on right edge
1838           double dpar = (y1 - npr.Value(nnn-1))/drparam;
1839           y0 = npl.Value(nnn-1) + dpar*dlparam; // param on left edge
1840           double dy = y1 - y0;
1841           for (j=1; j<nb; j++) {
1842             double x = npt.Value(i+1) + npb.Value(j)*(1-npt.Value(i+1));
1843             double y = y0 + dy*x;
1844             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
1845             gp_Pnt P = S->Value(UV.X(),UV.Y());
1846             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1847             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1848             NodesC.SetValue(j,i+1,N);
1849           }
1850         }
1851         double dy0 = (1-y0)/(addv+1);
1852         double dy1 = (1-y1)/(addv+1);
1853         for (i=1; i<=addv; i++) {
1854           double yy0 = y0 + dy0*i;
1855           double yy1 = y1 + dy1*i;
1856           double dyy = yy1 - yy0;
1857           for (j=1; j<=nb; j++) {
1858             double x = npt.Value(i+1+drl) + 
1859               npb.Value(j) * (npt.Value(nt-i) - npt.Value(i+1+drl));
1860             double y = yy0 + dyy*x;
1861             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
1862             gp_Pnt P = S->Value(UV.X(),UV.Y());
1863             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1864             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1865             NodesC.SetValue(j,i+drl+1,N);
1866           }
1867         }
1868       }
1869       else { // nr<nl
1870         n2 = 1;
1871         n1 = drl + 1;
1872         TColgp_SequenceOfXY UVtmp;
1873         double dlparam = npl.Value(nl) - npl.Value(nnn-1);
1874         double drparam = npr.Value(nnn) - npr.Value(nnn-1);
1875         double y0 = npl.Value(nnn-1);
1876         double y1 = npr.Value(nnn-1);
1877         for (i=1; i<=drl; i++) {
1878           // add existed nodes from right edge
1879           NodesC.SetValue(1,i+1,uv_el[nnn+i-2].node);
1880           y0 = npl.Value(nnn+i-1); // param on left edge
1881           double dpar = (y0 - npl.Value(nnn-1))/dlparam;
1882           y1 = npr.Value(nnn-1) + dpar*drparam; // param on right edge
1883           double dy = y1 - y0;
1884           for (j=2; j<=nb; j++) {
1885             double x = npb.Value(j)*npt.Value(nt-i);
1886             double y = y0 + dy*x;
1887             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
1888             gp_Pnt P = S->Value(UV.X(),UV.Y());
1889             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1890             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1891             NodesC.SetValue(j,i+1,N);
1892           }
1893         }
1894         double dy0 = (1-y0)/(addv+1);
1895         double dy1 = (1-y1)/(addv+1);
1896         for (i=1; i<=addv; i++) {
1897           double yy0 = y0 + dy0*i;
1898           double yy1 = y1 + dy1*i;
1899           double dyy = yy1 - yy0;
1900           for (j=1; j<=nb; j++) {
1901             double x = npt.Value(i+1) + 
1902               npb.Value(j) * (npt.Value(nt-i-drl) - npt.Value(i+1));
1903             double y = yy0 + dyy*x;
1904             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
1905             gp_Pnt P = S->Value(UV.X(),UV.Y());
1906             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1907             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1908             NodesC.SetValue(j,i+drl+1,N);
1909           }
1910         }
1911       }
1912       // create faces
1913       for (j=1; j<=drl+addv; j++) {
1914         for (i=1; i<nb; i++) {
1915           if (WisF) {
1916             SMDS_MeshFace* F =
1917               myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
1918                               NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
1919             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1920           }
1921           else {
1922             SMDS_MeshFace* F =
1923               myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i,j+1),
1924                               NodesC.Value(i+1,j+1), NodesC.Value(i+1,j));
1925             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1926           }
1927         }
1928       } // end nr<nl
1929
1930       StdMeshers_Array2OfNode NodesLast(1,nt,1,2);
1931       for (i=1; i<=nt; i++) {
1932         NodesLast.SetValue(i,2,uv_et[i-1].node);
1933       }
1934       int nnn=0;
1935       for (i=n1; i<drl+addv+1; i++) {
1936         nnn++;
1937         NodesLast.SetValue(nnn,1,NodesC.Value(1,i));
1938       }
1939       for (i=1; i<=nb; i++) {
1940         nnn++;
1941         NodesLast.SetValue(nnn,1,NodesC.Value(i,drl+addv+1));
1942       }
1943       for (i=drl+addv; i>=n2; i--) {
1944         nnn++;
1945         NodesLast.SetValue(nnn,1,NodesC.Value(nb,i));
1946       }
1947       for (i=1; i<nt; i++) {
1948         if (WisF) {
1949           SMDS_MeshFace* F =
1950             myHelper->AddFace(NodesLast.Value(i,1), NodesLast.Value(i+1,1),
1951                             NodesLast.Value(i+1,2), NodesLast.Value(i,2));
1952           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1953         }
1954         else {
1955           SMDS_MeshFace* F =
1956             myHelper->AddFace(NodesLast.Value(i,1), NodesLast.Value(i,2),
1957                             NodesLast.Value(i+1,2), NodesLast.Value(i+1,2));
1958           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1959         }
1960       }
1961     } // if ((drl+addv) > 0)
1962
1963   } // end new version implementation
1964
1965   bool isOk = true;
1966   return isOk;
1967 }
1968
1969
1970 //=======================================================================
1971 /*!
1972  * Evaluate only quandrangle faces
1973  */
1974 //=======================================================================
1975
1976 bool StdMeshers_Quadrangle_2D::EvaluateQuadPref(SMESH_Mesh &        aMesh,
1977                                                 const TopoDS_Shape& aShape,
1978                                                 std::vector<int>& aNbNodes,
1979                                                 MapShapeNbElems& aResMap,
1980                                                 bool IsQuadratic)
1981 {
1982   // Auxilary key in order to keep old variant
1983   // of meshing after implementation new variant
1984   // for bug 0016220 from Mantis.
1985   bool OldVersion = false;
1986   if (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
1987     OldVersion = true;
1988
1989   const TopoDS_Face& F = TopoDS::Face(aShape);
1990   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
1991
1992   int nb = aNbNodes[0];
1993   int nr = aNbNodes[1];
1994   int nt = aNbNodes[2];
1995   int nl = aNbNodes[3];
1996   int dh = abs(nb-nt);
1997   int dv = abs(nr-nl);
1998
1999   if (dh>=dv) {
2000     if (nt>nb) {
2001       // it is a base case => not shift 
2002     }
2003     else {
2004       // we have to shift on 2
2005       nb = aNbNodes[2];
2006       nr = aNbNodes[3];
2007       nt = aNbNodes[0];
2008       nl = aNbNodes[1];
2009     }
2010   }
2011   else {
2012     if (nr>nl) {
2013       // we have to shift quad on 1
2014       nb = aNbNodes[3];
2015       nr = aNbNodes[0];
2016       nt = aNbNodes[1];
2017       nl = aNbNodes[2];
2018     }
2019     else {
2020       // we have to shift quad on 3
2021       nb = aNbNodes[1];
2022       nr = aNbNodes[2];
2023       nt = aNbNodes[3];
2024       nl = aNbNodes[0];
2025     }
2026   }
2027
2028   dh = abs(nb-nt);
2029   dv = abs(nr-nl);
2030   int nbh  = Max(nb,nt);
2031   int nbv = Max(nr,nl);
2032   int addh = 0;
2033   int addv = 0;
2034
2035   if (dh>dv) {
2036     addv = (dh-dv)/2;
2037     nbv = nbv + addv;
2038   }
2039   else { // dv>=dh
2040     addh = (dv-dh)/2;
2041     nbh = nbh + addh;
2042   }
2043
2044   int dl,dr;
2045   if (OldVersion) {
2046     // add some params to right and left after the first param
2047     // insert to right
2048     dr = nbv - nr;
2049     // insert to left
2050     dl = nbv - nl;
2051   }
2052   
2053   int nnn = Min(nr,nl);
2054
2055   int nbNodes = 0;
2056   int nbFaces = 0;
2057   if (OldVersion) {
2058     // step1: create faces for left domain
2059     if (dl>0) {
2060       nbNodes += dl*(nl-1);
2061       nbFaces += dl*(nl-1);
2062     }
2063     // step2: create faces for right domain
2064     if (dr>0) {
2065       nbNodes += dr*(nr-1);
2066       nbFaces += dr*(nr-1);
2067     }
2068     // step3: create faces for central domain
2069     nbNodes += (nb-2)*(nnn-1) + (nbv-nnn-1)*(nb-2);
2070     nbFaces += (nb-1)*(nbv-1);
2071   }
2072   else { // New version (!OldVersion)
2073     nbNodes += (nnn-2)*(nb-2);
2074     nbFaces += (nnn-2)*(nb-1);
2075     int drl = abs(nr-nl);
2076     nbNodes += drl*(nb-1) + addv*nb;
2077     nbFaces += (drl+addv)*(nb-1) + (nt-1);
2078   } // end new version implementation
2079
2080   std::vector<int> aVec(SMDSEntity_Last);
2081   for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
2082   if (IsQuadratic) {
2083     aVec[SMDSEntity_Quad_Quadrangle] = nbFaces;
2084     aVec[SMDSEntity_Node] = nbNodes + nbFaces*4;
2085     if (aNbNodes.size()==5) {
2086       aVec[SMDSEntity_Quad_Triangle] = aNbNodes[3] - 1;
2087       aVec[SMDSEntity_Quad_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2088     }
2089   }
2090   else {
2091     aVec[SMDSEntity_Node] = nbNodes;
2092     aVec[SMDSEntity_Quadrangle] = nbFaces;
2093     if (aNbNodes.size()==5) {
2094       aVec[SMDSEntity_Triangle] = aNbNodes[3] - 1;
2095       aVec[SMDSEntity_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2096     }
2097   }
2098   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
2099   aResMap.insert(std::make_pair(sm,aVec));
2100
2101   return true;
2102 }
2103
2104
2105 //=============================================================================
2106 /*! Split quadrangle in to 2 triangles by smallest diagonal
2107  *   
2108  */
2109 //=============================================================================
2110 void StdMeshers_Quadrangle_2D::SplitQuad(SMESHDS_Mesh *theMeshDS,
2111                                          int theFaceID,
2112                                          const SMDS_MeshNode* theNode1,
2113                                          const SMDS_MeshNode* theNode2,
2114                                          const SMDS_MeshNode* theNode3,
2115                                          const SMDS_MeshNode* theNode4)
2116 {
2117   gp_Pnt a(theNode1->X(),theNode1->Y(),theNode1->Z());
2118   gp_Pnt b(theNode2->X(),theNode2->Y(),theNode2->Z());
2119   gp_Pnt c(theNode3->X(),theNode3->Y(),theNode3->Z());
2120   gp_Pnt d(theNode4->X(),theNode4->Y(),theNode4->Z());
2121   SMDS_MeshFace* face;
2122   if (a.Distance(c) > b.Distance(d)){
2123     face = myHelper->AddFace(theNode2, theNode4 , theNode1);
2124     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2125     face = myHelper->AddFace(theNode2, theNode3, theNode4);
2126     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2127
2128   }
2129   else{
2130     face = myHelper->AddFace(theNode1, theNode2 ,theNode3);
2131     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2132     face = myHelper->AddFace(theNode1, theNode3, theNode4);
2133     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2134   }
2135 }
2136
2137 namespace
2138 {
2139   enum uvPos { UV_A0, UV_A1, UV_A2, UV_A3, UV_B, UV_R, UV_T, UV_L, UV_SIZE };
2140
2141   inline  SMDS_MeshNode* makeNode( UVPtStruct &         uvPt,
2142                                    const double         y,
2143                                    FaceQuadStruct::Ptr& quad,
2144                                    const gp_UV*         UVs,
2145                                    SMESH_MesherHelper*  helper,
2146                                    Handle(Geom_Surface) S)
2147   {
2148     const vector<UVPtStruct>& uv_eb = quad->side[QUAD_BOTTOM_SIDE]->GetUVPtStruct();
2149     const vector<UVPtStruct>& uv_et = quad->side[QUAD_TOP_SIDE   ]->GetUVPtStruct();
2150     double rBot = ( uv_eb.size() - 1 ) * uvPt.normParam;
2151     double rTop = ( uv_et.size() - 1 ) * uvPt.normParam;
2152     int iBot = int( rBot );
2153     int iTop = int( rTop );
2154     double xBot = uv_eb[ iBot ].normParam + ( rBot - iBot ) * ( uv_eb[ iBot+1 ].normParam - uv_eb[ iBot ].normParam );
2155     double xTop = uv_et[ iTop ].normParam + ( rTop - iTop ) * ( uv_et[ iTop+1 ].normParam - uv_et[ iTop ].normParam );
2156     double x = xBot + y * ( xTop - xBot );
2157     
2158     gp_UV uv = calcUV(/*x,y=*/x, y,
2159                       /*a0,...=*/UVs[UV_A0], UVs[UV_A1], UVs[UV_A2], UVs[UV_A3],
2160                       /*p0=*/quad->side[QUAD_BOTTOM_SIDE]->Value2d( x ).XY(),
2161                       /*p1=*/UVs[ UV_R ],
2162                       /*p2=*/quad->side[QUAD_TOP_SIDE   ]->Value2d( x ).XY(),
2163                       /*p3=*/UVs[ UV_L ]);
2164     gp_Pnt P = S->Value( uv.X(), uv.Y() );
2165     uvPt.u = uv.X();
2166     uvPt.v = uv.Y();
2167     return helper->AddNode(P.X(), P.Y(), P.Z(), 0, uv.X(), uv.Y() );
2168   }
2169
2170   void reduce42( const vector<UVPtStruct>& curr_base,
2171                  vector<UVPtStruct>&       next_base,
2172                  const int                 j,
2173                  int &                     next_base_len,
2174                  FaceQuadStruct::Ptr&      quad,
2175                  gp_UV*                    UVs,
2176                  const double              y,
2177                  SMESH_MesherHelper*       helper,
2178                  Handle(Geom_Surface)&     S)
2179   {
2180     // add one "HH": nodes a,b,c,d,e and faces 1,2,3,4,5,6
2181     //
2182     //  .-----a-----b i + 1
2183     //  |\ 5  | 6  /|
2184     //  | \   |   / |
2185     //  |  c--d--e  |
2186     //  |1 |2 |3 |4 |
2187     //  |  |  |  |  |
2188     //  .--.--.--.--. i
2189     //
2190     //  j     j+2   j+4
2191
2192     // a (i + 1, j + 2)
2193     const SMDS_MeshNode*& Na = next_base[ ++next_base_len ].node;
2194     if ( !Na )
2195       Na = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2196
2197     // b (i + 1, j + 4)
2198     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2199     if ( !Nb )
2200       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2201
2202     // c
2203     double u = (curr_base[j + 2].u + next_base[next_base_len - 2].u) / 2.0;
2204     double v = (curr_base[j + 2].v + next_base[next_base_len - 2].v) / 2.0;
2205     gp_Pnt P = S->Value(u,v);
2206     SMDS_MeshNode* Nc = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2207
2208     // d
2209     u = (curr_base[j + 2].u + next_base[next_base_len - 1].u) / 2.0;
2210     v = (curr_base[j + 2].v + next_base[next_base_len - 1].v) / 2.0;
2211     P = S->Value(u,v);
2212     SMDS_MeshNode* Nd = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2213
2214     // e
2215     u = (curr_base[j + 2].u + next_base[next_base_len].u) / 2.0;
2216     v = (curr_base[j + 2].v + next_base[next_base_len].v) / 2.0;
2217     P = S->Value(u,v);
2218     SMDS_MeshNode* Ne = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2219
2220     // Faces
2221     helper->AddFace(curr_base[j + 0].node,
2222                     curr_base[j + 1].node, Nc,
2223                     next_base[next_base_len - 2].node);
2224
2225     helper->AddFace(curr_base[j + 1].node,
2226                     curr_base[j + 2].node, Nd, Nc);
2227
2228     helper->AddFace(curr_base[j + 2].node,
2229                     curr_base[j + 3].node, Ne, Nd);
2230
2231     helper->AddFace(curr_base[j + 3].node,
2232                     curr_base[j + 4].node, Nb, Ne);
2233
2234     helper->AddFace(Nc, Nd, Na, next_base[next_base_len - 2].node);
2235
2236     helper->AddFace(Nd, Ne, Nb, Na);
2237   }
2238
2239   void reduce31( const vector<UVPtStruct>& curr_base,
2240                  vector<UVPtStruct>&       next_base,
2241                  const int                 j,
2242                  int &                     next_base_len,
2243                  FaceQuadStruct::Ptr&      quad,
2244                  gp_UV*                    UVs,
2245                  const double              y,
2246                  SMESH_MesherHelper*       helper,
2247                  Handle(Geom_Surface)&     S)
2248   {
2249     // add one "H": nodes b,c,e and faces 1,2,4,5
2250     //
2251     //  .---------b i + 1
2252     //  |\   5   /|
2253     //  | \     / |
2254     //  |  c---e  |
2255     //  |1 |2  |4 |
2256     //  |  |   |  |
2257     //  .--.---.--. i
2258     //
2259     //  j j+1 j+2 j+3
2260
2261     // b (i + 1, j + 3)
2262     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2263     if ( !Nb )
2264       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2265
2266     // c and e
2267     double u1 = (curr_base[ j   ].u + next_base[ next_base_len-1 ].u ) / 2.0;
2268     double u2 = (curr_base[ j+3 ].u + next_base[ next_base_len   ].u ) / 2.0;
2269     double u3 = (u2 - u1) / 3.0;
2270     //
2271     double v1 = (curr_base[ j   ].v + next_base[ next_base_len-1 ].v ) / 2.0;
2272     double v2 = (curr_base[ j+3 ].v + next_base[ next_base_len   ].v ) / 2.0;
2273     double v3 = (v2 - v1) / 3.0;
2274     // c
2275     double u = u1 + u3;
2276     double v = v1 + v3;
2277     gp_Pnt P = S->Value(u,v);
2278     SMDS_MeshNode* Nc = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2279     // e
2280     u = u1 + u3 + u3;
2281     v = v1 + v3 + v3;
2282     P = S->Value(u,v);
2283     SMDS_MeshNode* Ne = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2284
2285     // Faces
2286     // 1
2287     helper->AddFace( curr_base[ j + 0 ].node,
2288                      curr_base[ j + 1 ].node,
2289                      Nc,
2290                      next_base[ next_base_len - 1 ].node);
2291     // 2
2292     helper->AddFace( curr_base[ j + 1 ].node,
2293                      curr_base[ j + 2 ].node, Ne, Nc);
2294     // 4
2295     helper->AddFace( curr_base[ j + 2 ].node,
2296                      curr_base[ j + 3 ].node, Nb, Ne);
2297     // 5
2298     helper->AddFace(Nc, Ne, Nb,
2299                     next_base[ next_base_len - 1 ].node);
2300   }
2301
2302   typedef void (* PReduceFunction) ( const vector<UVPtStruct>& curr_base,
2303                                      vector<UVPtStruct>&       next_base,
2304                                      const int                 j,
2305                                      int &                     next_base_len,
2306                                      FaceQuadStruct::Ptr &     quad,
2307                                      gp_UV*                    UVs,
2308                                      const double              y,
2309                                      SMESH_MesherHelper*       helper,
2310                                      Handle(Geom_Surface)&     S);
2311
2312 } // namespace
2313
2314 //=======================================================================
2315 /*!
2316  *  Implementation of Reduced algorithm (meshing with quadrangles only)
2317  */
2318 //=======================================================================
2319 bool StdMeshers_Quadrangle_2D::ComputeReduced (SMESH_Mesh &        aMesh,
2320                                                const TopoDS_Shape& aShape,
2321                                                FaceQuadStruct::Ptr quad)
2322 {
2323   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
2324   const TopoDS_Face& F = TopoDS::Face(aShape);
2325   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
2326   int i,j,geomFaceID = meshDS->ShapeToIndex(F);
2327
2328   int nb = quad->side[0]->NbPoints();
2329   int nr = quad->side[1]->NbPoints();
2330   int nt = quad->side[2]->NbPoints();
2331   int nl = quad->side[3]->NbPoints();
2332
2333   //  Simple Reduce 10->8->6->4 (3 steps)     Multiple Reduce 10->4 (1 step)
2334   //
2335   //  .-----.-----.-----.-----.               .-----.-----.-----.-----.
2336   //  |    / \    |    / \    |               |    / \    |    / \    |
2337   //  |   /    .--.--.    \   |               |    / \    |    / \    |
2338   //  |   /   /   |   \   \   |               |   /  .----.----.  \   |
2339   //  .---.---.---.---.---.---.               |   / / \   |   / \ \   |
2340   //  |   /  / \  |  / \  \   |               |   / / \   |   / \ \   |
2341   //  |  /  /   .-.-.   \  \  |               |  / /  .---.---.  \ \  |
2342   //  |  /  /  /  |  \  \  \  |               |  / / / \  |  / \ \ \  |
2343   //  .--.--.--.--.--.--.--.--.               |  / / /  \ | /  \ \ \  |
2344   //  |  / /  / \ | / \  \ \  |               | / / /   .-.-.   \ \ \ |
2345   //  | / /  /  .-.-.  \  \ \ |               | / / /  /  |  \  \ \ \ |
2346   //  | / / /  /  |  \  \ \ \ |               | / / /  /  |  \  \ \ \ |
2347   //  .-.-.-.--.--.--.--.-.-.-.               .-.-.-.--.--.--.--.-.-.-.
2348
2349   bool MultipleReduce = false;
2350   {
2351     int nb1 = nb;
2352     int nr1 = nr;
2353     int nt1 = nt;
2354
2355     if (nr == nl) {
2356       if (nb < nt) {
2357         nt1 = nb;
2358         nb1 = nt;
2359       }
2360     }
2361     else if (nb == nt) {
2362       nr1 = nb; // and == nt
2363       if (nl < nr) {
2364         nt1 = nl;
2365         nb1 = nr;
2366       }
2367       else {
2368         nt1 = nr;
2369         nb1 = nl;
2370       }
2371     }
2372     else {
2373       return false;
2374     }
2375
2376     // number of rows and columns
2377     int nrows = nr1 - 1;
2378     int ncol_top = nt1 - 1;
2379     int ncol_bot = nb1 - 1;
2380     // number of rows needed to reduce ncol_bot to ncol_top using simple 3->1 "tree" (see below)
2381     int nrows_tree31 = int( log( (double)(ncol_bot / ncol_top) ) / log((double) 3 )); // = log x base 3
2382     if ( nrows < nrows_tree31 )
2383       MultipleReduce = true;
2384   }
2385
2386   if (MultipleReduce) { // == ComputeQuadPref QUAD_QUADRANGLE_PREF_REVERSED
2387     //==================================================
2388     int dh = abs(nb-nt);
2389     int dv = abs(nr-nl);
2390
2391     if (dh >= dv) {
2392       if (nt > nb) {
2393         // it is a base case => not shift quad but may be replacement is need
2394         shiftQuad(quad,0,true);
2395       }
2396       else {
2397         // we have to shift quad on 2
2398         shiftQuad(quad,2,true);
2399       }
2400     }
2401     else {
2402       if (nr > nl) {
2403         // we have to shift quad on 1
2404         shiftQuad(quad,1,true);
2405       }
2406       else {
2407         // we have to shift quad on 3
2408         shiftQuad(quad,3,true);
2409       }
2410     }
2411
2412     nb = quad->side[0]->NbPoints();
2413     nr = quad->side[1]->NbPoints();
2414     nt = quad->side[2]->NbPoints();
2415     nl = quad->side[3]->NbPoints();
2416     dh = abs(nb-nt);
2417     dv = abs(nr-nl);
2418     int nbh = Max(nb,nt);
2419     int nbv = Max(nr,nl);
2420     int addh = 0;
2421     int addv = 0;
2422
2423     if (dh>dv) {
2424       addv = (dh-dv)/2;
2425       nbv = nbv + addv;
2426     }
2427     else { // dv>=dh
2428       addh = (dv-dh)/2;
2429       nbh = nbh + addh;
2430     }
2431
2432     const vector<UVPtStruct>& uv_eb = quad->side[0]->GetUVPtStruct(true,0);
2433     const vector<UVPtStruct>& uv_er = quad->side[1]->GetUVPtStruct(false,1);
2434     const vector<UVPtStruct>& uv_et = quad->side[2]->GetUVPtStruct(true,1);
2435     const vector<UVPtStruct>& uv_el = quad->side[3]->GetUVPtStruct(false,0);
2436
2437     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
2438       return error(COMPERR_BAD_INPUT_MESH);
2439
2440     if ( myNeedSmooth )
2441       UpdateDegenUV( quad );
2442
2443     // arrays for normalized params
2444     TColStd_SequenceOfReal npb, npr, npt, npl;
2445     for (j = 0; j < nb; j++) {
2446       npb.Append(uv_eb[j].normParam);
2447     }
2448     for (i = 0; i < nr; i++) {
2449       npr.Append(uv_er[i].normParam);
2450     }
2451     for (j = 0; j < nt; j++) {
2452       npt.Append(uv_et[j].normParam);
2453     }
2454     for (i = 0; i < nl; i++) {
2455       npl.Append(uv_el[i].normParam);
2456     }
2457
2458     int dl,dr;
2459     // orientation of face and 3 main domain for future faces
2460     //       0   top    1
2461     //      1------------1
2462     //       |   |  |   |
2463     //       |   |  |   |
2464     //       | L |  | R |
2465     //  left |   |  |   | rigth
2466     //       |  /    \  |
2467     //       | /  C   \ |
2468     //       |/        \|
2469     //      0------------0
2470     //       0  bottom  1
2471
2472     // add some params to right and left after the first param
2473     // insert to right
2474     dr = nbv - nr;
2475     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
2476     for (i=1; i<=dr; i++) {
2477       npr.InsertAfter(1,npr.Value(2)-dpr);
2478     }
2479     // insert to left
2480     dl = nbv - nl;
2481     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
2482     for (i=1; i<=dl; i++) {
2483       npl.InsertAfter(1,npl.Value(2)-dpr);
2484     }
2485   
2486     gp_XY a0 (uv_eb.front().u, uv_eb.front().v);
2487     gp_XY a1 (uv_eb.back().u,  uv_eb.back().v);
2488     gp_XY a2 (uv_et.back().u,  uv_et.back().v);
2489     gp_XY a3 (uv_et.front().u, uv_et.front().v);
2490
2491     int nnn = Min(nr,nl);
2492     // auxilary sequence of XY for creation of nodes
2493     // in the bottom part of central domain
2494     // it's length must be == nbv-nnn-1
2495     TColgp_SequenceOfXY UVL;
2496     TColgp_SequenceOfXY UVR;
2497     //==================================================
2498
2499     // step1: create faces for left domain
2500     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
2501     // add left nodes
2502     for (j=1; j<=nl; j++)
2503       NodesL.SetValue(1,j,uv_el[j-1].node);
2504     if (dl>0) {
2505       // add top nodes
2506       for (i=1; i<=dl; i++) 
2507         NodesL.SetValue(i+1,nl,uv_et[i].node);
2508       // create and add needed nodes
2509       TColgp_SequenceOfXY UVtmp;
2510       for (i=1; i<=dl; i++) {
2511         double x0 = npt.Value(i+1);
2512         double x1 = x0;
2513         // diagonal node
2514         double y0 = npl.Value(i+1);
2515         double y1 = npr.Value(i+1);
2516         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2517         gp_Pnt P = S->Value(UV.X(),UV.Y());
2518         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2519         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2520         NodesL.SetValue(i+1,1,N);
2521         if (UVL.Length()<nbv-nnn-1) UVL.Append(UV);
2522         // internal nodes
2523         for (j=2; j<nl; j++) {
2524           double y0 = npl.Value(dl+j);
2525           double y1 = npr.Value(dl+j);
2526           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2527           gp_Pnt P = S->Value(UV.X(),UV.Y());
2528           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2529           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2530           NodesL.SetValue(i+1,j,N);
2531           if (i==dl) UVtmp.Append(UV);
2532         }
2533       }
2534       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn-1; i++) {
2535         UVL.Append(UVtmp.Value(i));
2536       }
2537       // create faces
2538       for (i=1; i<=dl; i++) {
2539         for (j=1; j<nl; j++) {
2540             SMDS_MeshFace* F =
2541               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
2542                                 NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
2543             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2544         }
2545       }
2546     }
2547     else {
2548       // fill UVL using c2d
2549       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn-1; i++) {
2550         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
2551       }
2552     }
2553     
2554     // step2: create faces for right domain
2555     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
2556     // add right nodes
2557     for (j=1; j<=nr; j++) 
2558       NodesR.SetValue(1,j,uv_er[nr-j].node);
2559     if (dr>0) {
2560       // add top nodes
2561       for (i=1; i<=dr; i++) 
2562         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
2563       // create and add needed nodes
2564       TColgp_SequenceOfXY UVtmp;
2565       for (i=1; i<=dr; i++) {
2566         double x0 = npt.Value(nt-i);
2567         double x1 = x0;
2568         // diagonal node
2569         double y0 = npl.Value(i+1);
2570         double y1 = npr.Value(i+1);
2571         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2572         gp_Pnt P = S->Value(UV.X(),UV.Y());
2573         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2574         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2575         NodesR.SetValue(i+1,nr,N);
2576         if (UVR.Length()<nbv-nnn-1) UVR.Append(UV);
2577         // internal nodes
2578         for (j=2; j<nr; j++) {
2579           double y0 = npl.Value(nbv-j+1);
2580           double y1 = npr.Value(nbv-j+1);
2581           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2582           gp_Pnt P = S->Value(UV.X(),UV.Y());
2583           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2584           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2585           NodesR.SetValue(i+1,j,N);
2586           if (i==dr) UVtmp.Prepend(UV);
2587         }
2588       }
2589       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn-1; i++) {
2590         UVR.Append(UVtmp.Value(i));
2591       }
2592       // create faces
2593       for (i=1; i<=dr; i++) {
2594         for (j=1; j<nr; j++) {
2595             SMDS_MeshFace* F =
2596               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
2597                                 NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
2598             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2599         }
2600       }
2601     }
2602     else {
2603       // fill UVR using c2d
2604       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn-1; i++) {
2605         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
2606       }
2607     }
2608     
2609     // step3: create faces for central domain
2610     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
2611     // add first line using NodesL
2612     for (i=1; i<=dl+1; i++)
2613       NodesC.SetValue(1,i,NodesL(i,1));
2614     for (i=2; i<=nl; i++)
2615       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
2616     // add last line using NodesR
2617     for (i=1; i<=dr+1; i++)
2618       NodesC.SetValue(nb,i,NodesR(i,nr));
2619     for (i=1; i<nr; i++)
2620       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
2621     // add top nodes (last columns)
2622     for (i=dl+2; i<nbh-dr; i++) 
2623       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
2624     // add bottom nodes (first columns)
2625     for (i=2; i<nb; i++)
2626       NodesC.SetValue(i,1,uv_eb[i-1].node);
2627     
2628     // create and add needed nodes
2629     // add linear layers
2630     for (i=2; i<nb; i++) {
2631       double x0 = npt.Value(dl+i);
2632       double x1 = x0;
2633       for (j=1; j<nnn; j++) {
2634         double y0 = npl.Value(nbv-nnn+j);
2635         double y1 = npr.Value(nbv-nnn+j);
2636         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2637         gp_Pnt P = S->Value(UV.X(),UV.Y());
2638         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2639         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2640         NodesC.SetValue(i,nbv-nnn+j,N);
2641       }
2642     }
2643     // add diagonal layers
2644     for (i=1; i<nbv-nnn; i++) {
2645       double du = UVR.Value(i).X() - UVL.Value(i).X();
2646       double dv = UVR.Value(i).Y() - UVL.Value(i).Y();
2647       for (j=2; j<nb; j++) {
2648         double u = UVL.Value(i).X() + du*npb.Value(j);
2649         double v = UVL.Value(i).Y() + dv*npb.Value(j);
2650         gp_Pnt P = S->Value(u,v);
2651         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2652         meshDS->SetNodeOnFace(N, geomFaceID, u, v);
2653         NodesC.SetValue(j,i+1,N);
2654       }
2655     }
2656     // create faces
2657     for (i=1; i<nb; i++) {
2658       for (j=1; j<nbv; j++) {
2659           SMDS_MeshFace* F =
2660             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
2661                             NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
2662           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2663       }
2664     }
2665     // TODO ???
2666   } // end Multiple Reduce implementation
2667   else { // Simple Reduce (!MultipleReduce)
2668     //=========================================================
2669     if (nr == nl) {
2670       if (nt < nb) {
2671         // it is a base case => not shift quad
2672         //shiftQuad(quad,0,true);
2673       }
2674       else {
2675         // we have to shift quad on 2
2676         shiftQuad(quad,2,true);
2677       }
2678     }
2679     else {
2680       if (nl > nr) {
2681         // we have to shift quad on 1
2682         shiftQuad(quad,1,true);
2683       }
2684       else {
2685         // we have to shift quad on 3
2686         shiftQuad(quad,3,true);
2687       }
2688     }
2689
2690     nb = quad->side[0]->NbPoints();
2691     nr = quad->side[1]->NbPoints();
2692     nt = quad->side[2]->NbPoints();
2693     nl = quad->side[3]->NbPoints();
2694
2695     // number of rows and columns
2696     int nrows = nr - 1; // and also == nl - 1
2697     int ncol_top = nt - 1;
2698     int ncol_bot = nb - 1;
2699     int npair_top = ncol_top / 2;
2700     // maximum number of bottom elements for "linear" simple reduce 4->2
2701     int max_lin42 = ncol_top + npair_top * 2 * nrows;
2702     // maximum number of bottom elements for "linear" simple reduce 3->1
2703     int max_lin31 = ncol_top + ncol_top * 2 * nrows;
2704     // maximum number of bottom elements for "tree" simple reduce 4->2
2705     int max_tree42 = 0;
2706     // number of rows needed to reduce ncol_bot to ncol_top using simple 4->2 "tree"
2707     int nrows_tree42 = int( log( (double)(ncol_bot / ncol_top) )/log((double)2)  ); // needed to avoid overflow at pow(2) while computing max_tree42
2708     if (nrows_tree42 < nrows) {
2709       max_tree42 = npair_top * pow(2.0, nrows + 1);
2710       if ( ncol_top > npair_top * 2 ) {
2711         int delta = ncol_bot - max_tree42;
2712         for (int irow = 1; irow < nrows; irow++) {
2713           int nfour = delta / 4;
2714           delta -= nfour * 2;
2715         }
2716         if (delta <= (ncol_top - npair_top * 2))
2717           max_tree42 = ncol_bot;
2718       }
2719     }
2720     // maximum number of bottom elements for "tree" simple reduce 3->1
2721     //int max_tree31 = ncol_top * pow(3.0, nrows);
2722     bool is_lin_31 = false;
2723     bool is_lin_42 = false;
2724     bool is_tree_31 = false;
2725     bool is_tree_42 = false;
2726     int max_lin = max_lin42;
2727     if (ncol_bot > max_lin42) {
2728       if (ncol_bot <= max_lin31) {
2729         is_lin_31 = true;
2730         max_lin = max_lin31;
2731       }
2732     }
2733     else {
2734       // if ncol_bot is a 3*n or not 2*n
2735       if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
2736         is_lin_31 = true;
2737         max_lin = max_lin31;
2738       }
2739       else {
2740         is_lin_42 = true;
2741       }
2742     }
2743     if (ncol_bot > max_lin) { // not "linear"
2744       is_tree_31 = (ncol_bot > max_tree42);
2745       if (ncol_bot <= max_tree42) {
2746         if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
2747           is_tree_31 = true;
2748         }
2749         else {
2750           is_tree_42 = true;
2751         }
2752       }
2753     }
2754
2755     const vector<UVPtStruct>& uv_eb = quad->side[0]->GetUVPtStruct(true,0);
2756     const vector<UVPtStruct>& uv_er = quad->side[1]->GetUVPtStruct(false,1);
2757     const vector<UVPtStruct>& uv_et = quad->side[2]->GetUVPtStruct(true,1);
2758     const vector<UVPtStruct>& uv_el = quad->side[3]->GetUVPtStruct(false,0);
2759
2760     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
2761       return error(COMPERR_BAD_INPUT_MESH);
2762
2763     myHelper->SetElementsOnShape( true );
2764
2765     gp_UV uv[ UV_SIZE ];
2766     uv[ UV_A0 ].SetCoord( uv_eb.front().u, uv_eb.front().v);
2767     uv[ UV_A1 ].SetCoord( uv_eb.back().u,  uv_eb.back().v );
2768     uv[ UV_A2 ].SetCoord( uv_et.back().u,  uv_et.back().v );
2769     uv[ UV_A3 ].SetCoord( uv_et.front().u, uv_et.front().v);
2770
2771     vector<UVPtStruct> curr_base = uv_eb, next_base;
2772
2773     UVPtStruct nullUVPtStruct; nullUVPtStruct.node = 0;
2774
2775     int curr_base_len = nb;
2776     int next_base_len = 0;
2777
2778     if ( true )
2779     { // ------------------------------------------------------------------
2780       // New algorithm implemented by request of IPAL22856
2781       // "2D quadrangle mesher of reduced type works wrong"
2782       // http://bugtracker.opencascade.com/show_bug.cgi?id=22856
2783
2784       // the algorithm is following: all reduces are centred in horizontal
2785       // direction and are distributed among all rows
2786
2787       if (ncol_bot > max_tree42) {
2788         is_lin_31 = true;
2789       }
2790       else {
2791         if ((ncol_top/3)*3 == ncol_top ) {
2792           is_lin_31 = true;
2793         }
2794         else {
2795           is_lin_42 = true;
2796         }
2797       }
2798
2799       const int col_top_size  = is_lin_42 ? 2 : 1;
2800       const int col_base_size = is_lin_42 ? 4 : 3;
2801
2802       // Compute nb of "columns" (like in "linear" simple reducing) in all rows
2803
2804       vector<int> nb_col_by_row;
2805
2806       int delta_all = nb - nt;
2807       int delta_one_col = nrows * 2;
2808       int nb_col = delta_all / delta_one_col;
2809       int remainder = delta_all - nb_col * delta_one_col;
2810       if (remainder > 0) {
2811         nb_col++;
2812       }
2813       if ( nb_col * col_top_size >= nt ) // == "tree" reducing situation
2814       {
2815         // top row is full (all elements reduced), add "columns" one by one
2816         // in rows below until all bottom elements are reduced
2817         nb_col = ( nt - 1 ) / col_top_size;
2818         nb_col_by_row.resize( nrows, nb_col );
2819         int nbrows_not_full = nrows - 1;
2820         int cur_top_size = nt - 1;
2821         remainder = delta_all - nb_col * delta_one_col;
2822         while ( remainder > 0 )
2823         {
2824           delta_one_col = nbrows_not_full * 2;
2825           int nb_col_add = remainder / delta_one_col;
2826           cur_top_size += 2 * nb_col_by_row[ nbrows_not_full ];
2827           int nb_col_free = cur_top_size / col_top_size - nb_col_by_row[ nbrows_not_full-1 ];
2828           if ( nb_col_add > nb_col_free )
2829             nb_col_add = nb_col_free;
2830           for ( int irow = 0; irow < nbrows_not_full; ++irow )
2831             nb_col_by_row[ irow ] += nb_col_add;
2832           nbrows_not_full --;
2833           remainder -=  nb_col_add * delta_one_col;
2834         }
2835       }
2836       else // == "linear" reducing situation
2837       {
2838         nb_col_by_row.resize( nrows, nb_col );
2839         if (remainder > 0)
2840           for ( int irow = remainder / 2; irow < nrows; ++irow )
2841             nb_col_by_row[ irow ]--;
2842       }
2843
2844       // Make elements
2845
2846       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
2847
2848       const int reduce_grp_size = is_lin_42 ? 4 : 3;
2849
2850       for (i = 1; i < nr; i++) // layer by layer
2851       {
2852         nb_col = nb_col_by_row[ i-1 ];
2853         int nb_next = curr_base_len - nb_col * 2;
2854         if (nb_next < nt) nb_next = nt;
2855
2856         const double y = uv_el[ i ].normParam;
2857
2858         if ( i + 1 == nr ) // top
2859         {
2860           next_base = uv_et;
2861         }
2862         else
2863         {
2864           next_base.clear();
2865           next_base.resize( nb_next, nullUVPtStruct );
2866           next_base.front() = uv_el[i];
2867           next_base.back()  = uv_er[i];
2868
2869           // compute normalized param u
2870           double du = 1. / ( nb_next - 1 );
2871           next_base[0].normParam = 0.;
2872           for ( j = 1; j < nb_next; ++j )
2873             next_base[j].normParam = next_base[j-1].normParam + du;
2874         }
2875         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
2876         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
2877
2878         int free_left = ( curr_base_len - 1 - nb_col * col_base_size ) / 2;
2879         int free_middle = curr_base_len - 1 - nb_col * col_base_size - 2 * free_left;
2880
2881         // not reduced left elements
2882         for (j = 0; j < free_left; j++)
2883         {
2884           // f (i + 1, j + 1)
2885           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
2886           if ( !Nf )
2887             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
2888
2889           myHelper->AddFace(curr_base[ j ].node,
2890                             curr_base[ j+1 ].node,
2891                             Nf,
2892                             next_base[ next_base_len-1 ].node);
2893         }
2894
2895         for (int icol = 1; icol <= nb_col; icol++)
2896         {
2897           // add "H"
2898           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
2899
2900           j += reduce_grp_size;
2901
2902           // elements in the middle of "columns" added for symmetry
2903           if ( free_middle > 0 && ( nb_col % 2 == 0 ) && icol == nb_col / 2 )
2904           {
2905             for (int imiddle = 1; imiddle <= free_middle; imiddle++) {
2906               // f (i + 1, j + imiddle)
2907               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
2908               if ( !Nf )
2909                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
2910
2911               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
2912                                 curr_base[ j  +imiddle ].node,
2913                                 Nf,
2914                                 next_base[ next_base_len-1 ].node);
2915             }
2916             j += free_middle;
2917           }
2918         }
2919
2920         // not reduced right elements
2921         for (; j < curr_base_len-1; j++) {
2922           // f (i + 1, j + 1)
2923           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
2924           if ( !Nf )
2925             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
2926
2927           myHelper->AddFace(curr_base[ j ].node,
2928                             curr_base[ j+1 ].node,
2929                             Nf,
2930                             next_base[ next_base_len-1 ].node);
2931         }
2932
2933         curr_base_len = next_base_len + 1;
2934         next_base_len = 0;
2935         curr_base.swap( next_base );
2936       }
2937
2938     }
2939     else if ( is_tree_42 || is_tree_31 )
2940     {
2941       // "tree" simple reduce "42": 2->4->8->16->32->...
2942       //
2943       //  .-------------------------------.-------------------------------. nr
2944       //  |    \                          |                          /    |
2945       //  |         \     .---------------.---------------.     /         |
2946       //  |               |               |               |               |
2947       //  .---------------.---------------.---------------.---------------.
2948       //  | \             |             / | \             |             / |
2949       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
2950       //  |       |       |       |       |       |       |       |       |
2951       //  .-------.-------.-------.-------.-------.-------.-------.-------. i
2952       //  |\      |      /|\      |      /|\      |      /|\      |      /|
2953       //  |  \.---.---./  |  \.---.---./  |  \.---.---./  |  \.---.---./  |
2954       //  |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
2955       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.
2956       //  |\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|
2957       //  | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. |
2958       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
2959       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
2960       //  1                               j                               nb
2961
2962       // "tree" simple reduce "31": 1->3->9->27->...
2963       //
2964       //  .-----------------------------------------------------. nr
2965       //  |        \                                   /        |
2966       //  |                 .-----------------.                 |
2967       //  |                 |                 |                 |
2968       //  .-----------------.-----------------.-----------------.
2969       //  |   \         /   |   \         /   |   \         /   |
2970       //  |     .-----.     |     .-----.     |     .-----.     | i
2971       //  |     |     |     |     |     |     |     |     |     |
2972       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.
2973       //  |\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|
2974       //  | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. |
2975       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | |
2976       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
2977       //  1                          j                          nb
2978
2979       PReduceFunction reduceFunction = & ( is_tree_42 ? reduce42 : reduce31 );
2980
2981       const int reduce_grp_size = is_tree_42 ? 4 : 3;
2982
2983       for (i = 1; i < nr; i++) // layer by layer
2984       {
2985         // to stop reducing, if number of nodes reaches nt
2986         int delta = curr_base_len - nt;
2987
2988         // to calculate normalized parameter, we must know number of points in next layer
2989         int nb_reduce_groups = (curr_base_len - 1) / reduce_grp_size;
2990         int nb_next = nb_reduce_groups * (reduce_grp_size-2) + (curr_base_len - nb_reduce_groups*reduce_grp_size);
2991         if (nb_next < nt) nb_next = nt;
2992
2993         const double y = uv_el[ i ].normParam;
2994
2995         if ( i + 1 == nr ) // top
2996         {
2997           next_base = uv_et;
2998         }
2999         else
3000         {
3001           next_base.clear();
3002           next_base.resize( nb_next, nullUVPtStruct );
3003           next_base.front() = uv_el[i];
3004           next_base.back()  = uv_er[i];
3005
3006           // compute normalized param u
3007           double du = 1. / ( nb_next - 1 );
3008           next_base[0].normParam = 0.;
3009           for ( j = 1; j < nb_next; ++j )
3010             next_base[j].normParam = next_base[j-1].normParam + du;
3011         }
3012         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3013         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3014
3015         for (j = 0; j+reduce_grp_size < curr_base_len && delta > 0; j+=reduce_grp_size, delta-=2)
3016         {
3017           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3018         }
3019
3020         // not reduced side elements (if any)
3021         for (; j < curr_base_len-1; j++)
3022         {
3023           // f (i + 1, j + 1)
3024           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3025           if ( !Nf )
3026             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3027           
3028           myHelper->AddFace(curr_base[ j ].node,
3029                             curr_base[ j+1 ].node,
3030                             Nf,
3031                             next_base[ next_base_len-1 ].node);
3032         }
3033         curr_base_len = next_base_len + 1;
3034         next_base_len = 0;
3035         curr_base.swap( next_base );
3036       }
3037     } // end "tree" simple reduce
3038
3039     else if ( is_lin_42 || is_lin_31 ) {
3040       // "linear" simple reduce "31": 2->6->10->14
3041       //
3042       //  .-----------------------------.-----------------------------. nr
3043       //  |     \                 /     |     \                 /     |
3044       //  |         .---------.         |         .---------.         |
3045       //  |         |         |         |         |         |         |
3046       //  .---------.---------.---------.---------.---------.---------.
3047       //  |        / \       / \        |        / \       / \        |
3048       //  |       /   .-----.   \       |       /   .-----.   \       | i
3049       //  |      /    |     |    \      |      /    |     |    \      |
3050       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.-----.
3051       //  |    /     / \   / \     \    |    /     / \   / \     \    |
3052       //  |   /     /   .-.   \     \   |   /     /   .-.   \     \   |
3053       //  |  /     /   /   \   \     \  |  /     /   /   \   \     \  |
3054       //  .--.----.---.-----.---.-----.-.--.----.---.-----.---.-----.-. 1
3055       //  1                             j                             nb
3056
3057       // "linear" simple reduce "42": 4->8->12->16
3058       //
3059       //  .---------------.---------------.---------------.---------------. nr
3060       //  | \             |             / | \             |             / |
3061       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
3062       //  |       |       |       |       |       |       |       |       |
3063       //  .-------.-------.-------.-------.-------.-------.-------.-------.
3064       //  |      / \      |      / \      |      / \      |      / \      |
3065       //  |     /   \.----.----./   \     |     /   \.----.----./   \     | i
3066       //  |     /    |    |    |    \     |     /    |    |    |    \     |
3067       //  .-----.----.----.----.----.-----.-----.----.----.----.----.-----.
3068       //  |     /   / \   |  /  \   \     |     /   / \   |  /  \   \     |
3069       //  |    /   /    .-.-.    \   \    |    /   /    .-.-.    \   \    |
3070       //  |   /   /    /  |  \    \   \   |   /   /    /  |  \    \   \   |
3071       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---. 1
3072       //  1                               j                               nb
3073
3074       // nt = 5, nb = 7, nr = 4
3075       //int delta_all = 2;
3076       //int delta_one_col = 6;
3077       //int nb_col = 0;
3078       //int remainder = 2;
3079       //if (remainder > 0) nb_col++;
3080       //nb_col = 1;
3081       //int free_left = 1;
3082       //free_left += 2;
3083       //int free_middle = 4;
3084
3085       int delta_all = nb - nt;
3086       int delta_one_col = (nr - 1) * 2;
3087       int nb_col = delta_all / delta_one_col;
3088       int remainder = delta_all - nb_col * delta_one_col;
3089       if (remainder > 0) {
3090         nb_col++;
3091       }
3092       const int col_top_size = is_lin_42 ? 2 : 1;
3093       int free_left = ((nt - 1) - nb_col * col_top_size) / 2;
3094       free_left += nr - 2;
3095       int free_middle = (nr - 2) * 2;
3096       if (remainder > 0 && nb_col == 1) {
3097         int nb_rows_short_col = remainder / 2;
3098         int nb_rows_thrown = (nr - 1) - nb_rows_short_col;
3099         free_left -= nb_rows_thrown;
3100       }
3101
3102       // nt = 5, nb = 17, nr = 4
3103       //int delta_all = 12;
3104       //int delta_one_col = 6;
3105       //int nb_col = 2;
3106       //int remainder = 0;
3107       //int free_left = 2;
3108       //int free_middle = 4;
3109
3110       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
3111
3112       const int reduce_grp_size = is_lin_42 ? 4 : 3;
3113
3114       for (i = 1; i < nr; i++, free_middle -= 2, free_left -= 1) // layer by layer
3115       {
3116         // to calculate normalized parameter, we must know number of points in next layer
3117         int nb_next = curr_base_len - nb_col * 2;
3118         if (remainder > 0 && i > remainder / 2)
3119           // take into account short "column"
3120           nb_next += 2;
3121         if (nb_next < nt) nb_next = nt;
3122
3123         const double y = uv_el[ i ].normParam;
3124
3125         if ( i + 1 == nr ) // top
3126         {
3127           next_base = uv_et;
3128         }
3129         else
3130         {
3131           next_base.clear();
3132           next_base.resize( nb_next, nullUVPtStruct );
3133           next_base.front() = uv_el[i];
3134           next_base.back()  = uv_er[i];
3135
3136           // compute normalized param u
3137           double du = 1. / ( nb_next - 1 );
3138           next_base[0].normParam = 0.;
3139           for ( j = 1; j < nb_next; ++j )
3140             next_base[j].normParam = next_base[j-1].normParam + du;
3141         }
3142         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3143         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3144
3145         // not reduced left elements
3146         for (j = 0; j < free_left; j++)
3147         {
3148           // f (i + 1, j + 1)
3149           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3150           if ( !Nf )
3151             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3152
3153           myHelper->AddFace(curr_base[ j ].node,
3154                             curr_base[ j+1 ].node,
3155                             Nf,
3156                             next_base[ next_base_len-1 ].node);
3157         }
3158
3159         for (int icol = 1; icol <= nb_col; icol++) {
3160
3161           if (remainder > 0 && icol == nb_col && i > remainder / 2)
3162             // stop short "column"
3163             break;
3164
3165           // add "H"
3166           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3167
3168           j += reduce_grp_size;
3169
3170           // not reduced middle elements
3171           if (icol < nb_col) {
3172             if (remainder > 0 && icol == nb_col - 1 && i > remainder / 2)
3173               // pass middle elements before stopped short "column"
3174               break;
3175
3176             int free_add = free_middle;
3177             if (remainder > 0 && icol == nb_col - 1)
3178               // next "column" is short
3179               free_add -= (nr - 1) - (remainder / 2);
3180
3181             for (int imiddle = 1; imiddle <= free_add; imiddle++) {
3182               // f (i + 1, j + imiddle)
3183               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3184               if ( !Nf )
3185                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3186
3187               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
3188                                 curr_base[ j  +imiddle ].node,
3189                                 Nf,
3190                                 next_base[ next_base_len-1 ].node);
3191             }
3192             j += free_add;
3193           }
3194         }
3195
3196         // not reduced right elements
3197         for (; j < curr_base_len-1; j++) {
3198           // f (i + 1, j + 1)
3199           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3200           if ( !Nf )
3201             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3202
3203           myHelper->AddFace(curr_base[ j ].node,
3204                             curr_base[ j+1 ].node,
3205                             Nf,
3206                             next_base[ next_base_len-1 ].node);
3207         }
3208
3209         curr_base_len = next_base_len + 1;
3210         next_base_len = 0;
3211         curr_base.swap( next_base );
3212       }
3213
3214     } // end "linear" simple reduce
3215
3216     else {
3217       return false;
3218     }
3219   } // end Simple Reduce implementation
3220
3221   bool isOk = true;
3222   return isOk;
3223 }
3224
3225 //================================================================================
3226 namespace // data for smoothing
3227 {
3228   struct TSmoothNode;
3229   // --------------------------------------------------------------------------------
3230   /*!
3231    * \brief Structure used to check validity of node position after smoothing.
3232    *        It holds two nodes connected to a smoothed node and belonging to
3233    *        one mesh face
3234    */
3235   struct TTriangle
3236   {
3237     TSmoothNode* _n1;
3238     TSmoothNode* _n2;
3239     TTriangle( TSmoothNode* n1=0, TSmoothNode* n2=0 ): _n1(n1), _n2(n2) {}
3240
3241     inline bool IsForward( gp_UV uv ) const;
3242   };
3243   // --------------------------------------------------------------------------------
3244   /*!
3245    * \brief Data of a smoothed node
3246    */
3247   struct TSmoothNode
3248   {
3249     gp_XY _uv;
3250     vector< TTriangle > _triangles; // if empty, then node is not movable
3251   };
3252   // --------------------------------------------------------------------------------
3253   inline bool TTriangle::IsForward( gp_UV uv ) const
3254   {
3255     gp_Vec2d v1( uv, _n1->_uv ), v2( uv, _n2->_uv );
3256     double d = v1 ^ v2;
3257     return d > 1e-100;
3258   }
3259 }
3260
3261 //================================================================================
3262 /*!
3263  * \brief Set UV of nodes on degenerated VERTEXes in the middle of degenerated EDGE
3264  *
3265  * WARNING: this method must be called AFTER retrieving UVPtStruct's from quad
3266  */
3267 //================================================================================
3268
3269 void StdMeshers_Quadrangle_2D::UpdateDegenUV(FaceQuadStruct::Ptr quad)
3270 {
3271   for ( unsigned i = 0; i < quad->side.size(); ++i )
3272   {
3273     StdMeshers_FaceSide* side = quad->side[i];
3274     const vector<UVPtStruct>& uvVec = side->GetUVPtStruct();
3275
3276     // find which end of the side is on degenerated shape
3277     int degenInd = -1;
3278     if ( myHelper->IsDegenShape( uvVec[0].node->getshapeId() ))
3279       degenInd = 0;
3280     else if ( myHelper->IsDegenShape( uvVec.back().node->getshapeId() ))
3281       degenInd = uvVec.size() - 1;
3282     else
3283       continue;
3284
3285     // find another side sharing the degenerated shape
3286     bool isPrev = ( degenInd == 0 );
3287     if ( i >= QUAD_TOP_SIDE )
3288       isPrev = !isPrev;
3289     int i2 = ( isPrev ? ( i + 3 ) : ( i + 1 )) % 4;
3290     StdMeshers_FaceSide* side2 = quad->side[ i2 ];
3291     const vector<UVPtStruct>& uvVec2 = side2->GetUVPtStruct();
3292     int degenInd2 = -1;
3293     if ( uvVec[ degenInd ].node == uvVec2[0].node )
3294       degenInd2 = 0;
3295     else if ( uvVec[ degenInd ].node == uvVec2.back().node )
3296       degenInd2 = uvVec2.size() - 1;
3297     else
3298       throw SALOME_Exception( LOCALIZED( "Logical error" ));
3299
3300     // move UV in the middle
3301     uvPtStruct& uv1 = const_cast<uvPtStruct&>( uvVec [ degenInd  ]);
3302     uvPtStruct& uv2 = const_cast<uvPtStruct&>( uvVec2[ degenInd2 ]);
3303     uv1.u = uv2.u = 0.5 * ( uv1.u + uv2.u );
3304     uv1.v = uv2.v = 0.5 * ( uv1.v + uv2.v );
3305   }
3306 }
3307
3308 //================================================================================
3309 /*!
3310  * \brief Perform smoothing of 2D elements on a FACE with ignored degenerated EDGE
3311  */
3312 //================================================================================
3313
3314 void StdMeshers_Quadrangle_2D::Smooth (FaceQuadStruct::Ptr quad)
3315 {
3316   if ( !myNeedSmooth ) return;
3317
3318   // Get nodes to smooth
3319
3320   typedef map< const SMDS_MeshNode*, TSmoothNode, TIDCompare > TNo2SmooNoMap;
3321   TNo2SmooNoMap smooNoMap;
3322
3323   const TopoDS_Face& geomFace = TopoDS::Face( myHelper->GetSubShape() );
3324   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
3325   SMESHDS_SubMesh* fSubMesh = meshDS->MeshElements( geomFace );
3326   SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
3327   while ( nIt->more() ) // loop on nodes bound to a FACE
3328   {
3329     const SMDS_MeshNode* node = nIt->next();
3330     TSmoothNode & sNode = smooNoMap[ node ];
3331     sNode._uv = myHelper->GetNodeUV( geomFace, node );
3332
3333     // set sNode._triangles
3334     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator( SMDSAbs_Face );
3335     while ( fIt->more() )
3336     {
3337       const SMDS_MeshElement* face = fIt->next();
3338       const int nbN = face->NbCornerNodes();
3339       const int nInd = face->GetNodeIndex( node );
3340       const int prevInd = myHelper->WrapIndex( nInd - 1, nbN );
3341       const int nextInd = myHelper->WrapIndex( nInd + 1, nbN );
3342       const SMDS_MeshNode* prevNode = face->GetNode( prevInd );
3343       const SMDS_MeshNode* nextNode = face->GetNode( nextInd );
3344       sNode._triangles.push_back( TTriangle( & smooNoMap[ prevNode ],
3345                                              & smooNoMap[ nextNode ]));
3346     }
3347   }
3348   // set _uv of smooth nodes on FACE boundary
3349   for ( unsigned i = 0; i < quad->side.size(); ++i )
3350   {
3351     const vector<UVPtStruct>& uvVec = quad->side[i]->GetUVPtStruct();
3352     for ( unsigned j = 0; j < uvVec.size(); ++j )
3353     {
3354       TSmoothNode & sNode = smooNoMap[ uvVec[j].node ];
3355       sNode._uv.SetCoord( uvVec[j].u, uvVec[j].v );
3356     }
3357   }
3358
3359   // define refernce orientation in 2D
3360   TNo2SmooNoMap::iterator n2sn = smooNoMap.begin();
3361   for ( ; n2sn != smooNoMap.end(); ++n2sn )
3362     if ( !n2sn->second._triangles.empty() )
3363       break;
3364   if ( n2sn == smooNoMap.end() ) return;
3365   const TSmoothNode & sampleNode = n2sn->second;
3366   const bool refForward = ( sampleNode._triangles[0].IsForward( sampleNode._uv ));
3367
3368   // Smoothing
3369
3370   for ( int iLoop = 0; iLoop < 5; ++iLoop )
3371   {
3372     for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
3373     {
3374       TSmoothNode& sNode = n2sn->second;
3375       if ( sNode._triangles.empty() )
3376         continue; // not movable node
3377
3378       // compute a new UV
3379       gp_XY newUV (0,0);
3380       for ( unsigned i = 0; i < sNode._triangles.size(); ++i )
3381         newUV += sNode._triangles[i]._n1->_uv;
3382       newUV /= sNode._triangles.size();
3383
3384       // check validity of the newUV
3385       bool isValid = true;
3386       for ( unsigned i = 0; i < sNode._triangles.size() && isValid; ++i )
3387         isValid = ( sNode._triangles[i].IsForward( newUV ) == refForward );
3388
3389       if ( isValid )
3390         sNode._uv = newUV;
3391     }
3392   }
3393
3394   // Set new XYZ to the smoothed nodes
3395
3396   Handle(Geom_Surface) surface = BRep_Tool::Surface( geomFace );
3397
3398   for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
3399   {
3400     TSmoothNode& sNode = n2sn->second;
3401     if ( sNode._triangles.empty() )
3402       continue; // not movable node
3403
3404     SMDS_MeshNode* node = const_cast< SMDS_MeshNode*>( n2sn->first );
3405     gp_Pnt xyz = surface->Value( sNode._uv.X(), sNode._uv.Y() );
3406     meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
3407
3408     // store the new UV
3409     node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( sNode._uv.X(), sNode._uv.Y() )));
3410   }
3411
3412   // Move medium nodes in quadratic mesh
3413   if ( _quadraticMesh )
3414   {
3415     const TLinkNodeMap& links = myHelper->GetTLinkNodeMap();
3416     TLinkNodeMap::const_iterator linkIt = links.begin();
3417     for ( ; linkIt != links.end(); ++linkIt )
3418     {
3419       const SMESH_TLink& link = linkIt->first;
3420       SMDS_MeshNode*     node = const_cast< SMDS_MeshNode*>( linkIt->second );
3421
3422       if ( node->getshapeId() != myHelper->GetSubShapeID() )
3423         continue; // medium node is on EDGE or VERTEX
3424
3425       gp_XY uv1 = myHelper->GetNodeUV( geomFace, link.node1(), node );
3426       gp_XY uv2 = myHelper->GetNodeUV( geomFace, link.node2(), node );
3427
3428       gp_XY uv  = myHelper->GetMiddleUV( surface, uv1, uv2 );
3429       node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( uv.X(), uv.Y() )));
3430       
3431       gp_Pnt xyz = surface->Value( uv.X(), uv.Y() );
3432       meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
3433     }
3434   }
3435 }