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