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