Salome HOME
ObjectPool and SMDS_Position
[modules/smesh.git] / src / StdMeshers / StdMeshers_MEFISTO_2D.cxx
1 //  Copyright (C) 2007-2008  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.
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 //  SMESH SMESH : implementaion of SMESH idl descriptions
23 //  File   : StdMeshers_MEFISTO_2D.cxx
24 //           Moved here from SMESH_MEFISTO_2D.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //
28 #include "StdMeshers_MEFISTO_2D.hxx"
29
30 #include "SMESH_Gen.hxx"
31 #include "SMESH_Mesh.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_Block.hxx"
34 #include "SMESH_MesherHelper.hxx"
35 #include "SMESH_Comment.hxx"
36
37 #include "StdMeshers_FaceSide.hxx"
38 #include "StdMeshers_MaxElementArea.hxx"
39 #include "StdMeshers_LengthFromEdges.hxx"
40
41 #include "Rn.h"
42 #include "aptrte.h"
43
44 #include "SMDS_MeshElement.hxx"
45 #include "SMDS_MeshNode.hxx"
46 #include "SMDS_EdgePosition.hxx"
47 #include "SMDS_FacePosition.hxx"
48
49 #include "utilities.h"
50
51 #include <BRepTools.hxx>
52 #include <BRep_Tool.hxx>
53 #include <Geom_Curve.hxx>
54 #include <Geom2d_Curve.hxx>
55 #include <Geom_Surface.hxx>
56 #include <Precision.hxx>
57 #include <TopExp.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_ListIteratorOfListOfShape.hxx>
60 #include <TopTools_ListOfShape.hxx>
61 #include <TopTools_MapOfShape.hxx>
62 #include <TopoDS.hxx>
63 #include <TopoDS_Edge.hxx>
64 #include <TopoDS_Face.hxx>
65 #include <TopoDS_Iterator.hxx>
66 #include <gp_Pnt2d.hxx>
67
68 #include <BRep_Tool.hxx>
69 #include <GProp_GProps.hxx>
70 #include <BRepGProp.hxx>
71
72 using namespace std;
73
74 //=============================================================================
75 /*!
76  *  
77  */
78 //=============================================================================
79
80 StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D(int hypId, int studyId, SMESH_Gen * gen):
81   SMESH_2D_Algo(hypId, studyId, gen)
82 {
83   MESSAGE("StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D");
84   _name = "MEFISTO_2D";
85   _shapeType = (1 << TopAbs_FACE);
86   _compatibleHypothesis.push_back("MaxElementArea");
87   _compatibleHypothesis.push_back("LengthFromEdges");
88
89   _edgeLength = 0;
90   _maxElementArea = 0;
91   _hypMaxElementArea = NULL;
92   _hypLengthFromEdges = NULL;
93   myTool = 0;
94 }
95
96 //=============================================================================
97 /*!
98  *  
99  */
100 //=============================================================================
101
102 StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D()
103 {
104   MESSAGE("StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D");
105 }
106
107 //=============================================================================
108 /*!
109  *  
110  */
111 //=============================================================================
112
113 bool StdMeshers_MEFISTO_2D::CheckHypothesis
114                          (SMESH_Mesh&                          aMesh,
115                           const TopoDS_Shape&                  aShape,
116                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
117 {
118   _hypMaxElementArea = NULL;
119   _hypLengthFromEdges = NULL;
120   _edgeLength = 0;
121   _maxElementArea = 0;
122
123   list <const SMESHDS_Hypothesis * >::const_iterator itl;
124   const SMESHDS_Hypothesis *theHyp;
125
126   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
127   int nbHyp = hyps.size();
128   if (!nbHyp)
129   {
130     aStatus = SMESH_Hypothesis::HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
131     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
132   }
133
134   itl = hyps.begin();
135   theHyp = (*itl); // use only the first hypothesis
136
137   string hypName = theHyp->GetName();
138
139   bool isOk = false;
140
141   if (hypName == "MaxElementArea")
142   {
143     _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea *>(theHyp);
144     ASSERT(_hypMaxElementArea);
145     _maxElementArea = _hypMaxElementArea->GetMaxArea();
146     isOk = true;
147     aStatus = SMESH_Hypothesis::HYP_OK;
148   }
149
150   else if (hypName == "LengthFromEdges")
151   {
152     _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges *>(theHyp);
153     ASSERT(_hypLengthFromEdges);
154     isOk = true;
155     aStatus = SMESH_Hypothesis::HYP_OK;
156   }
157   else
158     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
159
160   if (isOk)
161   {
162     isOk = false;
163     if (_maxElementArea > 0)
164     {
165       //_edgeLength = 2 * sqrt(_maxElementArea);        // triangles : minorant
166       _edgeLength = sqrt(2. * _maxElementArea/sqrt(3.0));
167       isOk = true;
168     }
169     else
170       isOk = (_hypLengthFromEdges != NULL);     // **** check mode
171     if (!isOk)
172       aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
173   }
174
175   return isOk;
176 }
177
178 //=============================================================================
179 /*!
180  *  
181  */
182 //=============================================================================
183
184 bool StdMeshers_MEFISTO_2D::Compute(SMESH_Mesh & aMesh, const TopoDS_Shape & aShape)
185 {
186   MESSAGE("StdMeshers_MEFISTO_2D::Compute");
187
188   TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
189
190   // helper builds quadratic mesh if necessary
191   SMESH_MesherHelper helper(aMesh);
192   myTool = &helper;
193   _quadraticMesh = myTool->IsQuadraticSubMesh(aShape);
194   const bool ignoreMediumNodes = _quadraticMesh;
195
196   // get all edges of a face
197   TError problem;
198   TWireVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
199   int nbWires = wires.size();
200   if ( problem && !problem->IsOK() ) return error( problem );
201   if ( nbWires == 0 ) return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
202   if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
203     return error(COMPERR_BAD_INPUT_MESH,
204                  SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
205
206   // compute average edge length
207   if (!_hypMaxElementArea)
208   {
209     _edgeLength = 0;
210     int nbSegments = 0;
211     for ( int iW = 0; iW < nbWires; ++iW )
212     {
213       StdMeshers_FaceSidePtr wire = wires[ iW ];
214       _edgeLength += wire->Length();
215       nbSegments  += wire->NbSegments();
216     }
217     if ( nbSegments )
218       _edgeLength /= nbSegments;
219   }
220
221   if (/*_hypLengthFromEdges &&*/ _edgeLength < DBL_MIN )
222     _edgeLength = 100;
223
224   Z nblf;                 //nombre de lignes fermees (enveloppe en tete)
225   Z *nudslf = NULL;       //numero du dernier sommet de chaque ligne fermee
226   R2 *uvslf = NULL;       
227   Z nbpti = 0;            //nombre points internes futurs sommets de la triangulation
228   R2 *uvpti = NULL;
229   
230   Z nbst;
231   R2 *uvst = NULL;
232   Z nbt;
233   Z *nust = NULL;
234   Z ierr = 0;
235
236   Z nutysu = 1;           // 1: il existe un fonction areteideale_()
237   // Z  nutysu=0;         // 0: on utilise aretmx
238   R aretmx = _edgeLength; // longueur max aretes future triangulation
239   
240   nblf = nbWires;
241   
242   nudslf = new Z[1 + nblf];
243   nudslf[0] = 0;
244   int iw = 1;
245   int nbpnt = 0;
246
247   // count nb of input points
248   for ( int iW = 0; iW < nbWires; ++iW )
249   {
250     nbpnt += wires[iW]->NbPoints() - 1;
251     nudslf[iw++] = nbpnt;
252   }
253
254   uvslf = new R2[nudslf[nblf]];
255
256   double scalex, scaley;
257   ComputeScaleOnFace(aMesh, F, scalex, scaley);
258
259   // correspondence mefisto index --> Nodes
260   vector< const SMDS_MeshNode*> mefistoToDS(nbpnt, (const SMDS_MeshNode*)0);
261
262   bool isOk = false;
263
264   // fill input points UV
265   if ( LoadPoints(wires, uvslf, mefistoToDS, scalex, scaley) )
266   {
267     // Compute
268     aptrte(nutysu, aretmx,
269            nblf, nudslf, uvslf, nbpti, uvpti, nbst, uvst, nbt, nust, ierr);
270
271     if (ierr == 0)
272     {
273       MESSAGE("... End Triangulation Generated Triangle Number " << nbt);
274       MESSAGE("                                    Node Number " << nbst);
275       StoreResult(nbst, uvst, nbt, nust, mefistoToDS, scalex, scaley);
276       isOk = true;
277     }
278     else
279     {
280       error(ierr,"Error in Triangulation (aptrte())");
281     }
282   }
283   if (nudslf != NULL) delete[]nudslf;
284   if (uvslf != NULL)  delete[]uvslf;
285   if (uvst != NULL)   delete[]uvst;
286   if (nust != NULL)   delete[]nust;
287
288   return isOk;
289 }
290
291
292 //=============================================================================
293 /*!
294  *  
295  */
296 //=============================================================================
297
298 bool StdMeshers_MEFISTO_2D::Evaluate(SMESH_Mesh & aMesh,
299                                      const TopoDS_Shape & aShape,
300                                      MapShapeNbElems& aResMap)
301 {
302   MESSAGE("StdMeshers_MEFISTO_2D::Evaluate");
303
304   TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
305
306   double aLen = 0.0;
307   int NbSeg = 0;
308   bool IsQuadratic = false;
309   bool IsFirst = true;
310   TopExp_Explorer exp(F,TopAbs_EDGE);
311   for(; exp.More(); exp.Next()) {
312     TopoDS_Edge E = TopoDS::Edge(exp.Current());
313     MapShapeNbElemsItr anIt = aResMap.find( aMesh.GetSubMesh(E) );
314     if( anIt == aResMap.end() ) continue;
315     std::vector<int> aVec = (*anIt).second;
316     int nbe = Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
317     NbSeg += nbe;
318     if(IsFirst) {
319       IsQuadratic = ( aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge] );
320       IsFirst = false;
321     }
322     double a,b;
323     TopLoc_Location L;
324     Handle(Geom_Curve) C = BRep_Tool::Curve(E,L,a,b);
325     gp_Pnt P1;
326     C->D0(a,P1);
327     double dp = (b-a)/nbe;
328     for(int i=1; i<=nbe; i++) {
329       gp_Pnt P2;
330       C->D0(a+i*dp,P2);
331       aLen += P1.Distance(P2);
332       P1 = P2;
333     }
334   }
335   if(NbSeg<1) {
336     std::vector<int> aResVec(SMDSEntity_Last);
337     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
338     SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
339     aResMap.insert(std::make_pair(sm,aResVec));
340     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
341     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
342                                           "Submesh can not be evaluated",this));
343     return false;
344   }
345   aLen = aLen/NbSeg; // middle length
346
347   _edgeLength = Precision::Infinite();
348   double tmpLength = Min( _edgeLength, aLen );
349
350   GProp_GProps G;
351   BRepGProp::SurfaceProperties(aShape,G);
352   double anArea = G.Mass();
353
354   int nbFaces = Precision::IsInfinite( tmpLength ) ? 0 :
355     (int)( anArea/(tmpLength*tmpLength*sqrt(3.)/4) );
356   int nbNodes = (int) ( nbFaces*3 - (NbSeg-1)*2 ) / 6;
357
358   std::vector<int> aVec(SMDSEntity_Last);
359   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
360   if(IsQuadratic) {
361     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
362     aVec[SMDSEntity_Node] = (int)( nbNodes + nbFaces*3 - (NbSeg-1) );
363   }
364   else {
365     aVec[SMDSEntity_Node] = nbNodes;
366     aVec[SMDSEntity_Triangle] = nbFaces;
367   }
368   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
369   aResMap.insert(std::make_pair(sm,aVec));
370
371   return true;
372 }
373
374
375 //=======================================================================
376 //function : fixOverlappedLinkUV
377 //purpose  : prevent failure due to overlapped adjacent links
378 //=======================================================================
379
380 static bool fixOverlappedLinkUV( R2& uv0, const R2& uv1, const R2& uv2 )
381 {
382   gp_XY v1( uv0.x - uv1.x, uv0.y - uv1.y );
383   gp_XY v2( uv2.x - uv1.x, uv2.y - uv1.y );
384
385   double tol2 = DBL_MIN * DBL_MIN;
386   double sqMod1 = v1.SquareModulus();
387   if ( sqMod1 <= tol2 ) return false;
388   double sqMod2 = v2.SquareModulus();
389   if ( sqMod2 <= tol2 ) return false;
390
391   double dot = v1*v2;
392
393   // check sinus >= 1.e-3
394   const double minSin = 1.e-3;
395   if ( dot > 0 && 1 - dot * dot / ( sqMod1 * sqMod2 ) < minSin * minSin ) {
396     MESSAGE(" ___ FIX UV ____" << uv0.x << " " << uv0.y);
397     v1.SetCoord( -v1.Y(), v1.X() );
398     double delta = sqrt( sqMod1 ) * minSin;
399     if ( v1.X() < 0 )
400       uv0.x -= delta;
401     else
402       uv0.x += delta;
403     if ( v1.Y() < 0 )
404       uv0.y -= delta;
405     else
406       uv0.y += delta;
407 // #ifdef _DEBUG_
408 //     MESSAGE(" -> " << uv0.x << " " << uv0.y << " ");
409 //     MESSAGE("v1( " << v1.X() << " " << v1.Y() << " ) " <<
410 //       "v2( " << v2.X() << " " << v2.Y() << " ) ");
411 //    MESSAGE("SIN: " << sqrt(1 - dot * dot / (sqMod1 * sqMod2)));
412 //     v1.SetCoord( uv0.x - uv1.x, uv0.y - uv1.y );
413 //     v2.SetCoord( uv2.x - uv1.x, uv2.y - uv1.y );
414 //     gp_XY v3( uv2.x - uv0.x, uv2.y - uv0.y );
415 //     sqMod1 = v1.SquareModulus();
416 //     sqMod2 = v2.SquareModulus();
417 //     dot = v1*v2;
418 //     double sin = sqrt(1 - dot * dot / (sqMod1 * sqMod2));
419 //     MESSAGE("NEW SIN: " << sin);
420 // #endif
421     return true;
422   }
423   return false;
424 }
425
426 //=======================================================================
427 //function : fixCommonVertexUV
428 //purpose  : 
429 //=======================================================================
430
431 static bool fixCommonVertexUV (R2 &                 theUV,
432                                const TopoDS_Vertex& theV,
433                                const TopoDS_Face&   theF,
434                                const TopTools_IndexedDataMapOfShapeListOfShape & theVWMap,
435                                SMESH_Mesh &         theMesh,
436                                const double         theScaleX,
437                                const double         theScaleY,
438                                const bool           theCreateQuadratic)
439 {
440   if( !theVWMap.Contains( theV )) return false;
441
442   // check if there is another wire sharing theV
443   const TopTools_ListOfShape& WList = theVWMap.FindFromKey( theV );
444   TopTools_ListIteratorOfListOfShape aWIt;
445   TopTools_MapOfShape aWires;
446   for ( aWIt.Initialize( WList ); aWIt.More(); aWIt.Next() )
447     aWires.Add( aWIt.Value() );
448   if ( aWires.Extent() < 2 ) return false;
449
450   TopoDS_Shape anOuterWire = BRepTools::OuterWire(theF);
451   TopoDS_Shape anInnerWire;
452   for ( aWIt.Initialize( WList ); aWIt.More() && anInnerWire.IsNull(); aWIt.Next() )
453     if ( !anOuterWire.IsSame( aWIt.Value() ))
454       anInnerWire = aWIt.Value();
455
456   TopTools_ListOfShape EList;
457   list< double >       UList;
458
459   // find edges of theW sharing theV
460   // and find 2d normal to them at theV
461   gp_Vec2d N(0.,0.);
462   TopoDS_Iterator itE( anInnerWire );
463   for (  ; itE.More(); itE.Next() )
464   {
465     const TopoDS_Edge& E = TopoDS::Edge( itE.Value() );
466     TopoDS_Iterator itV( E );
467     for ( ; itV.More(); itV.Next() )
468     {
469       const TopoDS_Vertex & V = TopoDS::Vertex( itV.Value() );
470       if ( !V.IsSame( theV ))
471         continue;
472       EList.Append( E );
473       Standard_Real u = BRep_Tool::Parameter( V, E );
474       UList.push_back( u );
475       double f, l;
476       Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
477       gp_Vec2d d1;
478       gp_Pnt2d p;
479       C2d->D1( u, p, d1 );
480       gp_Vec2d n( d1.Y() * theScaleX, -d1.X() * theScaleY);
481       if ( E.Orientation() == TopAbs_REVERSED )
482         n.Reverse();
483       N += n.Normalized();
484     }
485   }
486
487   // define step size by which to move theUV
488
489   gp_Pnt2d nextUV; // uv of next node on edge, most distant of the four
490   gp_Pnt2d thisUV( theUV.x, theUV.y );
491   double maxDist = -DBL_MAX;
492   TopTools_ListIteratorOfListOfShape aEIt (EList);
493   list< double >::iterator aUIt = UList.begin();
494   for ( ; aEIt.More(); aEIt.Next(), aUIt++ )
495   {
496     const TopoDS_Edge& E = TopoDS::Edge( aEIt.Value() );
497     double f, l;
498     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
499
500     double umin = DBL_MAX, umax = -DBL_MAX;
501     SMDS_NodeIteratorPtr nIt = theMesh.GetSubMesh(E)->GetSubMeshDS()->GetNodes();
502     if ( !nIt->more() ) // no nodes on edge, only on vertices
503     {
504       umin = l;
505       umax = f;
506     }
507     else {
508       while ( nIt->more() ) {
509         const SMDS_MeshNode* node = nIt->next();
510         // check if node is medium
511         if ( theCreateQuadratic && SMESH_MesherHelper::IsMedium( node, SMDSAbs_Edge ))
512           continue;
513         const SMDS_EdgePosition* epos =
514           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
515         double u = epos->GetUParameter();
516         if ( u < umin )
517           umin = u;
518         if ( u > umax )
519           umax = u;
520       }
521     }
522     bool isFirstCommon = ( *aUIt == f );
523     gp_Pnt2d uv = C2d->Value( isFirstCommon ? umin : umax );
524     double dist = thisUV.SquareDistance( uv );
525     if ( dist > maxDist ) {
526       maxDist = dist;
527       nextUV  = uv;
528     }
529   }
530   R2 uv0, uv1, uv2;
531   uv0.x = thisUV.X();   uv0.y = thisUV.Y();
532   uv1.x = nextUV.X();   uv1.y = nextUV.Y(); 
533   uv2.x = thisUV.X();   uv2.y = thisUV.Y();
534
535   uv1.x *= theScaleX;   uv1.y *= theScaleY; 
536
537   if ( fixOverlappedLinkUV( uv0, uv1, uv2 ))
538   {
539     double step = thisUV.Distance( gp_Pnt2d( uv0.x, uv0.y ));
540
541     // move theUV along the normal by the step
542
543     N *= step;
544
545     MESSAGE("--fixCommonVertexUV move(" << theUV.x << " " << theUV.x
546             << ") by (" << N.X() << " " << N.Y() << ")" 
547             << endl << "--- MAX DIST " << maxDist);
548
549     theUV.x += N.X();
550     theUV.y += N.Y();
551
552     return true;
553   }
554   return false;
555 }
556
557 //=============================================================================
558 /*!
559  *  
560  */
561 //=============================================================================
562
563 bool StdMeshers_MEFISTO_2D::LoadPoints(TWireVector &                 wires,
564                                        R2 *                          uvslf,
565                                        vector<const SMDS_MeshNode*>& mefistoToDS,
566                                        double                        scalex,
567                                        double                        scaley)
568 {
569   // to avoid passing same uv points for a vertex common to 2 wires
570   TopoDS_Face F;
571   TopTools_IndexedDataMapOfShapeListOfShape VWMap;
572   if ( wires.size() > 1 )
573   {
574     F = TopoDS::Face( myTool->GetSubShape() );
575     TopExp::MapShapesAndAncestors( F, TopAbs_VERTEX, TopAbs_WIRE, VWMap );
576     int nbVertices = 0;
577     for ( int iW = 0; iW < wires.size(); ++iW )
578       nbVertices += wires[ iW ]->NbEdges();
579     if ( nbVertices == VWMap.Extent() )
580       VWMap.Clear(); // wires have no common vertices
581   }
582
583   int m = 0;
584
585   for ( int iW = 0; iW < wires.size(); ++iW )
586   {
587     const vector<UVPtStruct>& uvPtVec = wires[ iW ]->GetUVPtStruct();
588     if ( uvPtVec.size() != wires[ iW ]->NbPoints() ) {
589       return error(COMPERR_BAD_INPUT_MESH,SMESH_Comment("Unexpected nb of points on wire ")
590                    << iW << ": " << uvPtVec.size()<<" != "<<wires[ iW ]->NbPoints()
591                    << ", probably because of invalid node parameters on geom edges");
592     }
593     if ( m + uvPtVec.size()-1 > mefistoToDS.size() ) {
594       MESSAGE("Wrong mefistoToDS.size: "<<mefistoToDS.size()<<" < "<<m + uvPtVec.size()-1);
595       return error("Internal error");
596     }
597
598     list< int > mOnVertex;
599     vector<UVPtStruct>::const_iterator uvPt = uvPtVec.begin();
600     for ( ++uvPt; uvPt != uvPtVec.end(); ++uvPt )
601     {
602       // bind mefisto ID to node
603       mefistoToDS[m] = uvPt->node;
604       // set UV
605       uvslf[m].x = uvPt->u * scalex;
606       uvslf[m].y = uvPt->v * scaley;
607       if ( uvPt->node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
608         mOnVertex.push_back( m );
609       m++;
610     }
611
612     int mFirst = mOnVertex.front(), mLast = m - 1;
613     list< int >::iterator mIt = mOnVertex.begin();
614     for ( ; mIt != mOnVertex.end(); ++mIt)
615     {
616       int m = *mIt;
617       if ( iW && !VWMap.IsEmpty()) { // except outer wire
618         // avoid passing same uv point for a vertex common to 2 wires
619         int vID = mefistoToDS[m]->GetPosition()->GetShapeId();
620         TopoDS_Vertex V = TopoDS::Vertex( myTool->GetMeshDS()->IndexToShape( vID ));
621         if ( fixCommonVertexUV( uvslf[m], V, F, VWMap, *myTool->GetMesh(),
622                                 scalex, scaley, _quadraticMesh )) {
623           myNodesOnCommonV.push_back( mefistoToDS[m] );
624           continue;
625         }
626       }
627       // prevent failure on overlapped adjacent links,
628       // check only links ending in vertex nodes
629       int mB = m - 1, mA = m + 1; // indices Before and After
630       if ( mB < mFirst ) mB = mLast;
631       if ( mA > mLast )  mA = mFirst;
632       fixOverlappedLinkUV (uvslf[ mB ], uvslf[ m ], uvslf[ mA ]);
633     }
634   }
635
636   return true;
637 }
638
639 //=============================================================================
640 /*!
641  *  
642  */
643 //=============================================================================
644
645 void StdMeshers_MEFISTO_2D::ComputeScaleOnFace(SMESH_Mesh &        aMesh,
646                                                const TopoDS_Face & aFace,
647                                                double &            scalex,
648                                                double &            scaley)
649 {
650   TopoDS_Wire W = BRepTools::OuterWire(aFace);
651
652   double xmin = 1.e300;         // min & max of face 2D parametric coord.
653   double xmax = -1.e300;
654   double ymin = 1.e300;
655   double ymax = -1.e300;
656   int nbp = 23;
657   scalex = 1;
658   scaley = 1;
659
660   TopExp_Explorer wexp(W, TopAbs_EDGE);
661   for ( ; wexp.More(); wexp.Next())
662   {
663     const TopoDS_Edge & E = TopoDS::Edge( wexp.Current() );
664     double f, l;
665     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, aFace, f, l);
666     if ( C2d.IsNull() ) continue;
667     double du = (l - f) / double (nbp);
668     for (int i = 0; i <= nbp; i++)
669     {
670       double param = f + double (i) * du;
671       gp_Pnt2d p = C2d->Value(param);
672       if (p.X() < xmin)
673         xmin = p.X();
674       if (p.X() > xmax)
675         xmax = p.X();
676       if (p.Y() < ymin)
677         ymin = p.Y();
678       if (p.Y() > ymax)
679         ymax = p.Y();
680       //    MESSAGE(" "<< f<<" "<<l<<" "<<param<<" "<<xmin<<" "<<xmax<<" "<<ymin<<" "<<ymax);
681     }
682   }
683   //   SCRUTE(xmin);
684   //   SCRUTE(xmax);
685   //   SCRUTE(ymin);
686   //   SCRUTE(ymax);
687   double xmoy = (xmax + xmin) / 2.;
688   double ymoy = (ymax + ymin) / 2.;
689   double xsize = xmax - xmin;
690   double ysize = ymax - ymin;
691
692   TopLoc_Location L;
693   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace,L);       // 3D surface
694
695   double length_x = 0;
696   double length_y = 0;
697   gp_Pnt PX0 = S->Value(xmin, ymoy);
698   gp_Pnt PY0 = S->Value(xmoy, ymin);
699   double dx = xsize / double (nbp);
700   double dy = ysize / double (nbp);
701   for (int i = 1; i <= nbp; i++)
702   {
703     double x = xmin + double (i) * dx;
704     gp_Pnt PX = S->Value(x, ymoy);
705     double y = ymin + double (i) * dy;
706     gp_Pnt PY = S->Value(xmoy, y);
707     length_x += PX.Distance(PX0);
708     length_y += PY.Distance(PY0);
709     PX0 = PX;
710     PY0 = PY;
711   }
712   scalex = length_x / xsize;
713   scaley = length_y / ysize;
714 //   SCRUTE(xsize);
715 //   SCRUTE(ysize);
716   double xyratio = xsize*scalex/(ysize*scaley);
717   const double maxratio = 1.e2;
718   //SCRUTE(xyratio);
719   if (xyratio > maxratio) {
720     SCRUTE( scaley );
721     scaley *= xyratio / maxratio;
722     SCRUTE( scaley );
723   }
724   else if (xyratio < 1./maxratio) {
725     SCRUTE( scalex );
726     scalex *= 1 / xyratio / maxratio;
727     SCRUTE( scalex );
728   }
729   ASSERT(scalex);
730   ASSERT(scaley);
731 }
732
733 //=============================================================================
734 /*!
735  *  
736  */
737 //=============================================================================
738
739 void StdMeshers_MEFISTO_2D::StoreResult(Z nbst, R2 * uvst, Z nbt, Z * nust,
740                                         vector< const SMDS_MeshNode*>&mefistoToDS,
741                                         double scalex, double scaley)
742 {
743   SMESHDS_Mesh * meshDS = myTool->GetMeshDS();
744   int faceID = myTool->GetSubShapeID();
745
746   TopoDS_Face F = TopoDS::Face( myTool->GetSubShape() );
747   Handle(Geom_Surface) S = BRep_Tool::Surface( F );
748
749   Z n = mefistoToDS.size(); // nb input points
750   mefistoToDS.resize( nbst );
751   for ( ; n < nbst; n++)
752   {
753     if (!mefistoToDS[n])
754     {
755       double u = uvst[n][0] / scalex;
756       double v = uvst[n][1] / scaley;
757       gp_Pnt P = S->Value(u, v);
758
759       SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
760       meshDS->SetNodeOnFace(node, faceID, u, v);
761
762       //MESSAGE(P.X()<<" "<<P.Y()<<" "<<P.Z());
763       mefistoToDS[n] = node;
764       //MESSAGE("NEW: "<<n<<" "<<mefistoToDS[n+1]);
765     }
766   }
767
768   Z m = 0;
769
770   // triangle points must be in trigonometric order if face is Forward
771   // else they must be put clockwise
772
773   bool triangleIsWellOriented = ( F.Orientation() == TopAbs_FORWARD );
774
775   for (n = 1; n <= nbt; n++)
776   {
777     const SMDS_MeshNode * n1 = mefistoToDS[ nust[m++] - 1 ];
778     const SMDS_MeshNode * n2 = mefistoToDS[ nust[m++] - 1 ];
779     const SMDS_MeshNode * n3 = mefistoToDS[ nust[m++] - 1 ];
780
781     SMDS_MeshElement * elt;
782     if (triangleIsWellOriented)
783       elt = myTool->AddFace(n1, n2, n3);
784     else
785       elt = myTool->AddFace(n1, n3, n2);
786
787     meshDS->SetMeshElementOnShape(elt, faceID);
788     m++;
789   }
790
791   // remove bad elements built on vertices shared by wires
792
793   list<const SMDS_MeshNode*>::iterator itN = myNodesOnCommonV.begin();
794   for ( ; itN != myNodesOnCommonV.end(); itN++ )
795   {
796     const SMDS_MeshNode* node = *itN;
797     SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
798     while ( invElemIt->more() )
799     {
800       const SMDS_MeshElement* elem = invElemIt->next();
801       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
802       int nbSame = 0;
803       while ( itN->more() )
804         if ( itN->next() == node)
805           nbSame++;
806       if (nbSame > 1) {
807         MESSAGE( "RM bad element " << elem->GetID());
808         meshDS->RemoveElement( elem );
809       }
810     }
811   }
812 }