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