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