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