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