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