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