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