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