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