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