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