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