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