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