Salome HOME
PR: merged from V5_1_4rc1
[modules/smesh.git] / src / StdMeshers / StdMeshers_MEFISTO_2D.cxx
1 //  Copyright (C) 2007-2010  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   
241   nblf = nbWires;
242   
243   nudslf = new Z[1 + nblf];
244   nudslf[0] = 0;
245   int iw = 1;
246   int nbpnt = 0;
247
248   // count nb of input points
249   for ( int iW = 0; iW < nbWires; ++iW )
250   {
251     nbpnt += wires[iW]->NbPoints() - 1;
252     nudslf[iw++] = nbpnt;
253   }
254
255   uvslf = new R2[nudslf[nblf]];
256
257   double scalex, scaley;
258   ComputeScaleOnFace(aMesh, F, scalex, scaley);
259
260   // correspondence mefisto index --> Nodes
261   vector< const SMDS_MeshNode*> mefistoToDS(nbpnt, (const SMDS_MeshNode*)0);
262
263   bool isOk = false;
264
265   // fill input points UV
266   if ( LoadPoints(wires, uvslf, mefistoToDS, scalex, scaley) )
267   {
268     // Compute
269     aptrte(nutysu, aretmx,
270            nblf, nudslf, uvslf, nbpti, uvpti, nbst, uvst, nbt, nust, ierr);
271
272     if (ierr == 0)
273     {
274       MESSAGE("... End Triangulation Generated Triangle Number " << nbt);
275       MESSAGE("                                    Node Number " << nbst);
276       StoreResult(nbst, uvst, nbt, nust, mefistoToDS, scalex, scaley);
277       isOk = true;
278     }
279     else
280     {
281       error(ierr,"Error in Triangulation (aptrte())");
282     }
283   }
284   if (nudslf != NULL) delete[]nudslf;
285   if (uvslf != NULL)  delete[]uvslf;
286   if (uvst != NULL)   delete[]uvst;
287   if (nust != NULL)   delete[]nust;
288
289   return isOk;
290 }
291
292
293 //=============================================================================
294 /*!
295  *  
296  */
297 //=============================================================================
298
299 bool StdMeshers_MEFISTO_2D::Evaluate(SMESH_Mesh & aMesh,
300                                      const TopoDS_Shape & aShape,
301                                      MapShapeNbElems& aResMap)
302 {
303   MESSAGE("StdMeshers_MEFISTO_2D::Evaluate");
304
305   TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
306
307   double aLen = 0.0;
308   int NbSeg = 0;
309   bool IsQuadratic = false;
310   bool IsFirst = true;
311   TopExp_Explorer exp(F,TopAbs_EDGE);
312   for(; exp.More(); exp.Next()) {
313     TopoDS_Edge E = TopoDS::Edge(exp.Current());
314     MapShapeNbElemsItr anIt = aResMap.find( aMesh.GetSubMesh(E) );
315     if( anIt == aResMap.end() ) continue;
316     std::vector<int> aVec = (*anIt).second;
317     int nbe = Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
318     NbSeg += nbe;
319     if(IsFirst) {
320       IsQuadratic = ( aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge] );
321       IsFirst = false;
322     }
323     double a,b;
324     TopLoc_Location L;
325     Handle(Geom_Curve) C = BRep_Tool::Curve(E,L,a,b);
326     gp_Pnt P1;
327     C->D0(a,P1);
328     double dp = (b-a)/nbe;
329     for(int i=1; i<=nbe; i++) {
330       gp_Pnt P2;
331       C->D0(a+i*dp,P2);
332       aLen += P1.Distance(P2);
333       P1 = P2;
334     }
335   }
336   if(NbSeg<1) {
337     std::vector<int> aResVec(SMDSEntity_Last);
338     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
339     SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
340     aResMap.insert(std::make_pair(sm,aResVec));
341     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
342     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
343                                           "Submesh can not be evaluated",this));
344     return false;
345   }
346   aLen = aLen/NbSeg; // middle length
347
348   _edgeLength = Precision::Infinite();
349   double tmpLength = Min( _edgeLength, aLen );
350
351   GProp_GProps G;
352   BRepGProp::SurfaceProperties(aShape,G);
353   double anArea = G.Mass();
354
355   int nbFaces = Precision::IsInfinite( tmpLength ) ? 0 :
356     (int)( anArea/(tmpLength*tmpLength*sqrt(3.)/4) );
357   int nbNodes = (int) ( nbFaces*3 - (NbSeg-1)*2 ) / 6;
358
359   std::vector<int> aVec(SMDSEntity_Last);
360   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
361   if(IsQuadratic) {
362     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
363     aVec[SMDSEntity_Node] = (int)( nbNodes + nbFaces*3 - (NbSeg-1) );
364   }
365   else {
366     aVec[SMDSEntity_Node] = nbNodes;
367     aVec[SMDSEntity_Triangle] = nbFaces;
368   }
369   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
370   aResMap.insert(std::make_pair(sm,aVec));
371
372   return true;
373 }
374
375
376 //=======================================================================
377 //function : fixOverlappedLinkUV
378 //purpose  : prevent failure due to overlapped adjacent links
379 //=======================================================================
380
381 static bool fixOverlappedLinkUV( R2& uv0, const R2& uv1, const R2& uv2 )
382 {
383   gp_XY v1( uv0.x - uv1.x, uv0.y - uv1.y );
384   gp_XY v2( uv2.x - uv1.x, uv2.y - uv1.y );
385
386   double tol2 = DBL_MIN * DBL_MIN;
387   double sqMod1 = v1.SquareModulus();
388   if ( sqMod1 <= tol2 ) return false;
389   double sqMod2 = v2.SquareModulus();
390   if ( sqMod2 <= tol2 ) return false;
391
392   double dot = v1*v2;
393
394   // check sinus >= 1.e-3
395   const double minSin = 1.e-3;
396   if ( dot > 0 && 1 - dot * dot / ( sqMod1 * sqMod2 ) < minSin * minSin ) {
397     MESSAGE(" ___ FIX UV ____" << uv0.x << " " << uv0.y);
398     v1.SetCoord( -v1.Y(), v1.X() );
399     double delta = sqrt( sqMod1 ) * minSin;
400     if ( v1.X() < 0 )
401       uv0.x -= delta;
402     else
403       uv0.x += delta;
404     if ( v1.Y() < 0 )
405       uv0.y -= delta;
406     else
407       uv0.y += delta;
408 // #ifdef _DEBUG_
409 //     MESSAGE(" -> " << uv0.x << " " << uv0.y << " ");
410 //     MESSAGE("v1( " << v1.X() << " " << v1.Y() << " ) " <<
411 //       "v2( " << v2.X() << " " << v2.Y() << " ) ");
412 //    MESSAGE("SIN: " << sqrt(1 - dot * dot / (sqMod1 * sqMod2)));
413 //     v1.SetCoord( uv0.x - uv1.x, uv0.y - uv1.y );
414 //     v2.SetCoord( uv2.x - uv1.x, uv2.y - uv1.y );
415 //     gp_XY v3( uv2.x - uv0.x, uv2.y - uv0.y );
416 //     sqMod1 = v1.SquareModulus();
417 //     sqMod2 = v2.SquareModulus();
418 //     dot = v1*v2;
419 //     double sin = sqrt(1 - dot * dot / (sqMod1 * sqMod2));
420 //     MESSAGE("NEW SIN: " << sin);
421 // #endif
422     return true;
423   }
424   return false;
425 }
426
427 //=======================================================================
428 //function : fixCommonVertexUV
429 //purpose  : 
430 //=======================================================================
431
432 static bool fixCommonVertexUV (R2 &                 theUV,
433                                const TopoDS_Vertex& theV,
434                                const TopoDS_Face&   theF,
435                                const TopTools_IndexedDataMapOfShapeListOfShape & theVWMap,
436                                SMESH_Mesh &         theMesh,
437                                const double         theScaleX,
438                                const double         theScaleY,
439                                const bool           theCreateQuadratic)
440 {
441   if( !theVWMap.Contains( theV )) return false;
442
443   // check if there is another wire sharing theV
444   const TopTools_ListOfShape& WList = theVWMap.FindFromKey( theV );
445   TopTools_ListIteratorOfListOfShape aWIt;
446   TopTools_MapOfShape aWires;
447   for ( aWIt.Initialize( WList ); aWIt.More(); aWIt.Next() )
448     aWires.Add( aWIt.Value() );
449   if ( aWires.Extent() < 2 ) return false;
450
451   TopoDS_Shape anOuterWire = BRepTools::OuterWire(theF);
452   TopoDS_Shape anInnerWire;
453   for ( aWIt.Initialize( WList ); aWIt.More() && anInnerWire.IsNull(); aWIt.Next() )
454     if ( !anOuterWire.IsSame( aWIt.Value() ))
455       anInnerWire = aWIt.Value();
456
457   TopTools_ListOfShape EList;
458   list< double >       UList;
459
460   // find edges of theW sharing theV
461   // and find 2d normal to them at theV
462   gp_Vec2d N(0.,0.);
463   TopoDS_Iterator itE( anInnerWire );
464   for (  ; itE.More(); itE.Next() )
465   {
466     const TopoDS_Edge& E = TopoDS::Edge( itE.Value() );
467     TopoDS_Iterator itV( E );
468     for ( ; itV.More(); itV.Next() )
469     {
470       const TopoDS_Vertex & V = TopoDS::Vertex( itV.Value() );
471       if ( !V.IsSame( theV ))
472         continue;
473       EList.Append( E );
474       Standard_Real u = BRep_Tool::Parameter( V, E );
475       UList.push_back( u );
476       double f, l;
477       Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
478       gp_Vec2d d1;
479       gp_Pnt2d p;
480       C2d->D1( u, p, d1 );
481       gp_Vec2d n( d1.Y() * theScaleX, -d1.X() * theScaleY);
482       if ( E.Orientation() == TopAbs_REVERSED )
483         n.Reverse();
484       N += n.Normalized();
485     }
486   }
487
488   // define step size by which to move theUV
489
490   gp_Pnt2d nextUV; // uv of next node on edge, most distant of the four
491   gp_Pnt2d thisUV( theUV.x, theUV.y );
492   double maxDist = -DBL_MAX;
493   TopTools_ListIteratorOfListOfShape aEIt (EList);
494   list< double >::iterator aUIt = UList.begin();
495   for ( ; aEIt.More(); aEIt.Next(), aUIt++ )
496   {
497     const TopoDS_Edge& E = TopoDS::Edge( aEIt.Value() );
498     double f, l;
499     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
500
501     double umin = DBL_MAX, umax = -DBL_MAX;
502     SMDS_NodeIteratorPtr nIt = theMesh.GetSubMesh(E)->GetSubMeshDS()->GetNodes();
503     if ( !nIt->more() ) // no nodes on edge, only on vertices
504     {
505       umin = l;
506       umax = f;
507     }
508     else {
509       while ( nIt->more() ) {
510         const SMDS_MeshNode* node = nIt->next();
511         // check if node is medium
512         if ( theCreateQuadratic && SMESH_MesherHelper::IsMedium( node, SMDSAbs_Edge ))
513           continue;
514         const SMDS_EdgePosition* epos =
515           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
516         double u = epos->GetUParameter();
517         if ( u < umin )
518           umin = u;
519         if ( u > umax )
520           umax = u;
521       }
522     }
523     bool isFirstCommon = ( *aUIt == f );
524     gp_Pnt2d uv = C2d->Value( isFirstCommon ? umin : umax );
525     double dist = thisUV.SquareDistance( uv );
526     if ( dist > maxDist ) {
527       maxDist = dist;
528       nextUV  = uv;
529     }
530   }
531   R2 uv0, uv1, uv2;
532   uv0.x = thisUV.X();   uv0.y = thisUV.Y();
533   uv1.x = nextUV.X();   uv1.y = nextUV.Y(); 
534   uv2.x = thisUV.X();   uv2.y = thisUV.Y();
535
536   uv1.x *= theScaleX;   uv1.y *= theScaleY; 
537
538   if ( fixOverlappedLinkUV( uv0, uv1, uv2 ))
539   {
540     double step = thisUV.Distance( gp_Pnt2d( uv0.x, uv0.y ));
541
542     // move theUV along the normal by the step
543
544     N *= step;
545
546     MESSAGE("--fixCommonVertexUV move(" << theUV.x << " " << theUV.x
547             << ") by (" << N.X() << " " << N.Y() << ")" 
548             << endl << "--- MAX DIST " << maxDist);
549
550     theUV.x += N.X();
551     theUV.y += N.Y();
552
553     return true;
554   }
555   return false;
556 }
557
558 //=============================================================================
559 /*!
560  *  
561  */
562 //=============================================================================
563
564 bool StdMeshers_MEFISTO_2D::LoadPoints(TWireVector &                 wires,
565                                        R2 *                          uvslf,
566                                        vector<const SMDS_MeshNode*>& mefistoToDS,
567                                        double                        scalex,
568                                        double                        scaley)
569 {
570   // to avoid passing same uv points for a vertex common to 2 wires
571   TopoDS_Face F;
572   TopTools_IndexedDataMapOfShapeListOfShape VWMap;
573   if ( wires.size() > 1 )
574   {
575     F = TopoDS::Face( myTool->GetSubShape() );
576     TopExp::MapShapesAndAncestors( F, TopAbs_VERTEX, TopAbs_WIRE, VWMap );
577     int nbVertices = 0;
578     for ( int iW = 0; iW < wires.size(); ++iW )
579       nbVertices += wires[ iW ]->NbEdges();
580     if ( nbVertices == VWMap.Extent() )
581       VWMap.Clear(); // wires have no common vertices
582   }
583
584   int m = 0;
585
586   for ( int iW = 0; iW < wires.size(); ++iW )
587   {
588     const vector<UVPtStruct>& uvPtVec = wires[ iW ]->GetUVPtStruct();
589     if ( uvPtVec.size() != wires[ iW ]->NbPoints() ) {
590       return error(COMPERR_BAD_INPUT_MESH,SMESH_Comment("Unexpected nb of points on wire ")
591                    << iW << ": " << uvPtVec.size()<<" != "<<wires[ iW ]->NbPoints()
592                    << ", probably because of invalid node parameters on geom edges");
593     }
594     if ( m + uvPtVec.size()-1 > mefistoToDS.size() ) {
595       MESSAGE("Wrong mefistoToDS.size: "<<mefistoToDS.size()<<" < "<<m + uvPtVec.size()-1);
596       return error("Internal error");
597     }
598
599     list< int > mOnVertex;
600     vector<UVPtStruct>::const_iterator uvPt = uvPtVec.begin();
601     for ( ++uvPt; uvPt != uvPtVec.end(); ++uvPt )
602     {
603       // bind mefisto ID to node
604       mefistoToDS[m] = uvPt->node;
605       // set UV
606       uvslf[m].x = uvPt->u * scalex;
607       uvslf[m].y = uvPt->v * scaley;
608       switch ( uvPt->node->GetPosition()->GetTypeOfPosition())
609       {
610       case SMDS_TOP_VERTEX:
611         mOnVertex.push_back( m );
612         break;
613       case SMDS_TOP_EDGE:
614         // In order to detect degenerated faces easily, we replace
615         // nodes on a degenerated edge by node on the vertex of that edge
616         if ( myTool->IsDegenShape( uvPt->node->GetPosition()->GetShapeId() ))
617         {
618           int edgeID = uvPt->node->GetPosition()->GetShapeId();
619           SMESH_subMesh* edgeSM = myTool->GetMesh()->GetSubMeshContaining( edgeID );
620           SMESH_subMeshIteratorPtr smIt = edgeSM->getDependsOnIterator( /*includeSelf=*/0,
621                                                                         /*complexShapeFirst=*/0);
622           if ( smIt->more() )
623           {
624             SMESH_subMesh* vertexSM = smIt->next();
625             SMDS_NodeIteratorPtr nIt = vertexSM->GetSubMeshDS()->GetNodes();
626             if ( nIt->more() )
627               mefistoToDS[m] = nIt->next();
628           }
629         }
630         break;
631       default:;
632       }
633       m++;
634     }
635
636     int mFirst = mOnVertex.front(), mLast = m - 1;
637     list< int >::iterator mIt = mOnVertex.begin();
638     for ( ; mIt != mOnVertex.end(); ++mIt)
639     {
640       int m = *mIt;
641       if ( iW && !VWMap.IsEmpty()) { // except outer wire
642         // avoid passing same uv point for a vertex common to 2 wires
643         int vID = mefistoToDS[m]->GetPosition()->GetShapeId();
644         TopoDS_Vertex V = TopoDS::Vertex( myTool->GetMeshDS()->IndexToShape( vID ));
645         if ( fixCommonVertexUV( uvslf[m], V, F, VWMap, *myTool->GetMesh(),
646                                 scalex, scaley, _quadraticMesh )) {
647           myNodesOnCommonV.push_back( mefistoToDS[m] );
648           continue;
649         }
650       }
651       // prevent failure on overlapped adjacent links,
652       // check only links ending in vertex nodes
653       int mB = m - 1, mA = m + 1; // indices Before and After
654       if ( mB < mFirst ) mB = mLast;
655       if ( mA > mLast )  mA = mFirst;
656       fixOverlappedLinkUV (uvslf[ mB ], uvslf[ m ], uvslf[ mA ]);
657     }
658   }
659 //   cout << "MEFISTO INPUT************" << endl;
660 //   for ( int i =0; i < m; ++i )
661 //     cout << i << ": \t" << uvslf[i].x << ", " << uvslf[i].y << " Node " << mefistoToDS[i]->GetID()<< endl;
662
663   return true;
664 }
665
666 //=============================================================================
667 /*!
668  *  
669  */
670 //=============================================================================
671
672 void StdMeshers_MEFISTO_2D::ComputeScaleOnFace(SMESH_Mesh &        aMesh,
673                                                const TopoDS_Face & aFace,
674                                                double &            scalex,
675                                                double &            scaley)
676 {
677   TopoDS_Wire W = BRepTools::OuterWire(aFace);
678
679   double xmin = 1.e300;         // min & max of face 2D parametric coord.
680   double xmax = -1.e300;
681   double ymin = 1.e300;
682   double ymax = -1.e300;
683   int nbp = 23;
684   scalex = 1;
685   scaley = 1;
686
687   TopExp_Explorer wexp(W, TopAbs_EDGE);
688   for ( ; wexp.More(); wexp.Next())
689   {
690     const TopoDS_Edge & E = TopoDS::Edge( wexp.Current() );
691     double f, l;
692     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, aFace, f, l);
693     if ( C2d.IsNull() ) continue;
694     double du = (l - f) / double (nbp);
695     for (int i = 0; i <= nbp; i++)
696     {
697       double param = f + double (i) * du;
698       gp_Pnt2d p = C2d->Value(param);
699       if (p.X() < xmin)
700         xmin = p.X();
701       if (p.X() > xmax)
702         xmax = p.X();
703       if (p.Y() < ymin)
704         ymin = p.Y();
705       if (p.Y() > ymax)
706         ymax = p.Y();
707       //    MESSAGE(" "<< f<<" "<<l<<" "<<param<<" "<<xmin<<" "<<xmax<<" "<<ymin<<" "<<ymax);
708     }
709   }
710   //   SCRUTE(xmin);
711   //   SCRUTE(xmax);
712   //   SCRUTE(ymin);
713   //   SCRUTE(ymax);
714   double xmoy = (xmax + xmin) / 2.;
715   double ymoy = (ymax + ymin) / 2.;
716   double xsize = xmax - xmin;
717   double ysize = ymax - ymin;
718
719   TopLoc_Location L;
720   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace,L);       // 3D surface
721
722   double length_x = 0;
723   double length_y = 0;
724   gp_Pnt PX0 = S->Value(xmin, ymoy);
725   gp_Pnt PY0 = S->Value(xmoy, ymin);
726   double dx = xsize / double (nbp);
727   double dy = ysize / double (nbp);
728   for (int i = 1; i <= nbp; i++)
729   {
730     double x = xmin + double (i) * dx;
731     gp_Pnt PX = S->Value(x, ymoy);
732     double y = ymin + double (i) * dy;
733     gp_Pnt PY = S->Value(xmoy, y);
734     length_x += PX.Distance(PX0);
735     length_y += PY.Distance(PY0);
736     PX0 = PX;
737     PY0 = PY;
738   }
739   scalex = length_x / xsize;
740   scaley = length_y / ysize;
741 //   SCRUTE(xsize);
742 //   SCRUTE(ysize);
743   double xyratio = xsize*scalex/(ysize*scaley);
744   const double maxratio = 1.e2;
745   //SCRUTE(xyratio);
746   if (xyratio > maxratio) {
747     SCRUTE( scaley );
748     scaley *= xyratio / maxratio;
749     SCRUTE( scaley );
750   }
751   else if (xyratio < 1./maxratio) {
752     SCRUTE( scalex );
753     scalex *= 1 / xyratio / maxratio;
754     SCRUTE( scalex );
755   }
756   ASSERT(scalex);
757   ASSERT(scaley);
758 }
759
760 //=============================================================================
761 /*!
762  *  
763  */
764 //=============================================================================
765
766 void StdMeshers_MEFISTO_2D::StoreResult(Z nbst, R2 * uvst, Z nbt, Z * nust,
767                                         vector< const SMDS_MeshNode*>&mefistoToDS,
768                                         double scalex, double scaley)
769 {
770   SMESHDS_Mesh * meshDS = myTool->GetMeshDS();
771   int faceID = myTool->GetSubShapeID();
772
773   TopoDS_Face F = TopoDS::Face( myTool->GetSubShape() );
774   Handle(Geom_Surface) S = BRep_Tool::Surface( F );
775
776   Z n = mefistoToDS.size(); // nb input points
777   mefistoToDS.resize( nbst );
778   for ( ; n < nbst; n++)
779   {
780     if (!mefistoToDS[n])
781     {
782       double u = uvst[n][0] / scalex;
783       double v = uvst[n][1] / scaley;
784       gp_Pnt P = S->Value(u, v);
785
786       SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
787       meshDS->SetNodeOnFace(node, faceID, u, v);
788
789       //MESSAGE(P.X()<<" "<<P.Y()<<" "<<P.Z());
790       mefistoToDS[n] = node;
791       //MESSAGE("NEW: "<<n<<" "<<mefistoToDS[n+1]);
792     }
793   }
794
795   Z m = 0;
796
797   // triangle points must be in trigonometric order if face is Forward
798   // else they must be put clockwise
799
800   bool triangleIsWellOriented = ( F.Orientation() == TopAbs_FORWARD );
801
802   for (n = 1; n <= nbt; n++)
803   {
804     const SMDS_MeshNode * n1 = mefistoToDS[ nust[m++] - 1 ];
805     const SMDS_MeshNode * n2 = mefistoToDS[ nust[m++] - 1 ];
806     const SMDS_MeshNode * n3 = mefistoToDS[ nust[m++] - 1 ];
807
808     // avoid creating degenetrated faces
809     bool isDegen = ( myTool->HasDegeneratedEdges() && ( n1 == n2 || n1 == n3 || n2 == n3 ));
810     if ( !isDegen )
811     {
812       SMDS_MeshElement * elt;
813       if (triangleIsWellOriented)
814         elt = myTool->AddFace(n1, n2, n3);
815       else
816         elt = myTool->AddFace(n1, n3, n2);
817       meshDS->SetMeshElementOnShape(elt, faceID);
818     }
819     m++;
820   }
821
822   // remove bad elements built on vertices shared by wires
823
824   list<const SMDS_MeshNode*>::iterator itN = myNodesOnCommonV.begin();
825   for ( ; itN != myNodesOnCommonV.end(); itN++ )
826   {
827     const SMDS_MeshNode* node = *itN;
828     SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
829     while ( invElemIt->more() )
830     {
831       const SMDS_MeshElement* elem = invElemIt->next();
832       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
833       int nbSame = 0;
834       while ( itN->more() )
835         if ( itN->next() == node)
836           nbSame++;
837       if (nbSame > 1) {
838         MESSAGE( "RM bad element " << elem->GetID());
839         meshDS->RemoveElement( elem );
840       }
841     }
842   }
843 }