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