Salome HOME
1aee3df7e516f383ec69ac455b5557162d4ef3f6
[modules/smesh.git] / src / StdMeshers / StdMeshers_Quadrangle_2D.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
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_HypoFilter.hxx"
37 #include "SMESH_Mesh.hxx"
38 #include "SMESH_MeshAlgos.hxx"
39 #include "SMESH_MesherHelper.hxx"
40 #include "SMESH_subMesh.hxx"
41 #include "StdMeshers_FaceSide.hxx"
42 #include "StdMeshers_QuadrangleParams.hxx"
43 #include "StdMeshers_ViscousLayers2D.hxx"
44
45 #include <BRepBndLib.hxx>
46 #include <BRepClass_FaceClassifier.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_Box.hxx>
49 #include <GeomAPI_ProjectPointOnSurf.hxx>
50 #include <Geom_Surface.hxx>
51 #include <NCollection_DefineArray2.hxx>
52 #include <Precision.hxx>
53 #include <Quantity_Parameter.hxx>
54 #include <TColStd_SequenceOfInteger.hxx>
55 #include <TColStd_SequenceOfReal.hxx>
56 #include <TColgp_SequenceOfXY.hxx>
57 #include <TopExp.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_DataMapOfShapeReal.hxx>
60 #include <TopTools_ListIteratorOfListOfShape.hxx>
61 #include <TopTools_MapOfShape.hxx>
62 #include <TopoDS.hxx>
63
64 #include "utilities.h"
65 #include "Utils_ExceptHandlers.hxx"
66
67 #ifndef StdMeshers_Array2OfNode_HeaderFile
68 #define StdMeshers_Array2OfNode_HeaderFile
69 typedef const SMDS_MeshNode* SMDS_MeshNodePtr;
70 DEFINE_BASECOLLECTION (StdMeshers_BaseCollectionNodePtr, SMDS_MeshNodePtr)
71 DEFINE_ARRAY2(StdMeshers_Array2OfNode,
72               StdMeshers_BaseCollectionNodePtr, SMDS_MeshNodePtr)
73 #endif
74
75 using namespace std;
76
77 typedef gp_XY gp_UV;
78 typedef SMESH_Comment TComm;
79
80 //=============================================================================
81 /*!
82  *
83  */
84 //=============================================================================
85
86 StdMeshers_Quadrangle_2D::StdMeshers_Quadrangle_2D (int hypId, int studyId,
87                                                     SMESH_Gen* gen)
88   : SMESH_2D_Algo(hypId, studyId, gen),
89     myQuadranglePreference(false),
90     myTrianglePreference(false),
91     myTriaVertexID(-1),
92     myNeedSmooth(false),
93     myCheckOri(false),
94     myParams( NULL ),
95     myQuadType(QUAD_STANDARD),
96     myHelper( NULL )
97 {
98   MESSAGE("StdMeshers_Quadrangle_2D::StdMeshers_Quadrangle_2D");
99   _name = "Quadrangle_2D";
100   _shapeType = (1 << TopAbs_FACE);
101   _compatibleHypothesis.push_back("QuadrangleParams");
102   _compatibleHypothesis.push_back("QuadranglePreference");
103   _compatibleHypothesis.push_back("TrianglePreference");
104   _compatibleHypothesis.push_back("ViscousLayers2D");
105 }
106
107 //=============================================================================
108 /*!
109  *
110  */
111 //=============================================================================
112
113 StdMeshers_Quadrangle_2D::~StdMeshers_Quadrangle_2D()
114 {
115   MESSAGE("StdMeshers_Quadrangle_2D::~StdMeshers_Quadrangle_2D");
116 }
117
118 //=============================================================================
119 /*!
120  *  
121  */
122 //=============================================================================
123
124 bool StdMeshers_Quadrangle_2D::CheckHypothesis
125                          (SMESH_Mesh&                          aMesh,
126                           const TopoDS_Shape&                  aShape,
127                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
128 {
129   myTriaVertexID         = -1;
130   myQuadType             = QUAD_STANDARD;
131   myQuadranglePreference = false;
132   myTrianglePreference   = false;
133   myHelper               = (SMESH_MesherHelper*)NULL;
134   myParams               = NULL;
135   myQuadList.clear();
136
137   bool isOk = true;
138   aStatus   = SMESH_Hypothesis::HYP_OK;
139
140   const list <const SMESHDS_Hypothesis * >& hyps =
141     GetUsedHypothesis(aMesh, aShape, false);
142   const SMESHDS_Hypothesis * aHyp = 0;
143
144   bool isFirstParams = true;
145
146   // First assigned hypothesis (if any) is processed now
147   if (hyps.size() > 0) {
148     aHyp = hyps.front();
149     if (strcmp("QuadrangleParams", aHyp->GetName()) == 0)
150     {
151       myParams = (const StdMeshers_QuadrangleParams*)aHyp;
152       myTriaVertexID = myParams->GetTriaVertex();
153       myQuadType     = myParams->GetQuadType();
154       if (myQuadType == QUAD_QUADRANGLE_PREF ||
155           myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
156         myQuadranglePreference = true;
157       else if (myQuadType == QUAD_TRIANGLE_PREF)
158         myTrianglePreference = true;
159     }
160     else if (strcmp("QuadranglePreference", aHyp->GetName()) == 0) {
161       isFirstParams = false;
162       myQuadranglePreference = true;
163     }
164     else if (strcmp("TrianglePreference", aHyp->GetName()) == 0){
165       isFirstParams = false;
166       myTrianglePreference = true; 
167     }
168     else {
169       isFirstParams = false;
170     }
171   }
172
173   // Second(last) assigned hypothesis (if any) is processed now
174   if (hyps.size() > 1) {
175     aHyp = hyps.back();
176     if (isFirstParams) {
177       if (strcmp("QuadranglePreference", aHyp->GetName()) == 0) {
178         myQuadranglePreference = true;
179         myTrianglePreference = false; 
180         myQuadType = QUAD_STANDARD;
181       }
182       else if (strcmp("TrianglePreference", aHyp->GetName()) == 0){
183         myQuadranglePreference = false;
184         myTrianglePreference = true; 
185         myQuadType = QUAD_STANDARD;
186       }
187     }
188     else {
189       const StdMeshers_QuadrangleParams* aHyp2 = 
190         (const StdMeshers_QuadrangleParams*)aHyp;
191       myTriaVertexID = aHyp2->GetTriaVertex();
192
193       if (!myQuadranglePreference && !myTrianglePreference) { // priority of hypos
194         myQuadType = aHyp2->GetQuadType();
195         if (myQuadType == QUAD_QUADRANGLE_PREF ||
196             myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
197           myQuadranglePreference = true;
198         else if (myQuadType == QUAD_TRIANGLE_PREF)
199           myTrianglePreference = true;
200       }
201     }
202   }
203
204   return isOk;
205 }
206
207 //=============================================================================
208 /*!
209  *  
210  */
211 //=============================================================================
212
213 bool StdMeshers_Quadrangle_2D::Compute (SMESH_Mesh&         aMesh,
214                                         const TopoDS_Shape& aShape)
215 {
216   const TopoDS_Face& F = TopoDS::Face(aShape);
217   aMesh.GetSubMesh( F );
218
219   // do not initialize my fields before this as StdMeshers_ViscousLayers2D
220   // can call Compute() recursively
221   SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
222   if ( !proxyMesh )
223     return false;
224
225   myProxyMesh = proxyMesh;
226
227   SMESH_MesherHelper helper (aMesh);
228   myHelper = &helper;
229
230   _quadraticMesh = myHelper->IsQuadraticSubMesh(aShape);
231   myNeedSmooth = false;
232   myCheckOri   = false;
233
234   FaceQuadStruct::Ptr quad = CheckNbEdges( aMesh, F, /*considerMesh=*/true );
235   if (!quad)
236     return false;
237   myQuadList.clear();
238   myQuadList.push_back( quad );
239
240   if ( !getEnforcedUV() )
241     return false;
242
243   updateDegenUV( quad );
244
245   int n1 = quad->side[0].NbPoints();
246   int n2 = quad->side[1].NbPoints();
247   int n3 = quad->side[2].NbPoints();
248   int n4 = quad->side[3].NbPoints();
249
250   enum { NOT_COMPUTED = -1, COMPUTE_FAILED = 0, COMPUTE_OK = 1 };
251   int res = NOT_COMPUTED;
252   if (myQuadranglePreference)
253   {
254     int nfull = n1+n2+n3+n4;
255     if ((nfull % 2) == 0 && ((n1 != n3) || (n2 != n4)))
256     {
257       // special path genarating only quandrangle faces
258       res = computeQuadPref( aMesh, F, quad );
259     }
260   }
261   else if (myQuadType == QUAD_REDUCED)
262   {
263     int n13    = n1 - n3;
264     int n24    = n2 - n4;
265     int n13tmp = n13/2; n13tmp = n13tmp*2;
266     int n24tmp = n24/2; n24tmp = n24tmp*2;
267     if ((n1 == n3 && n2 != n4 && n24tmp == n24) ||
268         (n2 == n4 && n1 != n3 && n13tmp == n13))
269     {
270       res = computeReduced( aMesh, F, quad );
271     }
272     else
273     {
274       if ( n1 != n3 && n2 != n4 )
275         error( COMPERR_WARNING,
276                "To use 'Reduced' transition, "
277                "two opposite sides should have same number of segments, "
278                "but actual number of segments is different on all sides. "
279                "'Standard' transion has been used.");
280       else
281         error( COMPERR_WARNING,
282                "To use 'Reduced' transition, "
283                "two opposite sides should have an even difference in number of segments. "
284                "'Standard' transion has been used.");
285     }
286   }
287
288   if ( res == NOT_COMPUTED )
289   {
290     if ( n1 != n3 || n2 != n4 )
291       res = computeTriangles( aMesh, F, quad );
292     else
293       res = computeQuadDominant( aMesh, F );
294   }
295
296   if ( res == COMPUTE_OK && myNeedSmooth )
297     smooth( quad );
298
299   if ( res == COMPUTE_OK )
300     res = check();
301
302   return ( res == COMPUTE_OK );
303 }
304
305 //================================================================================
306 /*!
307  * \brief Compute quadrangles and triangles on the quad
308  */
309 //================================================================================
310
311 bool StdMeshers_Quadrangle_2D::computeTriangles(SMESH_Mesh&         aMesh,
312                                                 const TopoDS_Face&  aFace,
313                                                 FaceQuadStruct::Ptr quad)
314 {
315   int nb = quad->side[0].grid->NbPoints();
316   int nr = quad->side[1].grid->NbPoints();
317   int nt = quad->side[2].grid->NbPoints();
318   int nl = quad->side[3].grid->NbPoints();
319
320   // rotate the quad to have nbNodeOut sides on TOP [and LEFT]
321   if ( nb > nt )
322     quad->shift( nl > nr ? 3 : 2, true );
323   else if ( nr > nl )
324     quad->shift( 1, true );
325   else if ( nl > nr )
326     quad->shift( nt > nb ? 0 : 3, true );
327
328   if ( !setNormalizedGrid( quad ))
329     return false;
330
331   if ( quad->nbNodeOut( QUAD_TOP_SIDE    ))
332   {
333     splitQuad( quad, 0, quad->jSize-2 );
334   }
335   if ( quad->nbNodeOut( QUAD_BOTTOM_SIDE )) // this should not happen
336   {
337     splitQuad( quad, 0, 1 );
338   }
339   FaceQuadStruct::Ptr newQuad = myQuadList.back();
340   if ( quad != newQuad ) // split done
341   {
342     { // update left side limit till where to make triangles
343       FaceQuadStruct::Ptr botQuad = // a bottom part
344         ( quad->side[ QUAD_LEFT_SIDE ].from == 0 ) ? quad : newQuad;
345       if ( botQuad->nbNodeOut( QUAD_LEFT_SIDE ) > 0 )
346         botQuad->side[ QUAD_LEFT_SIDE ].to += botQuad->nbNodeOut( QUAD_LEFT_SIDE );
347       else if ( botQuad->nbNodeOut( QUAD_RIGHT_SIDE ) > 0 )
348         botQuad->side[ QUAD_RIGHT_SIDE ].to += botQuad->nbNodeOut( QUAD_RIGHT_SIDE );
349     }
350     // make quad be a greatest one
351     if ( quad->side[ QUAD_LEFT_SIDE ].NbPoints() == 2 ||
352          quad->side[ QUAD_RIGHT_SIDE ].NbPoints() == 2  )
353       quad = newQuad;
354     if ( !setNormalizedGrid( quad ))
355       return false;
356   }
357
358   if ( quad->nbNodeOut( QUAD_RIGHT_SIDE ))
359   {
360     splitQuad( quad, quad->iSize-2, 0 );
361   }
362   if ( quad->nbNodeOut( QUAD_LEFT_SIDE  ))
363   {
364     splitQuad( quad, 1, 0 );
365
366     if ( quad->nbNodeOut( QUAD_TOP_SIDE ))
367     {
368       newQuad = myQuadList.back();
369       if ( newQuad == quad ) // too narrow to split
370       {
371         // update left side limit till where to make triangles
372         quad->side[ QUAD_LEFT_SIDE ].to--;
373       }
374       else
375       {
376         FaceQuadStruct::Ptr leftQuad =
377           ( quad->side[ QUAD_BOTTOM_SIDE ].from == 0 ) ? quad : newQuad;
378         leftQuad->nbNodeOut( QUAD_TOP_SIDE ) = 0;
379       }
380     }
381   }
382
383   if ( ! computeQuadDominant( aMesh, aFace ))
384     return false;
385
386   // try to fix zero-area triangles near straight-angle corners
387
388   return true;
389 }
390
391 //================================================================================
392 /*!
393  * \brief Compute quadrangles and possibly triangles on all quads of myQuadList
394  */
395 //================================================================================
396
397 bool StdMeshers_Quadrangle_2D::computeQuadDominant(SMESH_Mesh&         aMesh,
398                                                    const TopoDS_Face&  aFace)
399 {
400   if ( !addEnforcedNodes() )
401     return false;
402
403   std::list< FaceQuadStruct::Ptr >::iterator quad = myQuadList.begin();
404   for ( ; quad != myQuadList.end(); ++quad )
405     if ( !computeQuadDominant( aMesh, aFace, *quad ))
406       return false;
407
408   return true;
409 }
410
411 //================================================================================
412 /*!
413  * \brief Compute quadrangles and possibly triangles
414  */
415 //================================================================================
416
417 bool StdMeshers_Quadrangle_2D::computeQuadDominant(SMESH_Mesh&         aMesh,
418                                                    const TopoDS_Face&  aFace,
419                                                    FaceQuadStruct::Ptr quad)
420 {
421   // --- set normalized grid on unit square in parametric domain
422
423   if ( !setNormalizedGrid( quad ))
424     return false;
425
426   // --- create nodes on points, and create quadrangles
427
428   int nbhoriz  = quad->iSize;
429   int nbvertic = quad->jSize;
430
431   // internal mesh nodes
432   SMESHDS_Mesh *  meshDS = aMesh.GetMeshDS();
433   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace);
434   int i,j,    geomFaceID = meshDS->ShapeToIndex(aFace);
435   for (i = 1; i < nbhoriz - 1; i++)
436     for (j = 1; j < nbvertic - 1; j++)
437     {
438       UVPtStruct& uvPnt = quad->UVPt( i, j );
439       gp_Pnt P          = S->Value( uvPnt.u, uvPnt.v );
440       uvPnt.node        = meshDS->AddNode(P.X(), P.Y(), P.Z());
441       meshDS->SetNodeOnFace( uvPnt.node, geomFaceID, uvPnt.u, uvPnt.v );
442     }
443   
444   // mesh faces
445
446   //             [2]
447   //      --.--.--.--.--.--  nbvertic
448   //     |                 | ^
449   //     |                 | ^
450   // [3] |                 | ^ j  [1]
451   //     |                 | ^
452   //     |                 | ^
453   //      ---.----.----.---  0
454   //     0 > > > > > > > > nbhoriz
455   //              i
456   //             [0]
457   
458   int ilow = 0;
459   int iup = nbhoriz - 1;
460   if (quad->nbNodeOut(3)) { ilow++; } else { if (quad->nbNodeOut(1)) iup--; }
461   
462   int jlow = 0;
463   int jup = nbvertic - 1;
464   if (quad->nbNodeOut(0)) { jlow++; } else { if (quad->nbNodeOut(2)) jup--; }
465   
466   // regular quadrangles
467   for (i = ilow; i < iup; i++) {
468     for (j = jlow; j < jup; j++) {
469       const SMDS_MeshNode *a, *b, *c, *d;
470       a = quad->uv_grid[ j      * nbhoriz + i    ].node;
471       b = quad->uv_grid[ j      * nbhoriz + i + 1].node;
472       c = quad->uv_grid[(j + 1) * nbhoriz + i + 1].node;
473       d = quad->uv_grid[(j + 1) * nbhoriz + i    ].node;
474       SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
475       if (face) {
476         meshDS->SetMeshElementOnShape(face, geomFaceID);
477       }
478     }
479   }
480
481   // Boundary elements (must always be on an outer boundary of the FACE)
482   
483   const vector<UVPtStruct>& uv_e0 = quad->side[0].grid->GetUVPtStruct();
484   const vector<UVPtStruct>& uv_e1 = quad->side[1].grid->GetUVPtStruct();
485   const vector<UVPtStruct>& uv_e2 = quad->side[2].grid->GetUVPtStruct();
486   const vector<UVPtStruct>& uv_e3 = quad->side[3].grid->GetUVPtStruct();
487
488   if (uv_e0.empty() || uv_e1.empty() || uv_e2.empty() || uv_e3.empty())
489     return error(COMPERR_BAD_INPUT_MESH);
490
491   double eps = Precision::Confusion();
492
493   int nbdown  = (int) uv_e0.size();
494   int nbup    = (int) uv_e2.size();
495   int nbright = (int) uv_e1.size();
496   int nbleft  = (int) uv_e3.size();
497
498   if (quad->nbNodeOut(0) && nbvertic == 2) // this should not occure
499   {
500     // Down edge is out
501     // 
502     // |___|___|___|___|___|___|
503     // |   |   |   |   |   |   |
504     // |___|___|___|___|___|___|
505     // |   |   |   |   |   |   |
506     // |___|___|___|___|___|___| __ first row of the regular grid
507     // .  .  .  .  .  .  .  .  . __ down edge nodes
508     // 
509     // >->->->->->->->->->->->-> -- direction of processing
510       
511     int g = 0; // number of last processed node in the regular grid
512     
513     // number of last node of the down edge to be processed
514     int stop = nbdown - 1;
515     // if right edge is out, we will stop at a node, previous to the last one
516     //if (quad->nbNodeOut(1)) stop--;
517     if ( quad->nbNodeOut( QUAD_RIGHT_SIDE ))
518       quad->UVPt( nbhoriz-1, 1 ).node = uv_e1[1].node;
519     if ( quad->nbNodeOut( QUAD_LEFT_SIDE ))
520       quad->UVPt( 0, 1 ).node = uv_e3[1].node;
521
522     // for each node of the down edge find nearest node
523     // in the first row of the regular grid and link them
524     for (i = 0; i < stop; i++) {
525       const SMDS_MeshNode *a, *b, *c, *d;
526       a = uv_e0[i].node;
527       b = uv_e0[i + 1].node;
528       gp_Pnt pb (b->X(), b->Y(), b->Z());
529       
530       // find node c in the regular grid, which will be linked with node b
531       int near = g;
532       if (i == stop - 1) {
533         // right bound reached, link with the rightmost node
534         near = iup;
535         c = quad->uv_grid[nbhoriz + iup].node;
536       }
537       else {
538         // find in the grid node c, nearest to the b
539         double mind = RealLast();
540         for (int k = g; k <= iup; k++) {
541           
542           const SMDS_MeshNode *nk;
543           if (k < ilow) // this can be, if left edge is out
544             nk = uv_e3[1].node; // get node from the left edge
545           else
546             nk = quad->uv_grid[nbhoriz + k].node; // get one of middle nodes
547
548           gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
549           double dist = pb.Distance(pnk);
550           if (dist < mind - eps) {
551             c = nk;
552             near = k;
553             mind = dist;
554           } else {
555             break;
556           }
557         }
558       }
559
560       if (near == g) { // make triangle
561         SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
562         if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
563       }
564       else { // make quadrangle
565         if (near - 1 < ilow)
566           d = uv_e3[1].node;
567         else
568           d = quad->uv_grid[nbhoriz + near - 1].node;
569         //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
570         
571         if (!myTrianglePreference){
572           SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
573           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
574         }
575         else {
576           splitQuadFace(meshDS, geomFaceID, a, b, c, d);
577         }
578
579         // if node d is not at position g - make additional triangles
580         if (near - 1 > g) {
581           for (int k = near - 1; k > g; k--) {
582             c = quad->uv_grid[nbhoriz + k].node;
583             if (k - 1 < ilow)
584               d = uv_e3[1].node;
585             else
586               d = quad->uv_grid[nbhoriz + k - 1].node;
587             SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
588             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
589           }
590         }
591         g = near;
592       }
593     }
594   } else {
595     if (quad->nbNodeOut(2) && nbvertic == 2)
596     {
597       // Up edge is out
598       // 
599       // <-<-<-<-<-<-<-<-<-<-<-<-< -- direction of processing
600       // 
601       // .  .  .  .  .  .  .  .  . __ up edge nodes
602       //  ___ ___ ___ ___ ___ ___  __ first row of the regular grid
603       // |   |   |   |   |   |   |
604       // |___|___|___|___|___|___|
605       // |   |   |   |   |   |   |
606       // |___|___|___|___|___|___|
607       // |   |   |   |   |   |   |
608
609       int g = nbhoriz - 1; // last processed node in the regular grid
610
611       ilow = 0;
612       iup = nbhoriz - 1;
613
614       int stop = 0;
615       if ( quad->side[3].grid->Edge(0).IsNull() ) // left side is simulated one
616       {
617         // quad divided at I but not at J, as nbvertic==nbright==2
618         stop++; // we stop at a second node
619       }
620       else
621       {
622         if ( quad->nbNodeOut( QUAD_RIGHT_SIDE ))
623           quad->UVPt( nbhoriz-1, 0 ).node = uv_e1[ nbright-2 ].node;
624         if ( quad->nbNodeOut( QUAD_LEFT_SIDE ))
625           quad->UVPt( 0, 0 ).node = uv_e3[ nbleft-2 ].node;
626
627         if ( nbright > 2 ) // there was a split at J
628           quad->nbNodeOut( QUAD_LEFT_SIDE ) = 0;
629       }
630       const SMDS_MeshNode *a, *b, *c, *d;
631       i = nbup - 1;
632       // avoid creating zero-area triangles near a straight-angle corner
633       {
634         a = uv_e2[i].node;
635         b = uv_e2[i-1].node;
636         c = uv_e1[nbright-2].node;
637         SMESH_TNodeXYZ pa( a ), pb( b ), pc( c );
638         double area = 0.5 * (( pb - pa ) ^ ( pc - pa )).Modulus();
639         if ( Abs( area ) < 1e-20 )
640         {
641           --g;
642           d = quad->UVPt( g, nbvertic-2 ).node;
643           if ( myTrianglePreference )
644           {
645             if ( SMDS_MeshFace* face = myHelper->AddFace(a, d, c))
646               meshDS->SetMeshElementOnShape(face, geomFaceID);
647           }
648           else
649           {
650             if ( SMDS_MeshFace* face = myHelper->AddFace(a, b, d, c))
651             {
652               meshDS->SetMeshElementOnShape(face, geomFaceID);
653               SMESH_ComputeErrorPtr& err = aMesh.GetSubMesh( aFace )->GetComputeError();
654               if ( !err || err->IsOK() || err->myName < COMPERR_WARNING )
655               {
656                 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
657                                                    "Bad quality quad created"));
658                 err->myBadElements.push_back( face );
659               }
660             }
661             --i;
662           }
663         }
664       }
665       // for each node of the up edge find nearest node
666       // in the first row of the regular grid and link them
667       for ( ; i > stop; i--) {
668         a = uv_e2[i].node;
669         b = uv_e2[i - 1].node;
670         gp_Pnt pb (b->X(), b->Y(), b->Z());
671
672         // find node c in the grid, which will be linked with node b
673         int near = g;
674         if (i == stop + 1) { // left bound reached, link with the leftmost node
675           c = quad->uv_grid[nbhoriz*(nbvertic - 2) + ilow].node;
676           near = ilow;
677         } else {
678           // find node c in the grid, nearest to the b
679           double mind = RealLast();
680           for (int k = g; k >= ilow; k--) {
681             const SMDS_MeshNode *nk;
682             if (k > iup)
683               nk = uv_e1[nbright - 2].node;
684             else
685               nk = quad->uv_grid[nbhoriz*(nbvertic - 2) + k].node;
686             gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
687             double dist = pb.Distance(pnk);
688             if (dist < mind - eps) {
689               c = nk;
690               near = k;
691               mind = dist;
692             } else {
693               break;
694             }
695           }
696         }
697
698         if (near == g) { // make triangle
699           SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
700           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
701         }
702         else { // make quadrangle
703           if (near + 1 > iup)
704             d = uv_e1[nbright - 2].node;
705           else
706             d = quad->uv_grid[nbhoriz*(nbvertic - 2) + near + 1].node;
707           //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
708           if (!myTrianglePreference){
709             SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
710             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
711           }
712           else {
713             splitQuadFace(meshDS, geomFaceID, a, b, c, d);
714           }
715
716           if (near + 1 < g) { // if d is not at g - make additional triangles
717             for (int k = near + 1; k < g; k++) {
718               c = quad->uv_grid[nbhoriz*(nbvertic - 2) + k].node;
719               if (k + 1 > iup)
720                 d = uv_e1[nbright - 2].node;
721               else
722                 d = quad->uv_grid[nbhoriz*(nbvertic - 2) + k + 1].node;
723               SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
724               if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
725             }
726           }
727           g = near;
728         }
729       }
730     }
731   }
732
733   // right or left boundary quadrangles
734   if (quad->nbNodeOut( QUAD_RIGHT_SIDE ) && nbhoriz == 2) // this should not occure
735   {
736     int g = 0; // last processed node in the grid
737     int stop = nbright - 1;
738     i = 0;
739     if (quad->side[ QUAD_RIGHT_SIDE ].from != i    ) i++;
740     if (quad->side[ QUAD_RIGHT_SIDE ].to   != stop ) stop--;
741     for ( ; i < stop; i++) {
742       const SMDS_MeshNode *a, *b, *c, *d;
743       a = uv_e1[i].node;
744       b = uv_e1[i + 1].node;
745       gp_Pnt pb (b->X(), b->Y(), b->Z());
746
747       // find node c in the grid, nearest to the b
748       int near = g;
749       if (i == stop - 1) { // up bondary reached
750         c = quad->uv_grid[nbhoriz*(jup + 1) - 2].node;
751         near = jup;
752       } else {
753         double mind = RealLast();
754         for (int k = g; k <= jup; k++) {
755           const SMDS_MeshNode *nk;
756           if (k < jlow)
757             nk = uv_e0[nbdown - 2].node;
758           else
759             nk = quad->uv_grid[nbhoriz*(k + 1) - 2].node;
760           gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
761           double dist = pb.Distance(pnk);
762           if (dist < mind - eps) {
763             c = nk;
764             near = k;
765             mind = dist;
766           } else {
767             break;
768           }
769         }
770       }
771
772       if (near == g) { // make triangle
773         SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
774         if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
775       }
776       else { // make quadrangle
777         if (near - 1 < jlow)
778           d = uv_e0[nbdown - 2].node;
779         else
780           d = quad->uv_grid[nbhoriz*near - 2].node;
781         //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
782
783         if (!myTrianglePreference){
784           SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
785           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
786         }
787         else {
788           splitQuadFace(meshDS, geomFaceID, a, b, c, d);
789         }
790
791         if (near - 1 > g) { // if d not is at g - make additional triangles
792           for (int k = near - 1; k > g; k--) {
793             c = quad->uv_grid[nbhoriz*(k + 1) - 2].node;
794             if (k - 1 < jlow)
795               d = uv_e0[nbdown - 2].node;
796             else
797               d = quad->uv_grid[nbhoriz*k - 2].node;
798             SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
799             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
800           }
801         }
802         g = near;
803       }
804     }
805   } else {
806     if (quad->nbNodeOut(3) && nbhoriz == 2) {
807 //      MESSAGE("left edge is out");
808       int g = nbvertic - 1; // last processed node in the grid
809       int stop = 0;
810       i = quad->side[ QUAD_LEFT_SIDE ].to-1; // nbleft - 1;
811
812       const SMDS_MeshNode *a, *b, *c, *d;
813       // avoid creating zero-area triangles near a straight-angle corner
814       {
815         a = uv_e3[i].node;
816         b = uv_e3[i-1].node;
817         c = quad->UVPt( 1, g ).node;
818         SMESH_TNodeXYZ pa( a ), pb( b ), pc( c );
819         double area = 0.5 * (( pb - pa ) ^ ( pc - pa )).Modulus();
820         if ( Abs( area ) < 1e-20 )
821         {
822           --g;
823           d = quad->UVPt( 1, g ).node;
824           if ( myTrianglePreference )
825           {
826             if ( SMDS_MeshFace* face = myHelper->AddFace(a, d, c))
827               meshDS->SetMeshElementOnShape(face, geomFaceID);
828           }
829           else
830           {
831             if ( SMDS_MeshFace* face = myHelper->AddFace(a, b, d, c))
832             {
833               meshDS->SetMeshElementOnShape(face, geomFaceID);
834               SMESH_ComputeErrorPtr& err = aMesh.GetSubMesh( aFace )->GetComputeError();
835               if ( !err || err->IsOK() || err->myName < COMPERR_WARNING )
836               {
837                 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
838                                                    "Bad quality quad created"));
839                 err->myBadElements.push_back( face );
840               }
841             }
842             --i;
843           }
844         }
845       }
846       for (; i > stop; i--) // loop on nodes on the left side
847       {
848         a = uv_e3[i].node;
849         b = uv_e3[i - 1].node;
850         gp_Pnt pb (b->X(), b->Y(), b->Z());
851
852         // find node c in the grid, nearest to the b
853         int near = g;
854         if (i == stop + 1) { // down bondary reached
855           c = quad->uv_grid[nbhoriz*jlow + 1].node;
856           near = jlow;
857         }
858         else {
859           double mind = RealLast();
860           for (int k = g; k >= jlow; k--) {
861             const SMDS_MeshNode *nk;
862             if (k > jup)
863               nk = quad->uv_grid[nbhoriz*jup + 1].node; //uv_e2[1].node;
864             else
865               nk = quad->uv_grid[nbhoriz*k + 1].node;
866             gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
867             double dist = pb.Distance(pnk);
868             if (dist < mind - eps) {
869               c = nk;
870               near = k;
871               mind = dist;
872             } else {
873               break;
874             }
875           }
876         }
877
878         if (near == g) { // make triangle
879           SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
880           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
881         }
882         else { // make quadrangle
883           if (near + 1 > jup)
884             d = quad->uv_grid[nbhoriz*jup + 1].node; //uv_e2[1].node;
885           else
886             d = quad->uv_grid[nbhoriz*(near + 1) + 1].node;
887           if (!myTrianglePreference) {
888             SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
889             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
890           }
891           else {
892             splitQuadFace(meshDS, geomFaceID, a, b, c, d);
893           }
894
895           if (near + 1 < g) { // if d not is at g - make additional triangles
896             for (int k = near + 1; k < g; k++) {
897               c = quad->uv_grid[nbhoriz*k + 1].node;
898               if (k + 1 > jup)
899                 d = quad->uv_grid[nbhoriz*jup + 1].node; //uv_e2[1].node;
900               else
901                 d = quad->uv_grid[nbhoriz*(k + 1) + 1].node;
902               SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
903               if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
904             }
905           }
906           g = near;
907         }
908       }
909     }
910   }
911
912   bool isOk = true;
913   return isOk;
914 }
915
916
917 //=============================================================================
918 /*!
919  *  Evaluate
920  */
921 //=============================================================================
922
923 bool StdMeshers_Quadrangle_2D::Evaluate(SMESH_Mesh&         aMesh,
924                                         const TopoDS_Shape& aFace,
925                                         MapShapeNbElems&    aResMap)
926
927 {
928   aMesh.GetSubMesh(aFace);
929
930   std::vector<int> aNbNodes(4);
931   bool IsQuadratic = false;
932   if (!checkNbEdgesForEvaluate(aMesh, aFace, aResMap, aNbNodes, IsQuadratic)) {
933     std::vector<int> aResVec(SMDSEntity_Last);
934     for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
935     SMESH_subMesh * sm = aMesh.GetSubMesh(aFace);
936     aResMap.insert(std::make_pair(sm,aResVec));
937     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
938     smError.reset(new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
939     return false;
940   }
941
942   if (myQuadranglePreference) {
943     int n1 = aNbNodes[0];
944     int n2 = aNbNodes[1];
945     int n3 = aNbNodes[2];
946     int n4 = aNbNodes[3];
947     int nfull = n1+n2+n3+n4;
948     int ntmp = nfull/2;
949     ntmp = ntmp*2;
950     if (nfull==ntmp && ((n1!=n3) || (n2!=n4))) {
951       // special path for using only quandrangle faces
952       return evaluateQuadPref(aMesh, aFace, aNbNodes, aResMap, IsQuadratic);
953       //return true;
954     }
955   }
956
957   int nbdown  = aNbNodes[0];
958   int nbup    = aNbNodes[2];
959
960   int nbright = aNbNodes[1];
961   int nbleft  = aNbNodes[3];
962
963   int nbhoriz  = Min(nbdown, nbup);
964   int nbvertic = Min(nbright, nbleft);
965
966   int dh = Max(nbdown, nbup) - nbhoriz;
967   int dv = Max(nbright, nbleft) - nbvertic;
968
969   //int kdh = 0;
970   //if (dh>0) kdh = 1;
971   //int kdv = 0;
972   //if (dv>0) kdv = 1;
973
974   int nbNodes = (nbhoriz-2)*(nbvertic-2);
975   //int nbFaces3 = dh + dv + kdh*(nbvertic-1)*2 + kdv*(nbhoriz-1)*2;
976   int nbFaces3 = dh + dv;
977   //if (kdh==1 && kdv==1) nbFaces3 -= 2;
978   //if (dh>0 && dv>0) nbFaces3 -= 2;
979   //int nbFaces4 = (nbhoriz-1-kdh)*(nbvertic-1-kdv);
980   int nbFaces4 = (nbhoriz-1)*(nbvertic-1);
981
982   std::vector<int> aVec(SMDSEntity_Last);
983   for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
984   if (IsQuadratic) {
985     aVec[SMDSEntity_Quad_Triangle] = nbFaces3;
986     aVec[SMDSEntity_Quad_Quadrangle] = nbFaces4;
987     int nbbndedges = nbdown + nbup + nbright + nbleft -4;
988     int nbintedges = (nbFaces4*4 + nbFaces3*3 - nbbndedges) / 2;
989     aVec[SMDSEntity_Node] = nbNodes + nbintedges;
990     if (aNbNodes.size()==5) {
991       aVec[SMDSEntity_Quad_Triangle] = nbFaces3 + aNbNodes[3] -1;
992       aVec[SMDSEntity_Quad_Quadrangle] = nbFaces4 - aNbNodes[3] +1;
993     }
994   }
995   else {
996     aVec[SMDSEntity_Node] = nbNodes;
997     aVec[SMDSEntity_Triangle] = nbFaces3;
998     aVec[SMDSEntity_Quadrangle] = nbFaces4;
999     if (aNbNodes.size()==5) {
1000       aVec[SMDSEntity_Triangle] = nbFaces3 + aNbNodes[3] - 1;
1001       aVec[SMDSEntity_Quadrangle] = nbFaces4 - aNbNodes[3] + 1;
1002     }
1003   }
1004   SMESH_subMesh * sm = aMesh.GetSubMesh(aFace);
1005   aResMap.insert(std::make_pair(sm,aVec));
1006
1007   return true;
1008 }
1009
1010 //================================================================================
1011 /*!
1012  * \brief Return true if the algorithm can mesh this shape
1013  *  \param [in] aShape - shape to check
1014  *  \param [in] toCheckAll - if true, this check returns OK if all shapes are OK,
1015  *              else, returns OK if at least one shape is OK
1016  */
1017 //================================================================================
1018
1019 bool StdMeshers_Quadrangle_2D::IsApplicable( const TopoDS_Shape & aShape, bool toCheckAll )
1020 {
1021   int nbFoundFaces = 0;
1022   for (TopExp_Explorer exp( aShape, TopAbs_FACE ); exp.More(); exp.Next(), ++nbFoundFaces )
1023   {
1024     const TopoDS_Shape& aFace = exp.Current();
1025     int nbWire = SMESH_MesherHelper::Count( aFace, TopAbs_WIRE, false );
1026     if ( nbWire != 1 ) {
1027       if ( toCheckAll ) return false;
1028       continue;
1029     }
1030
1031     int nbNoDegenEdges = 0;
1032     TopExp_Explorer eExp( aFace, TopAbs_EDGE );
1033     for ( ; eExp.More() && nbNoDegenEdges < 3; eExp.Next() ) {
1034       if ( !SMESH_Algo::isDegenerated( TopoDS::Edge( eExp.Current() )))
1035         ++nbNoDegenEdges;
1036     }
1037     if ( toCheckAll  && nbNoDegenEdges <  3 ) return false;
1038     if ( !toCheckAll && nbNoDegenEdges >= 3 ) return true;
1039   }
1040   return ( toCheckAll && nbFoundFaces != 0 );
1041 }
1042
1043 //================================================================================
1044 /*!
1045  * \brief Return true if only two given edges meat at their common vertex
1046  */
1047 //================================================================================
1048
1049 static bool twoEdgesMeatAtVertex(const TopoDS_Edge& e1,
1050                                  const TopoDS_Edge& e2,
1051                                  SMESH_Mesh &       mesh)
1052 {
1053   TopoDS_Vertex v;
1054   if (!TopExp::CommonVertex(e1, e2, v))
1055     return false;
1056   TopTools_ListIteratorOfListOfShape ancestIt(mesh.GetAncestors(v));
1057   for (; ancestIt.More() ; ancestIt.Next())
1058     if (ancestIt.Value().ShapeType() == TopAbs_EDGE)
1059       if (!e1.IsSame(ancestIt.Value()) && !e2.IsSame(ancestIt.Value()))
1060         return false;
1061   return true;
1062 }
1063
1064 //=============================================================================
1065 /*!
1066  *  
1067  */
1068 //=============================================================================
1069
1070 FaceQuadStruct::Ptr StdMeshers_Quadrangle_2D::CheckNbEdges(SMESH_Mesh &         aMesh,
1071                                                            const TopoDS_Shape & aShape,
1072                                                            const bool           considerMesh)
1073 {
1074   if ( !myQuadList.empty() && myQuadList.front()->face.IsSame( aShape ))
1075     return myQuadList.front();
1076
1077   TopoDS_Face F = TopoDS::Face(aShape);
1078   if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
1079   const bool ignoreMediumNodes = _quadraticMesh;
1080
1081   // verify 1 wire only
1082   list< TopoDS_Edge > edges;
1083   list< int > nbEdgesInWire;
1084   int nbWire = SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
1085   if (nbWire != 1) {
1086     error(COMPERR_BAD_SHAPE, TComm("Wrong number of wires: ") << nbWire);
1087     return FaceQuadStruct::Ptr();
1088   }
1089
1090   // find corner vertices of the quad
1091   vector<TopoDS_Vertex> corners;
1092   int nbDegenEdges, nbSides = getCorners( F, aMesh, edges, corners, nbDegenEdges, considerMesh );
1093   if ( nbSides == 0 )
1094   {
1095     return FaceQuadStruct::Ptr();
1096   }
1097   FaceQuadStruct::Ptr quad( new FaceQuadStruct );
1098   quad->side.reserve(nbEdgesInWire.front());
1099   quad->face = F;
1100
1101   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
1102   if ( nbSides == 3 ) // 3 sides and corners[0] is a vertex with myTriaVertexID
1103   {
1104     for ( int iSide = 0; iSide < 3; ++iSide )
1105     {
1106       list< TopoDS_Edge > sideEdges;
1107       TopoDS_Vertex nextSideV = corners[( iSide + 1 ) % 3 ];
1108       while ( edgeIt != edges.end() &&
1109               !nextSideV.IsSame( SMESH_MesherHelper::IthVertex( 0, *edgeIt )))
1110         if ( SMESH_Algo::isDegenerated( *edgeIt ))
1111           ++edgeIt;
1112         else
1113           sideEdges.push_back( *edgeIt++ );
1114       if ( !sideEdges.empty() )
1115         quad->side.push_back( StdMeshers_FaceSide::New(F, sideEdges, &aMesh, iSide < QUAD_TOP_SIDE,
1116                                                        ignoreMediumNodes, myProxyMesh));
1117       else
1118         --iSide;
1119     }
1120     const vector<UVPtStruct>& UVPSleft  = quad->side[0].GetUVPtStruct(true,0);
1121     /*  vector<UVPtStruct>& UVPStop   = */quad->side[1].GetUVPtStruct(false,1);
1122     /*  vector<UVPtStruct>& UVPSright = */quad->side[2].GetUVPtStruct(true,1);
1123     const SMDS_MeshNode* aNode = UVPSleft[0].node;
1124     gp_Pnt2d aPnt2d = UVPSleft[0].UV();
1125     quad->side.push_back( StdMeshers_FaceSide::New( quad->side[1].grid.get(), aNode, &aPnt2d ));
1126     myNeedSmooth = ( nbDegenEdges > 0 );
1127     return quad;
1128   }
1129   else // 4 sides
1130   {
1131     myNeedSmooth = ( corners.size() == 4 && nbDegenEdges > 0 );
1132     int iSide = 0, nbUsedDegen = 0, nbLoops = 0;
1133     for ( ; edgeIt != edges.end(); ++nbLoops )
1134     {
1135       list< TopoDS_Edge > sideEdges;
1136       TopoDS_Vertex nextSideV = corners[( iSide + 1 - nbUsedDegen ) % corners.size() ];
1137       bool nextSideVReached = false;
1138       do
1139       {
1140         const TopoDS_Edge& edge = *edgeIt;
1141         nextSideVReached = nextSideV.IsSame( myHelper->IthVertex( 1, edge ));
1142         if ( SMESH_Algo::isDegenerated( edge ))
1143         {
1144           if ( !myNeedSmooth ) // need to make a side on a degen edge
1145           {
1146             if ( sideEdges.empty() )
1147             {
1148               sideEdges.push_back( edge );
1149               ++nbUsedDegen;
1150             }
1151             else
1152             {
1153               break;
1154             }
1155           }
1156         }
1157         else
1158         {
1159           sideEdges.push_back( edge );
1160         }
1161         ++edgeIt;
1162       }
1163       while ( edgeIt != edges.end() && !nextSideVReached );
1164
1165       if ( !sideEdges.empty() )
1166       {
1167         quad->side.push_back
1168           ( StdMeshers_FaceSide::New( F, sideEdges, &aMesh, iSide < QUAD_TOP_SIDE,
1169                                       ignoreMediumNodes, myProxyMesh ));
1170         ++iSide;
1171       }
1172       if ( quad->side.size() == 4 )
1173         break;
1174       if ( nbLoops > 8 )
1175       {
1176         error(TComm("Bug: infinite loop in StdMeshers_Quadrangle_2D::CheckNbEdges()"));
1177         quad.reset();
1178         break;
1179       }
1180     }
1181     if ( quad && quad->side.size() != 4 )
1182     {
1183       error(TComm("Bug: ") << quad->side.size()  << " sides found instead of 4");
1184       quad.reset();
1185     }
1186   }
1187
1188   return quad;
1189 }
1190
1191
1192 //=============================================================================
1193 /*!
1194  *  
1195  */
1196 //=============================================================================
1197
1198 bool StdMeshers_Quadrangle_2D::checkNbEdgesForEvaluate(SMESH_Mesh&          aMesh,
1199                                                        const TopoDS_Shape & aShape,
1200                                                        MapShapeNbElems&     aResMap,
1201                                                        std::vector<int>&    aNbNodes,
1202                                                        bool&                IsQuadratic)
1203
1204 {
1205   const TopoDS_Face & F = TopoDS::Face(aShape);
1206
1207   // verify 1 wire only, with 4 edges
1208   list< TopoDS_Edge > edges;
1209   list< int > nbEdgesInWire;
1210   int nbWire = SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
1211   if (nbWire != 1) {
1212     return false;
1213   }
1214
1215   aNbNodes.resize(4);
1216
1217   int nbSides = 0;
1218   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
1219   SMESH_subMesh * sm = aMesh.GetSubMesh(*edgeIt);
1220   MapShapeNbElemsItr anIt = aResMap.find(sm);
1221   if (anIt==aResMap.end()) {
1222     return false;
1223   }
1224   std::vector<int> aVec = (*anIt).second;
1225   IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
1226   if (nbEdgesInWire.front() == 3) { // exactly 3 edges
1227     if (myTriaVertexID>0) {
1228       SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1229       TopoDS_Vertex V = TopoDS::Vertex(meshDS->IndexToShape(myTriaVertexID));
1230       if (!V.IsNull()) {
1231         TopoDS_Edge E1,E2,E3;
1232         for (; edgeIt != edges.end(); ++edgeIt) {
1233           TopoDS_Edge E =  TopoDS::Edge(*edgeIt);
1234           TopoDS_Vertex VF, VL;
1235           TopExp::Vertices(E, VF, VL, true);
1236           if (VF.IsSame(V))
1237             E1 = E;
1238           else if (VL.IsSame(V))
1239             E3 = E;
1240           else
1241             E2 = E;
1242         }
1243         SMESH_subMesh * sm = aMesh.GetSubMesh(E1);
1244         MapShapeNbElemsItr anIt = aResMap.find(sm);
1245         if (anIt==aResMap.end()) return false;
1246         std::vector<int> aVec = (*anIt).second;
1247         if (IsQuadratic)
1248           aNbNodes[0] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1249         else
1250           aNbNodes[0] = aVec[SMDSEntity_Node] + 2;
1251         sm = aMesh.GetSubMesh(E2);
1252         anIt = aResMap.find(sm);
1253         if (anIt==aResMap.end()) return false;
1254         aVec = (*anIt).second;
1255         if (IsQuadratic)
1256           aNbNodes[1] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1257         else
1258           aNbNodes[1] = aVec[SMDSEntity_Node] + 2;
1259         sm = aMesh.GetSubMesh(E3);
1260         anIt = aResMap.find(sm);
1261         if (anIt==aResMap.end()) return false;
1262         aVec = (*anIt).second;
1263         if (IsQuadratic)
1264           aNbNodes[2] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1265         else
1266           aNbNodes[2] = aVec[SMDSEntity_Node] + 2;
1267         aNbNodes[3] = aNbNodes[1];
1268         aNbNodes.resize(5);
1269         nbSides = 4;
1270       }
1271     }
1272   }
1273   if (nbEdgesInWire.front() == 4) { // exactly 4 edges
1274     for (; edgeIt != edges.end(); edgeIt++) {
1275       SMESH_subMesh * sm = aMesh.GetSubMesh(*edgeIt);
1276       MapShapeNbElemsItr anIt = aResMap.find(sm);
1277       if (anIt==aResMap.end()) {
1278         return false;
1279       }
1280       std::vector<int> aVec = (*anIt).second;
1281       if (IsQuadratic)
1282         aNbNodes[nbSides] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1283       else
1284         aNbNodes[nbSides] = aVec[SMDSEntity_Node] + 2;
1285       nbSides++;
1286     }
1287   }
1288   else if (nbEdgesInWire.front() > 4) { // more than 4 edges - try to unite some
1289     list< TopoDS_Edge > sideEdges;
1290     while (!edges.empty()) {
1291       sideEdges.clear();
1292       sideEdges.splice(sideEdges.end(), edges, edges.begin()); // edges.front() -> sideEdges.end()
1293       bool sameSide = true;
1294       while (!edges.empty() && sameSide) {
1295         sameSide = SMESH_Algo::IsContinuous(sideEdges.back(), edges.front());
1296         if (sameSide)
1297           sideEdges.splice(sideEdges.end(), edges, edges.begin());
1298       }
1299       if (nbSides == 0) { // go backward from the first edge
1300         sameSide = true;
1301         while (!edges.empty() && sameSide) {
1302           sameSide = SMESH_Algo::IsContinuous(sideEdges.front(), edges.back());
1303           if (sameSide)
1304             sideEdges.splice(sideEdges.begin(), edges, --edges.end());
1305         }
1306       }
1307       list<TopoDS_Edge>::iterator ite = sideEdges.begin();
1308       aNbNodes[nbSides] = 1;
1309       for (; ite!=sideEdges.end(); ite++) {
1310         SMESH_subMesh * sm = aMesh.GetSubMesh(*ite);
1311         MapShapeNbElemsItr anIt = aResMap.find(sm);
1312         if (anIt==aResMap.end()) {
1313           return false;
1314         }
1315         std::vector<int> aVec = (*anIt).second;
1316         if (IsQuadratic)
1317           aNbNodes[nbSides] += (aVec[SMDSEntity_Node]-1)/2 + 1;
1318         else
1319           aNbNodes[nbSides] += aVec[SMDSEntity_Node] + 1;
1320       }
1321       ++nbSides;
1322     }
1323     // issue 20222. Try to unite only edges shared by two same faces
1324     if (nbSides < 4) {
1325       nbSides = 0;
1326       SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
1327       while (!edges.empty()) {
1328         sideEdges.clear();
1329         sideEdges.splice(sideEdges.end(), edges, edges.begin());
1330         bool sameSide = true;
1331         while (!edges.empty() && sameSide) {
1332           sameSide =
1333             SMESH_Algo::IsContinuous(sideEdges.back(), edges.front()) &&
1334             twoEdgesMeatAtVertex(sideEdges.back(), edges.front(), aMesh);
1335           if (sameSide)
1336             sideEdges.splice(sideEdges.end(), edges, edges.begin());
1337         }
1338         if (nbSides == 0) { // go backward from the first edge
1339           sameSide = true;
1340           while (!edges.empty() && sameSide) {
1341             sameSide =
1342               SMESH_Algo::IsContinuous(sideEdges.front(), edges.back()) &&
1343               twoEdgesMeatAtVertex(sideEdges.front(), edges.back(), aMesh);
1344             if (sameSide)
1345               sideEdges.splice(sideEdges.begin(), edges, --edges.end());
1346           }
1347         }
1348         list<TopoDS_Edge>::iterator ite = sideEdges.begin();
1349         aNbNodes[nbSides] = 1;
1350         for (; ite!=sideEdges.end(); ite++) {
1351           SMESH_subMesh * sm = aMesh.GetSubMesh(*ite);
1352           MapShapeNbElemsItr anIt = aResMap.find(sm);
1353           if (anIt==aResMap.end()) {
1354             return false;
1355           }
1356           std::vector<int> aVec = (*anIt).second;
1357           if (IsQuadratic)
1358             aNbNodes[nbSides] += (aVec[SMDSEntity_Node]-1)/2 + 1;
1359           else
1360             aNbNodes[nbSides] += aVec[SMDSEntity_Node] + 1;
1361         }
1362         ++nbSides;
1363       }
1364     }
1365   }
1366   if (nbSides != 4) {
1367     if (!nbSides)
1368       nbSides = nbEdgesInWire.front();
1369     error(COMPERR_BAD_SHAPE, TComm("Face must have 4 sides but not ") << nbSides);
1370     return false;
1371   }
1372
1373   return true;
1374 }
1375
1376
1377 //=============================================================================
1378 /*!
1379  *  CheckAnd2Dcompute
1380  */
1381 //=============================================================================
1382
1383 FaceQuadStruct::Ptr
1384 StdMeshers_Quadrangle_2D::CheckAnd2Dcompute (SMESH_Mesh &         aMesh,
1385                                              const TopoDS_Shape & aShape,
1386                                              const bool           CreateQuadratic)
1387 {
1388   _quadraticMesh = CreateQuadratic;
1389
1390   FaceQuadStruct::Ptr quad = CheckNbEdges(aMesh, aShape);
1391   if ( quad )
1392   {
1393     // set normalized grid on unit square in parametric domain
1394     if ( ! setNormalizedGrid( quad ))
1395       quad.reset();
1396   }
1397   return quad;
1398 }
1399
1400 namespace
1401 {
1402   inline const vector<UVPtStruct>& getUVPtStructIn(FaceQuadStruct::Ptr& quad, int i, int nbSeg)
1403   {
1404     bool   isXConst   = (i == QUAD_BOTTOM_SIDE || i == QUAD_TOP_SIDE);
1405     double constValue = (i == QUAD_BOTTOM_SIDE || i == QUAD_LEFT_SIDE) ? 0 : 1;
1406     return
1407       quad->nbNodeOut(i) ?
1408       quad->side[i].grid->SimulateUVPtStruct(nbSeg,isXConst,constValue) :
1409       quad->side[i].grid->GetUVPtStruct     (isXConst,constValue);
1410   }
1411   inline gp_UV calcUV(double x, double y,
1412                       const gp_UV& a0,const gp_UV& a1,const gp_UV& a2,const gp_UV& a3,
1413                       const gp_UV& p0,const gp_UV& p1,const gp_UV& p2,const gp_UV& p3)
1414   {
1415     return
1416       ((1 - y) * p0 + x * p1 + y * p2 + (1 - x) * p3 ) -
1417       ((1 - x) * (1 - y) * a0 + x * (1 - y) * a1 + x * y * a2 + (1 - x) * y * a3);
1418   }
1419 }
1420
1421 //=============================================================================
1422 /*!
1423  *  
1424  */
1425 //=============================================================================
1426
1427 bool StdMeshers_Quadrangle_2D::setNormalizedGrid (FaceQuadStruct::Ptr quad)
1428 {
1429   if ( !quad->uv_grid.empty() )
1430     return true;
1431
1432   // Algorithme décrit dans "Génération automatique de maillages"
1433   // P.L. GEORGE, MASSON, Â§ 6.4.1 p. 84-85
1434   // traitement dans le domaine paramétrique 2d u,v
1435   // transport - projection sur le carré unité
1436
1437   //      max             min                    0     x1     1
1438   //     |<----north-2-------^                a3 -------------> a2
1439   //     |                   |                   ^1          1^
1440   //    west-3            east-1 =right          |            |
1441   //     |                   |         ==>       |            |
1442   //  y0 |                   | y1                |            |
1443   //     |                   |                   |0          0|
1444   //     v----south-0-------->                a0 -------------> a1
1445   //      min             max                    0     x0     1
1446   //             =down
1447   //
1448   const FaceQuadStruct::Side & bSide = quad->side[0];
1449   const FaceQuadStruct::Side & rSide = quad->side[1];
1450   const FaceQuadStruct::Side & tSide = quad->side[2];
1451   const FaceQuadStruct::Side & lSide = quad->side[3];
1452
1453   int nbhoriz  = Min( bSide.NbPoints(), tSide.NbPoints() );
1454   int nbvertic = Min( rSide.NbPoints(), lSide.NbPoints() );
1455
1456   if ( myQuadList.size() == 1 )
1457   {
1458     // all sub-quads must have NO sides with nbNodeOut > 0
1459     quad->nbNodeOut(0) = Max( 0, bSide.grid->NbPoints() - tSide.grid->NbPoints() );
1460     quad->nbNodeOut(1) = Max( 0, rSide.grid->NbPoints() - lSide.grid->NbPoints() );
1461     quad->nbNodeOut(2) = Max( 0, tSide.grid->NbPoints() - bSide.grid->NbPoints() );
1462     quad->nbNodeOut(3) = Max( 0, lSide.grid->NbPoints() - rSide.grid->NbPoints() );
1463   }
1464   const vector<UVPtStruct>& uv_e0 = bSide.GetUVPtStruct();
1465   const vector<UVPtStruct>& uv_e1 = rSide.GetUVPtStruct();
1466   const vector<UVPtStruct>& uv_e2 = tSide.GetUVPtStruct();
1467   const vector<UVPtStruct>& uv_e3 = lSide.GetUVPtStruct();
1468   if (uv_e0.empty() || uv_e1.empty() || uv_e2.empty() || uv_e3.empty())
1469     //return error("Can't find nodes on sides");
1470     return error(COMPERR_BAD_INPUT_MESH);
1471
1472   quad->uv_grid.resize( nbvertic * nbhoriz );
1473   quad->iSize = nbhoriz;
1474   quad->jSize = nbvertic;
1475   UVPtStruct *uv_grid = & quad->uv_grid[0];
1476
1477   quad->uv_box.Clear();
1478
1479   // copy data of face boundary
1480
1481   FaceQuadStruct::SideIterator sideIter;
1482
1483   { // BOTTOM
1484     const int     j = 0;
1485     const double x0 = bSide.First().normParam;
1486     const double dx = bSide.Last().normParam - bSide.First().normParam;
1487     for ( sideIter.Init( bSide ); sideIter.More(); sideIter.Next() ) {
1488       sideIter.UVPt().x = ( sideIter.UVPt().normParam - x0 ) / dx;
1489       sideIter.UVPt().y = 0.;
1490       uv_grid[ j * nbhoriz + sideIter.Count() ] = sideIter.UVPt();
1491       quad->uv_box.Add( sideIter.UVPt().UV() );
1492     }
1493   }
1494   { // RIGHT
1495     const int     i = nbhoriz - 1;
1496     const double y0 = rSide.First().normParam;
1497     const double dy = rSide.Last().normParam - rSide.First().normParam;
1498     sideIter.Init( rSide );
1499     if ( quad->UVPt( i, sideIter.Count() ).node )
1500       sideIter.Next(); // avoid copying from a split emulated side
1501     for ( ; sideIter.More(); sideIter.Next() ) {
1502       sideIter.UVPt().x = 1.;
1503       sideIter.UVPt().y = ( sideIter.UVPt().normParam - y0 ) / dy;
1504       uv_grid[ sideIter.Count() * nbhoriz + i ] = sideIter.UVPt();
1505       quad->uv_box.Add( sideIter.UVPt().UV() );
1506     }
1507   }
1508   { // TOP
1509     const int     j = nbvertic - 1;
1510     const double x0 = tSide.First().normParam;
1511     const double dx = tSide.Last().normParam - tSide.First().normParam;
1512     int i = 0, nb = nbhoriz;
1513     sideIter.Init( tSide );
1514     if ( quad->UVPt( nb-1, j ).node ) --nb; // avoid copying from a split emulated side
1515     for ( ; i < nb; i++, sideIter.Next()) {
1516       sideIter.UVPt().x = ( sideIter.UVPt().normParam - x0 ) / dx;
1517       sideIter.UVPt().y = 1.;
1518       uv_grid[ j * nbhoriz + i ] = sideIter.UVPt();
1519       quad->uv_box.Add( sideIter.UVPt().UV() );
1520     }
1521   }
1522   { // LEFT
1523     const int i = 0;
1524     const double y0 = lSide.First().normParam;
1525     const double dy = lSide.Last().normParam - lSide.First().normParam;
1526     int j = 0, nb = nbvertic;
1527     sideIter.Init( lSide );
1528     if ( quad->UVPt( i, j    ).node )
1529       ++j, sideIter.Next(); // avoid copying from a split emulated side
1530     if ( quad->UVPt( i, nb-1 ).node )
1531       --nb;
1532     for ( ; j < nb; j++, sideIter.Next()) {
1533       sideIter.UVPt().x = 0.;
1534       sideIter.UVPt().y = ( sideIter.UVPt().normParam - y0 ) / dy;
1535       uv_grid[ j * nbhoriz + i ] = sideIter.UVPt();
1536       quad->uv_box.Add( sideIter.UVPt().UV() );
1537     }
1538   }
1539
1540   // normalized 2d parameters on grid
1541
1542   for (int i = 1; i < nbhoriz-1; i++)
1543   {
1544     const double x0 = quad->UVPt( i, 0          ).x;
1545     const double x1 = quad->UVPt( i, nbvertic-1 ).x;
1546     for (int j = 1; j < nbvertic-1; j++)
1547     {
1548       const double y0 = quad->UVPt( 0,         j ).y;
1549       const double y1 = quad->UVPt( nbhoriz-1, j ).y;
1550       // --- intersection : x=x0+(y0+x(y1-y0))(x1-x0)
1551       double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1552       double y = y0 + x * (y1 - y0);
1553       int   ij = j * nbhoriz + i;
1554       uv_grid[ij].x = x;
1555       uv_grid[ij].y = y;
1556       uv_grid[ij].node = NULL;
1557     }
1558   }
1559
1560   // projection on 2d domain (u,v)
1561
1562   gp_UV a0 = quad->UVPt( 0,         0          ).UV();
1563   gp_UV a1 = quad->UVPt( nbhoriz-1, 0          ).UV();
1564   gp_UV a2 = quad->UVPt( nbhoriz-1, nbvertic-1 ).UV();
1565   gp_UV a3 = quad->UVPt( 0,         nbvertic-1 ).UV();
1566
1567   for (int i = 1; i < nbhoriz-1; i++)
1568   {
1569     gp_UV p0 = quad->UVPt( i, 0          ).UV();
1570     gp_UV p2 = quad->UVPt( i, nbvertic-1 ).UV();
1571     for (int j = 1; j < nbvertic-1; j++)
1572     {
1573       gp_UV p1 = quad->UVPt( nbhoriz-1, j ).UV();
1574       gp_UV p3 = quad->UVPt( 0,         j ).UV();
1575
1576       int ij = j * nbhoriz + i;
1577       double x = uv_grid[ij].x;
1578       double y = uv_grid[ij].y;
1579
1580       gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1581
1582       uv_grid[ij].u = uv.X();
1583       uv_grid[ij].v = uv.Y();
1584     }
1585   }
1586   return true;
1587 }
1588
1589 //=======================================================================
1590 //function : ShiftQuad
1591 //purpose  : auxilary function for computeQuadPref
1592 //=======================================================================
1593
1594 void StdMeshers_Quadrangle_2D::shiftQuad(FaceQuadStruct::Ptr& quad, const int num )
1595 {
1596   quad->shift( num, /*ori=*/true, /*keepGrid=*/myQuadList.size() > 1 );
1597 }
1598
1599 //================================================================================
1600 /*!
1601  * \brief Rotate sides of a quad by given nb of quartes
1602  *  \param nb  - number of rotation quartes
1603  *  \param ori - to keep orientation of sides as in an unit quad or not
1604  *  \param keepGrid - if \c true Side::grid is not changed, Side::from and Side::to
1605  *         are altered instead
1606  */
1607 //================================================================================
1608
1609 void FaceQuadStruct::shift( size_t nb, bool ori, bool keepGrid )
1610 {
1611   if ( nb == 0 ) return;
1612
1613   vector< Side > newSides( side.size() );
1614   vector< Side* > sidePtrs( side.size() );
1615   for (int i = QUAD_BOTTOM_SIDE; i < NB_QUAD_SIDES; ++i)
1616   {
1617     int id = (i + nb) % NB_QUAD_SIDES;
1618     if ( ori )
1619     {
1620       bool wasForward = (i  < QUAD_TOP_SIDE);
1621       bool newForward = (id < QUAD_TOP_SIDE);
1622       if ( wasForward != newForward )
1623         side[ i ].Reverse( keepGrid );
1624     }
1625     newSides[ id ] = side[ i ];
1626     sidePtrs[ i ] = & side[ i ];
1627   }
1628   // make newSides refer newSides via Side::Contact's
1629   for ( size_t i = 0; i < newSides.size(); ++i )
1630   {
1631     FaceQuadStruct::Side& ns = newSides[ i ];
1632     for ( size_t iC = 0; iC < ns.contacts.size(); ++iC )
1633     {
1634       FaceQuadStruct::Side* oSide = ns.contacts[iC].other_side;
1635       vector< Side* >::iterator sIt = std::find( sidePtrs.begin(), sidePtrs.end(), oSide );
1636       if ( sIt != sidePtrs.end() )
1637         ns.contacts[iC].other_side = & newSides[ *sIt - sidePtrs[0] ];
1638     }
1639   }
1640   newSides.swap( side );
1641
1642   uv_grid.clear();
1643 }
1644
1645 //=======================================================================
1646 //function : calcUV
1647 //purpose  : auxilary function for computeQuadPref
1648 //=======================================================================
1649
1650 static gp_UV calcUV(double x0, double x1, double y0, double y1,
1651                     FaceQuadStruct::Ptr& quad,
1652                     const gp_UV& a0, const gp_UV& a1,
1653                     const gp_UV& a2, const gp_UV& a3)
1654 {
1655   double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1656   double y = y0 + x * (y1 - y0);
1657
1658   gp_UV p0 = quad->side[QUAD_BOTTOM_SIDE].grid->Value2d(x).XY();
1659   gp_UV p1 = quad->side[QUAD_RIGHT_SIDE ].grid->Value2d(y).XY();
1660   gp_UV p2 = quad->side[QUAD_TOP_SIDE   ].grid->Value2d(x).XY();
1661   gp_UV p3 = quad->side[QUAD_LEFT_SIDE  ].grid->Value2d(y).XY();
1662
1663   gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1664
1665   return uv;
1666 }
1667
1668 //=======================================================================
1669 //function : calcUV2
1670 //purpose  : auxilary function for computeQuadPref
1671 //=======================================================================
1672
1673 static gp_UV calcUV2(double x, double y,
1674                      FaceQuadStruct::Ptr& quad,
1675                      const gp_UV& a0, const gp_UV& a1,
1676                      const gp_UV& a2, const gp_UV& a3)
1677 {
1678   gp_UV p0 = quad->side[QUAD_BOTTOM_SIDE].grid->Value2d(x).XY();
1679   gp_UV p1 = quad->side[QUAD_RIGHT_SIDE ].grid->Value2d(y).XY();
1680   gp_UV p2 = quad->side[QUAD_TOP_SIDE   ].grid->Value2d(x).XY();
1681   gp_UV p3 = quad->side[QUAD_LEFT_SIDE  ].grid->Value2d(y).XY();
1682
1683   gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1684
1685   return uv;
1686 }
1687
1688
1689 //=======================================================================
1690 /*!
1691  * Create only quandrangle faces
1692  */
1693 //=======================================================================
1694
1695 bool StdMeshers_Quadrangle_2D::computeQuadPref (SMESH_Mesh &        aMesh,
1696                                                 const TopoDS_Face&  aFace,
1697                                                 FaceQuadStruct::Ptr quad)
1698 {
1699   const bool OldVersion = (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED);
1700   const bool WisF = true;
1701
1702   SMESHDS_Mesh *  meshDS = aMesh.GetMeshDS();
1703   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace);
1704   int i,j,    geomFaceID = meshDS->ShapeToIndex(aFace);
1705
1706   int nb = quad->side[0].NbPoints();
1707   int nr = quad->side[1].NbPoints();
1708   int nt = quad->side[2].NbPoints();
1709   int nl = quad->side[3].NbPoints();
1710   int dh = abs(nb-nt);
1711   int dv = abs(nr-nl);
1712
1713   if ( myForcedPnts.empty() )
1714   {
1715     // rotate sides to be as in the picture below and to have
1716     // dh >= dv and nt > nb
1717     if ( dh >= dv )
1718       shiftQuad( quad, ( nt > nb ) ? 0 : 2 );
1719     else
1720       shiftQuad( quad, ( nr > nl ) ? 1 : 3 );
1721   }
1722   else
1723   {
1724     // rotate the quad to have nt > nb [and nr > nl]
1725     if ( nb > nt )
1726       shiftQuad ( quad, nr > nl ? 1 : 2 );
1727     else if ( nr > nl )
1728       shiftQuad( quad, nb == nt ? 1 : 0 );
1729     else if ( nl > nr )
1730       shiftQuad( quad, 3 );
1731   }
1732
1733   nb = quad->side[0].NbPoints();
1734   nr = quad->side[1].NbPoints();
1735   nt = quad->side[2].NbPoints();
1736   nl = quad->side[3].NbPoints();
1737   dh = abs(nb-nt);
1738   dv = abs(nr-nl);
1739   int nbh  = Max(nb,nt);
1740   int nbv  = Max(nr,nl);
1741   int addh = 0;
1742   int addv = 0;
1743
1744   // Orientation of face and 3 main domain for future faces
1745   // ----------- Old version ---------------
1746   //       0   top    1
1747   //      1------------1
1748   //       |   |  |   |
1749   //       |   |C |   |
1750   //       | L |  | R |
1751   //  left |   |__|   | rigth
1752   //       |  /    \  |
1753   //       | /  C   \ |
1754   //       |/        \|
1755   //      0------------0
1756   //       0  bottom  1
1757
1758   // ----------- New version ---------------
1759   //       0   top    1
1760   //      1------------1
1761   //       |   |__|   |
1762   //       |  /    \  |
1763   //       | /  C   \ |
1764   //  left |/________\| rigth
1765   //       |          |
1766   //       |    C     |
1767   //       |          |
1768   //      0------------0
1769   //       0  bottom  1
1770
1771
1772   const int bfrom = quad->side[0].from;
1773   const int rfrom = quad->side[1].from;
1774   const int tfrom = quad->side[2].from;
1775   const int lfrom = quad->side[3].from;
1776   {
1777     const vector<UVPtStruct>& uv_eb_vec = quad->side[0].GetUVPtStruct(true,0);
1778     const vector<UVPtStruct>& uv_er_vec = quad->side[1].GetUVPtStruct(false,1);
1779     const vector<UVPtStruct>& uv_et_vec = quad->side[2].GetUVPtStruct(true,1);
1780     const vector<UVPtStruct>& uv_el_vec = quad->side[3].GetUVPtStruct(false,0);
1781     if (uv_eb_vec.empty() ||
1782         uv_er_vec.empty() ||
1783         uv_et_vec.empty() ||
1784         uv_el_vec.empty())
1785       return error(COMPERR_BAD_INPUT_MESH);
1786   }
1787   FaceQuadStruct::SideIterator uv_eb, uv_er, uv_et, uv_el;
1788   uv_eb.Init( quad->side[0] );
1789   uv_er.Init( quad->side[1] );
1790   uv_et.Init( quad->side[2] );
1791   uv_el.Init( quad->side[3] );
1792
1793   gp_UV a0,a1,a2,a3, p0,p1,p2,p3, uv;
1794   double x,y;
1795
1796   a0 = uv_eb[ 0 ].UV();
1797   a1 = uv_er[ 0 ].UV();
1798   a2 = uv_er[ nr-1 ].UV();
1799   a3 = uv_et[ 0 ].UV();
1800
1801   if ( !myForcedPnts.empty() )
1802   {
1803     if ( dv != 0 && dh != 0 ) // here myQuadList.size() == 1
1804     {
1805       const int dmin = Min( dv, dh );
1806
1807       // Make a side separating domains L and Cb
1808       StdMeshers_FaceSidePtr sideLCb;
1809       UVPtStruct p3dom; // a point where 3 domains meat
1810       {                                                     //   dmin
1811         vector<UVPtStruct> pointsLCb( dmin+1 );             // 1--------1
1812         pointsLCb[0] = uv_eb[0];                            //  |   |  |
1813         for ( int i = 1; i <= dmin; ++i )                   //  |   |Ct|
1814         {                                                   //  | L |  |
1815           x  = uv_et[ i ].normParam;                        //  |   |__|
1816           y  = uv_er[ i ].normParam;                        //  |  /   |
1817           p0 = quad->side[0].grid->Value2d( x ).XY();       //  | / Cb |dmin
1818           p1 = uv_er[ i ].UV();                             //  |/     |
1819           p2 = uv_et[ i ].UV();                             // 0--------0
1820           p3 = quad->side[3].grid->Value2d( y ).XY();
1821           uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1822           pointsLCb[ i ].u = uv.X();
1823           pointsLCb[ i ].v = uv.Y();
1824         }
1825         sideLCb = StdMeshers_FaceSide::New( pointsLCb, aFace );
1826         p3dom   = pointsLCb.back();
1827       }
1828       // Make a side separating domains L and Ct
1829       StdMeshers_FaceSidePtr sideLCt;
1830       {
1831         vector<UVPtStruct> pointsLCt( nl );
1832         pointsLCt[0]     = p3dom;
1833         pointsLCt.back() = uv_et[ dmin ];
1834         x  = uv_et[ dmin ].normParam;
1835         p0 = quad->side[0].grid->Value2d( x ).XY();
1836         p2 = uv_et[ dmin ].UV();
1837         double y0 = uv_er[ dmin ].normParam;
1838         for ( int i = 1; i < nl-1; ++i )
1839         {
1840           y  = y0 + i / ( nl-1. ) * ( 1. - y0 );
1841           p1 = quad->side[1].grid->Value2d( y ).XY();
1842           p3 = quad->side[3].grid->Value2d( y ).XY();
1843           uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1844           pointsLCt[ i ].u = uv.X();
1845           pointsLCt[ i ].v = uv.Y();
1846         }
1847         sideLCt = StdMeshers_FaceSide::New( pointsLCt, aFace );
1848       }
1849       // Make a side separating domains Cb and Ct
1850       StdMeshers_FaceSidePtr sideCbCt;
1851       {
1852         vector<UVPtStruct> pointsCbCt( nb );
1853         pointsCbCt[0]     = p3dom;
1854         pointsCbCt.back() = uv_er[ dmin ];
1855         y  = uv_er[ dmin ].normParam;
1856         p1 = uv_er[ dmin ].UV();
1857         p3 = quad->side[3].grid->Value2d( y ).XY();
1858         double x0 = uv_et[ dmin ].normParam;
1859         for ( int i = 1; i < nb-1; ++i )
1860         {
1861           x  = x0 + i / ( nb-1. ) * ( 1. - x0 );
1862           p2 = quad->side[2].grid->Value2d( x ).XY();
1863           p0 = quad->side[0].grid->Value2d( x ).XY();
1864           uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1865           pointsCbCt[ i ].u = uv.X();
1866           pointsCbCt[ i ].v = uv.Y();
1867         }
1868         sideCbCt = StdMeshers_FaceSide::New( pointsCbCt, aFace );
1869       }
1870       // Make Cb quad
1871       FaceQuadStruct* qCb = new FaceQuadStruct( quad->face, "Cb" );
1872       myQuadList.push_back( FaceQuadStruct::Ptr( qCb ));
1873       qCb->side.resize(4);
1874       qCb->side[0] = quad->side[0];
1875       qCb->side[1] = quad->side[1];
1876       qCb->side[2] = sideCbCt;
1877       qCb->side[3] = sideLCb;
1878       qCb->side[1].to = dmin+1;
1879       // Make L quad
1880       FaceQuadStruct* qL = new FaceQuadStruct( quad->face, "L" );
1881       myQuadList.push_back( FaceQuadStruct::Ptr( qL ));
1882       qL->side.resize(4);
1883       qL->side[0] = sideLCb;
1884       qL->side[1] = sideLCt;
1885       qL->side[2] = quad->side[2];
1886       qL->side[3] = quad->side[3];
1887       qL->side[2].to = dmin+1;
1888       // Make Ct from the main quad
1889       FaceQuadStruct::Ptr qCt = quad;
1890       qCt->side[0] = sideCbCt;
1891       qCt->side[3] = sideLCt;
1892       qCt->side[1].from = dmin;
1893       qCt->side[2].from = dmin;
1894       qCt->uv_grid.clear();
1895       qCt->name = "Ct";
1896
1897       // Connect sides
1898       qCb->side[3].AddContact( dmin, & qCb->side[2], 0 );
1899       qCb->side[3].AddContact( dmin, & qCt->side[3], 0 );
1900       qCt->side[3].AddContact(    0, & qCt->side[0], 0 );
1901       qCt->side[0].AddContact(    0, & qL ->side[0], dmin );
1902       qL ->side[0].AddContact( dmin, & qL ->side[1], 0 );
1903       qL ->side[0].AddContact( dmin, & qCb->side[2], 0 );
1904
1905       if ( dh == dv )
1906         return computeQuadDominant( aMesh, aFace );
1907       else
1908         return computeQuadPref( aMesh, aFace, qCt );
1909
1910     } // if ( dv != 0 && dh != 0 )
1911
1912     const int db = quad->side[0].IsReversed() ? -1 : +1;
1913     const int dr = quad->side[1].IsReversed() ? -1 : +1;
1914     const int dt = quad->side[2].IsReversed() ? -1 : +1;
1915     const int dl = quad->side[3].IsReversed() ? -1 : +1;
1916
1917     // Case dv == 0,  here possibly myQuadList.size() > 1
1918     //
1919     //     lw   nb  lw = dh/2
1920     //    +------------+
1921     //    |   |    |   |
1922     //    |   | Ct |   |
1923     //    | L |    | R |
1924     //    |   |____|   |
1925     //    |  /      \  |
1926     //    | /   Cb   \ |
1927     //    |/          \|
1928     //    +------------+
1929     const int lw = dh/2; // lateral width
1930
1931     double yCbL, yCbR;
1932     {
1933       double   lL = quad->side[3].Length();
1934       double lLwL = quad->side[2].Length( tfrom,
1935                                           tfrom + ( lw ) * dt );
1936       yCbL = lLwL / ( lLwL + lL );
1937
1938       double   lR = quad->side[1].Length();
1939       double lLwR = quad->side[2].Length( tfrom + ( lw + nb-1 ) * dt,
1940                                           tfrom + ( lw + nb-1 + lw ) * dt);
1941       yCbR = lLwR / ( lLwR + lR );
1942     }
1943     // Make sides separating domains Cb and L and R
1944     StdMeshers_FaceSidePtr sideLCb, sideRCb;
1945     UVPtStruct pTBL, pTBR; // points where 3 domains meat
1946     {
1947       vector<UVPtStruct> pointsLCb( lw+1 ), pointsRCb( lw+1 );
1948       pointsLCb[0] = uv_eb[ 0    ];
1949       pointsRCb[0] = uv_eb[ nb-1 ];
1950       for ( int i = 1, i2 = nt-2; i <= lw; ++i, --i2 )
1951       {
1952         x  = quad->side[2].Param( i );
1953         y  = yCbL * i / lw;
1954         p0 = quad->side[0].Value2d( x );
1955         p1 = quad->side[1].Value2d( y );
1956         p2 = uv_et[ i ].UV();
1957         p3 = quad->side[3].Value2d( y );
1958         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1959         pointsLCb[ i ].u = uv.X();
1960         pointsLCb[ i ].v = uv.Y();
1961         pointsLCb[ i ].x = x;
1962
1963         x  = quad->side[2].Param( i2 );
1964         y  = yCbR * i / lw;
1965         p1 = quad->side[1].Value2d( y );
1966         p0 = quad->side[0].Value2d( x );
1967         p2 = uv_et[ i2 ].UV();
1968         p3 = quad->side[3].Value2d( y );
1969         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1970         pointsRCb[ i ].u = uv.X();
1971         pointsRCb[ i ].v = uv.Y();
1972         pointsRCb[ i ].x = x;
1973       }
1974       sideLCb = StdMeshers_FaceSide::New( pointsLCb, aFace );
1975       sideRCb = StdMeshers_FaceSide::New( pointsRCb, aFace );
1976       pTBL    = pointsLCb.back();
1977       pTBR    = pointsRCb.back();
1978     }
1979     // Make sides separating domains Ct and L and R
1980     StdMeshers_FaceSidePtr sideLCt, sideRCt;
1981     {
1982       vector<UVPtStruct> pointsLCt( nl ), pointsRCt( nl );
1983       pointsLCt[0]     = pTBL;
1984       pointsLCt.back() = uv_et[ lw ];
1985       pointsRCt[0]     = pTBR;
1986       pointsRCt.back() = uv_et[ lw + nb - 1 ];
1987       x  = pTBL.x;
1988       p0 = quad->side[0].Value2d( x );
1989       p2 = uv_et[ lw ].UV();
1990       int     iR = lw + nb - 1;
1991       double  xR = pTBR.x;
1992       gp_UV  p0R = quad->side[0].Value2d( xR );
1993       gp_UV  p2R = uv_et[ iR ].UV();
1994       for ( int i = 1; i < nl-1; ++i )
1995       {
1996         y  = yCbL + ( 1. - yCbL ) * i / (nl-1.);
1997         p1 = quad->side[1].Value2d( y );
1998         p3 = quad->side[3].Value2d( y );
1999         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
2000         pointsLCt[ i ].u = uv.X();
2001         pointsLCt[ i ].v = uv.Y();
2002
2003         y  = yCbR + ( 1. - yCbR ) * i / (nl-1.);
2004         p1 = quad->side[1].Value2d( y );
2005         p3 = quad->side[3].Value2d( y );
2006         uv = calcUV( xR,y, a0,a1,a2,a3, p0R,p1,p2R,p3 );
2007         pointsRCt[ i ].u = uv.X();
2008         pointsRCt[ i ].v = uv.Y();
2009       }
2010       sideLCt = StdMeshers_FaceSide::New( pointsLCt, aFace );
2011       sideRCt = StdMeshers_FaceSide::New( pointsRCt, aFace );
2012     }
2013     // Make a side separating domains Cb and Ct
2014     StdMeshers_FaceSidePtr sideCbCt;
2015     {
2016       vector<UVPtStruct> pointsCbCt( nb );
2017       pointsCbCt[0]     = pTBL;
2018       pointsCbCt.back() = pTBR;
2019       p1 = quad->side[1].Value2d( yCbR );
2020       p3 = quad->side[3].Value2d( yCbL );
2021       for ( int i = 1; i < nb-1; ++i )
2022       {
2023         x  = quad->side[2].Param( i + lw );
2024         y  = yCbL + ( yCbR - yCbL ) * i / (nb-1.);
2025         p2 = uv_et[ i + lw ].UV();
2026         p0 = quad->side[0].Value2d( x );
2027         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
2028         pointsCbCt[ i ].u = uv.X();
2029         pointsCbCt[ i ].v = uv.Y();
2030       }
2031       sideCbCt = StdMeshers_FaceSide::New( pointsCbCt, aFace );
2032     }
2033     // Make Cb quad
2034     FaceQuadStruct* qCb = new FaceQuadStruct( quad->face, "Cb" );
2035     myQuadList.push_back( FaceQuadStruct::Ptr( qCb ));
2036     qCb->side.resize(4);
2037     qCb->side[0] = quad->side[0];
2038     qCb->side[1] = sideRCb;
2039     qCb->side[2] = sideCbCt;
2040     qCb->side[3] = sideLCb;
2041     // Make L quad
2042     FaceQuadStruct* qL = new FaceQuadStruct( quad->face, "L" );
2043     myQuadList.push_back( FaceQuadStruct::Ptr( qL ));
2044     qL->side.resize(4);
2045     qL->side[0] = sideLCb;
2046     qL->side[1] = sideLCt;
2047     qL->side[2] = quad->side[2];
2048     qL->side[3] = quad->side[3];
2049     qL->side[2].to = ( lw + 1 ) * dt + tfrom;
2050     // Make R quad
2051     FaceQuadStruct* qR = new FaceQuadStruct( quad->face, "R" );
2052     myQuadList.push_back( FaceQuadStruct::Ptr( qR ));
2053     qR->side.resize(4);
2054     qR->side[0] = sideRCb;
2055     qR->side[0].from = lw;
2056     qR->side[0].to   = -1;
2057     qR->side[0].di   = -1;
2058     qR->side[1] = quad->side[1];
2059     qR->side[2] = quad->side[2];
2060     qR->side[2].from = ( lw + nb-1 ) * dt + tfrom;
2061     qR->side[3] = sideRCt;
2062     // Make Ct from the main quad
2063     FaceQuadStruct::Ptr qCt = quad;
2064     qCt->side[0] = sideCbCt;
2065     qCt->side[1] = sideRCt;
2066     qCt->side[2].from = ( lw ) * dt + tfrom;
2067     qCt->side[2].to   = ( lw + nb ) * dt + tfrom;
2068     qCt->side[3] = sideLCt;
2069     qCt->uv_grid.clear();
2070     qCt->name = "Ct";
2071
2072     // Connect sides
2073     qCb->side[3].AddContact( lw, & qCb->side[2], 0 );
2074     qCb->side[3].AddContact( lw, & qCt->side[3], 0 );
2075     qCt->side[3].AddContact( 0,  & qCt->side[0], 0 );
2076     qCt->side[0].AddContact( 0,  & qL ->side[0], lw );
2077     qL ->side[0].AddContact( lw, & qL ->side[1], 0 );
2078     qL ->side[0].AddContact( lw, & qCb->side[2], 0 );
2079     //
2080     qCb->side[1].AddContact( lw,   & qCb->side[2], nb-1 );
2081     qCb->side[1].AddContact( lw,   & qCt->side[1], 0 );
2082     qCt->side[0].AddContact( nb-1, & qCt->side[1], 0 );
2083     qCt->side[0].AddContact( nb-1, & qR ->side[0], lw );
2084     qR ->side[3].AddContact( 0,    & qR ->side[0], lw );
2085     qR ->side[3].AddContact( 0,    & qCb->side[2], nb-1 );
2086
2087     return computeQuadDominant( aMesh, aFace );
2088
2089   } // if ( !myForcedPnts.empty() )
2090
2091   if ( dh > dv ) {
2092     addv = (dh-dv)/2;
2093     nbv  = nbv + addv;
2094   }
2095   else { // dv >= dh
2096     addh = (dv-dh)/2;
2097     nbh  = nbh + addh;
2098   }
2099
2100   // arrays for normalized params
2101   TColStd_SequenceOfReal npb, npr, npt, npl;
2102   for (i=0; i<nb; i++) {
2103     npb.Append(uv_eb[i].normParam);
2104   }
2105   for (i=0; i<nr; i++) {
2106     npr.Append(uv_er[i].normParam);
2107   }
2108   for (i=0; i<nt; i++) {
2109     npt.Append(uv_et[i].normParam);
2110   }
2111   for (i=0; i<nl; i++) {
2112     npl.Append(uv_el[i].normParam);
2113   }
2114
2115   int dl,dr;
2116   if (OldVersion) {
2117     // add some params to right and left after the first param
2118     // insert to right
2119     dr = nbv - nr;
2120     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
2121     for (i=1; i<=dr; i++) {
2122       npr.InsertAfter(1,npr.Value(2)-dpr);
2123     }
2124     // insert to left
2125     dl = nbv - nl;
2126     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
2127     for (i=1; i<=dl; i++) {
2128       npl.InsertAfter(1,npl.Value(2)-dpr);
2129     }
2130   }
2131
2132   int nnn = Min(nr,nl);
2133   // auxilary sequence of XY for creation nodes
2134   // in the bottom part of central domain
2135   // Length of UVL and UVR must be == nbv-nnn
2136   TColgp_SequenceOfXY UVL, UVR, UVT;
2137
2138   if (OldVersion) {
2139     // step1: create faces for left domain
2140     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
2141     // add left nodes
2142     for (j=1; j<=nl; j++)
2143       NodesL.SetValue(1,j,uv_el[j-1].node);
2144     if (dl>0) {
2145       // add top nodes
2146       for (i=1; i<=dl; i++)
2147         NodesL.SetValue(i+1,nl,uv_et[i].node);
2148       // create and add needed nodes
2149       TColgp_SequenceOfXY UVtmp;
2150       for (i=1; i<=dl; i++) {
2151         double x0 = npt.Value(i+1);
2152         double x1 = x0;
2153         // diagonal node
2154         double y0 = npl.Value(i+1);
2155         double y1 = npr.Value(i+1);
2156         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2157         gp_Pnt P = S->Value(UV.X(),UV.Y());
2158         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2159         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2160         NodesL.SetValue(i+1,1,N);
2161         if (UVL.Length()<nbv-nnn) UVL.Append(UV);
2162         // internal nodes
2163         for (j=2; j<nl; j++) {
2164           double y0 = npl.Value(dl+j);
2165           double y1 = npr.Value(dl+j);
2166           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2167           gp_Pnt P = S->Value(UV.X(),UV.Y());
2168           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2169           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2170           NodesL.SetValue(i+1,j,N);
2171           if (i==dl) UVtmp.Append(UV);
2172         }
2173       }
2174       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn; i++) {
2175         UVL.Append(UVtmp.Value(i));
2176       }
2177       // create faces
2178       for (i=1; i<=dl; i++) {
2179         for (j=1; j<nl; j++) {
2180           if (WisF) {
2181             SMDS_MeshFace* F =
2182               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
2183                                 NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
2184             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2185           }
2186         }
2187       }
2188     }
2189     else {
2190       // fill UVL using c2d
2191       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn; i++) {
2192         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
2193       }
2194     }
2195
2196     // step2: create faces for right domain
2197     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
2198     // add right nodes
2199     for (j=1; j<=nr; j++)
2200       NodesR.SetValue(1,j,uv_er[nr-j].node);
2201     if (dr>0) {
2202       // add top nodes
2203       for (i=1; i<=dr; i++)
2204         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
2205       // create and add needed nodes
2206       TColgp_SequenceOfXY UVtmp;
2207       for (i=1; i<=dr; i++) {
2208         double x0 = npt.Value(nt-i);
2209         double x1 = x0;
2210         // diagonal node
2211         double y0 = npl.Value(i+1);
2212         double y1 = npr.Value(i+1);
2213         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2214         gp_Pnt P = S->Value(UV.X(),UV.Y());
2215         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2216         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2217         NodesR.SetValue(i+1,nr,N);
2218         if (UVR.Length()<nbv-nnn) UVR.Append(UV);
2219         // internal nodes
2220         for (j=2; j<nr; j++) {
2221           double y0 = npl.Value(nbv-j+1);
2222           double y1 = npr.Value(nbv-j+1);
2223           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2224           gp_Pnt P = S->Value(UV.X(),UV.Y());
2225           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2226           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2227           NodesR.SetValue(i+1,j,N);
2228           if (i==dr) UVtmp.Prepend(UV);
2229         }
2230       }
2231       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn; i++) {
2232         UVR.Append(UVtmp.Value(i));
2233       }
2234       // create faces
2235       for (i=1; i<=dr; i++) {
2236         for (j=1; j<nr; j++) {
2237           if (WisF) {
2238             SMDS_MeshFace* F =
2239               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
2240                                 NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
2241             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2242           }
2243         }
2244       }
2245     }
2246     else {
2247       // fill UVR using c2d
2248       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn; i++) {
2249         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
2250       }
2251     }
2252
2253     // step3: create faces for central domain
2254     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
2255     // add first line using NodesL
2256     for (i=1; i<=dl+1; i++)
2257       NodesC.SetValue(1,i,NodesL(i,1));
2258     for (i=2; i<=nl; i++)
2259       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
2260     // add last line using NodesR
2261     for (i=1; i<=dr+1; i++)
2262       NodesC.SetValue(nb,i,NodesR(i,nr));
2263     for (i=1; i<nr; i++)
2264       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
2265     // add top nodes (last columns)
2266     for (i=dl+2; i<nbh-dr; i++)
2267       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
2268     // add bottom nodes (first columns)
2269     for (i=2; i<nb; i++)
2270       NodesC.SetValue(i,1,uv_eb[i-1].node);
2271
2272     // create and add needed nodes
2273     // add linear layers
2274     for (i=2; i<nb; i++) {
2275       double x0 = npt.Value(dl+i);
2276       double x1 = x0;
2277       for (j=1; j<nnn; j++) {
2278         double y0 = npl.Value(nbv-nnn+j);
2279         double y1 = npr.Value(nbv-nnn+j);
2280         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2281         gp_Pnt P = S->Value(UV.X(),UV.Y());
2282         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2283         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2284         NodesC.SetValue(i,nbv-nnn+j,N);
2285         if ( j==1 )
2286           UVT.Append( UV );
2287       }
2288     }
2289     // add diagonal layers
2290     gp_UV A2 = UVR.Value(nbv-nnn);
2291     gp_UV A3 = UVL.Value(nbv-nnn);
2292     for (i=1; i<nbv-nnn; i++) {
2293       gp_UV p1 = UVR.Value(i);
2294       gp_UV p3 = UVL.Value(i);
2295       double y = i / double(nbv-nnn);
2296       for (j=2; j<nb; j++) {
2297         double x = npb.Value(j);
2298         gp_UV p0( uv_eb[j-1].u, uv_eb[j-1].v );
2299         gp_UV p2 = UVT.Value( j-1 );
2300         gp_UV UV = calcUV(x, y, a0, a1, A2, A3, p0,p1,p2,p3 );
2301         gp_Pnt P = S->Value(UV.X(),UV.Y());
2302         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2303         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
2304         NodesC.SetValue(j,i+1,N);
2305       }
2306     }
2307     // create faces
2308     for (i=1; i<nb; i++) {
2309       for (j=1; j<nbv; j++) {
2310         if (WisF) {
2311           SMDS_MeshFace* F =
2312             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
2313                               NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
2314           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2315         }
2316       }
2317     }
2318   }
2319
2320   else { // New version (!OldVersion)
2321     // step1: create faces for bottom rectangle domain
2322     StdMeshers_Array2OfNode NodesBRD(1,nb,1,nnn-1);
2323     // fill UVL and UVR using c2d
2324     for (j=0; j<nb; j++) {
2325       NodesBRD.SetValue(j+1,1,uv_eb[j].node);
2326     }
2327     for (i=1; i<nnn-1; i++) {
2328       NodesBRD.SetValue(1,i+1,uv_el[i].node);
2329       NodesBRD.SetValue(nb,i+1,uv_er[i].node);
2330       for (j=2; j<nb; j++) {
2331         double x = npb.Value(j);
2332         double y = (1-x) * npl.Value(i+1) + x * npr.Value(i+1);
2333         gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2334         gp_Pnt P = S->Value(UV.X(),UV.Y());
2335         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2336         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
2337         NodesBRD.SetValue(j,i+1,N);
2338       }
2339     }
2340     for (j=1; j<nnn-1; j++) {
2341       for (i=1; i<nb; i++) {
2342         if (WisF) {
2343           SMDS_MeshFace* F =
2344             myHelper->AddFace(NodesBRD.Value(i,j), NodesBRD.Value(i+1,j),
2345                               NodesBRD.Value(i+1,j+1), NodesBRD.Value(i,j+1));
2346           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2347         }
2348       }
2349     }
2350     int drl = abs(nr-nl);
2351     // create faces for region C
2352     StdMeshers_Array2OfNode NodesC(1,nb,1,drl+1+addv);
2353     // add nodes from previous region
2354     for (j=1; j<=nb; j++) {
2355       NodesC.SetValue(j,1,NodesBRD.Value(j,nnn-1));
2356     }
2357     if ((drl+addv) > 0) {
2358       int n1,n2;
2359       if (nr>nl) {
2360         n1 = 1;
2361         n2 = drl + 1;
2362         TColgp_SequenceOfXY UVtmp;
2363         double drparam = npr.Value(nr) - npr.Value(nnn-1);
2364         double dlparam = npl.Value(nnn) - npl.Value(nnn-1);
2365         double y0,y1;
2366         for (i=1; i<=drl; i++) {
2367           // add existed nodes from right edge
2368           NodesC.SetValue(nb,i+1,uv_er[nnn+i-2].node);
2369           //double dtparam = npt.Value(i+1);
2370           y1 = npr.Value(nnn+i-1); // param on right edge
2371           double dpar = (y1 - npr.Value(nnn-1))/drparam;
2372           y0 = npl.Value(nnn-1) + dpar*dlparam; // param on left edge
2373           double dy = y1 - y0;
2374           for (j=1; j<nb; j++) {
2375             double x = npt.Value(i+1) + npb.Value(j)*(1-npt.Value(i+1));
2376             double y = y0 + dy*x;
2377             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2378             gp_Pnt P = S->Value(UV.X(),UV.Y());
2379             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2380             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2381             NodesC.SetValue(j,i+1,N);
2382           }
2383         }
2384         double dy0 = (1-y0)/(addv+1);
2385         double dy1 = (1-y1)/(addv+1);
2386         for (i=1; i<=addv; i++) {
2387           double yy0 = y0 + dy0*i;
2388           double yy1 = y1 + dy1*i;
2389           double dyy = yy1 - yy0;
2390           for (j=1; j<=nb; j++) {
2391             double x = npt.Value(i+1+drl) +
2392               npb.Value(j) * (npt.Value(nt-i) - npt.Value(i+1+drl));
2393             double y = yy0 + dyy*x;
2394             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2395             gp_Pnt P = S->Value(UV.X(),UV.Y());
2396             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2397             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2398             NodesC.SetValue(j,i+drl+1,N);
2399           }
2400         }
2401       }
2402       else { // nr<nl
2403         n2 = 1;
2404         n1 = drl + 1;
2405         TColgp_SequenceOfXY UVtmp;
2406         double dlparam = npl.Value(nl) - npl.Value(nnn-1);
2407         double drparam = npr.Value(nnn) - npr.Value(nnn-1);
2408         double y0 = npl.Value(nnn-1);
2409         double y1 = npr.Value(nnn-1);
2410         for (i=1; i<=drl; i++) {
2411           // add existed nodes from right edge
2412           NodesC.SetValue(1,i+1,uv_el[nnn+i-2].node);
2413           y0 = npl.Value(nnn+i-1); // param on left edge
2414           double dpar = (y0 - npl.Value(nnn-1))/dlparam;
2415           y1 = npr.Value(nnn-1) + dpar*drparam; // param on right edge
2416           double dy = y1 - y0;
2417           for (j=2; j<=nb; j++) {
2418             double x = npb.Value(j)*npt.Value(nt-i);
2419             double y = y0 + dy*x;
2420             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2421             gp_Pnt P = S->Value(UV.X(),UV.Y());
2422             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2423             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2424             NodesC.SetValue(j,i+1,N);
2425           }
2426         }
2427         double dy0 = (1-y0)/(addv+1);
2428         double dy1 = (1-y1)/(addv+1);
2429         for (i=1; i<=addv; i++) {
2430           double yy0 = y0 + dy0*i;
2431           double yy1 = y1 + dy1*i;
2432           double dyy = yy1 - yy0;
2433           for (j=1; j<=nb; j++) {
2434             double x = npt.Value(i+1) +
2435               npb.Value(j) * (npt.Value(nt-i-drl) - npt.Value(i+1));
2436             double y = yy0 + dyy*x;
2437             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2438             gp_Pnt P = S->Value(UV.X(),UV.Y());
2439             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2440             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2441             NodesC.SetValue(j,i+drl+1,N);
2442           }
2443         }
2444       }
2445       // create faces
2446       for (j=1; j<=drl+addv; j++) {
2447         for (i=1; i<nb; i++) {
2448           if (WisF) {
2449             SMDS_MeshFace* F =
2450               myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
2451                                 NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
2452             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2453           }
2454         }
2455       } // end nr<nl
2456
2457       StdMeshers_Array2OfNode NodesLast(1,nt,1,2);
2458       for (i=1; i<=nt; i++) {
2459         NodesLast.SetValue(i,2,uv_et[i-1].node);
2460       }
2461       int nnn=0;
2462       for (i=n1; i<drl+addv+1; i++) {
2463         nnn++;
2464         NodesLast.SetValue(nnn,1,NodesC.Value(1,i));
2465       }
2466       for (i=1; i<=nb; i++) {
2467         nnn++;
2468         NodesLast.SetValue(nnn,1,NodesC.Value(i,drl+addv+1));
2469       }
2470       for (i=drl+addv; i>=n2; i--) {
2471         nnn++;
2472         NodesLast.SetValue(nnn,1,NodesC.Value(nb,i));
2473       }
2474       for (i=1; i<nt; i++) {
2475         if (WisF) {
2476           SMDS_MeshFace* F =
2477             myHelper->AddFace(NodesLast.Value(i,1), NodesLast.Value(i+1,1),
2478                               NodesLast.Value(i+1,2), NodesLast.Value(i,2));
2479           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2480         }
2481       }
2482     } // if ((drl+addv) > 0)
2483
2484   } // end new version implementation
2485
2486   bool isOk = true;
2487   return isOk;
2488 }
2489
2490
2491 //=======================================================================
2492 /*!
2493  * Evaluate only quandrangle faces
2494  */
2495 //=======================================================================
2496
2497 bool StdMeshers_Quadrangle_2D::evaluateQuadPref(SMESH_Mesh &        aMesh,
2498                                                 const TopoDS_Shape& aShape,
2499                                                 std::vector<int>&   aNbNodes,
2500                                                 MapShapeNbElems&    aResMap,
2501                                                 bool                IsQuadratic)
2502 {
2503   // Auxilary key in order to keep old variant
2504   // of meshing after implementation new variant
2505   // for bug 0016220 from Mantis.
2506   bool OldVersion = false;
2507   if (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
2508     OldVersion = true;
2509
2510   const TopoDS_Face& F = TopoDS::Face(aShape);
2511   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
2512
2513   int nb = aNbNodes[0];
2514   int nr = aNbNodes[1];
2515   int nt = aNbNodes[2];
2516   int nl = aNbNodes[3];
2517   int dh = abs(nb-nt);
2518   int dv = abs(nr-nl);
2519
2520   if (dh>=dv) {
2521     if (nt>nb) {
2522       // it is a base case => not shift 
2523     }
2524     else {
2525       // we have to shift on 2
2526       nb = aNbNodes[2];
2527       nr = aNbNodes[3];
2528       nt = aNbNodes[0];
2529       nl = aNbNodes[1];
2530     }
2531   }
2532   else {
2533     if (nr>nl) {
2534       // we have to shift quad on 1
2535       nb = aNbNodes[3];
2536       nr = aNbNodes[0];
2537       nt = aNbNodes[1];
2538       nl = aNbNodes[2];
2539     }
2540     else {
2541       // we have to shift quad on 3
2542       nb = aNbNodes[1];
2543       nr = aNbNodes[2];
2544       nt = aNbNodes[3];
2545       nl = aNbNodes[0];
2546     }
2547   }
2548
2549   dh = abs(nb-nt);
2550   dv = abs(nr-nl);
2551   int nbh  = Max(nb,nt);
2552   int nbv = Max(nr,nl);
2553   int addh = 0;
2554   int addv = 0;
2555
2556   if (dh>dv) {
2557     addv = (dh-dv)/2;
2558     nbv = nbv + addv;
2559   }
2560   else { // dv>=dh
2561     addh = (dv-dh)/2;
2562     nbh = nbh + addh;
2563   }
2564
2565   int dl,dr;
2566   if (OldVersion) {
2567     // add some params to right and left after the first param
2568     // insert to right
2569     dr = nbv - nr;
2570     // insert to left
2571     dl = nbv - nl;
2572   }
2573   
2574   int nnn = Min(nr,nl);
2575
2576   int nbNodes = 0;
2577   int nbFaces = 0;
2578   if (OldVersion) {
2579     // step1: create faces for left domain
2580     if (dl>0) {
2581       nbNodes += dl*(nl-1);
2582       nbFaces += dl*(nl-1);
2583     }
2584     // step2: create faces for right domain
2585     if (dr>0) {
2586       nbNodes += dr*(nr-1);
2587       nbFaces += dr*(nr-1);
2588     }
2589     // step3: create faces for central domain
2590     nbNodes += (nb-2)*(nnn-1) + (nbv-nnn-1)*(nb-2);
2591     nbFaces += (nb-1)*(nbv-1);
2592   }
2593   else { // New version (!OldVersion)
2594     nbNodes += (nnn-2)*(nb-2);
2595     nbFaces += (nnn-2)*(nb-1);
2596     int drl = abs(nr-nl);
2597     nbNodes += drl*(nb-1) + addv*nb;
2598     nbFaces += (drl+addv)*(nb-1) + (nt-1);
2599   } // end new version implementation
2600
2601   std::vector<int> aVec(SMDSEntity_Last);
2602   for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
2603   if (IsQuadratic) {
2604     aVec[SMDSEntity_Quad_Quadrangle] = nbFaces;
2605     aVec[SMDSEntity_Node] = nbNodes + nbFaces*4;
2606     if (aNbNodes.size()==5) {
2607       aVec[SMDSEntity_Quad_Triangle] = aNbNodes[3] - 1;
2608       aVec[SMDSEntity_Quad_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2609     }
2610   }
2611   else {
2612     aVec[SMDSEntity_Node] = nbNodes;
2613     aVec[SMDSEntity_Quadrangle] = nbFaces;
2614     if (aNbNodes.size()==5) {
2615       aVec[SMDSEntity_Triangle] = aNbNodes[3] - 1;
2616       aVec[SMDSEntity_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2617     }
2618   }
2619   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
2620   aResMap.insert(std::make_pair(sm,aVec));
2621
2622   return true;
2623 }
2624
2625 //=============================================================================
2626 /*! Split quadrangle in to 2 triangles by smallest diagonal
2627  *   
2628  */
2629 //=============================================================================
2630
2631 void StdMeshers_Quadrangle_2D::splitQuadFace(SMESHDS_Mesh *       theMeshDS,
2632                                              int                  theFaceID,
2633                                              const SMDS_MeshNode* theNode1,
2634                                              const SMDS_MeshNode* theNode2,
2635                                              const SMDS_MeshNode* theNode3,
2636                                              const SMDS_MeshNode* theNode4)
2637 {
2638   SMDS_MeshFace* face;
2639   if ( SMESH_TNodeXYZ( theNode1 ).SquareDistance( theNode3 ) >
2640        SMESH_TNodeXYZ( theNode2 ).SquareDistance( theNode4 ) )
2641   {
2642     face = myHelper->AddFace(theNode2, theNode4 , theNode1);
2643     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2644     face = myHelper->AddFace(theNode2, theNode3, theNode4);
2645     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2646   }
2647   else
2648   {
2649     face = myHelper->AddFace(theNode1, theNode2 ,theNode3);
2650     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2651     face = myHelper->AddFace(theNode1, theNode3, theNode4);
2652     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2653   }
2654 }
2655
2656 namespace
2657 {
2658   enum uvPos { UV_A0, UV_A1, UV_A2, UV_A3, UV_B, UV_R, UV_T, UV_L, UV_SIZE };
2659
2660   inline  SMDS_MeshNode* makeNode( UVPtStruct &         uvPt,
2661                                    const double         y,
2662                                    FaceQuadStruct::Ptr& quad,
2663                                    const gp_UV*         UVs,
2664                                    SMESH_MesherHelper*  helper,
2665                                    Handle(Geom_Surface) S)
2666   {
2667     const vector<UVPtStruct>& uv_eb = quad->side[QUAD_BOTTOM_SIDE].GetUVPtStruct();
2668     const vector<UVPtStruct>& uv_et = quad->side[QUAD_TOP_SIDE   ].GetUVPtStruct();
2669     double rBot = ( uv_eb.size() - 1 ) * uvPt.normParam;
2670     double rTop = ( uv_et.size() - 1 ) * uvPt.normParam;
2671     int iBot = int( rBot );
2672     int iTop = int( rTop );
2673     double xBot = uv_eb[ iBot ].normParam + ( rBot - iBot ) * ( uv_eb[ iBot+1 ].normParam - uv_eb[ iBot ].normParam );
2674     double xTop = uv_et[ iTop ].normParam + ( rTop - iTop ) * ( uv_et[ iTop+1 ].normParam - uv_et[ iTop ].normParam );
2675     double x = xBot + y * ( xTop - xBot );
2676     
2677     gp_UV uv = calcUV(/*x,y=*/x, y,
2678                       /*a0,...=*/UVs[UV_A0], UVs[UV_A1], UVs[UV_A2], UVs[UV_A3],
2679                       /*p0=*/quad->side[QUAD_BOTTOM_SIDE].grid->Value2d( x ).XY(),
2680                       /*p1=*/UVs[ UV_R ],
2681                       /*p2=*/quad->side[QUAD_TOP_SIDE   ].grid->Value2d( x ).XY(),
2682                       /*p3=*/UVs[ UV_L ]);
2683     gp_Pnt P = S->Value( uv.X(), uv.Y() );
2684     uvPt.u = uv.X();
2685     uvPt.v = uv.Y();
2686     return helper->AddNode(P.X(), P.Y(), P.Z(), 0, uv.X(), uv.Y() );
2687   }
2688
2689   void reduce42( const vector<UVPtStruct>& curr_base,
2690                  vector<UVPtStruct>&       next_base,
2691                  const int                 j,
2692                  int &                     next_base_len,
2693                  FaceQuadStruct::Ptr&      quad,
2694                  gp_UV*                    UVs,
2695                  const double              y,
2696                  SMESH_MesherHelper*       helper,
2697                  Handle(Geom_Surface)&     S)
2698   {
2699     // add one "HH": nodes a,b,c,d,e and faces 1,2,3,4,5,6
2700     //
2701     //  .-----a-----b i + 1
2702     //  |\ 5  | 6  /|
2703     //  | \   |   / |
2704     //  |  c--d--e  |
2705     //  |1 |2 |3 |4 |
2706     //  |  |  |  |  |
2707     //  .--.--.--.--. i
2708     //
2709     //  j     j+2   j+4
2710
2711     // a (i + 1, j + 2)
2712     const SMDS_MeshNode*& Na = next_base[ ++next_base_len ].node;
2713     if ( !Na )
2714       Na = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2715
2716     // b (i + 1, j + 4)
2717     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2718     if ( !Nb )
2719       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2720
2721     // c
2722     double u = (curr_base[j + 2].u + next_base[next_base_len - 2].u) / 2.0;
2723     double v = (curr_base[j + 2].v + next_base[next_base_len - 2].v) / 2.0;
2724     gp_Pnt P = S->Value(u,v);
2725     SMDS_MeshNode* Nc = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2726
2727     // d
2728     u = (curr_base[j + 2].u + next_base[next_base_len - 1].u) / 2.0;
2729     v = (curr_base[j + 2].v + next_base[next_base_len - 1].v) / 2.0;
2730     P = S->Value(u,v);
2731     SMDS_MeshNode* Nd = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2732
2733     // e
2734     u = (curr_base[j + 2].u + next_base[next_base_len].u) / 2.0;
2735     v = (curr_base[j + 2].v + next_base[next_base_len].v) / 2.0;
2736     P = S->Value(u,v);
2737     SMDS_MeshNode* Ne = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2738
2739     // Faces
2740     helper->AddFace(curr_base[j + 0].node,
2741                     curr_base[j + 1].node, Nc,
2742                     next_base[next_base_len - 2].node);
2743
2744     helper->AddFace(curr_base[j + 1].node,
2745                     curr_base[j + 2].node, Nd, Nc);
2746
2747     helper->AddFace(curr_base[j + 2].node,
2748                     curr_base[j + 3].node, Ne, Nd);
2749
2750     helper->AddFace(curr_base[j + 3].node,
2751                     curr_base[j + 4].node, Nb, Ne);
2752
2753     helper->AddFace(Nc, Nd, Na, next_base[next_base_len - 2].node);
2754
2755     helper->AddFace(Nd, Ne, Nb, Na);
2756   }
2757
2758   void reduce31( const vector<UVPtStruct>& curr_base,
2759                  vector<UVPtStruct>&       next_base,
2760                  const int                 j,
2761                  int &                     next_base_len,
2762                  FaceQuadStruct::Ptr&      quad,
2763                  gp_UV*                    UVs,
2764                  const double              y,
2765                  SMESH_MesherHelper*       helper,
2766                  Handle(Geom_Surface)&     S)
2767   {
2768     // add one "H": nodes b,c,e and faces 1,2,4,5
2769     //
2770     //  .---------b i + 1
2771     //  |\   5   /|
2772     //  | \     / |
2773     //  |  c---e  |
2774     //  |1 |2  |4 |
2775     //  |  |   |  |
2776     //  .--.---.--. i
2777     //
2778     //  j j+1 j+2 j+3
2779
2780     // b (i + 1, j + 3)
2781     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2782     if ( !Nb )
2783       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2784
2785     // c and e
2786     double u1 = (curr_base[ j   ].u + next_base[ next_base_len-1 ].u ) / 2.0;
2787     double u2 = (curr_base[ j+3 ].u + next_base[ next_base_len   ].u ) / 2.0;
2788     double u3 = (u2 - u1) / 3.0;
2789     //
2790     double v1 = (curr_base[ j   ].v + next_base[ next_base_len-1 ].v ) / 2.0;
2791     double v2 = (curr_base[ j+3 ].v + next_base[ next_base_len   ].v ) / 2.0;
2792     double v3 = (v2 - v1) / 3.0;
2793     // c
2794     double u = u1 + u3;
2795     double v = v1 + v3;
2796     gp_Pnt P = S->Value(u,v);
2797     SMDS_MeshNode* Nc = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2798     // e
2799     u = u1 + u3 + u3;
2800     v = v1 + v3 + v3;
2801     P = S->Value(u,v);
2802     SMDS_MeshNode* Ne = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2803
2804     // Faces
2805     // 1
2806     helper->AddFace( curr_base[ j + 0 ].node,
2807                      curr_base[ j + 1 ].node,
2808                      Nc,
2809                      next_base[ next_base_len - 1 ].node);
2810     // 2
2811     helper->AddFace( curr_base[ j + 1 ].node,
2812                      curr_base[ j + 2 ].node, Ne, Nc);
2813     // 4
2814     helper->AddFace( curr_base[ j + 2 ].node,
2815                      curr_base[ j + 3 ].node, Nb, Ne);
2816     // 5
2817     helper->AddFace(Nc, Ne, Nb,
2818                     next_base[ next_base_len - 1 ].node);
2819   }
2820
2821   typedef void (* PReduceFunction) ( const vector<UVPtStruct>& curr_base,
2822                                      vector<UVPtStruct>&       next_base,
2823                                      const int                 j,
2824                                      int &                     next_base_len,
2825                                      FaceQuadStruct::Ptr &     quad,
2826                                      gp_UV*                    UVs,
2827                                      const double              y,
2828                                      SMESH_MesherHelper*       helper,
2829                                      Handle(Geom_Surface)&     S);
2830
2831 } // namespace
2832
2833 //=======================================================================
2834 /*!
2835  *  Implementation of Reduced algorithm (meshing with quadrangles only)
2836  */
2837 //=======================================================================
2838
2839 bool StdMeshers_Quadrangle_2D::computeReduced (SMESH_Mesh &        aMesh,
2840                                                const TopoDS_Face&  aFace,
2841                                                FaceQuadStruct::Ptr quad)
2842 {
2843   SMESHDS_Mesh * meshDS  = aMesh.GetMeshDS();
2844   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace);
2845   int i,j,geomFaceID     = meshDS->ShapeToIndex(aFace);
2846
2847   int nb = quad->side[0].NbPoints(); // bottom
2848   int nr = quad->side[1].NbPoints(); // right
2849   int nt = quad->side[2].NbPoints(); // top
2850   int nl = quad->side[3].NbPoints(); // left
2851
2852   //  Simple Reduce 10->8->6->4 (3 steps)     Multiple Reduce 10->4 (1 step)
2853   //
2854   //  .-----.-----.-----.-----.               .-----.-----.-----.-----.
2855   //  |    / \    |    / \    |               |    / \    |    / \    |
2856   //  |   /    .--.--.    \   |               |    / \    |    / \    |
2857   //  |   /   /   |   \   \   |               |   /  .----.----.  \   |
2858   //  .---.---.---.---.---.---.               |   / / \   |   / \ \   |
2859   //  |   /  / \  |  / \  \   |               |   / / \   |   / \ \   |
2860   //  |  /  /   .-.-.   \  \  |               |  / /  .---.---.  \ \  |
2861   //  |  /  /  /  |  \  \  \  |               |  / / / \  |  / \ \ \  |
2862   //  .--.--.--.--.--.--.--.--.               |  / / /  \ | /  \ \ \  |
2863   //  |  / /  / \ | / \  \ \  |               | / / /   .-.-.   \ \ \ |
2864   //  | / /  /  .-.-.  \  \ \ |               | / / /  /  |  \  \ \ \ |
2865   //  | / / /  /  |  \  \ \ \ |               | / / /  /  |  \  \ \ \ |
2866   //  .-.-.-.--.--.--.--.-.-.-.               .-.-.-.--.--.--.--.-.-.-.
2867
2868   bool MultipleReduce = false;
2869   {
2870     int nb1 = nb;
2871     int nr1 = nr;
2872     int nt1 = nt;
2873
2874     if (nr == nl) {
2875       if (nb < nt) {
2876         nt1 = nb;
2877         nb1 = nt;
2878       }
2879     }
2880     else if (nb == nt) {
2881       nr1 = nb; // and == nt
2882       if (nl < nr) {
2883         nt1 = nl;
2884         nb1 = nr;
2885       }
2886       else {
2887         nt1 = nr;
2888         nb1 = nl;
2889       }
2890     }
2891     else {
2892       return false;
2893     }
2894
2895     // number of rows and columns
2896     int nrows    = nr1 - 1;
2897     int ncol_top = nt1 - 1;
2898     int ncol_bot = nb1 - 1;
2899     // number of rows needed to reduce ncol_bot to ncol_top using simple 3->1 "tree" (see below)
2900     int nrows_tree31 =
2901       int( ceil( log( double(ncol_bot) / ncol_top) / log( 3.))); // = log x base 3
2902     if ( nrows < nrows_tree31 )
2903     {
2904       MultipleReduce = true;
2905       error( COMPERR_WARNING,
2906              SMESH_Comment("To use 'Reduced' transition, "
2907                            "number of face rows should be at least ")
2908              << nrows_tree31 << ". Actual number of face rows is " << nrows << ". "
2909              "'Quadrangle preference (reversed)' transion has been used.");
2910     }
2911   }
2912
2913   if (MultipleReduce) { // == computeQuadPref QUAD_QUADRANGLE_PREF_REVERSED
2914     //==================================================
2915     int dh = abs(nb-nt);
2916     int dv = abs(nr-nl);
2917
2918     if (dh >= dv) {
2919       if (nt > nb) {
2920         // it is a base case => not shift quad but may be replacement is need
2921         shiftQuad(quad,0);
2922       }
2923       else {
2924         // we have to shift quad on 2
2925         shiftQuad(quad,2);
2926       }
2927     }
2928     else {
2929       if (nr > nl) {
2930         // we have to shift quad on 1
2931         shiftQuad(quad,1);
2932       }
2933       else {
2934         // we have to shift quad on 3
2935         shiftQuad(quad,3);
2936       }
2937     }
2938
2939     nb = quad->side[0].NbPoints();
2940     nr = quad->side[1].NbPoints();
2941     nt = quad->side[2].NbPoints();
2942     nl = quad->side[3].NbPoints();
2943     dh = abs(nb-nt);
2944     dv = abs(nr-nl);
2945     int nbh = Max(nb,nt);
2946     int nbv = Max(nr,nl);
2947     int addh = 0;
2948     int addv = 0;
2949
2950     if (dh>dv) {
2951       addv = (dh-dv)/2;
2952       nbv = nbv + addv;
2953     }
2954     else { // dv>=dh
2955       addh = (dv-dh)/2;
2956       nbh = nbh + addh;
2957     }
2958
2959     const vector<UVPtStruct>& uv_eb = quad->side[0].GetUVPtStruct(true,0);
2960     const vector<UVPtStruct>& uv_er = quad->side[1].GetUVPtStruct(false,1);
2961     const vector<UVPtStruct>& uv_et = quad->side[2].GetUVPtStruct(true,1);
2962     const vector<UVPtStruct>& uv_el = quad->side[3].GetUVPtStruct(false,0);
2963
2964     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
2965       return error(COMPERR_BAD_INPUT_MESH);
2966
2967     // arrays for normalized params
2968     TColStd_SequenceOfReal npb, npr, npt, npl;
2969     for (j = 0; j < nb; j++) {
2970       npb.Append(uv_eb[j].normParam);
2971     }
2972     for (i = 0; i < nr; i++) {
2973       npr.Append(uv_er[i].normParam);
2974     }
2975     for (j = 0; j < nt; j++) {
2976       npt.Append(uv_et[j].normParam);
2977     }
2978     for (i = 0; i < nl; i++) {
2979       npl.Append(uv_el[i].normParam);
2980     }
2981
2982     int dl,dr;
2983     // orientation of face and 3 main domain for future faces
2984     //       0   top    1
2985     //      1------------1
2986     //       |   |  |   |
2987     //       |   |  |   |
2988     //       | L |  | R |
2989     //  left |   |  |   | rigth
2990     //       |  /    \  |
2991     //       | /  C   \ |
2992     //       |/        \|
2993     //      0------------0
2994     //       0  bottom  1
2995
2996     // add some params to right and left after the first param
2997     // insert to right
2998     dr = nbv - nr;
2999     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
3000     for (i=1; i<=dr; i++) {
3001       npr.InsertAfter(1,npr.Value(2)-dpr);
3002     }
3003     // insert to left
3004     dl = nbv - nl;
3005     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
3006     for (i=1; i<=dl; i++) {
3007       npl.InsertAfter(1,npl.Value(2)-dpr);
3008     }
3009   
3010     gp_XY a0 (uv_eb.front().u, uv_eb.front().v);
3011     gp_XY a1 (uv_eb.back().u,  uv_eb.back().v);
3012     gp_XY a2 (uv_et.back().u,  uv_et.back().v);
3013     gp_XY a3 (uv_et.front().u, uv_et.front().v);
3014
3015     int nnn = Min(nr,nl);
3016     // auxilary sequence of XY for creation of nodes
3017     // in the bottom part of central domain
3018     // it's length must be == nbv-nnn-1
3019     TColgp_SequenceOfXY UVL;
3020     TColgp_SequenceOfXY UVR;
3021     //==================================================
3022
3023     // step1: create faces for left domain
3024     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
3025     // add left nodes
3026     for (j=1; j<=nl; j++)
3027       NodesL.SetValue(1,j,uv_el[j-1].node);
3028     if (dl>0) {
3029       // add top nodes
3030       for (i=1; i<=dl; i++) 
3031         NodesL.SetValue(i+1,nl,uv_et[i].node);
3032       // create and add needed nodes
3033       TColgp_SequenceOfXY UVtmp;
3034       for (i=1; i<=dl; i++) {
3035         double x0 = npt.Value(i+1);
3036         double x1 = x0;
3037         // diagonal node
3038         double y0 = npl.Value(i+1);
3039         double y1 = npr.Value(i+1);
3040         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3041         gp_Pnt P = S->Value(UV.X(),UV.Y());
3042         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3043         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3044         NodesL.SetValue(i+1,1,N);
3045         if (UVL.Length()<nbv-nnn-1) UVL.Append(UV);
3046         // internal nodes
3047         for (j=2; j<nl; j++) {
3048           double y0 = npl.Value(dl+j);
3049           double y1 = npr.Value(dl+j);
3050           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3051           gp_Pnt P = S->Value(UV.X(),UV.Y());
3052           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3053           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3054           NodesL.SetValue(i+1,j,N);
3055           if (i==dl) UVtmp.Append(UV);
3056         }
3057       }
3058       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn-1; i++) {
3059         UVL.Append(UVtmp.Value(i));
3060       }
3061       // create faces
3062       for (i=1; i<=dl; i++) {
3063         for (j=1; j<nl; j++) {
3064             SMDS_MeshFace* F =
3065               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
3066                                 NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
3067             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
3068         }
3069       }
3070     }
3071     else {
3072       // fill UVL using c2d
3073       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn-1; i++) {
3074         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
3075       }
3076     }
3077     
3078     // step2: create faces for right domain
3079     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
3080     // add right nodes
3081     for (j=1; j<=nr; j++) 
3082       NodesR.SetValue(1,j,uv_er[nr-j].node);
3083     if (dr>0) {
3084       // add top nodes
3085       for (i=1; i<=dr; i++) 
3086         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
3087       // create and add needed nodes
3088       TColgp_SequenceOfXY UVtmp;
3089       for (i=1; i<=dr; i++) {
3090         double x0 = npt.Value(nt-i);
3091         double x1 = x0;
3092         // diagonal node
3093         double y0 = npl.Value(i+1);
3094         double y1 = npr.Value(i+1);
3095         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3096         gp_Pnt P = S->Value(UV.X(),UV.Y());
3097         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3098         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3099         NodesR.SetValue(i+1,nr,N);
3100         if (UVR.Length()<nbv-nnn-1) UVR.Append(UV);
3101         // internal nodes
3102         for (j=2; j<nr; j++) {
3103           double y0 = npl.Value(nbv-j+1);
3104           double y1 = npr.Value(nbv-j+1);
3105           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3106           gp_Pnt P = S->Value(UV.X(),UV.Y());
3107           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3108           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3109           NodesR.SetValue(i+1,j,N);
3110           if (i==dr) UVtmp.Prepend(UV);
3111         }
3112       }
3113       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn-1; i++) {
3114         UVR.Append(UVtmp.Value(i));
3115       }
3116       // create faces
3117       for (i=1; i<=dr; i++) {
3118         for (j=1; j<nr; j++) {
3119             SMDS_MeshFace* F =
3120               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
3121                                 NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
3122             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
3123         }
3124       }
3125     }
3126     else {
3127       // fill UVR using c2d
3128       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn-1; i++) {
3129         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
3130       }
3131     }
3132     
3133     // step3: create faces for central domain
3134     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
3135     // add first line using NodesL
3136     for (i=1; i<=dl+1; i++)
3137       NodesC.SetValue(1,i,NodesL(i,1));
3138     for (i=2; i<=nl; i++)
3139       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
3140     // add last line using NodesR
3141     for (i=1; i<=dr+1; i++)
3142       NodesC.SetValue(nb,i,NodesR(i,nr));
3143     for (i=1; i<nr; i++)
3144       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
3145     // add top nodes (last columns)
3146     for (i=dl+2; i<nbh-dr; i++) 
3147       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
3148     // add bottom nodes (first columns)
3149     for (i=2; i<nb; i++)
3150       NodesC.SetValue(i,1,uv_eb[i-1].node);
3151
3152     // create and add needed nodes
3153     // add linear layers
3154     for (i=2; i<nb; i++) {
3155       double x0 = npt.Value(dl+i);
3156       double x1 = x0;
3157       for (j=1; j<nnn; j++) {
3158         double y0 = npl.Value(nbv-nnn+j);
3159         double y1 = npr.Value(nbv-nnn+j);
3160         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3161         gp_Pnt P = S->Value(UV.X(),UV.Y());
3162         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3163         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3164         NodesC.SetValue(i,nbv-nnn+j,N);
3165       }
3166     }
3167     // add diagonal layers
3168     for (i=1; i<nbv-nnn; i++) {
3169       double du = UVR.Value(i).X() - UVL.Value(i).X();
3170       double dv = UVR.Value(i).Y() - UVL.Value(i).Y();
3171       for (j=2; j<nb; j++) {
3172         double u = UVL.Value(i).X() + du*npb.Value(j);
3173         double v = UVL.Value(i).Y() + dv*npb.Value(j);
3174         gp_Pnt P = S->Value(u,v);
3175         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3176         meshDS->SetNodeOnFace(N, geomFaceID, u, v);
3177         NodesC.SetValue(j,i+1,N);
3178       }
3179     }
3180     // create faces
3181     for (i=1; i<nb; i++) {
3182       for (j=1; j<nbv; j++) {
3183         SMDS_MeshFace* F =
3184           myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
3185                             NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
3186         if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
3187       }
3188     }
3189   } // end Multiple Reduce implementation
3190   else { // Simple Reduce (!MultipleReduce)
3191     //=========================================================
3192     if (nr == nl) {
3193       if (nt < nb) {
3194         // it is a base case => not shift quad
3195         //shiftQuad(quad,0,true);
3196       }
3197       else {
3198         // we have to shift quad on 2
3199         shiftQuad(quad,2);
3200       }
3201     }
3202     else {
3203       if (nl > nr) {
3204         // we have to shift quad on 1
3205         shiftQuad(quad,1);
3206       }
3207       else {
3208         // we have to shift quad on 3
3209         shiftQuad(quad,3);
3210       }
3211     }
3212
3213     nb = quad->side[0].NbPoints();
3214     nr = quad->side[1].NbPoints();
3215     nt = quad->side[2].NbPoints();
3216     nl = quad->side[3].NbPoints();
3217
3218     // number of rows and columns
3219     int nrows = nr - 1; // and also == nl - 1
3220     int ncol_top = nt - 1;
3221     int ncol_bot = nb - 1;
3222     int npair_top = ncol_top / 2;
3223     // maximum number of bottom elements for "linear" simple reduce 4->2
3224     int max_lin42 = ncol_top + npair_top * 2 * nrows;
3225     // maximum number of bottom elements for "linear" simple reduce 3->1
3226     int max_lin31 = ncol_top + ncol_top * 2 * nrows;
3227     // maximum number of bottom elements for "tree" simple reduce 4->2
3228     int max_tree42 = 0;
3229     // number of rows needed to reduce ncol_bot to ncol_top using simple 4->2 "tree"
3230     int nrows_tree42 = int( log( (double)(ncol_bot / ncol_top) )/log((double)2)  ); // needed to avoid overflow at pow(2) while computing max_tree42
3231     if (nrows_tree42 < nrows) {
3232       max_tree42 = npair_top * pow(2.0, nrows + 1);
3233       if ( ncol_top > npair_top * 2 ) {
3234         int delta = ncol_bot - max_tree42;
3235         for (int irow = 1; irow < nrows; irow++) {
3236           int nfour = delta / 4;
3237           delta -= nfour * 2;
3238         }
3239         if (delta <= (ncol_top - npair_top * 2))
3240           max_tree42 = ncol_bot;
3241       }
3242     }
3243     // maximum number of bottom elements for "tree" simple reduce 3->1
3244     //int max_tree31 = ncol_top * pow(3.0, nrows);
3245     bool is_lin_31 = false;
3246     bool is_lin_42 = false;
3247     bool is_tree_31 = false;
3248     bool is_tree_42 = false;
3249     int max_lin = max_lin42;
3250     if (ncol_bot > max_lin42) {
3251       if (ncol_bot <= max_lin31) {
3252         is_lin_31 = true;
3253         max_lin = max_lin31;
3254       }
3255     }
3256     else {
3257       // if ncol_bot is a 3*n or not 2*n
3258       if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
3259         is_lin_31 = true;
3260         max_lin = max_lin31;
3261       }
3262       else {
3263         is_lin_42 = true;
3264       }
3265     }
3266     if (ncol_bot > max_lin) { // not "linear"
3267       is_tree_31 = (ncol_bot > max_tree42);
3268       if (ncol_bot <= max_tree42) {
3269         if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
3270           is_tree_31 = true;
3271         }
3272         else {
3273           is_tree_42 = true;
3274         }
3275       }
3276     }
3277
3278     const vector<UVPtStruct>& uv_eb = quad->side[0].GetUVPtStruct(true,0);
3279     const vector<UVPtStruct>& uv_er = quad->side[1].GetUVPtStruct(false,1);
3280     const vector<UVPtStruct>& uv_et = quad->side[2].GetUVPtStruct(true,1);
3281     const vector<UVPtStruct>& uv_el = quad->side[3].GetUVPtStruct(false,0);
3282
3283     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
3284       return error(COMPERR_BAD_INPUT_MESH);
3285
3286     myHelper->SetElementsOnShape( true );
3287
3288     gp_UV uv[ UV_SIZE ];
3289     uv[ UV_A0 ].SetCoord( uv_eb.front().u, uv_eb.front().v);
3290     uv[ UV_A1 ].SetCoord( uv_eb.back().u,  uv_eb.back().v );
3291     uv[ UV_A2 ].SetCoord( uv_et.back().u,  uv_et.back().v );
3292     uv[ UV_A3 ].SetCoord( uv_et.front().u, uv_et.front().v);
3293
3294     vector<UVPtStruct> curr_base = uv_eb, next_base;
3295
3296     UVPtStruct nullUVPtStruct; nullUVPtStruct.node = 0;
3297
3298     int curr_base_len = nb;
3299     int next_base_len = 0;
3300
3301     if ( true )
3302     { // ------------------------------------------------------------------
3303       // New algorithm implemented by request of IPAL22856
3304       // "2D quadrangle mesher of reduced type works wrong"
3305       // http://bugtracker.opencascade.com/show_bug.cgi?id=22856
3306
3307       // the algorithm is following: all reduces are centred in horizontal
3308       // direction and are distributed among all rows
3309
3310       if (ncol_bot > max_tree42) {
3311         is_lin_31 = true;
3312       }
3313       else {
3314         if ((ncol_top/3)*3 == ncol_top ) {
3315           is_lin_31 = true;
3316         }
3317         else {
3318           is_lin_42 = true;
3319         }
3320       }
3321
3322       const int col_top_size  = is_lin_42 ? 2 : 1;
3323       const int col_base_size = is_lin_42 ? 4 : 3;
3324
3325       // Compute nb of "columns" (like in "linear" simple reducing) in all rows
3326
3327       vector<int> nb_col_by_row;
3328
3329       int delta_all     = nb - nt;
3330       int delta_one_col = nrows * 2;
3331       int nb_col        = delta_all / delta_one_col;
3332       int remainder     = delta_all - nb_col * delta_one_col;
3333       if (remainder > 0) {
3334         nb_col++;
3335       }
3336       if ( nb_col * col_top_size >= nt ) // == "tree" reducing situation
3337       {
3338         // top row is full (all elements reduced), add "columns" one by one
3339         // in rows below until all bottom elements are reduced
3340         nb_col = ( nt - 1 ) / col_top_size;
3341         nb_col_by_row.resize( nrows, nb_col );
3342         int nbrows_not_full = nrows - 1;
3343         int cur_top_size    = nt - 1;
3344         remainder = delta_all - nb_col * delta_one_col;
3345         while ( remainder > 0 )
3346         {
3347           delta_one_col   = nbrows_not_full * 2;
3348           int nb_col_add  = remainder / delta_one_col;
3349           cur_top_size   += 2 * nb_col_by_row[ nbrows_not_full ];
3350           int nb_col_free = cur_top_size / col_top_size - nb_col_by_row[ nbrows_not_full-1 ];
3351           if ( nb_col_add > nb_col_free )
3352             nb_col_add = nb_col_free;
3353           for ( int irow = 0; irow < nbrows_not_full; ++irow )
3354             nb_col_by_row[ irow ] += nb_col_add;
3355           nbrows_not_full --;
3356           remainder -=  nb_col_add * delta_one_col;
3357         }
3358       }
3359       else // == "linear" reducing situation
3360       {
3361         nb_col_by_row.resize( nrows, nb_col );
3362         if (remainder > 0)
3363           for ( int irow = remainder / 2; irow < nrows; ++irow )
3364             nb_col_by_row[ irow ]--;
3365       }
3366
3367       // Make elements
3368
3369       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
3370
3371       const int reduce_grp_size = is_lin_42 ? 4 : 3;
3372
3373       for (i = 1; i < nr; i++) // layer by layer
3374       {
3375         nb_col = nb_col_by_row[ i-1 ];
3376         int nb_next = curr_base_len - nb_col * 2;
3377         if (nb_next < nt) nb_next = nt;
3378
3379         const double y = uv_el[ i ].normParam;
3380
3381         if ( i + 1 == nr ) // top
3382         {
3383           next_base = uv_et;
3384         }
3385         else
3386         {
3387           next_base.clear();
3388           next_base.resize( nb_next, nullUVPtStruct );
3389           next_base.front() = uv_el[i];
3390           next_base.back()  = uv_er[i];
3391
3392           // compute normalized param u
3393           double du = 1. / ( nb_next - 1 );
3394           next_base[0].normParam = 0.;
3395           for ( j = 1; j < nb_next; ++j )
3396             next_base[j].normParam = next_base[j-1].normParam + du;
3397         }
3398         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3399         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3400
3401         int free_left = ( curr_base_len - 1 - nb_col * col_base_size ) / 2;
3402         int free_middle = curr_base_len - 1 - nb_col * col_base_size - 2 * free_left;
3403
3404         // not reduced left elements
3405         for (j = 0; j < free_left; j++)
3406         {
3407           // f (i + 1, j + 1)
3408           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3409           if ( !Nf )
3410             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3411
3412           myHelper->AddFace(curr_base[ j ].node,
3413                             curr_base[ j+1 ].node,
3414                             Nf,
3415                             next_base[ next_base_len-1 ].node);
3416         }
3417
3418         for (int icol = 1; icol <= nb_col; icol++)
3419         {
3420           // add "H"
3421           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3422
3423           j += reduce_grp_size;
3424
3425           // elements in the middle of "columns" added for symmetry
3426           if ( free_middle > 0 && ( nb_col % 2 == 0 ) && icol == nb_col / 2 )
3427           {
3428             for (int imiddle = 1; imiddle <= free_middle; imiddle++) {
3429               // f (i + 1, j + imiddle)
3430               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3431               if ( !Nf )
3432                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3433
3434               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
3435                                 curr_base[ j  +imiddle ].node,
3436                                 Nf,
3437                                 next_base[ next_base_len-1 ].node);
3438             }
3439             j += free_middle;
3440           }
3441         }
3442
3443         // not reduced right elements
3444         for (; j < curr_base_len-1; j++) {
3445           // f (i + 1, j + 1)
3446           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3447           if ( !Nf )
3448             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3449
3450           myHelper->AddFace(curr_base[ j ].node,
3451                             curr_base[ j+1 ].node,
3452                             Nf,
3453                             next_base[ next_base_len-1 ].node);
3454         }
3455
3456         curr_base_len = next_base_len + 1;
3457         next_base_len = 0;
3458         curr_base.swap( next_base );
3459       }
3460
3461     }
3462     else if ( is_tree_42 || is_tree_31 )
3463     {
3464       // "tree" simple reduce "42": 2->4->8->16->32->...
3465       //
3466       //  .-------------------------------.-------------------------------. nr
3467       //  |    \                          |                          /    |
3468       //  |         \     .---------------.---------------.     /         |
3469       //  |               |               |               |               |
3470       //  .---------------.---------------.---------------.---------------.
3471       //  | \             |             / | \             |             / |
3472       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
3473       //  |       |       |       |       |       |       |       |       |
3474       //  .-------.-------.-------.-------.-------.-------.-------.-------. i
3475       //  |\      |      /|\      |      /|\      |      /|\      |      /|
3476       //  |  \.---.---./  |  \.---.---./  |  \.---.---./  |  \.---.---./  |
3477       //  |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
3478       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.
3479       //  |\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|
3480       //  | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. |
3481       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
3482       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
3483       //  1                               j                               nb
3484
3485       // "tree" simple reduce "31": 1->3->9->27->...
3486       //
3487       //  .-----------------------------------------------------. nr
3488       //  |        \                                   /        |
3489       //  |                 .-----------------.                 |
3490       //  |                 |                 |                 |
3491       //  .-----------------.-----------------.-----------------.
3492       //  |   \         /   |   \         /   |   \         /   |
3493       //  |     .-----.     |     .-----.     |     .-----.     | i
3494       //  |     |     |     |     |     |     |     |     |     |
3495       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.
3496       //  |\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|
3497       //  | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. |
3498       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | |
3499       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
3500       //  1                          j                          nb
3501
3502       PReduceFunction reduceFunction = & ( is_tree_42 ? reduce42 : reduce31 );
3503
3504       const int reduce_grp_size = is_tree_42 ? 4 : 3;
3505
3506       for (i = 1; i < nr; i++) // layer by layer
3507       {
3508         // to stop reducing, if number of nodes reaches nt
3509         int delta = curr_base_len - nt;
3510
3511         // to calculate normalized parameter, we must know number of points in next layer
3512         int nb_reduce_groups = (curr_base_len - 1) / reduce_grp_size;
3513         int nb_next = nb_reduce_groups * (reduce_grp_size-2) + (curr_base_len - nb_reduce_groups*reduce_grp_size);
3514         if (nb_next < nt) nb_next = nt;
3515
3516         const double y = uv_el[ i ].normParam;
3517
3518         if ( i + 1 == nr ) // top
3519         {
3520           next_base = uv_et;
3521         }
3522         else
3523         {
3524           next_base.clear();
3525           next_base.resize( nb_next, nullUVPtStruct );
3526           next_base.front() = uv_el[i];
3527           next_base.back()  = uv_er[i];
3528
3529           // compute normalized param u
3530           double du = 1. / ( nb_next - 1 );
3531           next_base[0].normParam = 0.;
3532           for ( j = 1; j < nb_next; ++j )
3533             next_base[j].normParam = next_base[j-1].normParam + du;
3534         }
3535         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3536         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3537
3538         for (j = 0; j+reduce_grp_size < curr_base_len && delta > 0; j+=reduce_grp_size, delta-=2)
3539         {
3540           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3541         }
3542
3543         // not reduced side elements (if any)
3544         for (; j < curr_base_len-1; j++)
3545         {
3546           // f (i + 1, j + 1)
3547           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3548           if ( !Nf )
3549             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3550           
3551           myHelper->AddFace(curr_base[ j ].node,
3552                             curr_base[ j+1 ].node,
3553                             Nf,
3554                             next_base[ next_base_len-1 ].node);
3555         }
3556         curr_base_len = next_base_len + 1;
3557         next_base_len = 0;
3558         curr_base.swap( next_base );
3559       }
3560     } // end "tree" simple reduce
3561
3562     else if ( is_lin_42 || is_lin_31 ) {
3563       // "linear" simple reduce "31": 2->6->10->14
3564       //
3565       //  .-----------------------------.-----------------------------. nr
3566       //  |     \                 /     |     \                 /     |
3567       //  |         .---------.         |         .---------.         |
3568       //  |         |         |         |         |         |         |
3569       //  .---------.---------.---------.---------.---------.---------.
3570       //  |        / \       / \        |        / \       / \        |
3571       //  |       /   .-----.   \       |       /   .-----.   \       | i
3572       //  |      /    |     |    \      |      /    |     |    \      |
3573       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.-----.
3574       //  |    /     / \   / \     \    |    /     / \   / \     \    |
3575       //  |   /     /   .-.   \     \   |   /     /   .-.   \     \   |
3576       //  |  /     /   /   \   \     \  |  /     /   /   \   \     \  |
3577       //  .--.----.---.-----.---.-----.-.--.----.---.-----.---.-----.-. 1
3578       //  1                             j                             nb
3579
3580       // "linear" simple reduce "42": 4->8->12->16
3581       //
3582       //  .---------------.---------------.---------------.---------------. nr
3583       //  | \             |             / | \             |             / |
3584       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
3585       //  |       |       |       |       |       |       |       |       |
3586       //  .-------.-------.-------.-------.-------.-------.-------.-------.
3587       //  |      / \      |      / \      |      / \      |      / \      |
3588       //  |     /   \.----.----./   \     |     /   \.----.----./   \     | i
3589       //  |     /    |    |    |    \     |     /    |    |    |    \     |
3590       //  .-----.----.----.----.----.-----.-----.----.----.----.----.-----.
3591       //  |     /   / \   |  /  \   \     |     /   / \   |  /  \   \     |
3592       //  |    /   /    .-.-.    \   \    |    /   /    .-.-.    \   \    |
3593       //  |   /   /    /  |  \    \   \   |   /   /    /  |  \    \   \   |
3594       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---. 1
3595       //  1                               j                               nb
3596
3597       // nt = 5, nb = 7, nr = 4
3598       //int delta_all = 2;
3599       //int delta_one_col = 6;
3600       //int nb_col = 0;
3601       //int remainder = 2;
3602       //if (remainder > 0) nb_col++;
3603       //nb_col = 1;
3604       //int free_left = 1;
3605       //free_left += 2;
3606       //int free_middle = 4;
3607
3608       int delta_all = nb - nt;
3609       int delta_one_col = (nr - 1) * 2;
3610       int nb_col = delta_all / delta_one_col;
3611       int remainder = delta_all - nb_col * delta_one_col;
3612       if (remainder > 0) {
3613         nb_col++;
3614       }
3615       const int col_top_size = is_lin_42 ? 2 : 1;
3616       int free_left = ((nt - 1) - nb_col * col_top_size) / 2;
3617       free_left += nr - 2;
3618       int free_middle = (nr - 2) * 2;
3619       if (remainder > 0 && nb_col == 1) {
3620         int nb_rows_short_col = remainder / 2;
3621         int nb_rows_thrown = (nr - 1) - nb_rows_short_col;
3622         free_left -= nb_rows_thrown;
3623       }
3624
3625       // nt = 5, nb = 17, nr = 4
3626       //int delta_all = 12;
3627       //int delta_one_col = 6;
3628       //int nb_col = 2;
3629       //int remainder = 0;
3630       //int free_left = 2;
3631       //int free_middle = 4;
3632
3633       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
3634
3635       const int reduce_grp_size = is_lin_42 ? 4 : 3;
3636
3637       for (i = 1; i < nr; i++, free_middle -= 2, free_left -= 1) // layer by layer
3638       {
3639         // to calculate normalized parameter, we must know number of points in next layer
3640         int nb_next = curr_base_len - nb_col * 2;
3641         if (remainder > 0 && i > remainder / 2)
3642           // take into account short "column"
3643           nb_next += 2;
3644         if (nb_next < nt) nb_next = nt;
3645
3646         const double y = uv_el[ i ].normParam;
3647
3648         if ( i + 1 == nr ) // top
3649         {
3650           next_base = uv_et;
3651         }
3652         else
3653         {
3654           next_base.clear();
3655           next_base.resize( nb_next, nullUVPtStruct );
3656           next_base.front() = uv_el[i];
3657           next_base.back()  = uv_er[i];
3658
3659           // compute normalized param u
3660           double du = 1. / ( nb_next - 1 );
3661           next_base[0].normParam = 0.;
3662           for ( j = 1; j < nb_next; ++j )
3663             next_base[j].normParam = next_base[j-1].normParam + du;
3664         }
3665         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3666         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3667
3668         // not reduced left elements
3669         for (j = 0; j < free_left; j++)
3670         {
3671           // f (i + 1, j + 1)
3672           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3673           if ( !Nf )
3674             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3675
3676           myHelper->AddFace(curr_base[ j ].node,
3677                             curr_base[ j+1 ].node,
3678                             Nf,
3679                             next_base[ next_base_len-1 ].node);
3680         }
3681
3682         for (int icol = 1; icol <= nb_col; icol++) {
3683
3684           if (remainder > 0 && icol == nb_col && i > remainder / 2)
3685             // stop short "column"
3686             break;
3687
3688           // add "H"
3689           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3690
3691           j += reduce_grp_size;
3692
3693           // not reduced middle elements
3694           if (icol < nb_col) {
3695             if (remainder > 0 && icol == nb_col - 1 && i > remainder / 2)
3696               // pass middle elements before stopped short "column"
3697               break;
3698
3699             int free_add = free_middle;
3700             if (remainder > 0 && icol == nb_col - 1)
3701               // next "column" is short
3702               free_add -= (nr - 1) - (remainder / 2);
3703
3704             for (int imiddle = 1; imiddle <= free_add; imiddle++) {
3705               // f (i + 1, j + imiddle)
3706               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3707               if ( !Nf )
3708                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3709
3710               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
3711                                 curr_base[ j  +imiddle ].node,
3712                                 Nf,
3713                                 next_base[ next_base_len-1 ].node);
3714             }
3715             j += free_add;
3716           }
3717         }
3718
3719         // not reduced right elements
3720         for (; j < curr_base_len-1; j++) {
3721           // f (i + 1, j + 1)
3722           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3723           if ( !Nf )
3724             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3725
3726           myHelper->AddFace(curr_base[ j ].node,
3727                             curr_base[ j+1 ].node,
3728                             Nf,
3729                             next_base[ next_base_len-1 ].node);
3730         }
3731
3732         curr_base_len = next_base_len + 1;
3733         next_base_len = 0;
3734         curr_base.swap( next_base );
3735       }
3736
3737     } // end "linear" simple reduce
3738
3739     else {
3740       return false;
3741     }
3742   } // end Simple Reduce implementation
3743
3744   bool isOk = true;
3745   return isOk;
3746 }
3747
3748 //================================================================================
3749 namespace // data for smoothing
3750 {
3751   struct TSmoothNode;
3752   // --------------------------------------------------------------------------------
3753   /*!
3754    * \brief Structure used to check validity of node position after smoothing.
3755    *        It holds two nodes connected to a smoothed node and belonging to
3756    *        one mesh face
3757    */
3758   struct TTriangle
3759   {
3760     TSmoothNode* _n1;
3761     TSmoothNode* _n2;
3762     TTriangle( TSmoothNode* n1=0, TSmoothNode* n2=0 ): _n1(n1), _n2(n2) {}
3763
3764     inline bool IsForward( gp_UV uv ) const;
3765   };
3766   // --------------------------------------------------------------------------------
3767   /*!
3768    * \brief Data of a smoothed node
3769    */
3770   struct TSmoothNode
3771   {
3772     gp_XY  _uv;
3773     gp_XYZ _xyz;
3774     vector< TTriangle > _triangles; // if empty, then node is not movable
3775   };
3776   // --------------------------------------------------------------------------------
3777   inline bool TTriangle::IsForward( gp_UV uv ) const
3778   {
3779     gp_Vec2d v1( uv, _n1->_uv ), v2( uv, _n2->_uv );
3780     double d = v1 ^ v2;
3781     return d > 1e-100;
3782   }
3783   //================================================================================
3784   /*!
3785    * \brief Returns area of a triangle
3786    */
3787   //================================================================================
3788
3789   double getArea( const gp_UV uv1, const gp_UV uv2, const gp_UV uv3 )
3790   {
3791     gp_XY v1 = uv1 - uv2, v2 = uv3 - uv2;
3792     double a = v2 ^ v1;
3793     return a;
3794   }
3795 }
3796
3797 //================================================================================
3798 /*!
3799  * \brief Set UV of nodes on degenerated VERTEXes in the middle of degenerated EDGE
3800  *
3801  * WARNING: this method must be called AFTER retrieving UVPtStruct's from quad
3802  */
3803 //================================================================================
3804
3805 void StdMeshers_Quadrangle_2D::updateDegenUV(FaceQuadStruct::Ptr quad)
3806 {
3807   if ( myNeedSmooth )
3808
3809     // Set UV of nodes on degenerated VERTEXes in the middle of degenerated EDGE
3810     // --------------------------------------------------------------------------
3811     for ( unsigned i = 0; i < quad->side.size(); ++i )
3812     {
3813       const vector<UVPtStruct>& uvVec = quad->side[i].GetUVPtStruct();
3814
3815       // find which end of the side is on degenerated shape
3816       int degenInd = -1;
3817       if ( myHelper->IsDegenShape( uvVec[0].node->getshapeId() ))
3818         degenInd = 0;
3819       else if ( myHelper->IsDegenShape( uvVec.back().node->getshapeId() ))
3820         degenInd = uvVec.size() - 1;
3821       else
3822         continue;
3823
3824       // find another side sharing the degenerated shape
3825       bool isPrev = ( degenInd == 0 );
3826       if ( i >= QUAD_TOP_SIDE )
3827         isPrev = !isPrev;
3828       int i2 = ( isPrev ? ( i + 3 ) : ( i + 1 )) % 4;
3829       const vector<UVPtStruct>& uvVec2 = quad->side[ i2 ].GetUVPtStruct();
3830       int degenInd2 = -1;
3831       if (      uvVec[ degenInd ].node == uvVec2.front().node )
3832         degenInd2 = 0;
3833       else if ( uvVec[ degenInd ].node == uvVec2.back().node )
3834         degenInd2 = uvVec2.size() - 1;
3835       else
3836         throw SALOME_Exception( LOCALIZED( "Logical error" ));
3837
3838       // move UV in the middle
3839       uvPtStruct& uv1 = const_cast<uvPtStruct&>( uvVec [ degenInd  ]);
3840       uvPtStruct& uv2 = const_cast<uvPtStruct&>( uvVec2[ degenInd2 ]);
3841       uv1.u = uv2.u = 0.5 * ( uv1.u + uv2.u );
3842       uv1.v = uv2.v = 0.5 * ( uv1.v + uv2.v );
3843     }
3844
3845   else if ( quad->side.size() == 4 /*&& myQuadType == QUAD_STANDARD*/)
3846
3847     // Set number of nodes on a degenerated side to be same as on an opposite side
3848     // ----------------------------------------------------------------------------
3849     for ( unsigned i = 0; i < quad->side.size(); ++i )
3850     {
3851       StdMeshers_FaceSidePtr degSide = quad->side[i];
3852       if ( !myHelper->IsDegenShape( degSide->EdgeID(0) ))
3853         continue;
3854       StdMeshers_FaceSidePtr oppSide = quad->side[( i+2 ) % quad->side.size() ];
3855       if ( degSide->NbSegments() == oppSide->NbSegments() )
3856         continue;
3857
3858       // make new side data
3859       const vector<UVPtStruct>& uvVecDegOld = degSide->GetUVPtStruct();
3860       const SMDS_MeshNode*   n = uvVecDegOld[0].node;
3861       Handle(Geom2d_Curve) c2d = degSide->Curve2d(0);
3862       double f = degSide->FirstU(0), l = degSide->LastU(0);
3863       gp_Pnt2d p1 = uvVecDegOld.front().UV();
3864       gp_Pnt2d p2 = uvVecDegOld.back().UV();
3865
3866       quad->side[i] = StdMeshers_FaceSide::New( oppSide.get(), n, &p1, &p2, c2d, f, l );
3867     }
3868 }
3869
3870 //================================================================================
3871 /*!
3872  * \brief Perform smoothing of 2D elements on a FACE with ignored degenerated EDGE
3873  */
3874 //================================================================================
3875
3876 void StdMeshers_Quadrangle_2D::smooth (FaceQuadStruct::Ptr quad)
3877 {
3878   if ( !myNeedSmooth ) return;
3879
3880   // Get nodes to smooth
3881
3882   // TODO: do not smooth fixed nodes
3883
3884   typedef map< const SMDS_MeshNode*, TSmoothNode, TIDCompare > TNo2SmooNoMap;
3885   TNo2SmooNoMap smooNoMap;
3886
3887   const TopoDS_Face&  geomFace = TopoDS::Face( myHelper->GetSubShape() );
3888   Handle(Geom_Surface) surface = BRep_Tool::Surface( geomFace );
3889   double U1, U2, V1, V2;
3890   surface->Bounds(U1, U2, V1, V2);
3891   GeomAPI_ProjectPointOnSurf proj;
3892   proj.Init( surface, U1, U2, V1, V2, BRep_Tool::Tolerance( geomFace ) );
3893
3894   SMESHDS_Mesh*        meshDS = myHelper->GetMeshDS();
3895   SMESHDS_SubMesh*   fSubMesh = meshDS->MeshElements( geomFace );
3896   SMDS_NodeIteratorPtr    nIt = fSubMesh->GetNodes();
3897   while ( nIt->more() ) // loop on nodes bound to a FACE
3898   {
3899     const SMDS_MeshNode* node = nIt->next();
3900     TSmoothNode & sNode = smooNoMap[ node ];
3901     sNode._uv  = myHelper->GetNodeUV( geomFace, node );
3902     sNode._xyz = SMESH_TNodeXYZ( node );
3903
3904     // set sNode._triangles
3905     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator( SMDSAbs_Face );
3906     while ( fIt->more() )
3907     {
3908       const SMDS_MeshElement* face = fIt->next();
3909       const int nbN     = face->NbCornerNodes();
3910       const int nInd    = face->GetNodeIndex( node );
3911       const int prevInd = myHelper->WrapIndex( nInd - 1, nbN );
3912       const int nextInd = myHelper->WrapIndex( nInd + 1, nbN );
3913       const SMDS_MeshNode* prevNode = face->GetNode( prevInd );
3914       const SMDS_MeshNode* nextNode = face->GetNode( nextInd );
3915       sNode._triangles.push_back( TTriangle( & smooNoMap[ prevNode ],
3916                                              & smooNoMap[ nextNode ]));
3917     }
3918   }
3919   // set _uv of smooth nodes on FACE boundary
3920   for ( unsigned i = 0; i < quad->side.size(); ++i )
3921   {
3922     const vector<UVPtStruct>& uvVec = quad->side[i].GetUVPtStruct();
3923     for ( unsigned j = 0; j < uvVec.size(); ++j )
3924     {
3925       TSmoothNode & sNode = smooNoMap[ uvVec[j].node ];
3926       sNode._uv  = uvVec[j].UV();
3927       sNode._xyz = SMESH_TNodeXYZ( uvVec[j].node );
3928     }
3929   }
3930
3931   // define refernce orientation in 2D
3932   TNo2SmooNoMap::iterator n2sn = smooNoMap.begin();
3933   for ( ; n2sn != smooNoMap.end(); ++n2sn )
3934     if ( !n2sn->second._triangles.empty() )
3935       break;
3936   if ( n2sn == smooNoMap.end() ) return;
3937   const TSmoothNode & sampleNode = n2sn->second;
3938   const bool refForward = ( sampleNode._triangles[0].IsForward( sampleNode._uv ));
3939
3940   // Smoothing
3941
3942   for ( int iLoop = 0; iLoop < 5; ++iLoop )
3943   {
3944     for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
3945     {
3946       TSmoothNode& sNode = n2sn->second;
3947       if ( sNode._triangles.empty() )
3948         continue; // not movable node
3949
3950       gp_XY newUV;
3951       bool isValid = false;
3952       bool use3D   = ( iLoop > 2 ); // 3 loops in 2D and 2, in 3D
3953
3954       if ( use3D )
3955       {
3956         // compute a new XYZ
3957         gp_XYZ newXYZ (0,0,0);
3958         for ( unsigned i = 0; i < sNode._triangles.size(); ++i )
3959           newXYZ += sNode._triangles[i]._n1->_xyz;
3960         newXYZ /= sNode._triangles.size();
3961
3962         // compute a new UV by projection
3963         proj.Perform( newXYZ );
3964         isValid = ( proj.IsDone() && proj.NbPoints() > 0 );
3965         if ( isValid )
3966         {
3967           // check validity of the newUV
3968           Quantity_Parameter u,v;
3969           proj.LowerDistanceParameters( u, v );
3970           newUV.SetCoord( u, v );
3971           for ( unsigned i = 0; i < sNode._triangles.size() && isValid; ++i )
3972             isValid = ( sNode._triangles[i].IsForward( newUV ) == refForward );
3973         }
3974       }
3975       if ( !isValid )
3976       {
3977         // compute a new UV by averaging
3978         newUV.SetCoord(0.,0.);
3979         for ( unsigned i = 0; i < sNode._triangles.size(); ++i )
3980           newUV += sNode._triangles[i]._n1->_uv;
3981         newUV /= sNode._triangles.size();
3982
3983         // check validity of the newUV
3984         isValid = true;
3985         for ( unsigned i = 0; i < sNode._triangles.size() && isValid; ++i )
3986           isValid = ( sNode._triangles[i].IsForward( newUV ) == refForward );
3987       }
3988       if ( isValid )
3989       {
3990         sNode._uv = newUV;
3991         sNode._xyz = surface->Value( newUV.X(), newUV.Y() ).XYZ();
3992       }
3993     }
3994   }
3995
3996   // Set new XYZ to the smoothed nodes
3997
3998   for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
3999   {
4000     TSmoothNode& sNode = n2sn->second;
4001     if ( sNode._triangles.empty() )
4002       continue; // not movable node
4003
4004     SMDS_MeshNode* node = const_cast< SMDS_MeshNode*>( n2sn->first );
4005     gp_Pnt xyz = surface->Value( sNode._uv.X(), sNode._uv.Y() );
4006     meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
4007
4008     // store the new UV
4009     node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( sNode._uv.X(), sNode._uv.Y() )));
4010   }
4011
4012   // Move medium nodes in quadratic mesh
4013   if ( _quadraticMesh )
4014   {
4015     const TLinkNodeMap& links = myHelper->GetTLinkNodeMap();
4016     TLinkNodeMap::const_iterator linkIt = links.begin();
4017     for ( ; linkIt != links.end(); ++linkIt )
4018     {
4019       const SMESH_TLink& link = linkIt->first;
4020       SMDS_MeshNode*     node = const_cast< SMDS_MeshNode*>( linkIt->second );
4021
4022       if ( node->getshapeId() != myHelper->GetSubShapeID() )
4023         continue; // medium node is on EDGE or VERTEX
4024
4025       gp_XY uv1 = myHelper->GetNodeUV( geomFace, link.node1(), node );
4026       gp_XY uv2 = myHelper->GetNodeUV( geomFace, link.node2(), node );
4027
4028       gp_XY uv  = myHelper->GetMiddleUV( surface, uv1, uv2 );
4029       node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( uv.X(), uv.Y() )));
4030       
4031       gp_Pnt xyz = surface->Value( uv.X(), uv.Y() );
4032       meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
4033     }
4034   }
4035 }
4036
4037 //================================================================================
4038 /*!
4039  * \brief Checks validity of generated faces
4040  */
4041 //================================================================================
4042
4043 bool StdMeshers_Quadrangle_2D::check()
4044 {
4045   const bool isOK = true;
4046   if ( !myCheckOri || myQuadList.empty() || !myQuadList.front() || !myHelper )
4047     return isOK;
4048
4049   TopoDS_Face      geomFace = TopoDS::Face( myHelper->GetSubShape() );
4050   SMESHDS_Mesh*    meshDS   = myHelper->GetMeshDS();
4051   SMESHDS_SubMesh* fSubMesh = meshDS->MeshElements( geomFace );
4052   bool toCheckUV;
4053   if ( geomFace.Orientation() >= TopAbs_INTERNAL ) geomFace.Orientation( TopAbs_FORWARD );
4054
4055   // Get a reference orientation sign
4056
4057   double okSign;
4058   {
4059     TError err;
4060     TSideVector wireVec =
4061       StdMeshers_FaceSide::GetFaceWires( geomFace, *myHelper->GetMesh(), true, err );
4062     StdMeshers_FaceSidePtr wire = wireVec[0];
4063
4064     // find a right angle VERTEX
4065     int iVertex;
4066     double maxAngle = -1e100;
4067     for ( int i = 0; i < wire->NbEdges(); ++i )
4068     {
4069       int iPrev = myHelper->WrapIndex( i-1, wire->NbEdges() );
4070       const TopoDS_Edge& e1 = wire->Edge( iPrev );
4071       const TopoDS_Edge& e2 = wire->Edge( i );
4072       double angle = myHelper->GetAngle( e1, e2, geomFace );
4073       if (( maxAngle < angle ) &&
4074           ( 5.* M_PI/180 < angle && angle < 175.* M_PI/180  ))
4075       {
4076         maxAngle = angle;
4077         iVertex = i;
4078       }
4079     }
4080     if ( maxAngle < -2*M_PI ) return isOK;
4081
4082     // get a sign of 2D area of a corner face
4083
4084     int iPrev = myHelper->WrapIndex( iVertex-1, wire->NbEdges() );
4085     const TopoDS_Edge& e1 = wire->Edge( iPrev );
4086     const TopoDS_Edge& e2 = wire->Edge( iVertex );
4087
4088     gp_Vec2d v1, v2; gp_Pnt2d p;
4089     double u[2];
4090     {
4091       bool rev = ( e1.Orientation() == TopAbs_REVERSED );
4092       Handle(Geom2d_Curve) c = BRep_Tool::CurveOnSurface( e1, geomFace, u[0], u[1] );
4093       c->D1( u[ !rev ], p, v1 );
4094       if ( !rev )
4095         v1.Reverse();
4096     }
4097     {
4098       bool rev = ( e2.Orientation() == TopAbs_REVERSED );
4099       Handle(Geom2d_Curve) c = BRep_Tool::CurveOnSurface( e2, geomFace, u[0], u[1] );
4100       c->D1( u[ rev ], p, v2 );
4101       if ( rev )
4102         v2.Reverse();
4103     }
4104
4105     okSign = v2 ^ v1;
4106
4107     if ( maxAngle < 0 )
4108       okSign *= -1;
4109   }
4110
4111   // Look for incorrectly oriented faces
4112
4113   std::list<const SMDS_MeshElement*> badFaces;
4114
4115   const SMDS_MeshNode* nn [ 8 ]; // 8 is just for safety
4116   gp_UV                uv [ 8 ];
4117   SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
4118   while ( fIt->more() ) // loop on faces bound to a FACE
4119   {
4120     const SMDS_MeshElement* f = fIt->next();
4121
4122     const int nbN = f->NbCornerNodes();
4123     for ( int i = 0; i < nbN; ++i )
4124       nn[ i ] = f->GetNode( i );
4125
4126     const SMDS_MeshNode* nInFace = 0;
4127     if ( myHelper->HasSeam() )
4128       for ( int i = 0; i < nbN && !nInFace; ++i )
4129         if ( !myHelper->IsSeamShape( nn[i]->getshapeId() ))
4130           nInFace = nn[i];
4131
4132     for ( int i = 0; i < nbN; ++i )
4133       uv[ i ] = myHelper->GetNodeUV( geomFace, nn[i], nInFace, &toCheckUV );
4134
4135     switch ( nbN ) {
4136     case 4:
4137     {
4138       double sign1 = getArea( uv[0], uv[1], uv[2] );
4139       double sign2 = getArea( uv[0], uv[2], uv[3] );
4140       if ( sign1 * sign2 < 0 )
4141       {
4142         sign2 = getArea( uv[1], uv[2], uv[3] );
4143         sign1 = getArea( uv[1], uv[3], uv[0] );
4144         if ( sign1 * sign2 < 0 )
4145           continue; // this should not happen
4146       }
4147       if ( sign1 * okSign < 0 )
4148         badFaces.push_back ( f );
4149       break;
4150     }
4151     case 3:
4152     {
4153       double sign = getArea( uv[0], uv[1], uv[2] );
4154       if ( sign * okSign < 0 )
4155         badFaces.push_back ( f );
4156       break;
4157     }
4158     default:;
4159     }
4160   }
4161
4162   if ( !badFaces.empty() )
4163   {
4164     SMESH_subMesh* fSM = myHelper->GetMesh()->GetSubMesh( geomFace );
4165     SMESH_ComputeErrorPtr& err = fSM->GetComputeError();
4166     err.reset ( new SMESH_ComputeError( COMPERR_ALGO_FAILED,
4167                                         "Inverted elements generated"));
4168     err->myBadElements.swap( badFaces );
4169
4170     return !isOK;
4171   }
4172
4173   return isOK;
4174 }
4175
4176 /*//================================================================================
4177 /*!
4178  * \brief Finds vertices at the most sharp face corners
4179  *  \param [in] theFace - the FACE
4180  *  \param [in,out] theWire - the ordered edges of the face. It can be modified to
4181  *         have the first VERTEX of the first EDGE in \a vertices
4182  *  \param [out] theVertices - the found corner vertices in the order corresponding to
4183  *         the order of EDGEs in \a theWire
4184  *  \param [out] theNbDegenEdges - nb of degenerated EDGEs in theFace
4185  *  \param [in] theConsiderMesh - if \c true, only meshed VERTEXes are considered
4186  *         as possible corners
4187  *  \return int - number of quad sides found: 0, 3 or 4
4188  */
4189 //================================================================================
4190
4191 int StdMeshers_Quadrangle_2D::getCorners(const TopoDS_Face&          theFace,
4192                                          SMESH_Mesh &                theMesh,
4193                                          std::list<TopoDS_Edge>&     theWire,
4194                                          std::vector<TopoDS_Vertex>& theVertices,
4195                                          int &                       theNbDegenEdges,
4196                                          const bool                  theConsiderMesh)
4197 {
4198   theNbDegenEdges = 0;
4199
4200   SMESH_MesherHelper helper( theMesh );
4201
4202   // sort theVertices by angle
4203   multimap<double, TopoDS_Vertex> vertexByAngle;
4204   TopTools_DataMapOfShapeReal angleByVertex;
4205   TopoDS_Edge prevE = theWire.back();
4206   if ( SMESH_Algo::isDegenerated( prevE ))
4207   {
4208     list<TopoDS_Edge>::reverse_iterator edge = ++theWire.rbegin();
4209     while ( SMESH_Algo::isDegenerated( *edge ))
4210       ++edge;
4211     if ( edge == theWire.rend() )
4212       return false;
4213     prevE = *edge;
4214   }
4215   list<TopoDS_Edge>::iterator edge = theWire.begin();
4216   for ( ; edge != theWire.end(); ++edge )
4217   {
4218     if ( SMESH_Algo::isDegenerated( *edge ))
4219     {
4220       ++theNbDegenEdges;
4221       continue;
4222     }
4223     TopoDS_Vertex v = helper.IthVertex( 0, *edge );
4224     if ( !theConsiderMesh || SMESH_Algo::VertexNode( v, helper.GetMeshDS() ))
4225     {
4226       double angle = SMESH_MesherHelper::GetAngle( prevE, *edge, theFace );
4227       vertexByAngle.insert( make_pair( angle, v ));
4228       angleByVertex.Bind( v, angle );
4229     }
4230     prevE = *edge;
4231   }
4232
4233   // find out required nb of corners (3 or 4)
4234   int nbCorners = 4;
4235   TopoDS_Shape triaVertex = helper.GetMeshDS()->IndexToShape( myTriaVertexID );
4236   if ( !triaVertex.IsNull() &&
4237        triaVertex.ShapeType() == TopAbs_VERTEX &&
4238        helper.IsSubShape( triaVertex, theFace ) &&
4239        ( vertexByAngle.size() != 4 || vertexByAngle.begin()->first < 5 * M_PI/180. ))
4240     nbCorners = 3;
4241   else
4242     triaVertex.Nullify();
4243
4244   // check nb of available corners
4245   if ( nbCorners == 3 )
4246   {
4247     if ( vertexByAngle.size() < 3 )
4248       return error(COMPERR_BAD_SHAPE,
4249                    TComm("Face must have 3 sides but not ") << vertexByAngle.size() );
4250   }
4251   else
4252   {
4253     if ( vertexByAngle.size() == 3 && theNbDegenEdges == 0 )
4254     {
4255       if ( myTriaVertexID < 1 )
4256         return error(COMPERR_BAD_PARMETERS,
4257                      "No Base vertex provided for a trilateral geometrical face");
4258         
4259       TComm comment("Invalid Base vertex: ");
4260       comment << myTriaVertexID << " its ID is not among [ ";
4261       multimap<double, TopoDS_Vertex>::iterator a2v = vertexByAngle.begin();
4262       comment << helper.GetMeshDS()->ShapeToIndex( a2v->second ) << ", "; a2v++;
4263       comment << helper.GetMeshDS()->ShapeToIndex( a2v->second ) << ", "; a2v++;
4264       comment << helper.GetMeshDS()->ShapeToIndex( a2v->second ) << " ]";
4265       return error(COMPERR_BAD_PARMETERS, comment );
4266     }
4267     if ( vertexByAngle.size() + ( theNbDegenEdges > 0 ) < 4 &&
4268          vertexByAngle.size() + theNbDegenEdges != 4 )
4269       return error(COMPERR_BAD_SHAPE,
4270                    TComm("Face must have 4 sides but not ") << vertexByAngle.size() );
4271   }
4272
4273   // put all corner vertices in a map
4274   TopTools_MapOfShape vMap;
4275   if ( nbCorners == 3 )
4276     vMap.Add( triaVertex );
4277   multimap<double, TopoDS_Vertex>::reverse_iterator a2v = vertexByAngle.rbegin();
4278   for ( int iC = 0; a2v != vertexByAngle.rend() && iC < nbCorners; ++a2v, ++iC )
4279     vMap.Add( (*a2v).second );
4280
4281   // check if there are possible variations in choosing corners
4282   bool isThereVariants = false;
4283   if ( vertexByAngle.size() > nbCorners )
4284   {
4285     double lostAngle = a2v->first;
4286     double lastAngle = ( --a2v, a2v->first );
4287     isThereVariants  = ( lostAngle * 1.1 >= lastAngle );
4288   }
4289
4290   myCheckOri = ( vertexByAngle.size() > nbCorners ||
4291                  vertexByAngle.begin()->first < 5.* M_PI/180 );
4292
4293   // make theWire begin from a corner vertex or triaVertex
4294   if ( nbCorners == 3 )
4295     while ( !triaVertex.IsSame( ( helper.IthVertex( 0, theWire.front() ))) ||
4296             SMESH_Algo::isDegenerated( theWire.front() ))
4297       theWire.splice( theWire.end(), theWire, theWire.begin() );
4298   else
4299     while ( !vMap.Contains( helper.IthVertex( 0, theWire.front() )) ||
4300             SMESH_Algo::isDegenerated( theWire.front() ))
4301       theWire.splice( theWire.end(), theWire, theWire.begin() );
4302
4303   // fill the result vector and prepare for its refinement
4304   theVertices.clear();
4305   vector< double >      angles;
4306   vector< TopoDS_Edge > edgeVec;
4307   vector< int >         cornerInd, nbSeg;
4308   angles.reserve( vertexByAngle.size() );
4309   edgeVec.reserve( vertexByAngle.size() );
4310   nbSeg.reserve( vertexByAngle.size() );
4311   cornerInd.reserve( nbCorners );
4312   for ( edge = theWire.begin(); edge != theWire.end(); ++edge )
4313   {
4314     if ( SMESH_Algo::isDegenerated( *edge ))
4315       continue;
4316     TopoDS_Vertex v = helper.IthVertex( 0, *edge );
4317     bool   isCorner = vMap.Contains( v );
4318     if ( isCorner )
4319     {
4320       theVertices.push_back( v );
4321       cornerInd.push_back( angles.size() );
4322     }
4323     angles.push_back( angleByVertex.IsBound( v ) ? angleByVertex( v ) : -M_PI );
4324     edgeVec.push_back( *edge );
4325     if ( theConsiderMesh && isThereVariants )
4326     {
4327       if ( SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( *edge ))
4328         nbSeg.push_back( sm->NbNodes() + 1 );
4329       else
4330         nbSeg.push_back( 0 );
4331     }
4332   }
4333
4334   // refine the result vector - make sides elual by length if
4335   // there are several equal angles
4336   if ( isThereVariants )
4337   {
4338     if ( nbCorners == 3 )
4339       angles[0] = 2 * M_PI; // not to move the base triangle VERTEX
4340
4341     set< int > refinedCorners;
4342     for ( size_t iC = 0; iC < cornerInd.size(); ++iC )
4343     {
4344       int iV = cornerInd[iC];
4345       if ( !refinedCorners.insert( iV ).second )
4346         continue;
4347       list< int > equalVertices;
4348       equalVertices.push_back( iV );
4349       int nbC[2] = { 0, 0 };
4350       // find equal angles backward and forward from the iV-th corner vertex
4351       for ( int isFwd = 0; isFwd < 2; ++isFwd )
4352       {
4353         int     dV = isFwd ? +1 : -1;
4354         int iCNext = helper.WrapIndex( iC + dV, cornerInd.size() );
4355         int iVNext = helper.WrapIndex( iV + dV, angles.size() );
4356         while ( iVNext != iV )
4357         {
4358           bool equal = Abs( angles[iV] - angles[iVNext] ) < 0.1 * angles[iV];
4359           if ( equal )
4360             equalVertices.insert( isFwd ? equalVertices.end() : equalVertices.begin(), iVNext );
4361           if ( iVNext == cornerInd[ iCNext ])
4362           {
4363             if ( !equal )
4364               break;
4365             nbC[ isFwd ]++;
4366             refinedCorners.insert( cornerInd[ iCNext ] );
4367             iCNext = helper.WrapIndex( iCNext + dV, cornerInd.size() );
4368           }
4369           iVNext = helper.WrapIndex( iVNext + dV, angles.size() );
4370         }
4371       }
4372       // move corners to make sides equal by length
4373       int nbEqualV  = equalVertices.size();
4374       int nbExcessV = nbEqualV - ( 1 + nbC[0] + nbC[1] );
4375       if ( nbExcessV > 0 )
4376       {
4377         // calculate normalized length of each side enclosed between neighbor equalVertices
4378         vector< double > curLengths;
4379         double totalLen = 0;
4380         vector< int > evVec( equalVertices.begin(), equalVertices.end() );
4381         int   iEV = 0;
4382         int    iE = cornerInd[ helper.WrapIndex( iC - nbC[0] - 1, cornerInd.size() )];
4383         int iEEnd = cornerInd[ helper.WrapIndex( iC + nbC[1] + 1, cornerInd.size() )];
4384         while ( curLengths.size() < nbEqualV + 1 )
4385         {
4386           curLengths.push_back( totalLen );
4387           do {
4388             curLengths.back() += SMESH_Algo::EdgeLength( edgeVec[ iE ]);
4389             iE = helper.WrapIndex( iE + 1, edgeVec.size());
4390             if ( iEV < evVec.size() && iE == evVec[ iEV++ ] )
4391               break;
4392           }
4393           while( iE != iEEnd );
4394           totalLen = curLengths.back();
4395         }
4396         curLengths.resize( equalVertices.size() );
4397         for ( size_t iS = 0; iS < curLengths.size(); ++iS )
4398           curLengths[ iS ] /= totalLen;
4399
4400         // find equalVertices most close to the ideal sub-division of all sides
4401         int iBestEV = 0;
4402         int iCorner = helper.WrapIndex( iC - nbC[0], cornerInd.size() );
4403         int nbSides = 2 + nbC[0] + nbC[1];
4404         for ( int iS = 1; iS < nbSides; ++iS, ++iBestEV )
4405         {
4406           double idealLen = iS / double( nbSides );
4407           double d, bestDist = 1.;
4408           for ( iEV = iBestEV; iEV < curLengths.size(); ++iEV )
4409             if (( d = Abs( idealLen - curLengths[ iEV ])) < bestDist )
4410             {
4411               bestDist = d;
4412               iBestEV  = iEV;
4413             }
4414           if ( iBestEV > iS-1 + nbExcessV )
4415             iBestEV = iS-1 + nbExcessV;
4416           theVertices[ iCorner ] = helper.IthVertex( 0, edgeVec[ evVec[ iBestEV ]]);
4417           iCorner = helper.WrapIndex( iCorner + 1, cornerInd.size() );
4418         }
4419       }
4420     }
4421   }
4422
4423   return nbCorners;
4424 }
4425
4426 //================================================================================
4427 /*!
4428  * \brief Constructor of a side of quad
4429  */
4430 //================================================================================
4431
4432 FaceQuadStruct::Side::Side(StdMeshers_FaceSidePtr theGrid)
4433   : grid(theGrid), nbNodeOut(0), from(0), to(theGrid ? theGrid->NbPoints() : 0 ), di(1)
4434 {
4435 }
4436
4437 //=============================================================================
4438 /*!
4439  * \brief Constructor of a quad
4440  */
4441 //=============================================================================
4442
4443 FaceQuadStruct::FaceQuadStruct(const TopoDS_Face& F, const std::string& theName)
4444   : face( F ), name( theName )
4445 {
4446   side.reserve(4);
4447 }
4448
4449 //================================================================================
4450 /*!
4451  * \brief Fills myForcedPnts
4452  */
4453 //================================================================================
4454
4455 bool StdMeshers_Quadrangle_2D::getEnforcedUV()
4456 {
4457   myForcedPnts.clear();
4458   if ( !myParams ) return true; // missing hypothesis
4459
4460   std::vector< TopoDS_Shape > shapes;
4461   std::vector< gp_Pnt >       points;
4462   myParams->GetEnforcedNodes( shapes, points );
4463
4464   TopTools_IndexedMapOfShape vMap;
4465   for ( size_t i = 0; i < shapes.size(); ++i )
4466     if ( !shapes[i].IsNull() )
4467       TopExp::MapShapes( shapes[i], TopAbs_VERTEX, vMap );
4468
4469   size_t nbPoints = points.size();
4470   for ( int i = 1; i <= vMap.Extent(); ++i )
4471     points.push_back( BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))));
4472
4473   // find out if all points must be in the FACE, which is so if
4474   // myParams is a local hypothesis on the FACE being meshed
4475   bool isStrictCheck = false;
4476   {
4477     SMESH_HypoFilter paramFilter( SMESH_HypoFilter::Is( myParams ));
4478     TopoDS_Shape assignedTo;
4479     if ( myHelper->GetMesh()->GetHypothesis( myHelper->GetSubShape(),
4480                                              paramFilter,
4481                                              /*ancestors=*/true,
4482                                              &assignedTo ))
4483       isStrictCheck = ( assignedTo.IsSame( myHelper->GetSubShape() ));
4484   }
4485
4486   multimap< double, ForcedPoint > sortedFP; // sort points by distance from EDGEs
4487
4488   Standard_Real u1,u2,v1,v2;
4489   const TopoDS_Face&   face = TopoDS::Face( myHelper->GetSubShape() );
4490   const double          tol = BRep_Tool::Tolerance( face );
4491   Handle(Geom_Surface) surf = BRep_Tool::Surface( face );
4492   surf->Bounds( u1,u2,v1,v2 );
4493   GeomAPI_ProjectPointOnSurf project;
4494   project.Init(surf, u1,u2, v1,v2, tol );
4495   Bnd_Box bbox;
4496   BRepBndLib::Add( face, bbox );
4497   double farTol = 0.01 * sqrt( bbox.SquareExtent() );
4498
4499   for ( size_t iP = 0; iP < points.size(); ++iP )
4500   {
4501     project.Perform( points[ iP ]);
4502     if ( !project.IsDone() )
4503     {
4504       if ( isStrictCheck && iP < nbPoints )
4505         return error
4506           (TComm("Projection of an enforced point to the face failed - (")
4507            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4508       continue;
4509     }
4510     if ( project.LowerDistance() > farTol )
4511     {
4512       if ( isStrictCheck && iP < nbPoints )
4513         return error
4514           (COMPERR_BAD_PARMETERS, TComm("An enforced point is too far from the face, dist = ")
4515            << project.LowerDistance() << " - ("
4516            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4517       continue;
4518     }
4519     Quantity_Parameter u, v;
4520     project.LowerDistanceParameters(u, v);
4521     gp_Pnt2d uv( u, v );
4522     BRepClass_FaceClassifier clsf ( face, uv, tol );
4523     switch ( clsf.State() ) {
4524     case TopAbs_IN:
4525     {
4526       double edgeDist =  ( Min( Abs( u - u1 ), Abs( u - u2 )) +
4527                            Min( Abs( v - v1 ), Abs( v - v2 )));
4528       ForcedPoint fp;
4529       fp.uv  = uv.XY();
4530       fp.xyz = points[ iP ].XYZ();
4531       if ( iP >= nbPoints )
4532         fp.vertex = TopoDS::Vertex( vMap( iP - nbPoints + 1 ));
4533
4534       sortedFP.insert( make_pair( edgeDist, fp ));
4535       break;
4536     }
4537     case TopAbs_OUT:
4538     {
4539       if ( isStrictCheck && iP < nbPoints )
4540         return error
4541           (COMPERR_BAD_PARMETERS, TComm("An enforced point is out of the face boundary - ")
4542            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4543       break;
4544     }
4545     case TopAbs_ON:
4546     {
4547       if ( isStrictCheck && iP < nbPoints )
4548         return error
4549           (COMPERR_BAD_PARMETERS, TComm("An enforced point is on the face boundary - ")
4550            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4551       break;
4552     }
4553     default:
4554     {
4555       if ( isStrictCheck && iP < nbPoints )
4556         return error
4557           (TComm("Classification of an enforced point ralative to the face boundary failed - ")
4558            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4559     }
4560     }
4561   }
4562
4563   multimap< double, ForcedPoint >::iterator d2uv = sortedFP.begin();
4564   for ( ; d2uv != sortedFP.end(); ++d2uv )
4565     myForcedPnts.push_back( (*d2uv).second );
4566
4567   return true;
4568 }
4569
4570 //================================================================================
4571 /*!
4572  * \brief Splits quads by adding points of enforced nodes and create nodes on
4573  *        the sides shared by quads
4574  */
4575 //================================================================================
4576
4577 bool StdMeshers_Quadrangle_2D::addEnforcedNodes()
4578 {
4579   // if ( myForcedPnts.empty() )
4580   //   return true;
4581
4582   // make a map of quads sharing a side
4583   map< StdMeshers_FaceSidePtr, vector< FaceQuadStruct::Ptr > > quadsBySide;
4584   list< FaceQuadStruct::Ptr >::iterator quadIt = myQuadList.begin();
4585   for ( ; quadIt != myQuadList.end(); ++quadIt )
4586     for ( size_t iSide = 0; iSide < (*quadIt)->side.size(); ++iSide )
4587     {
4588       if ( !setNormalizedGrid( *quadIt ))
4589         return false;
4590       quadsBySide[ (*quadIt)->side[iSide] ].push_back( *quadIt );
4591     }
4592
4593   SMESH_Mesh*          mesh = myHelper->GetMesh();
4594   SMESHDS_Mesh*      meshDS = myHelper->GetMeshDS();
4595   const TopoDS_Face&   face = TopoDS::Face( myHelper->GetSubShape() );
4596   Handle(Geom_Surface) surf = BRep_Tool::Surface( face );
4597
4598   for ( size_t iFP = 0; iFP < myForcedPnts.size(); ++iFP )
4599   {
4600     bool isNodeEnforced = false;
4601
4602     // look for a quad enclosing a enforced point
4603     for ( quadIt = myQuadList.begin(); quadIt != myQuadList.end(); ++quadIt )
4604     {
4605       FaceQuadStruct::Ptr quad = *quadIt;
4606       if ( !setNormalizedGrid( *quadIt ))
4607         return false;
4608       int i,j;
4609       if ( !quad->findCell( myForcedPnts[ iFP ], i, j ))
4610         continue;
4611
4612       // a grid cell is found, select a node of the cell to move
4613       // to the enforced point to and to split the quad at
4614       multimap< double, pair< int, int > > ijByDist;
4615       for ( int di = 0; di < 2; ++di )
4616         for ( int dj = 0; dj < 2; ++dj )
4617         {
4618           double dist2 = ( myForcedPnts[ iFP ].uv - quad->UVPt( i+di,j+dj ).UV() ).SquareModulus();
4619           ijByDist.insert( make_pair( dist2, make_pair( di,dj )));
4620         }
4621       // try all nodes starting from the closest one
4622       set< FaceQuadStruct::Ptr > changedQuads;
4623       multimap< double, pair< int, int > >::iterator d2ij = ijByDist.begin();
4624       for ( ; !isNodeEnforced  &&  d2ij != ijByDist.end(); ++d2ij )
4625       {
4626         int di = d2ij->second.first;
4627         int dj = d2ij->second.second;
4628
4629         // check if a node is at a side
4630         int iSide = -1;
4631         if ( dj== 0 && j == 0 )
4632           iSide = QUAD_BOTTOM_SIDE;
4633         else if ( dj == 1 && j+2 == quad->jSize )
4634           iSide = QUAD_TOP_SIDE;
4635         else if ( di == 0 && i == 0 )
4636           iSide = QUAD_LEFT_SIDE;
4637         else if ( di == 1 && i+2 == quad->iSize )
4638           iSide = QUAD_RIGHT_SIDE;
4639
4640         if ( iSide > -1 ) // ----- node is at a side
4641         {
4642           FaceQuadStruct::Side& side = quad->side[ iSide ];
4643           // check if this node can be moved
4644           if ( quadsBySide[ side ].size() < 2 )
4645             continue; // its a face boundary -> can't move the node
4646
4647           int quadNodeIndex = ( iSide % 2 ) ? j : i;
4648           int sideNodeIndex = side.ToSideIndex( quadNodeIndex );
4649           if ( side.IsForced( sideNodeIndex ))
4650           {
4651             // the node is already moved to another enforced point
4652             isNodeEnforced = quad->isEqual( myForcedPnts[ iFP ], i, j );
4653             continue;
4654           }
4655           // make a node of a side forced
4656           vector<UVPtStruct>& points = (vector<UVPtStruct>&) side.GetUVPtStruct();
4657           points[ sideNodeIndex ].u = myForcedPnts[ iFP ].U();
4658           points[ sideNodeIndex ].v = myForcedPnts[ iFP ].V();
4659
4660           updateSideUV( side, sideNodeIndex, quadsBySide );
4661
4662           // update adjacent sides
4663           set< StdMeshers_FaceSidePtr > updatedSides;
4664           updatedSides.insert( side );
4665           for ( size_t i = 0; i < side.contacts.size(); ++i )
4666             if ( side.contacts[i].point == sideNodeIndex )
4667             {
4668               const vector< FaceQuadStruct::Ptr >& adjQuads =
4669                 quadsBySide[ *side.contacts[i].other_side ];
4670               if ( adjQuads.size() > 1 &&
4671                    updatedSides.insert( * side.contacts[i].other_side ).second )
4672               {
4673                 updateSideUV( *side.contacts[i].other_side,
4674                               side.contacts[i].other_point,
4675                               quadsBySide );
4676               }
4677               changedQuads.insert( adjQuads.begin(), adjQuads.end() );
4678             }
4679           const vector< FaceQuadStruct::Ptr >& adjQuads = quadsBySide[ side ];
4680           changedQuads.insert( adjQuads.begin(), adjQuads.end() );
4681
4682           isNodeEnforced = true;
4683         }
4684         else // ------------------ node is inside the quad
4685         {
4686           i += di;
4687           j += dj;
4688           // make a new side passing through IJ node and split the quad
4689           int indForced, iNewSide;
4690           if ( quad->iSize < quad->jSize ) // split vertically
4691           {
4692             quad->updateUV( myForcedPnts[ iFP ].uv, i, j, /*isVert=*/true );
4693             indForced = j;
4694             iNewSide  = splitQuad( quad, i, 0 );
4695           }
4696           else
4697           {
4698             quad->updateUV( myForcedPnts[ iFP ].uv, i, j, /*isVert=*/false );
4699             indForced = i;
4700             iNewSide  = splitQuad( quad, 0, j );
4701           }
4702           FaceQuadStruct::Ptr   newQuad = myQuadList.back();
4703           FaceQuadStruct::Side& newSide = newQuad->side[ iNewSide ];
4704
4705           newSide.forced_nodes.insert( indForced );
4706           quad->side[( iNewSide+2 ) % 4 ].forced_nodes.insert( indForced );
4707
4708           quadsBySide[ newSide ].push_back( quad );
4709           quadsBySide[ newQuad->side[0] ].push_back( newQuad );
4710           quadsBySide[ newQuad->side[1] ].push_back( newQuad );
4711           quadsBySide[ newQuad->side[2] ].push_back( newQuad );
4712           quadsBySide[ newQuad->side[3] ].push_back( newQuad );
4713
4714           isNodeEnforced = true;
4715
4716         } // end of "node is inside the quad"
4717
4718       } // loop on nodes of the cell
4719
4720       // remove out-of-date uv grid of changedQuads
4721       set< FaceQuadStruct::Ptr >::iterator qIt = changedQuads.begin();
4722       for ( ; qIt != changedQuads.end(); ++qIt )
4723         (*qIt)->uv_grid.clear();
4724
4725       if ( isNodeEnforced )
4726         break;
4727
4728     } // loop on quads
4729
4730     if ( !isNodeEnforced )
4731     {
4732       if ( !myForcedPnts[ iFP ].vertex.IsNull() )
4733         return error(TComm("Unable to move any node to vertex #")
4734                      <<myHelper->GetMeshDS()->ShapeToIndex( myForcedPnts[ iFP ].vertex ));
4735       else
4736         return error(TComm("Unable to move any node to point ( ")
4737                      << myForcedPnts[iFP].xyz.X() << ", "
4738                      << myForcedPnts[iFP].xyz.Y() << ", "
4739                      << myForcedPnts[iFP].xyz.Z() << " )");
4740     }
4741
4742   } // loop on enforced points
4743
4744   // Compute nodes on all sides, where not yet present
4745
4746   for ( quadIt = myQuadList.begin(); quadIt != myQuadList.end(); ++quadIt )
4747   {
4748     FaceQuadStruct::Ptr quad = *quadIt;
4749     for ( int iSide = 0; iSide < 4; ++iSide )
4750     {
4751       FaceQuadStruct::Side & side = quad->side[ iSide ];
4752       if ( side.nbNodeOut > 0 )
4753         continue; // emulated side
4754       vector< FaceQuadStruct::Ptr >& quadVec = quadsBySide[ side ];
4755       if ( quadVec.size() <= 1 )
4756         continue; // outer side
4757
4758       bool missedNodesOnSide = false;
4759       const vector<UVPtStruct>& points = side.grid->GetUVPtStruct();
4760       for ( size_t iC = 0; iC < side.contacts.size(); ++iC )
4761       {
4762         const vector<UVPtStruct>& oGrid = side.contacts[iC].other_side->grid->GetUVPtStruct();
4763         const UVPtStruct&         uvPt  = points[ side.contacts[iC].point ];
4764         if ( side.contacts[iC].other_point >= oGrid.size()      ||
4765              side.contacts[iC].point       >= points.size() )
4766           throw SALOME_Exception( "StdMeshers_Quadrangle_2D::addEnforcedNodes(): wrong contact" );
4767         if ( oGrid[ side.contacts[iC].other_point ].node )
4768           (( UVPtStruct& ) uvPt).node = oGrid[ side.contacts[iC].other_point ].node;
4769       }
4770       for ( size_t iP = 0; iP < points.size(); ++iP )
4771         if ( !points[ iP ].node )
4772         {
4773           UVPtStruct& uvPnt = ( UVPtStruct& ) points[ iP ];
4774           gp_Pnt P = surf->Value( uvPnt.u, uvPnt.v );
4775           uvPnt.node = meshDS->AddNode(P.X(), P.Y(), P.Z());
4776           meshDS->SetNodeOnFace( uvPnt.node, myHelper->GetSubShapeID(), uvPnt.u, uvPnt.v );
4777           missedNodesOnSide = true;
4778         }
4779       if ( missedNodesOnSide )
4780       {
4781         // clear uv_grid where nodes are missing
4782         for ( size_t iQ = 0; iQ < quadVec.size(); ++iQ )
4783           quadVec[ iQ ]->uv_grid.clear();
4784       }
4785     }
4786   }
4787
4788   return true;
4789 }
4790
4791 //================================================================================
4792 /*!
4793  * \brief Splits a quad at I or J. Returns an index of a new side in the new quad
4794  */
4795 //================================================================================
4796
4797 int StdMeshers_Quadrangle_2D::splitQuad(FaceQuadStruct::Ptr quad, int I, int J)
4798 {
4799   FaceQuadStruct* newQuad = new FaceQuadStruct( quad->face );
4800   myQuadList.push_back( FaceQuadStruct::Ptr( newQuad ));
4801
4802   vector<UVPtStruct> points;
4803   if ( I > 0 && I <= quad->iSize-2 )
4804   {
4805     points.reserve( quad->jSize );
4806     for ( int jP = 0; jP < quad->jSize; ++jP )
4807       points.push_back( quad->UVPt( I, jP ));
4808
4809     newQuad->side.resize( 4 );
4810     newQuad->side[ QUAD_BOTTOM_SIDE ] = quad->side[ QUAD_BOTTOM_SIDE ];
4811     newQuad->side[ QUAD_RIGHT_SIDE  ] = quad->side[ QUAD_RIGHT_SIDE  ];
4812     newQuad->side[ QUAD_TOP_SIDE    ] = quad->side[ QUAD_TOP_SIDE    ];
4813     newQuad->side[ QUAD_LEFT_SIDE   ] = StdMeshers_FaceSide::New( points, quad->face );
4814
4815     FaceQuadStruct::Side& newSide  = newQuad->side[ QUAD_LEFT_SIDE ];
4816     FaceQuadStruct::Side& newSide2 = quad->side   [ QUAD_RIGHT_SIDE ];
4817
4818     quad->side[ QUAD_RIGHT_SIDE  ] = newSide;
4819
4820     int iBot = quad->side[ QUAD_BOTTOM_SIDE ].ToSideIndex( I );
4821     int iTop = quad->side[ QUAD_TOP_SIDE    ].ToSideIndex( I );
4822
4823     newSide.AddContact ( 0,               & quad->side[ QUAD_BOTTOM_SIDE ], iBot );
4824     newSide2.AddContact( 0,               & quad->side[ QUAD_BOTTOM_SIDE ], iBot );
4825     newSide.AddContact ( quad->jSize - 1, & quad->side[ QUAD_TOP_SIDE    ], iTop );
4826     newSide2.AddContact( quad->jSize - 1, & quad->side[ QUAD_TOP_SIDE    ], iTop );
4827     // cout << "Contact: L " << &newSide << " "<< newSide.NbPoints()
4828     //      << " R " << &newSide2 << " "<< newSide2.NbPoints()
4829     //      << " B " << &quad->side[ QUAD_BOTTOM_SIDE ] << " "<< quad->side[ QUAD_BOTTOM_SIDE].NbPoints()
4830     //      << " T " << &quad->side[ QUAD_TOP_SIDE ]  << " "<< quad->side[ QUAD_TOP_SIDE].NbPoints()<< endl;
4831
4832     newQuad->side[ QUAD_BOTTOM_SIDE ].from = iBot;
4833     newQuad->side[ QUAD_TOP_SIDE    ].from = iTop;
4834     newQuad->name = ( TComm("Right of I=") << I );
4835
4836     quad->side[ QUAD_BOTTOM_SIDE ].to = iBot + 1;
4837     quad->side[ QUAD_TOP_SIDE    ].to = iTop + 1;
4838     quad->uv_grid.clear();
4839
4840     return QUAD_LEFT_SIDE;
4841   }
4842   else if ( J > 0  && J <= quad->jSize-2 ) //// split horizontally, a new quad is below an old one
4843   {
4844     points.reserve( quad->iSize );
4845     for ( int iP = 0; iP < quad->iSize; ++iP )
4846       points.push_back( quad->UVPt( iP, J ));
4847
4848     newQuad->side.resize( 4 );
4849     newQuad->side[ QUAD_BOTTOM_SIDE ] = quad->side[ QUAD_BOTTOM_SIDE ];
4850     newQuad->side[ QUAD_RIGHT_SIDE  ] = quad->side[ QUAD_RIGHT_SIDE  ];
4851     newQuad->side[ QUAD_TOP_SIDE    ] = StdMeshers_FaceSide::New( points, quad->face );
4852     newQuad->side[ QUAD_LEFT_SIDE   ] = quad->side[ QUAD_LEFT_SIDE   ];
4853
4854     FaceQuadStruct::Side& newSide  = newQuad->side[ QUAD_TOP_SIDE    ];
4855     FaceQuadStruct::Side& newSide2 = quad->side   [ QUAD_BOTTOM_SIDE ];
4856
4857     quad->side[ QUAD_BOTTOM_SIDE ] = newSide;
4858
4859     int iLft = quad->side[ QUAD_LEFT_SIDE  ].ToSideIndex( J );
4860     int iRgt = quad->side[ QUAD_RIGHT_SIDE ].ToSideIndex( J );
4861
4862     newSide.AddContact ( 0,               & quad->side[ QUAD_LEFT_SIDE  ], iLft );
4863     newSide2.AddContact( 0,               & quad->side[ QUAD_LEFT_SIDE  ], iLft );
4864     newSide.AddContact ( quad->iSize - 1, & quad->side[ QUAD_RIGHT_SIDE ], iRgt );
4865     newSide2.AddContact( quad->iSize - 1, & quad->side[ QUAD_RIGHT_SIDE ], iRgt );
4866     // cout << "Contact: T " << &newSide << " "<< newSide.NbPoints()
4867     //      << " B " << &newSide2 << " "<< newSide2.NbPoints()
4868     //      << " L " << &quad->side[ QUAD_LEFT_SIDE ] << " "<< quad->side[ QUAD_LEFT_SIDE].NbPoints()
4869     //      << " R " << &quad->side[ QUAD_RIGHT_SIDE ]  << " "<< quad->side[ QUAD_RIGHT_SIDE].NbPoints()<< endl;
4870
4871     newQuad->side[ QUAD_RIGHT_SIDE ].to = iRgt+1;
4872     newQuad->side[ QUAD_LEFT_SIDE  ].to = iLft+1;
4873     newQuad->name = ( TComm("Below J=") << J );
4874
4875     quad->side[ QUAD_RIGHT_SIDE ].from = iRgt;
4876     quad->side[ QUAD_LEFT_SIDE  ].from = iLft;
4877     quad->uv_grid.clear();
4878
4879     return QUAD_TOP_SIDE;
4880   }
4881
4882   myQuadList.pop_back();
4883   return -1;
4884 }
4885
4886 //================================================================================
4887 /*!
4888  * \brief Updates UV of a side after moving its node
4889  */
4890 //================================================================================
4891
4892 void StdMeshers_Quadrangle_2D::updateSideUV( FaceQuadStruct::Side&  side,
4893                                              int                    iForced,
4894                                              const TQuadsBySide&    quadsBySide,
4895                                              int *                  iNext)
4896 {
4897   if ( !iNext )
4898   {
4899     side.forced_nodes.insert( iForced );
4900
4901     // update parts of the side before and after iForced
4902
4903     set<int>::iterator iIt = side.forced_nodes.upper_bound( iForced );
4904     int iEnd = Min( side.NbPoints()-1, ( iIt == side.forced_nodes.end() ) ? int(1e7) : *iIt );
4905     if ( iForced + 1 < iEnd )
4906       updateSideUV( side, iForced, quadsBySide, &iEnd );
4907
4908     iIt = side.forced_nodes.lower_bound( iForced );
4909     int iBeg = Max( 0, ( iIt == side.forced_nodes.begin() ) ? 0 : *--iIt );
4910     if ( iForced - 1 > iBeg )
4911       updateSideUV( side, iForced, quadsBySide, &iBeg );
4912
4913     return;
4914   }
4915
4916   const int iFrom    = Min ( iForced, *iNext );
4917   const int iTo      = Max ( iForced, *iNext ) + 1;
4918   const int sideSize = iTo - iFrom;
4919
4920   vector<UVPtStruct> points[4]; // side points of a temporary quad
4921
4922   // from the quads get grid points adjacent to the side
4923   // to make two sides of a temporary quad
4924   vector< FaceQuadStruct::Ptr > quads = quadsBySide.find( side )->second; // copy!
4925   for ( int is2nd = 0; is2nd < 2; ++is2nd )
4926   {
4927     points[ is2nd ].reserve( sideSize );
4928     int nbLoops = 0;
4929     while ( points[is2nd].size() < sideSize )
4930     {
4931       int iCur = iFrom + points[is2nd].size() - int( !points[is2nd].empty() );
4932
4933       // look for a quad adjacent to iCur-th point of the side
4934       for ( size_t iQ = 0; iQ < quads.size(); ++iQ )
4935       {
4936         FaceQuadStruct::Ptr q = quads[ iQ ];
4937         if ( !q )
4938           continue;
4939         size_t iS;
4940         for ( iS = 0; iS < q->side.size(); ++iS )
4941           if ( side.grid == q->side[ iS ].grid )
4942             break;
4943         bool isOut;
4944         if ( !q->side[ iS ].IsReversed() )
4945           isOut = ( q->side[ iS ].from > iCur || q->side[ iS ].to-1 <= iCur );
4946         else
4947           isOut = ( q->side[ iS ].to  >= iCur || q->side[ iS ].from <= iCur );
4948         if ( isOut )
4949           continue;
4950         if ( !setNormalizedGrid( q ))
4951           continue;
4952
4953         // found - copy points
4954         int i,j,di,dj,nb;
4955         if ( iS % 2 ) // right or left
4956         {
4957           i  = ( iS == QUAD_LEFT_SIDE ) ? 1 : q->iSize-2;
4958           j  = q->side[ iS ].ToQuadIndex( iCur );
4959           di = 0;
4960           dj = ( q->side[ iS ].IsReversed() ) ? -1  : +1;
4961           nb = ( q->side[ iS ].IsReversed() ) ? j+1 : q->jSize-j;
4962         }
4963         else // bottom or top
4964         {
4965           i  = q->side[ iS ].ToQuadIndex( iCur );
4966           j  = ( iS == QUAD_BOTTOM_SIDE )  ?  1 : q->jSize-2;
4967           di = ( q->side[ iS ].IsReversed() ) ? -1  : +1;
4968           dj = 0;
4969           nb = ( q->side[ iS ].IsReversed() ) ? i+1 : q->iSize-i;
4970         }
4971         if ( !points[is2nd].empty() )
4972         {
4973           gp_UV lastUV = points[is2nd].back().UV();
4974           gp_UV quadUV = q->UVPt( i, j ).UV();
4975           if ( ( lastUV - quadUV ).SquareModulus() > 1e-10 )
4976             continue; // quad is on the other side of the side
4977           i += di; j += dj; --nb;
4978         }
4979         for ( ; nb > 0 ; --nb )
4980         {
4981           points[ is2nd ].push_back( q->UVPt( i, j ));
4982           if ( points[is2nd].size() >= sideSize )
4983             break;
4984           i += di; j += dj;
4985         }
4986         quads[ iQ ].reset(); // not to use this quad anymore
4987
4988         if ( points[is2nd].size() >= sideSize )
4989           break;
4990       } // loop on quads
4991
4992       if ( nbLoops++ > quads.size() )
4993         throw SALOME_Exception( "StdMeshers_Quadrangle_2D::updateSideUV() bug: infinite loop" );
4994
4995     } // while ( points[is2nd].size() < sideSize )
4996   } // two loops to fill points[0] and points[1]
4997
4998   // points for other pair of opposite sides of the temporary quad
4999
5000   enum { L,R,B,T }; // side index of points[]
5001
5002   points[B].push_back( points[L].front() );
5003   points[B].push_back( side.GetUVPtStruct()[ iFrom ]);
5004   points[B].push_back( points[R].front() );
5005
5006   points[T].push_back( points[L].back() );
5007   points[T].push_back( side.GetUVPtStruct()[ iTo-1 ]);
5008   points[T].push_back( points[R].back() );
5009
5010   // make the temporary quad
5011   FaceQuadStruct::Ptr tmpQuad
5012     ( new FaceQuadStruct( TopoDS::Face( myHelper->GetSubShape() ), "tmpQuad"));
5013   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[B] )); // bottom
5014   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[R] )); // right
5015   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[T] ));
5016   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[L] ));
5017
5018   // compute new UV of the side
5019   setNormalizedGrid( tmpQuad );
5020   gp_UV uv = tmpQuad->UVPt(1,0).UV();
5021   tmpQuad->updateUV( uv, 1,0, /*isVertical=*/true );
5022
5023   // update UV of the side
5024   vector<UVPtStruct>& sidePoints = (vector<UVPtStruct>&) side.GetUVPtStruct();
5025   for ( int i = iFrom; i < iTo; ++i )
5026   {
5027     const uvPtStruct& uvPt = tmpQuad->UVPt( 1, i-iFrom );
5028     sidePoints[ i ].u = uvPt.u;
5029     sidePoints[ i ].v = uvPt.v;
5030   }
5031 }
5032
5033 //================================================================================
5034 /*!
5035  * \brief Finds indices of a grid quad enclosing the given enforced UV
5036  */
5037 //================================================================================
5038
5039 bool FaceQuadStruct::findCell( const gp_XY& UV, int & I, int & J )
5040 {
5041   // setNormalizedGrid() must be called before!
5042   if ( uv_box.IsOut( UV ))
5043     return false;
5044
5045   // find an approximate position
5046   double x = 0.5, y = 0.5;
5047   gp_XY t0 = UVPt( iSize - 1, 0 ).UV();
5048   gp_XY t1 = UVPt( 0, jSize - 1 ).UV();
5049   gp_XY t2 = UVPt( 0, 0         ).UV();
5050   SMESH_MeshAlgos::GetBarycentricCoords( UV, t0, t1, t2, x, y );
5051   x = Min( 1., Max( 0., x ));
5052   y = Min( 1., Max( 0., y ));
5053
5054   // precise the position
5055   normPa2IJ( x,y, I,J );
5056   if ( !isNear( UV, I,J ))
5057   {
5058     // look for the most close IJ by traversing uv_grid in the middle
5059     double dist2, minDist2 = ( UV - UVPt( I,J ).UV() ).SquareModulus();
5060     for ( int isU = 0; isU < 2; ++isU )
5061     {
5062       int ind1 = isU ? 0 : iSize / 2;
5063       int ind2 = isU ? jSize / 2 : 0;
5064       int di1  = isU ? Max( 2, iSize / 20 ) : 0;
5065       int di2  = isU ? 0 : Max( 2, jSize / 20 );
5066       int i,nb = isU ? iSize / di1 : jSize / di2;
5067       for ( i = 0; i < nb; ++i, ind1 += di1, ind2 += di2 )
5068         if (( dist2 = ( UV - UVPt( ind1,ind2 ).UV() ).SquareModulus() ) < minDist2 )
5069         {
5070           I = ind1;
5071           J = ind2;
5072           if ( isNear( UV, I,J ))
5073             return true;
5074           minDist2 = ( UV - UVPt( I,J ).UV() ).SquareModulus();
5075         }
5076     }
5077     if ( !isNear( UV, I,J, Max( iSize, jSize ) /2 ))
5078       return false;
5079   }
5080   return true;
5081 }
5082
5083 //================================================================================
5084 /*!
5085  * \brief Find indices (i,j) of a point in uv_grid by normalized parameters (x,y)
5086  */
5087 //================================================================================
5088
5089 void FaceQuadStruct::normPa2IJ(double X, double Y, int & I, int & J )
5090 {
5091
5092   I = Min( int ( iSize * X ), iSize - 2 );
5093   J = Min( int ( jSize * Y ), jSize - 2 );
5094
5095   int oldI, oldJ;
5096   do
5097   {
5098     oldI = I, oldJ = J;
5099     while ( X <= UVPt( I,J ).x   && I != 0 )
5100       --I;
5101     while ( X >  UVPt( I+1,J ).x && I+2 < iSize )
5102       ++I;
5103     while ( Y <= UVPt( I,J ).y   && J != 0 )
5104       --J;
5105     while ( Y >  UVPt( I,J+1 ).y && J+2 < jSize )
5106       ++J;
5107   } while ( oldI != I || oldJ != J );
5108 }
5109
5110 //================================================================================
5111 /*!
5112  * \brief Looks for UV in quads around a given (I,J) and precise (I,J)
5113  */
5114 //================================================================================
5115
5116 bool FaceQuadStruct::isNear( const gp_XY& UV, int & I, int & J, int nbLoops )
5117 {
5118   if ( I+1 >= iSize ) I = iSize - 2;
5119   if ( J+1 >= jSize ) J = jSize - 2;
5120
5121   double bcI, bcJ;
5122   gp_XY uvI, uvJ, uv0, uv1;
5123   for ( int iLoop = 0; iLoop < nbLoops; ++iLoop )
5124   {
5125     int oldI = I, oldJ = J;
5126
5127     uvI = UVPt( I+1, J ).UV();
5128     uvJ = UVPt( I, J+1 ).UV();
5129     uv0 = UVPt( I, J   ).UV();
5130     SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv0, bcI, bcJ );
5131     if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
5132       return true;
5133
5134     if ( I > 0       && bcI < 0. ) --I;
5135     if ( I+2 < iSize && bcI > 1. ) ++I;
5136     if ( J > 0       && bcJ < 0. ) --J;
5137     if ( J+2 < jSize && bcJ > 1. ) ++J;
5138
5139     uv1 = UVPt( I+1,J+1).UV();
5140     if ( I != oldI || J != oldJ )
5141     {
5142       uvI = UVPt( I+1, J ).UV();
5143       uvJ = UVPt( I, J+1 ).UV();
5144     }
5145     SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv1, bcI, bcJ );
5146     if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
5147       return true;
5148
5149     if ( I > 0       && bcI > 1. ) --I;
5150     if ( I+2 < iSize && bcI < 0. ) ++I;
5151     if ( J > 0       && bcJ > 1. ) --J;
5152     if ( J+2 < jSize && bcJ < 0. ) ++J;
5153
5154     if ( I == oldI && J == oldJ )
5155       return false;
5156
5157     if ( iLoop+1 == nbLoops )
5158     {
5159       uvI = UVPt( I+1, J ).UV();
5160       uvJ = UVPt( I, J+1 ).UV();
5161       uv0 = UVPt( I, J   ).UV();
5162       SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv0, bcI, bcJ );
5163       if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
5164         return true;
5165
5166       uv1 = UVPt( I+1,J+1).UV();
5167       SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv1, bcI, bcJ );
5168       if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
5169         return true;
5170     }
5171   }
5172   return false;
5173 }
5174
5175 //================================================================================
5176 /*!
5177  * \brief Checks if a given UV is equal to a given grid point
5178  */
5179 //================================================================================
5180
5181 bool FaceQuadStruct::isEqual( const gp_XY& UV, int I, int J )
5182 {
5183   TopLoc_Location loc;
5184   Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
5185   gp_Pnt p1 = surf->Value( UV.X(), UV.Y() );
5186   gp_Pnt p2 = surf->Value( UVPt( I,J ).u, UVPt( I,J ).v );
5187
5188   double dist2 = 1e100;
5189   for ( int di = -1; di < 2; di += 2 )
5190   {
5191     int i = I + di;
5192     if ( i < 0 || i+1 >= iSize ) continue;
5193     for ( int dj = -1; dj < 2; dj += 2 )
5194     {
5195       int j = J + dj;
5196       if ( j < 0 || j+1 >= jSize ) continue;
5197
5198       dist2 = Min( dist2,
5199                    p2.SquareDistance( surf->Value( UVPt( i,j ).u, UVPt( i,j ).v )));
5200     }
5201   }
5202   double tol2 = dist2 / 1000.;
5203   return p1.SquareDistance( p2 ) < tol2;
5204 }
5205
5206 //================================================================================
5207 /*!
5208  * \brief Recompute UV of grid points around a moved point in one direction
5209  */
5210 //================================================================================
5211
5212 void FaceQuadStruct::updateUV( const gp_XY& UV, int I, int J, bool isVertical )
5213 {
5214   UVPt( I, J ).u = UV.X();
5215   UVPt( I, J ).v = UV.Y();
5216
5217   if ( isVertical )
5218   {
5219     // above J
5220     if ( J+1 < jSize-1 )
5221     {
5222       gp_UV a0 = UVPt( 0,       J       ).UV();
5223       gp_UV a1 = UVPt( iSize-1, J       ).UV();
5224       gp_UV a2 = UVPt( iSize-1, jSize-1 ).UV();
5225       gp_UV a3 = UVPt( 0,       jSize-1 ).UV();
5226
5227       gp_UV p0 = UVPt( I, J       ).UV();
5228       gp_UV p2 = UVPt( I, jSize-1 ).UV();
5229       const double y0 = UVPt( I, J ).y, dy = 1. - y0;
5230       for (int j = J+1; j < jSize-1; j++)
5231       {
5232         gp_UV p1 = UVPt( iSize-1, j ).UV();
5233         gp_UV p3 = UVPt( 0,       j ).UV();
5234
5235         UVPtStruct& uvPt = UVPt( I, j );
5236         gp_UV uv = calcUV( uvPt.x, ( uvPt.y - y0 ) / dy, a0,a1,a2,a3, p0,p1,p2,p3);
5237         uvPt.u = uv.X();
5238         uvPt.v = uv.Y();
5239       }
5240     }
5241     // under J
5242     if ( J-1 > 0 )
5243     {
5244       gp_UV a0 = UVPt( 0,       0 ).UV();
5245       gp_UV a1 = UVPt( iSize-1, 0 ).UV();
5246       gp_UV a2 = UVPt( iSize-1, J ).UV();
5247       gp_UV a3 = UVPt( 0,       J ).UV();
5248
5249       gp_UV p0 = UVPt( I, 0 ).UV();
5250       gp_UV p2 = UVPt( I, J ).UV();
5251       const double y0 = 0., dy = UVPt( I, J ).y - y0;
5252       for (int j = 1; j < J; j++)
5253       {
5254         gp_UV p1 = UVPt( iSize-1, j ).UV();
5255         gp_UV p3 = UVPt( 0,       j ).UV();
5256
5257         UVPtStruct& uvPt = UVPt( I, j );
5258         gp_UV uv = calcUV( uvPt.x, ( uvPt.y - y0 ) / dy, a0,a1,a2,a3, p0,p1,p2,p3);
5259         uvPt.u = uv.X();
5260         uvPt.v = uv.Y();
5261       }
5262     }
5263   }
5264   else  // horizontally
5265   {
5266     // before I
5267     if ( I-1 > 0 )
5268     {
5269       gp_UV a0 = UVPt( 0, 0 ).UV();
5270       gp_UV a1 = UVPt( I, 0 ).UV();
5271       gp_UV a2 = UVPt( I, jSize-1 ).UV();
5272       gp_UV a3 = UVPt( 0, jSize-1 ).UV();
5273
5274       gp_UV p1 = UVPt( I, J ).UV();
5275       gp_UV p3 = UVPt( 0, J ).UV();
5276       const double x0 = 0., dx = UVPt( I, J ).x - x0;
5277       for (int i = 1; i < I; i++)
5278       {
5279         gp_UV p0 = UVPt( i, 0       ).UV();
5280         gp_UV p2 = UVPt( i, jSize-1 ).UV();
5281
5282         UVPtStruct& uvPt = UVPt( i, J );
5283         gp_UV uv = calcUV(( uvPt.x - x0 ) / dx , uvPt.y, a0,a1,a2,a3, p0,p1,p2,p3);
5284         uvPt.u = uv.X();
5285         uvPt.v = uv.Y();
5286       }
5287     }
5288     // after I
5289     if ( I+1 < iSize-1 )
5290     {
5291       gp_UV a0 = UVPt( I,       0 ).UV();
5292       gp_UV a1 = UVPt( iSize-1, 0 ).UV();
5293       gp_UV a2 = UVPt( iSize-1, jSize-1 ).UV();
5294       gp_UV a3 = UVPt( I,       jSize-1 ).UV();
5295
5296       gp_UV p1 = UVPt( iSize-1, J ).UV();
5297       gp_UV p3 = UVPt( I,       J ).UV();
5298       const double x0 = UVPt( I, J ).x, dx = 1. - x0;
5299       for (int i = I+1; i < iSize-1; i++)
5300       {
5301         gp_UV p0 = UVPt( i, 0       ).UV();
5302         gp_UV p2 = UVPt( i, jSize-1 ).UV();
5303
5304         UVPtStruct& uvPt = UVPt( i, J );
5305         gp_UV uv = calcUV(( uvPt.x - x0 ) / dx , uvPt.y, a0,a1,a2,a3, p0,p1,p2,p3);
5306         uvPt.u = uv.X();
5307         uvPt.v = uv.Y();
5308       }
5309     }
5310   }
5311 }
5312
5313 //================================================================================
5314 /*!
5315  * \brief Side copying
5316  */
5317 //================================================================================
5318
5319 FaceQuadStruct::Side& FaceQuadStruct::Side::operator=(const Side& otherSide)
5320 {
5321   grid = otherSide.grid;
5322   from = otherSide.from;
5323   to   = otherSide.to;
5324   di   = otherSide.di;
5325   forced_nodes = otherSide.forced_nodes;
5326   contacts     = otherSide.contacts;
5327   nbNodeOut    = otherSide.nbNodeOut;
5328
5329   for ( size_t iC = 0; iC < contacts.size(); ++iC )
5330   {
5331     FaceQuadStruct::Side* oSide = contacts[iC].other_side;
5332     for ( size_t iOC = 0; iOC < oSide->contacts.size(); ++iOC )
5333       if ( oSide->contacts[iOC].other_side == & otherSide )
5334       {
5335         // cout << "SHIFT old " << &otherSide << " " << otherSide.NbPoints()
5336         //      << " -> new " << this << " " << this->NbPoints() << endl;
5337         oSide->contacts[iOC].other_side = this;
5338       }
5339   }
5340   return *this;
5341 }
5342
5343 //================================================================================
5344 /*!
5345  * \brief Converts node index of a quad to node index of this side
5346  */
5347 //================================================================================
5348
5349 int FaceQuadStruct::Side::ToSideIndex( int quadNodeIndex ) const
5350 {
5351   return from + di * quadNodeIndex;
5352 }
5353
5354 //================================================================================
5355 /*!
5356  * \brief Converts node index of this side to node index of a quad
5357  */
5358 //================================================================================
5359
5360 int FaceQuadStruct::Side::ToQuadIndex( int sideNodeIndex ) const
5361 {
5362   return ( sideNodeIndex - from ) * di;
5363 }
5364
5365 //================================================================================
5366 /*!
5367  * \brief Reverse the side
5368  */
5369 //================================================================================
5370
5371 bool FaceQuadStruct::Side::Reverse(bool keepGrid)
5372 {
5373   if ( grid )
5374   {
5375     if ( keepGrid )
5376     {
5377       from -= di;
5378       to   -= di;
5379       std::swap( from, to );
5380       di   *= -1;
5381     }
5382     else
5383     {
5384       grid->Reverse();
5385     }
5386   }
5387   return (bool)grid;
5388 }
5389
5390 //================================================================================
5391 /*!
5392  * \brief Checks if a node is enforced
5393  *  \param [in] nodeIndex - an index of a node in a size
5394  *  \return bool - \c true if the node is forced
5395  */
5396 //================================================================================
5397
5398 bool FaceQuadStruct::Side::IsForced( int nodeIndex ) const
5399 {
5400   if ( nodeIndex < 0 || nodeIndex >= grid->NbPoints() )
5401     throw SALOME_Exception( " FaceQuadStruct::Side::IsForced(): wrong index" );
5402
5403   if ( forced_nodes.count( nodeIndex ) )
5404     return true;
5405
5406   for ( size_t i = 0; i < this->contacts.size(); ++i )
5407     if ( contacts[ i ].point == nodeIndex &&
5408          contacts[ i ].other_side->forced_nodes.count( contacts[ i ].other_point ))
5409       return true;
5410
5411   return false;
5412 }
5413
5414 //================================================================================
5415 /*!
5416  * \brief Sets up a contact between this and another side
5417  */
5418 //================================================================================
5419
5420 void FaceQuadStruct::Side::AddContact( int ip, Side* side, int iop )
5421 {
5422   if ( ip  >= GetUVPtStruct().size()      ||
5423        iop >= side->GetUVPtStruct().size() )
5424     throw SALOME_Exception( "FaceQuadStruct::Side::AddContact(): wrong point" );
5425   {
5426     contacts.resize( contacts.size() + 1 );
5427     Contact&    c = contacts.back();
5428     c.point       = ip;
5429     c.other_side  = side;
5430     c.other_point = iop;
5431   }
5432   {
5433     side->contacts.resize( side->contacts.size() + 1 );
5434     Contact&    c = side->contacts.back();
5435     c.point       = iop;
5436     c.other_side  = this;
5437     c.other_point = ip;
5438   }
5439 }
5440
5441 //================================================================================
5442 /*!
5443  * \brief Returns a normalized parameter of a point indexed within a quadrangle
5444  */
5445 //================================================================================
5446
5447 double FaceQuadStruct::Side::Param( int i ) const
5448 {
5449   const vector<UVPtStruct>& points = GetUVPtStruct();
5450   return (( points[ from + i * di ].normParam - points[ from ].normParam ) /
5451           ( points[ to   - 1 * di ].normParam - points[ from ].normParam ));
5452 }
5453
5454 //================================================================================
5455 /*!
5456  * \brief Returns UV by a parameter normalized within a quadrangle
5457  */
5458 //================================================================================
5459
5460 gp_XY FaceQuadStruct::Side::Value2d( double x ) const
5461 {
5462   const vector<UVPtStruct>& points = GetUVPtStruct();
5463   double u = ( points[ from ].normParam +
5464                x * ( points[ to-di ].normParam - points[ from ].normParam ));
5465   return grid->Value2d( u ).XY();
5466 }
5467
5468 //================================================================================
5469 /*!
5470  * \brief Returns side length
5471  */
5472 //================================================================================
5473
5474 double FaceQuadStruct::Side::Length(int theFrom, int theTo) const
5475 {
5476   if ( IsReversed() != ( theTo < theFrom ))
5477     std::swap( theTo, theFrom );
5478
5479   const vector<UVPtStruct>& points = GetUVPtStruct();
5480   double r;
5481   if ( theFrom == theTo && theTo == -1 )
5482     r = Abs( First().normParam -
5483              Last ().normParam );
5484   else if ( IsReversed() )
5485     r = Abs( points[ Max( to,   theTo+1 ) ].normParam -
5486              points[ Min( from, theFrom ) ].normParam );
5487   else
5488     r = Abs( points[ Min( to,   theTo-1 ) ].normParam -
5489              points[ Max( from, theFrom ) ].normParam );
5490   return r * grid->Length();
5491 }