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