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