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