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