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