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