]> SALOME platform Git repositories - plugins/blsurfplugin.git/blob - src/BLSURFPlugin/BLSURFPlugin_BLSURF.cxx
Salome HOME
6c7b214f2fa31ca407b74756da39d13e47ca5bce
[plugins/blsurfplugin.git] / src / BLSURFPlugin / BLSURFPlugin_BLSURF.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D
2 //
3 //  This library is free software; you can redistribute it and/or
4 //  modify it under the terms of the GNU Lesser General Public
5 //  License as published by the Free Software Foundation; either
6 //  version 2.1 of the License.
7 //
8 //  This library is distributed in the hope that it will be useful,
9 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
10 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 //  Lesser General Public License for more details.
12 //
13 //  You should have received a copy of the GNU Lesser General Public
14 //  License along with this library; if not, write to the Free Software
15 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // ---
20 // File    : BLSURFPlugin_BLSURF.cxx
21 // Authors : Francis KLOSS (OCC) & Patrick LAUG (INRIA) & Lioka RAZAFINDRAZAKA (CEA)
22 //           & Aurelien ALLEAUME (DISTENE)
23 //           Size maps developement: Nicolas GEIMER (OCC) & Gilles DAVID (EURIWARE)
24 // ---
25 //
26 #include "BLSURFPlugin_BLSURF.hxx"
27 #include "BLSURFPlugin_Hypothesis.hxx"
28
29 #include <structmember.h>
30
31
32 #include <SMESH_Gen.hxx>
33 #include <SMESH_Mesh.hxx>
34 #include <SMESH_ControlsDef.hxx>
35
36 #include <utilities.h>
37
38 #include <limits>
39 #include <list>
40 #include <vector>
41 #include <set>
42 #include <cstdlib>
43
44 #include <BRep_Tool.hxx>
45 #include <TopExp.hxx>
46 #include <TopExp_Explorer.hxx>
47 #include <TopoDS.hxx>
48 #include <NCollection_Map.hxx>
49 #include <Standard_ErrorHandler.hxx>
50
51 extern "C"{
52 #include "distene/blsurf.h"
53 #include <distene/api.h>
54 }
55
56 #include <Geom_Surface.hxx>
57 #include <Handle_Geom_Surface.hxx>
58 #include <Geom2d_Curve.hxx>
59 #include <Handle_Geom2d_Curve.hxx>
60 #include <Geom_Curve.hxx>
61 #include <Handle_Geom_Curve.hxx>
62 #include <TopoDS_Vertex.hxx>
63 #include <TopoDS_Edge.hxx>
64 #include <TopoDS_Wire.hxx>
65 #include <TopoDS_Face.hxx>
66 #include <TopoDS_Shape.hxx>
67 #include <gp_Pnt2d.hxx>
68 #include <TopTools_IndexedMapOfShape.hxx>
69 #include <BRepTools.hxx>
70 #include <TopTools_DataMapOfShapeInteger.hxx>
71 #include <GProp_GProps.hxx>
72 #include <BRepGProp.hxx>
73
74 #ifndef WNT
75 #include <fenv.h>
76 #endif
77
78 #include <GeomAPI_ProjectPointOnCurve.hxx>
79 #include <GeomAPI_ProjectPointOnSurf.hxx>
80 #include <gp_XY.hxx>
81 #include <gp_XYZ.hxx>
82 // #include <BRepClass_FaceClassifier.hxx>
83 #include <TopTools_MapOfShape.hxx>
84
85 /* ==================================
86  * ===========  PYTHON ==============
87  * ==================================*/
88
89 typedef struct {
90   PyObject_HEAD
91   int softspace;
92   std::string *out;
93   } PyStdOut;
94
95 static void
96 PyStdOut_dealloc(PyStdOut *self)
97 {
98   PyObject_Del(self);
99 }
100
101 static PyObject *
102 PyStdOut_write(PyStdOut *self, PyObject *args)
103 {
104   char *c;
105   int l;
106   if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
107     return NULL;
108
109   //std::cerr << c ;
110   *(self->out)=*(self->out)+c;
111
112   Py_INCREF(Py_None);
113   return Py_None;
114 }
115
116 static PyMethodDef PyStdOut_methods[] = {
117   {"write",  (PyCFunction)PyStdOut_write,  METH_VARARGS,
118     PyDoc_STR("write(string) -> None")},
119   {NULL,    NULL}   /* sentinel */
120 };
121
122 static PyMemberDef PyStdOut_memberlist[] = {
123   {"softspace", T_INT,  offsetof(PyStdOut, softspace), 0,
124    "flag indicating that a space needs to be printed; used by print"},
125   {NULL} /* Sentinel */
126 };
127
128 static PyTypeObject PyStdOut_Type = {
129   /* The ob_type field must be initialized in the module init function
130    * to be portable to Windows without using C++. */
131   PyObject_HEAD_INIT(NULL)
132   0,                            /*ob_size*/
133   "PyOut",                      /*tp_name*/
134   sizeof(PyStdOut),             /*tp_basicsize*/
135   0,                            /*tp_itemsize*/
136   /* methods */
137   (destructor)PyStdOut_dealloc, /*tp_dealloc*/
138   0,                            /*tp_print*/
139   0,                            /*tp_getattr*/
140   0,                            /*tp_setattr*/
141   0,                            /*tp_compare*/
142   0,                            /*tp_repr*/
143   0,                            /*tp_as_number*/
144   0,                            /*tp_as_sequence*/
145   0,                            /*tp_as_mapping*/
146   0,                            /*tp_hash*/
147   0,                            /*tp_call*/
148   0,                            /*tp_str*/
149   PyObject_GenericGetAttr,      /*tp_getattro*/
150   /* softspace is writable:  we must supply tp_setattro */
151   PyObject_GenericSetAttr,      /* tp_setattro */
152   0,                            /*tp_as_buffer*/
153   Py_TPFLAGS_DEFAULT,           /*tp_flags*/
154   0,                            /*tp_doc*/
155   0,                            /*tp_traverse*/
156   0,                            /*tp_clear*/
157   0,                            /*tp_richcompare*/
158   0,                            /*tp_weaklistoffset*/
159   0,                            /*tp_iter*/
160   0,                            /*tp_iternext*/
161   PyStdOut_methods,             /*tp_methods*/
162   PyStdOut_memberlist,          /*tp_members*/
163   0,                            /*tp_getset*/
164   0,                            /*tp_base*/
165   0,                            /*tp_dict*/
166   0,                            /*tp_descr_get*/
167   0,                            /*tp_descr_set*/
168   0,                            /*tp_dictoffset*/
169   0,                            /*tp_init*/
170   0,                            /*tp_alloc*/
171   0,                            /*tp_new*/
172   0,                            /*tp_free*/
173   0,                            /*tp_is_gc*/
174 };
175
176 PyObject * newPyStdOut( std::string& out )
177 {
178   PyStdOut *self;
179   self = PyObject_New(PyStdOut, &PyStdOut_Type);
180   if (self == NULL)
181     return NULL;
182   self->softspace = 0;
183   self->out=&out;
184   return (PyObject*)self;
185 }
186
187
188 ////////////////////////END PYTHON///////////////////////////
189
190 //////////////////MY MAPS////////////////////////////////////////
191 TopTools_IndexedMapOfShape FacesWithSizeMap;
192 std::map<int,string> FaceId2SizeMap;
193 TopTools_IndexedMapOfShape EdgesWithSizeMap;
194 std::map<int,string> EdgeId2SizeMap;
195 TopTools_IndexedMapOfShape VertecesWithSizeMap;
196 std::map<int,string> VertexId2SizeMap;
197
198 std::map<int,PyObject*> FaceId2PythonSmp;
199 std::map<int,PyObject*> EdgeId2PythonSmp;
200 std::map<int,PyObject*> VertexId2PythonSmp;
201
202 std::map<int,std::vector<double> > FaceId2AttractorCoords;
203
204 TopTools_IndexedMapOfShape FacesWithEnforcedVerteces;
205 std::map< int, std::set< std::vector<double> > > FaceId2EnforcedVertexCoords;
206
207 bool HasSizeMapOnFace=false;
208 bool HasSizeMapOnEdge=false;
209 bool HasSizeMapOnVertex=false;
210
211
212 //=============================================================================
213 /*!
214  *
215  */
216 //=============================================================================
217
218 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
219                                                SMESH_Gen* gen)
220   : SMESH_2D_Algo(hypId, studyId, gen)
221 {
222   MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
223
224   _name = "BLSURF";
225   _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
226   _compatibleHypothesis.push_back("BLSURF_Parameters");
227   _requireDescretBoundary = false;
228   _onlyUnaryInput = false;
229   _hypothesis = NULL;
230
231   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
232   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
233   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
234
235   MESSAGE("studyid = " << _studyId);
236
237   myStudy = NULL;
238   myStudy = aStudyMgr->GetStudyByID(_studyId);
239   MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
240
241   /* Initialize the Python interpreter */
242   assert(Py_IsInitialized());
243   PyGILState_STATE gstate;
244   gstate = PyGILState_Ensure();
245
246   main_mod = NULL;
247   main_mod = PyImport_AddModule("__main__");
248
249   main_dict = NULL;
250   main_dict = PyModule_GetDict(main_mod);
251
252   PyRun_SimpleString("from math import *");
253   PyGILState_Release(gstate);
254
255   FacesWithSizeMap.Clear();
256   FaceId2SizeMap.clear();
257   EdgesWithSizeMap.Clear();
258   EdgeId2SizeMap.clear();
259   VertecesWithSizeMap.Clear();
260   VertexId2SizeMap.clear();
261   FaceId2PythonSmp.clear();
262   EdgeId2PythonSmp.clear();
263   VertexId2PythonSmp.clear();
264   FaceId2AttractorCoords.clear();
265   FacesWithEnforcedVerteces.Clear();
266   FaceId2EnforcedVertexCoords.clear();
267
268 }
269
270 //=============================================================================
271 /*!
272  *
273  */
274 //=============================================================================
275
276 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
277 {
278   MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
279 }
280
281
282 //=============================================================================
283 /*!
284  *
285  */
286 //=============================================================================
287
288 bool BLSURFPlugin_BLSURF::CheckHypothesis
289                          (SMESH_Mesh&                          aMesh,
290                           const TopoDS_Shape&                  aShape,
291                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
292 {
293   _hypothesis = NULL;
294
295   list<const SMESHDS_Hypothesis*>::const_iterator itl;
296   const SMESHDS_Hypothesis* theHyp;
297
298   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
299   int nbHyp = hyps.size();
300   if (!nbHyp)
301   {
302     aStatus = SMESH_Hypothesis::HYP_OK;
303     return true;  // can work with no hypothesis
304   }
305
306   itl = hyps.begin();
307   theHyp = (*itl); // use only the first hypothesis
308
309   string hypName = theHyp->GetName();
310
311   if (hypName == "BLSURF_Parameters")
312   {
313     _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
314     ASSERT(_hypothesis);
315     if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
316          _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
317       //  hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
318       aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
319     else
320       aStatus = SMESH_Hypothesis::HYP_OK;
321   }
322   else
323     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
324
325   return aStatus == SMESH_Hypothesis::HYP_OK;
326 }
327
328 //=============================================================================
329 /*!
330  * Pass parameters to BLSURF
331  */
332 //=============================================================================
333
334 inline std::string to_string(double d)
335 {
336    std::ostringstream o;
337    o << d;
338    return o.str();
339 }
340
341 inline std::string to_string(int i)
342 {
343    std::ostringstream o;
344    o << i;
345    return o.str();
346 }
347
348 double _smp_phy_size;
349 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
350 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
351 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
352
353 double my_u_min=1e6,my_v_min=1e6,my_u_max=-1e6,my_v_max=-1e6;
354
355 typedef struct {
356         gp_XY uv;
357         gp_XYZ xyz;
358 } projectionPoint;
359 /////////////////////////////////////////////////////////
360 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_XYZ& point)
361 {
362   projectionPoint myPoint;
363   Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
364   GeomAPI_ProjectPointOnSurf projector( point, surface );
365   if ( !projector.IsDone() || projector.NbPoints()==0 )
366     throw "Can't project";
367
368   Quantity_Parameter u,v;
369   projector.LowerDistanceParameters(u,v);
370   myPoint.uv = gp_XY(u,v);
371   gp_Pnt aPnt = projector.NearestPoint();
372   myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
373   //return gp_XY(u,v);
374   return myPoint;
375 }
376 /////////////////////////////////////////////////////////
377
378 /////////////////////////////////////////////////////////
379 double getT(const TopoDS_Edge& edge, const gp_XYZ& point)
380 {
381   Standard_Real f,l;
382   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
383   GeomAPI_ProjectPointOnCurve projector( point, curve);
384   if ( projector.NbPoints() == 0 )
385     throw;
386   return projector.LowerDistanceParameter();
387 }
388
389 /////////////////////////////////////////////////////////
390 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
391 {
392   MESSAGE("BLSURFPlugin_BLSURF::entryToShape"<<entry );
393   GEOM::GEOM_Object_var aGeomObj;
394   TopoDS_Shape S = TopoDS_Shape();
395   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
396   SALOMEDS::GenericAttribute_var anAttr;
397
398   if (!aSObj->_is_nil() && aSObj->FindAttribute(anAttr, "AttributeIOR")) {
399     SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
400     CORBA::String_var aVal = anIOR->Value();
401     CORBA::Object_var obj = myStudy->ConvertIORToObject(aVal);
402     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
403   }
404   if ( !aGeomObj->_is_nil() )
405     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
406   return S;
407 }
408
409 /////////////////////////////////////////////////////////
410 void createEnforcedVertexOnFace(TopoDS_Shape GeomShape, BLSURFPlugin_Hypothesis::TEnforcedVertexList enforcedVertexList)
411 {
412   double xe, ye, ze;
413   std::vector<double> coords;
414   BLSURFPlugin_Hypothesis::TEnforcedVertex enforcedVertex;
415   BLSURFPlugin_Hypothesis::TEnforcedVertexList::const_iterator evlIt = enforcedVertexList.begin();
416
417   for( ; evlIt != enforcedVertexList.end() ; ++evlIt ) {
418     coords.clear();
419     enforcedVertex = *evlIt;
420     xe = enforcedVertex[0];
421     ye = enforcedVertex[1];
422     ze = enforcedVertex[2];
423     MESSAGE("Enforced Vertex: " << xe << ", " << ye << ", " << ze);
424     // Get the (u,v) values of the enforced vertex on the face
425     projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_XYZ(xe,ye,ze));
426     gp_XY uvPoint = myPoint.uv;
427     gp_XYZ xyzPoint = myPoint.xyz;
428     Standard_Real u0 = uvPoint.X();
429     Standard_Real v0 = uvPoint.Y();
430     Standard_Real x0 = xyzPoint.X();
431     Standard_Real y0 = xyzPoint.Y();
432     Standard_Real z0 = xyzPoint.Z();
433     MESSAGE("Projected Vertex: " << x0 << ", " << y0 << ", " << z0);
434     coords.push_back(u0);
435     coords.push_back(v0);
436     coords.push_back(x0);
437     coords.push_back(y0);
438     coords.push_back(z0);
439   
440     int key = 0;
441     if (! FacesWithEnforcedVerteces.Contains(TopoDS::Face(GeomShape))) {
442       key = FacesWithEnforcedVerteces.Add(TopoDS::Face(GeomShape));
443     }
444     else {
445       key = FacesWithEnforcedVerteces.FindIndex(TopoDS::Face(GeomShape));
446     }
447
448     // If a node is already created by an attractor, do not create enforced vertex
449     int attractorKey = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
450     bool sameAttractor = false;
451     if (attractorKey >= 0)
452       if (FaceId2AttractorCoords.count(attractorKey) > 0)
453         if (FaceId2AttractorCoords[attractorKey] == coords)
454           sameAttractor = true;
455
456     if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
457       MESSAGE("Map of enf. vertex has key " << key)
458       MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
459       if (not sameAttractor)
460         FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
461       else
462         MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
463       MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
464     }
465     else {
466       MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
467       if (not sameAttractor) {
468         std::set< std::vector<double> > ens;
469         ens.insert(coords);
470         FaceId2EnforcedVertexCoords[key] = ens;
471       }
472       else
473         MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
474     }
475   }
476 }
477
478 /////////////////////////////////////////////////////////
479 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction)
480 {
481   MESSAGE("Attractor function: "<< AttractorFunction);
482   double xa, ya, za; // Coordinates of attractor point
483   double a, b;       // Attractor parameter
484   bool createNode=false; // To create a node on attractor projection
485   int pos1, pos2;
486   const char *sep = ";";
487   // atIt->second has the following pattern:
488   // ATTRACTOR(xa;ya;za;a;b)
489   // where:
490   // xa;ya;za : coordinates of  attractor
491   // a        : desired size on attractor
492   // b        : distance of influence of attractor
493   //
494   // We search the parameters in the string
495   // xa
496   pos1 = AttractorFunction.find(sep);
497   if (pos1!=string::npos)
498   xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
499   // ya
500   pos2 = AttractorFunction.find(sep, pos1+1);
501   if (pos2!=string::npos) {
502   ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
503   pos1 = pos2;
504     }
505   // za
506   pos2 = AttractorFunction.find(sep, pos1+1);
507   if (pos2!=string::npos) {
508   za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
509   pos1 = pos2;
510   }
511   // a
512   pos2 = AttractorFunction.find(sep, pos1+1);
513   if (pos2!=string::npos) {
514   a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
515   pos1 = pos2;
516   }
517   // b
518   pos2 = AttractorFunction.find(sep, pos1+1);
519   if (pos2!=string::npos) {
520   b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
521     pos1 = pos2;
522   }
523   // createNode
524   pos2 = AttractorFunction.find(")");
525   if (pos2!=string::npos) {
526     string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
527     MESSAGE("createNode: " << createNodeStr);
528     createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
529   }
530
531   // Get the (u,v) values of the attractor on the face
532   projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_XYZ(xa,ya,za));
533   gp_XY uvPoint = myPoint.uv;
534   gp_XYZ xyzPoint = myPoint.xyz;
535   Standard_Real u0 = uvPoint.X();
536   Standard_Real v0 = uvPoint.Y();
537   Standard_Real x0 = xyzPoint.X();
538   Standard_Real y0 = xyzPoint.Y();
539   Standard_Real z0 = xyzPoint.Z();
540   std::vector<double> coords;
541   coords.push_back(u0);
542   coords.push_back(v0);
543   coords.push_back(x0);
544   coords.push_back(y0);
545   coords.push_back(z0);
546   // We construct the python function
547   ostringstream attractorFunctionStream;
548   attractorFunctionStream << "def f(u,v): return ";
549   attractorFunctionStream << _smp_phy_size << "-(" << _smp_phy_size <<"-" << a << ")";
550   attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
551
552   MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
553
554   int key;
555   if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
556     key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
557   }
558   else {
559     key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
560   }
561   FaceId2SizeMap[key] =attractorFunctionStream.str();
562   if (createNode) {
563     MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
564     FaceId2AttractorCoords[key] = coords;
565   }
566 }
567
568 /////////////////////////////////////////////////////////
569
570 void BLSURFPlugin_BLSURF::SetParameters(const BLSURFPlugin_Hypothesis* hyp, blsurf_session_t *bls)
571 {
572   int    _topology      = BLSURFPlugin_Hypothesis::GetDefaultTopology();
573   int    _physicalMesh  = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
574   double _phySize       = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
575   int    _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
576   double _angleMeshS    = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
577   double _angleMeshC    = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
578   double _gradation     = BLSURFPlugin_Hypothesis::GetDefaultGradation();
579   bool   _quadAllowed   = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
580   bool   _decimesh      = BLSURFPlugin_Hypothesis::GetDefaultDecimesh();
581   int    _verb          = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
582
583   if (hyp) {
584     MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
585     _topology      = (int) hyp->GetTopology();
586     _physicalMesh  = (int) hyp->GetPhysicalMesh();
587     _phySize       = hyp->GetPhySize();
588     _geometricMesh = (int) hyp->GetGeometricMesh();
589     _angleMeshS    = hyp->GetAngleMeshS();
590     _angleMeshC    = hyp->GetAngleMeshC();
591     _gradation     = hyp->GetGradation();
592     _quadAllowed   = hyp->GetQuadAllowed();
593     _decimesh      = hyp->GetDecimesh();
594     _verb          = hyp->GetVerbosity();
595
596     if ( hyp->GetPhyMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
597       blsurf_set_param(bls, "hphymin", to_string(hyp->GetPhyMin()).c_str());
598     if ( hyp->GetPhyMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
599       blsurf_set_param(bls, "hphymax", to_string(hyp->GetPhyMax()).c_str());
600     if ( hyp->GetGeoMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
601       blsurf_set_param(bls, "hgeomin", to_string(hyp->GetGeoMin()).c_str());
602     if ( hyp->GetGeoMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
603       blsurf_set_param(bls, "hgeomax", to_string(hyp->GetGeoMax()).c_str());
604
605     const BLSURFPlugin_Hypothesis::TOptionValues & opts = hyp->GetOptionValues();
606     BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
607     for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
608       if ( !opIt->second.empty() ) {
609         MESSAGE("blsurf_set_param(): " << opIt->first << " = " << opIt->second);
610         blsurf_set_param(bls, opIt->first.c_str(), opIt->second.c_str());
611       }
612
613   } else {
614     MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
615   }
616   _smp_phy_size = _phySize;
617   blsurf_set_param(bls, "topo_points",       _topology > 0 ? "1" : "0");
618   blsurf_set_param(bls, "topo_curves",       _topology > 0 ? "1" : "0");
619   blsurf_set_param(bls, "topo_project",      _topology > 0 ? "1" : "0");
620   blsurf_set_param(bls, "clean_boundary",    _topology > 1 ? "1" : "0");
621   blsurf_set_param(bls, "close_boundary",    _topology > 1 ? "1" : "0");
622   blsurf_set_param(bls, "hphy_flag",         to_string(_physicalMesh).c_str());
623 //  blsurf_set_param(bls, "hphy_flag",         "2");
624   if ((to_string(_physicalMesh))=="2"){
625     
626     TopoDS_Shape GeomShape;
627     TopAbs_ShapeEnum GeomType;
628     //
629     // Standard Size Maps
630     //
631     MESSAGE("Setting a Size Map");
632     const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
633     BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
634     for ( ; smIt != sizeMaps.end(); ++smIt ) {
635       if ( !smIt->second.empty() ) {
636         MESSAGE("blsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
637         GeomShape = entryToShape(smIt->first);
638         GeomType  = GeomShape.ShapeType();
639         MESSAGE("Geomtype is " << GeomType);
640         int key = -1;
641         // Group Management
642         if (GeomType == TopAbs_COMPOUND){
643           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
644             // Group of faces
645             if (it.Value().ShapeType() == TopAbs_FACE){
646               HasSizeMapOnFace = true;
647               if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
648                 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
649               }
650               else {
651                 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
652 //                 MESSAGE("Face with key " << key << " already in map");
653               }
654               FaceId2SizeMap[key] = smIt->second;
655             }
656             // Group of edges
657             if (it.Value().ShapeType() == TopAbs_EDGE){
658               HasSizeMapOnEdge = true;
659               HasSizeMapOnFace = true;
660               if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
661                 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
662               }
663               else {
664                 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
665 //                 MESSAGE("Edge with key " << key << " already in map");
666               }
667               EdgeId2SizeMap[key] = smIt->second;
668             }
669             // Group of verteces
670             if (it.Value().ShapeType() == TopAbs_VERTEX){
671               HasSizeMapOnVertex = true;
672               HasSizeMapOnEdge = true;
673               HasSizeMapOnFace = true;
674               if (! VertecesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
675                 key = VertecesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
676               }
677               else {
678                 key = VertecesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
679 //                 MESSAGE("Vertex with key " << key << " already in map");
680               }
681               VertexId2SizeMap[key] = smIt->second;
682             }
683           }
684         }
685         // Single face
686         if (GeomType == TopAbs_FACE){
687           HasSizeMapOnFace = true;
688           if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
689             key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
690           }
691           else {
692             key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
693 //             MESSAGE("Face with key " << key << " already in map");
694           }
695           FaceId2SizeMap[key] = smIt->second;
696         }
697         // Single edge
698         if (GeomType == TopAbs_EDGE){
699           HasSizeMapOnEdge = true;
700           HasSizeMapOnFace = true;
701           if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
702             key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
703           }
704           else {
705             key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
706 //             MESSAGE("Edge with key " << key << " already in map");
707           }
708           EdgeId2SizeMap[key] = smIt->second;
709         }
710         // Single vertex
711         if (GeomType == TopAbs_VERTEX){
712           HasSizeMapOnVertex = true;
713           HasSizeMapOnEdge   = true;
714           HasSizeMapOnFace   = true;
715           if (! VertecesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
716             key = VertecesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
717           }
718           else {
719             key = VertecesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
720 //             MESSAGE("Vertex with key " << key << " already in map");
721           }
722           VertexId2SizeMap[key] = smIt->second;
723         }
724       }
725     }
726
727     //
728     // Attractors
729     //
730     MESSAGE("Setting Attractors");
731     const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
732     BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
733     for ( ; atIt != attractors.end(); ++atIt ) {
734       if ( !atIt->second.empty() ) {
735         MESSAGE("blsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
736         GeomShape = entryToShape(atIt->first);
737         GeomType  = GeomShape.ShapeType();
738         // Group Management
739         if (GeomType == TopAbs_COMPOUND){
740           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
741             if (it.Value().ShapeType() == TopAbs_FACE){
742               HasSizeMapOnFace = true;
743               createAttractorOnFace(it.Value(), atIt->second);
744             }
745           }
746         }
747                 
748         if (GeomType == TopAbs_FACE){
749           HasSizeMapOnFace = true;
750           createAttractorOnFace(GeomShape, atIt->second);
751         }
752 /*
753         if (GeomType == TopAbs_EDGE){
754           HasSizeMapOnEdge = true;
755           HasSizeMapOnFace = true;
756         EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
757         }
758         if (GeomType == TopAbs_VERTEX){
759           HasSizeMapOnVertex = true;
760           HasSizeMapOnEdge   = true;
761           HasSizeMapOnFace   = true;
762         VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
763         }
764 */
765       }
766     }
767
768
769     //
770     // Enforced Verteces
771     //
772     MESSAGE("Setting Enforced Verteces");
773     const BLSURFPlugin_Hypothesis::TEnforcedVertexMap enforcedVertexMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerteces(hyp);
774     BLSURFPlugin_Hypothesis::TEnforcedVertexMap::const_iterator enfIt = enforcedVertexMap.begin();
775     for ( ; enfIt != enforcedVertexMap.end(); ++enfIt ) {
776       if ( !enfIt->second.empty() ) {
777         GeomShape = entryToShape(enfIt->first);
778         GeomType  = GeomShape.ShapeType();
779         // Group Management
780         if (GeomType == TopAbs_COMPOUND){
781           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
782             if (it.Value().ShapeType() == TopAbs_FACE){
783               HasSizeMapOnFace = true;
784               createEnforcedVertexOnFace(it.Value(), enfIt->second);
785             }
786           }
787         }
788             
789         if (GeomType == TopAbs_FACE){
790           HasSizeMapOnFace = true;
791           createEnforcedVertexOnFace(GeomShape, enfIt->second);
792         }
793       }
794     }
795
796 //    if (HasSizeMapOnFace){
797     // In all size map cases (hphy_flag = 2), at least map on face must be defined
798     MESSAGE("Setting Size Map on FACES ");
799     blsurf_data_set_sizemap_iso_cad_face(bls, size_on_surface, &_smp_phy_size);
800 //    }
801
802     if (HasSizeMapOnEdge){
803       MESSAGE("Setting Size Map on EDGES ");
804       blsurf_data_set_sizemap_iso_cad_edge(bls, size_on_edge, &_smp_phy_size);
805     }
806     if (HasSizeMapOnVertex){
807       MESSAGE("Setting Size Map on VERTICES ");
808       blsurf_data_set_sizemap_iso_cad_point(bls, size_on_vertex, &_smp_phy_size);
809     }
810   }
811   blsurf_set_param(bls, "hphydef",           to_string(_phySize).c_str());
812   blsurf_set_param(bls, "hgeo_flag",         to_string(_geometricMesh).c_str());
813   blsurf_set_param(bls, "relax_size",        _decimesh ? "0": to_string(_geometricMesh).c_str());
814   blsurf_set_param(bls, "angle_meshs",       to_string(_angleMeshS).c_str());
815   blsurf_set_param(bls, "angle_meshc",       to_string(_angleMeshC).c_str());
816   blsurf_set_param(bls, "gradation",         to_string(_gradation).c_str());
817   blsurf_set_param(bls, "patch_independent", _decimesh ? "1" : "0");
818   blsurf_set_param(bls, "element",           _quadAllowed ? "q1.0" : "p1");
819   blsurf_set_param(bls, "verb",              to_string(_verb).c_str());
820 }
821
822
823
824
825
826
827 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
828 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
829                   real *duu, real *duv, real *dvv, void *user_data);
830 status_t message_callback(message_t *msg, void *user_data);
831
832 //=============================================================================
833 /*!
834  *
835  */
836 //=============================================================================
837
838 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
839
840   MESSAGE("BLSURFPlugin_BLSURF::Compute");
841
842   if (aShape.ShapeType() == TopAbs_COMPOUND) {
843     MESSAGE("  the shape is a COMPOUND");
844   }
845   else {
846     MESSAGE("  the shape is UNKNOWN");
847   };
848
849   context_t *ctx =  context_new();
850   context_set_message_callback(ctx, message_callback, &_comment);
851
852   cad_t *c = cad_new(ctx);
853
854   blsurf_session_t *bls = blsurf_session_new(ctx);
855
856   FacesWithSizeMap.Clear();
857   FaceId2SizeMap.clear();
858   EdgesWithSizeMap.Clear();
859   EdgeId2SizeMap.clear();
860   VertecesWithSizeMap.Clear();
861   VertexId2SizeMap.clear();
862
863   MESSAGE("BEGIN SetParameters");
864   SetParameters(_hypothesis, bls);
865   MESSAGE("END SetParameters");
866
867   TopTools_IndexedMapOfShape fmap;
868   TopTools_IndexedMapOfShape emap;
869   TopTools_IndexedMapOfShape pmap;
870   vector<Handle(Geom2d_Curve)> curves;
871   vector<Handle(Geom_Surface)> surfaces;
872
873   fmap.Clear();
874   FaceId2PythonSmp.clear();
875   emap.Clear();
876   EdgeId2PythonSmp.clear();
877   pmap.Clear();
878   VertexId2PythonSmp.clear();
879   surfaces.resize(0);
880   curves.resize(0);
881
882   assert(Py_IsInitialized());
883   PyGILState_STATE gstate;
884   gstate = PyGILState_Ensure();
885
886   string theSizeMapStr;
887   
888   /****************************************************************************************
889                                   FACES
890   *****************************************************************************************/
891   int iface = 0;
892   string bad_end = "return";
893   int faceKey = -1;
894   for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next()) {
895     TopoDS_Face f=TopoDS::Face(face_iter.Current());
896     
897     if (fmap.FindIndex(f) > 0)
898       continue;
899
900     fmap.Add(f);
901     iface++;
902     surfaces.push_back(BRep_Tool::Surface(f));
903
904     cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
905     cad_face_set_tag(fce, iface);
906     if(f.Orientation() != TopAbs_FORWARD){
907       cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
908     } else {
909       cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
910     }
911     
912     if (HasSizeMapOnFace){
913       std::cout << "A size map is defined on a face" << std::endl;
914       // Classic size map
915       faceKey = FacesWithSizeMap.FindIndex(f);
916       
917       if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()){
918         theSizeMapStr = FaceId2SizeMap[faceKey];
919         // check if function ends with "return"
920         if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
921           continue;
922         // Expr To Python function, verification is performed at validation in GUI
923         PyObject * obj = NULL;
924         obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
925         Py_DECREF(obj);
926         PyObject * func = NULL;
927         func = PyObject_GetAttrString(main_mod, "f");
928         FaceId2PythonSmp[iface]=func;
929         FaceId2SizeMap.erase(faceKey);
930       }
931       
932       // Specific size map = Attractor
933       std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
934       int iatt=0;
935       for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
936         if (attractor_iter->first == faceKey) {
937           MESSAGE("Face indice: " << iface);
938           MESSAGE("Adding attractor");
939           
940           double xyzCoords[3]  = {attractor_iter->second[2],
941                                   attractor_iter->second[3],
942                                   attractor_iter->second[4]};
943           
944           MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
945           gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
946           BRepClass_FaceClassifier scl(f,P,1e-7);
947           // scl.Perform() is bugged. The function was rewritten
948 //          scl.Perform();
949           BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
950           TopAbs_State result = scl.State();
951           MESSAGE("Position of point on face: "<<result);
952           if ( result == TopAbs_OUT )
953               MESSAGE("Point is out of face: node is not created");
954           if ( result == TopAbs_UNKNOWN )
955               MESSAGE("Point position on face is unknown: node is not created");
956           if ( result == TopAbs_ON )
957               MESSAGE("Point is on border of face: node is not created");
958           if ( result == TopAbs_IN )
959           {
960             // Point is inside face and not on border
961             MESSAGE("Point is in face: node is created");
962             double uvCoords[2]   = {attractor_iter->second[0],attractor_iter->second[1]};
963             iatt++;
964             MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << iatt);
965             cad_point_t* point_p = cad_point_new(fce, iatt, uvCoords);
966             cad_point_set_tag(point_p, iatt);
967           }
968           FaceId2AttractorCoords.erase(faceKey);
969         }
970       }
971       
972       // Enforced Verteces
973       faceKey = FacesWithEnforcedVerteces.FindIndex(f);
974       std::map<int,std::set<std::vector<double> > >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
975       if (evmIt != FaceId2EnforcedVertexCoords.end()) {
976         std::cout << "Some enforced verteces are defined" << std::endl;
977         int ienf = 0;
978         std::set<std::vector<double> > evl;
979 //         std::vector<double> ev;
980         MESSAGE("Face indice: " << iface);
981         MESSAGE("Adding enforced verteces");
982         evl = evmIt->second;
983         MESSAGE("Number of verteces to add: "<< evl.size())
984         std::set< std::vector<double> >::const_iterator evlIt = evl.begin();
985         for (; evlIt != evl.end(); ++evlIt) {
986 //           ev = *evlIt;
987 //         for (int i=0; i<evl.size() ; i++) {
988 //           ev = evl[i];
989           
990 //           double xyzCoords[3]  = {ev[2], ev[3], ev[4]};
991           double xyzCoords[3]  = {evlIt->at(0), evlIt->at(3), evlIt->at(4)};
992           MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
993           gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
994           BRepClass_FaceClassifier scl(f,P,1e-7);
995           // scl.Perform() is bugged. The function was rewritten
996 //          scl.Perform();
997           BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
998           TopAbs_State result = scl.State();
999           MESSAGE("Position of point on face: "<<result);
1000           if ( result == TopAbs_OUT )
1001               MESSAGE("Point is out of face: node is not created");
1002           if ( result == TopAbs_UNKNOWN )
1003               MESSAGE("Point position on face is unknown: node is not created");
1004           if ( result == TopAbs_ON )
1005               MESSAGE("Point is on border of face: node is not created");
1006           if ( result == TopAbs_IN )
1007           {
1008             // Point is inside face and not on border
1009             MESSAGE("Point is in face: node is created");
1010 //             double uvCoords[2]   = {ev[0],ev[1]};
1011             double uvCoords[2]   = {evlIt->at(0),evlIt->at(1)};
1012             ienf++;
1013             MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
1014             cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
1015             cad_point_set_tag(point_p, ienf);
1016           }
1017         }
1018         FaceId2EnforcedVertexCoords.erase(faceKey);
1019       }
1020       else
1021         std::cout << "No enforced vertex defined" << std::endl;
1022     }
1023     
1024     
1025     /****************************************************************************************
1026                                     EDGES
1027     *****************************************************************************************/
1028     int edgeKey = -1;
1029     for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next()) {
1030       TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
1031       int ic = emap.FindIndex(e);
1032       if (ic <= 0)
1033         ic = emap.Add(e);
1034
1035       double tmin,tmax;
1036       curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
1037       
1038       if (HasSizeMapOnEdge){
1039         edgeKey = EdgesWithSizeMap.FindIndex(e);
1040         if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
1041           theSizeMapStr = EdgeId2SizeMap[faceKey];
1042           if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1043             continue;
1044           // Expr To Python function, verification is performed at validation in GUI
1045           PyObject * obj = NULL;
1046           obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1047           Py_DECREF(obj);
1048           PyObject * func = NULL;
1049           func = PyObject_GetAttrString(main_mod, "f");
1050           EdgeId2PythonSmp[ic]=func;
1051           EdgeId2SizeMap.erase(edgeKey);
1052         }
1053       }
1054       cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
1055       cad_edge_set_tag(edg, ic);
1056       cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
1057       if (e.Orientation() == TopAbs_INTERNAL)
1058         cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
1059
1060       int npts = 0;
1061       int ip1, ip2, *ip;
1062       gp_Pnt2d e0 = curves.back()->Value(tmin);
1063       gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
1064       Standard_Real d1=0,d2=0;
1065       
1066       
1067       /****************************************************************************************
1068                                       VERTECES
1069       *****************************************************************************************/
1070       int vertexKey = -1;
1071       for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
1072         TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
1073         ++npts;
1074         if (npts == 1){
1075           ip = &ip1;
1076           d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
1077         } else {
1078           ip = &ip2;
1079           d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
1080         }
1081         *ip = pmap.FindIndex(v);
1082         if(*ip <= 0)
1083           *ip = pmap.Add(v);
1084         
1085         vertexKey = VertecesWithSizeMap.FindIndex(v);
1086         if (HasSizeMapOnVertex){
1087           vertexKey = VertecesWithSizeMap.FindIndex(v);
1088           if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
1089             theSizeMapStr = VertexId2SizeMap[faceKey];
1090             if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1091               continue;
1092             // Expr To Python function, verification is performed at validation in GUI
1093             PyObject * obj = NULL;
1094             obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1095             Py_DECREF(obj);
1096             PyObject * func = NULL;
1097             func = PyObject_GetAttrString(main_mod, "f");
1098             VertexId2PythonSmp[*ip]=func;
1099 //             VertexId2SizeMap.erase(vertexKey);   // do not erase if using a vector
1100           }
1101         }
1102       }
1103       if (npts != 2) {
1104         // should not happen
1105         MESSAGE("An edge does not have 2 extremities.");
1106       } else {
1107         if (d1 < d2)
1108           cad_edge_set_extremities(edg, ip1, ip2);
1109         else
1110           cad_edge_set_extremities(edg, ip2, ip1);
1111       }
1112     } // for edge
1113   } //for face
1114
1115
1116   PyGILState_Release(gstate);
1117
1118   blsurf_data_set_cad(bls, c);
1119
1120   std::cout << std::endl;
1121   std::cout << "Beginning of Surface Mesh generation" << std::endl;
1122   std::cout << std::endl;
1123
1124   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1125 #ifndef WNT
1126   feclearexcept( FE_ALL_EXCEPT );
1127   int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1128 #endif
1129
1130   status_t status = STATUS_ERROR;
1131
1132   try {
1133     OCC_CATCH_SIGNALS;
1134
1135     status = blsurf_compute_mesh(bls);
1136
1137   }
1138   catch ( std::exception& exc ) {
1139     _comment += exc.what();
1140   }
1141   catch (Standard_Failure& ex) {
1142     _comment += ex.DynamicType()->Name();
1143     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
1144       _comment += ": ";
1145       _comment += ex.GetMessageString();
1146     }
1147   }
1148   catch (...) {
1149     if ( _comment.empty() )
1150       _comment = "Exception in blsurf_compute_mesh()";
1151   }
1152   if ( status != STATUS_OK) {
1153     blsurf_session_delete(bls);
1154     cad_delete(c);
1155     context_delete(ctx);
1156
1157     return error(_comment);
1158   }
1159
1160   std::cout << std::endl;
1161   std::cout << "End of Surface Mesh generation" << std::endl;
1162   std::cout << std::endl;
1163
1164   mesh_t *msh;
1165   blsurf_data_get_mesh(bls, &msh);
1166   if(!msh){
1167     blsurf_session_delete(bls);
1168     cad_delete(c);
1169     context_delete(ctx);
1170
1171     return error(_comment);
1172     //return false;
1173   }
1174
1175   integer nv, ne, nt, nq, vtx[4], tag;
1176   real xyz[3];
1177
1178   mesh_get_vertex_count(msh, &nv);
1179   mesh_get_edge_count(msh, &ne);
1180   mesh_get_triangle_count(msh, &nt);
1181   mesh_get_quadrangle_count(msh, &nq);
1182
1183
1184   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1185   SMDS_MeshNode** nodes = new SMDS_MeshNode*[nv+1];
1186   bool* tags = new bool[nv+1];
1187
1188   for(int iv=1;iv<=nv;iv++) {
1189     mesh_get_vertex_coordinates(msh, iv, xyz);
1190     mesh_get_vertex_tag(msh, iv, &tag);
1191     nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
1192     // internal point are tagged to zero
1193     if(tag){
1194       meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
1195       tags[iv] = false;
1196     } else {
1197       tags[iv] = true;
1198     }
1199   }
1200
1201   for(int it=1;it<=ne;it++) {
1202     mesh_get_edge_vertices(msh, it, vtx);
1203     SMDS_MeshEdge* edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
1204     mesh_get_edge_tag(msh, it, &tag);
1205
1206     if (tags[vtx[0]]) {
1207       Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
1208       tags[vtx[0]] = false;
1209     };
1210     if (tags[vtx[1]]) {
1211       Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
1212       tags[vtx[1]] = false;
1213     };
1214     meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
1215
1216   }
1217
1218   for(int it=1;it<=nt;it++) {
1219     mesh_get_triangle_vertices(msh, it, vtx);
1220     SMDS_MeshFace* tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
1221     mesh_get_triangle_tag(msh, it, &tag);
1222     meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
1223     if (tags[vtx[0]]) {
1224       meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
1225       tags[vtx[0]] = false;
1226     };
1227     if (tags[vtx[1]]) {
1228       meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
1229       tags[vtx[1]] = false;
1230     };
1231     if (tags[vtx[2]]) {
1232       meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
1233       tags[vtx[2]] = false;
1234     };
1235   }
1236
1237   for(int it=1;it<=nq;it++) {
1238     mesh_get_quadrangle_vertices(msh, it, vtx);
1239     SMDS_MeshFace* quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
1240     mesh_get_quadrangle_tag(msh, it, &tag);
1241     meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
1242     if (tags[vtx[0]]) {
1243       meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
1244       tags[vtx[0]] = false;
1245     };
1246     if (tags[vtx[1]]) {
1247       meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
1248       tags[vtx[1]] = false;
1249     };
1250     if (tags[vtx[2]]) {
1251       meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
1252       tags[vtx[2]] = false;
1253     };
1254     if (tags[vtx[3]]) {
1255       meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
1256       tags[vtx[3]] = false;
1257     };
1258   }
1259
1260   delete nodes;
1261
1262   /* release the mesh object */
1263   blsurf_data_regain_mesh(bls, msh);
1264
1265   /* clean up everything */
1266   blsurf_session_delete(bls);
1267   cad_delete(c);
1268
1269   context_delete(ctx);
1270
1271   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1272 #ifndef WNT
1273   if ( oldFEFlags > 0 )
1274     feenableexcept( oldFEFlags );
1275   feclearexcept( FE_ALL_EXCEPT );
1276 #endif
1277   
1278   std::cout << "FacesWithSizeMap" << std::endl;
1279   FacesWithSizeMap.Statistics(std::cout);
1280   std::cout << "EdgesWithSizeMap" << std::endl;
1281   EdgesWithSizeMap.Statistics(std::cout);
1282   std::cout << "VertecesWithSizeMap" << std::endl;
1283   VertecesWithSizeMap.Statistics(std::cout);
1284   std::cout << "FacesWithEnforcedVerteces" << std::endl;
1285   FacesWithEnforcedVerteces.Statistics(std::cout);
1286   
1287   return true;
1288 }
1289
1290 //=============================================================================
1291 /*!
1292  *  SetNodeOnEdge
1293  */
1294 //=============================================================================
1295
1296 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* node, const TopoDS_Shape& ed) {
1297   const TopoDS_Edge edge = TopoDS::Edge(ed);
1298
1299   gp_Pnt pnt(node->X(), node->Y(), node->Z());
1300
1301   Standard_Real p0 = 0.0;
1302   Standard_Real p1 = 1.0;
1303   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, p0, p1);
1304
1305   GeomAPI_ProjectPointOnCurve proj(pnt, curve);
1306
1307   double pa = (double)proj.Parameter(1);
1308
1309   GProp_GProps LProps;
1310   BRepGProp::LinearProperties(ed, LProps);
1311   double lg = (double)LProps.Mass();
1312
1313   meshDS->SetNodeOnEdge(node, edge, pa);
1314 }
1315
1316 //=============================================================================
1317 /*!
1318  *
1319  */
1320 //=============================================================================
1321
1322 ostream & BLSURFPlugin_BLSURF::SaveTo(ostream & save)
1323 {
1324   return save;
1325 }
1326
1327 //=============================================================================
1328 /*!
1329  *
1330  */
1331 //=============================================================================
1332
1333 istream & BLSURFPlugin_BLSURF::LoadFrom(istream & load)
1334 {
1335   return load;
1336 }
1337
1338 //=============================================================================
1339 /*!
1340  *
1341  */
1342 //=============================================================================
1343
1344 ostream & operator << (ostream & save, BLSURFPlugin_BLSURF & hyp)
1345 {
1346   return hyp.SaveTo( save );
1347 }
1348
1349 //=============================================================================
1350 /*!
1351  *
1352  */
1353 //=============================================================================
1354
1355 istream & operator >> (istream & load, BLSURFPlugin_BLSURF & hyp)
1356 {
1357   return hyp.LoadFrom( load );
1358 }
1359
1360 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
1361 {
1362   const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
1363
1364   if (uv){
1365     gp_Pnt2d P;
1366     P=pargeo->Value(t);
1367     uv[0]=P.X(); uv[1]=P.Y();
1368   }
1369
1370   if(dt) {
1371     gp_Vec2d V1;
1372     V1=pargeo->DN(t,1);
1373     dt[0]=V1.X(); dt[1]=V1.Y();
1374   }
1375
1376   if(dtt){
1377     gp_Vec2d V2;
1378     V2=pargeo->DN(t,2);
1379     dtt[0]=V2.X(); dtt[1]=V2.Y();
1380   }
1381
1382   return 0;
1383 }
1384
1385 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1386                   real *duu, real *duv, real *dvv, void *user_data)
1387 {
1388   const Geom_Surface* geometry = (const Geom_Surface*) user_data;
1389
1390   if(xyz){
1391    gp_Pnt P;
1392    P=geometry->Value(uv[0],uv[1]);   // S.D0(U,V,P);
1393    xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
1394   }
1395
1396   if(du && dv){
1397     gp_Pnt P;
1398     gp_Vec D1U,D1V;
1399
1400     geometry->D1(uv[0],uv[1],P,D1U,D1V);
1401     du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
1402     dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
1403   }
1404
1405   if(duu && duv && dvv){
1406     gp_Pnt P;
1407     gp_Vec D1U,D1V;
1408     gp_Vec D2U,D2V,D2UV;
1409
1410     geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
1411     duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
1412     duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
1413     dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
1414   }
1415
1416   return 0;
1417 }
1418
1419
1420 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
1421 {
1422   if (face_id == 1) {
1423     if (my_u_min > uv[0]) {
1424       my_u_min = uv[0];
1425     }
1426     if (my_v_min > uv[1]) {
1427       my_v_min = uv[1];
1428     }
1429     if (my_u_max < uv[0]) {
1430       my_u_max = uv[0];
1431     }
1432     if (my_v_max < uv[1]) {
1433       my_v_max = uv[1];
1434     }
1435   }
1436
1437   if (FaceId2PythonSmp.count(face_id) != 0){
1438     PyObject * pyresult = NULL;
1439     PyObject* new_stderr = NULL;
1440     assert(Py_IsInitialized());
1441     PyGILState_STATE gstate;
1442     gstate = PyGILState_Ensure();
1443     pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],"(f,f)",uv[0],uv[1]);
1444     double result;
1445     if ( pyresult == NULL){
1446       fflush(stderr);
1447       string err_description="";
1448       new_stderr = newPyStdOut(err_description);
1449       PySys_SetObject("stderr", new_stderr);
1450       PyErr_Print();
1451       PySys_SetObject("stderr", PySys_GetObject("__stderr__"));
1452       Py_DECREF(new_stderr);
1453       MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
1454       result = *((double*)user_data);
1455       }
1456     else {
1457       result = PyFloat_AsDouble(pyresult);
1458       Py_DECREF(pyresult);
1459     }
1460     *size = result;
1461     //MESSAGE("f(" << uv[0] << "," << uv[1] << ")" << " = " << result);
1462     PyGILState_Release(gstate);
1463   }
1464   else {
1465     *size = *((double*)user_data);
1466   }
1467   return STATUS_OK;
1468 }
1469
1470 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
1471 {
1472   if (EdgeId2PythonSmp.count(edge_id) != 0){
1473     PyObject * pyresult = NULL;
1474     PyObject* new_stderr = NULL;
1475     assert(Py_IsInitialized());
1476     PyGILState_STATE gstate;
1477     gstate = PyGILState_Ensure();
1478     pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],"(f)",t);
1479     double result;
1480     if ( pyresult == NULL){
1481       fflush(stderr);
1482       string err_description="";
1483       new_stderr = newPyStdOut(err_description);
1484       PySys_SetObject("stderr", new_stderr);
1485       PyErr_Print();
1486       PySys_SetObject("stderr", PySys_GetObject("__stderr__"));
1487       Py_DECREF(new_stderr);
1488       MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
1489       result = *((double*)user_data);
1490       }
1491     else {
1492       result = PyFloat_AsDouble(pyresult);
1493       Py_DECREF(pyresult);
1494     }
1495     *size = result;
1496     PyGILState_Release(gstate);
1497   }
1498   else {
1499     *size = *((double*)user_data);
1500   }
1501   return STATUS_OK;
1502 }
1503
1504 status_t size_on_vertex(integer point_id, real *size, void *user_data)
1505 {
1506   if (VertexId2PythonSmp.count(point_id) != 0){
1507     PyObject * pyresult = NULL;
1508     PyObject* new_stderr = NULL;
1509     assert(Py_IsInitialized());
1510     PyGILState_STATE gstate;
1511     gstate = PyGILState_Ensure();
1512     pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],"");
1513     double result;
1514     if ( pyresult == NULL){
1515       fflush(stderr);
1516       string err_description="";
1517       new_stderr = newPyStdOut(err_description);
1518       PySys_SetObject("stderr", new_stderr);
1519       PyErr_Print();
1520       PySys_SetObject("stderr", PySys_GetObject("__stderr__"));
1521       Py_DECREF(new_stderr);
1522       MESSAGE("Can't evaluate f()" << " error is " << err_description);
1523       result = *((double*)user_data);
1524       }
1525     else {
1526       result = PyFloat_AsDouble(pyresult);
1527       Py_DECREF(pyresult);
1528     }
1529     *size = result;
1530     PyGILState_Release(gstate);
1531   }
1532   else {
1533     *size = *((double*)user_data);
1534   }
1535  return STATUS_OK;
1536 }
1537
1538 status_t message_callback(message_t *msg, void *user_data)
1539 {
1540   integer errnumber = 0;
1541   char *desc;
1542   message_get_number(msg, &errnumber);
1543   message_get_description(msg, &desc);
1544   if ( errnumber < 0 ) {
1545     string * error = (string*)user_data;
1546 //   if ( !error->empty() )
1547 //     *error += "\n";
1548     // remove ^A from the tail
1549     int len = strlen( desc );
1550     while (len > 0 && desc[len-1] != '\n')
1551       len--;
1552     error->append( desc, len );
1553   }
1554   else {
1555       std::cout << desc << std::endl;
1556   }
1557   return STATUS_OK;
1558 }
1559
1560
1561 //=============================================================================
1562 /*!
1563  *  
1564  */
1565 //=============================================================================
1566 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
1567                                    const TopoDS_Shape& aShape,
1568                                    MapShapeNbElems& aResMap)
1569 {
1570   int    _physicalMesh  = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
1571   double _phySize       = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
1572   //int    _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
1573   //double _angleMeshS    = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
1574   double _angleMeshC    = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
1575   if(_hypothesis) {
1576     _physicalMesh  = (int) _hypothesis->GetPhysicalMesh();
1577     _phySize       = _hypothesis->GetPhySize();
1578     //_geometricMesh = (int) hyp->GetGeometricMesh();
1579     //_angleMeshS    = hyp->GetAngleMeshS();
1580     _angleMeshC    = _hypothesis->GetAngleMeshC();
1581   }
1582
1583   bool IsQuadratic = false;
1584
1585   // ----------------
1586   // evaluate 1D 
1587   // ----------------
1588   TopTools_DataMapOfShapeInteger EdgesMap;
1589   double fullLen = 0.0;
1590   double fullNbSeg = 0;
1591   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
1592     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
1593     if( EdgesMap.IsBound(E) )
1594       continue;
1595     SMESH_subMesh *sm = aMesh.GetSubMesh(E);
1596     double aLen = SMESH_Algo::EdgeLength(E);
1597     fullLen += aLen;
1598     int nb1d = 0;
1599     if(_physicalMesh==1) {
1600        nb1d = (int)( aLen/_phySize + 1 );
1601     }
1602     else {
1603       // use geometry
1604       double f,l;
1605       Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
1606       double fullAng = 0.0;
1607       double dp = (l-f)/200;
1608       gp_Pnt P1,P2,P3;
1609       C->D0(f,P1);
1610       C->D0(f+dp,P2);
1611       gp_Vec V1(P1,P2);
1612       for(int j=2; j<=200; j++) {
1613         C->D0(f+dp*j,P3);
1614         gp_Vec V2(P2,P3);
1615         fullAng += fabs(V1.Angle(V2));
1616         V1 = V2;
1617         P2 = P3;
1618       }
1619       nb1d = (int)( fullAng/_angleMeshC + 1 );
1620     }
1621     fullNbSeg += nb1d;
1622     std::vector<int> aVec(17);
1623     for(int i=0; i<17; i++) aVec[i]=0;
1624     if( IsQuadratic > 0 ) {
1625       aVec[0] = 2*nb1d - 1;
1626       aVec[2] = nb1d;
1627     }
1628     else {
1629       aVec[0] = nb1d - 1;
1630       aVec[1] = nb1d;
1631     }
1632     aResMap.insert(std::make_pair(sm,aVec));
1633     EdgesMap.Bind(E,nb1d);
1634   }
1635   double ELen = fullLen/fullNbSeg;
1636   // ----------------
1637   // evaluate 2D 
1638   // ----------------
1639   // try to evaluate as in MEFISTO
1640   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
1641     TopoDS_Face F = TopoDS::Face( exp.Current() );
1642     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
1643     GProp_GProps G;
1644     BRepGProp::SurfaceProperties(F,G);
1645     double anArea = G.Mass();
1646     int nb1d = 0;
1647     for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
1648       nb1d += EdgesMap.Find(exp1.Current());
1649     }
1650     int nbFaces = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
1651     int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
1652     std::vector<int> aVec(17);
1653     for(int i=0; i<17; i++) aVec[i]=0;
1654     if( IsQuadratic ) {
1655       int nb1d_in = (nbFaces*3 - nb1d) / 2;
1656       aVec[0] = nbNodes + nb1d_in;
1657       aVec[4] = nbFaces;
1658     }
1659     else {
1660       aVec[0] = nbNodes;
1661       aVec[3] = nbFaces;
1662     }
1663     aResMap.insert(std::make_pair(sm,aVec));
1664   }
1665
1666   // ----------------
1667   // evaluate 3D
1668   // ----------------
1669   GProp_GProps G;
1670   BRepGProp::VolumeProperties(aShape,G);
1671   double aVolume = G.Mass();
1672   double tetrVol = 0.1179*ELen*ELen*ELen;
1673   int nbVols = (int)aVolume/tetrVol;
1674   int nb1d_in = (int) ( ( nbVols*6 - fullNbSeg ) / 6 );
1675   std::vector<int> aVec(17);
1676   for(int i=0; i<17; i++) aVec[i]=0;
1677   if( IsQuadratic ) {
1678     aVec[0] = nb1d_in/3 + 1 + nb1d_in;
1679     aVec[9] = nbVols;
1680   }
1681   else {
1682     aVec[0] = nb1d_in/3 + 1;
1683     aVec[8] = nbVols;
1684   }
1685   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1686   aResMap.insert(std::make_pair(sm,aVec));
1687
1688   return true;
1689 }
1690
1691 //=============================================================================
1692 /*!
1693  *  Rewritting of the BRepClass_FaceClassifier::Perform function which is bugged (CAS 6.3sp6)
1694  *  Following line was added:
1695  *        myExtrem.Perform(P);
1696  */
1697 //=============================================================================
1698 void  BLSURFPlugin_BLSURF::BRepClass_FaceClassifierPerform(BRepClass_FaceClassifier* fc,
1699                     const TopoDS_Face& face, 
1700                     const gp_Pnt& P, 
1701                     const Standard_Real Tol)
1702 {
1703   //-- Voir BRepExtrema_ExtPF.cxx 
1704   BRepAdaptor_Surface Surf(face);
1705   Standard_Real U1, U2, V1, V2;
1706   BRepTools::UVBounds(face, U1, U2, V1, V2);
1707   Extrema_ExtPS myExtrem;
1708   myExtrem.Initialize(Surf, U1, U2, V1, V2, Tol, Tol);
1709   myExtrem.Perform(P);
1710   //----------------------------------------------------------
1711   //-- On cherche le point le plus proche , PUIS 
1712   //-- On le classifie. 
1713   Standard_Integer nbv    = 0; // xpu
1714   Standard_Real MaxDist   =  RealLast();
1715   Standard_Integer indice = 0;
1716   if(myExtrem.IsDone()) {
1717     nbv = myExtrem.NbExt();
1718     for (Standard_Integer i = 1; i <= nbv; i++) {
1719       Standard_Real d = myExtrem.Value(i);
1720       d = Abs(d);
1721       if(d <= MaxDist) { 
1722     MaxDist = d;
1723     indice = i;
1724       }
1725     }
1726   }
1727   if(indice) { 
1728     gp_Pnt2d Puv;
1729     Standard_Real U1,U2;
1730     myExtrem.Point(indice).Parameter(U1, U2);
1731     Puv.SetCoord(U1, U2);
1732     fc->Perform(face, Puv, Tol);
1733   }
1734   else { 
1735     fc->Perform(face, gp_Pnt2d(U1-1.0,V1 - 1.0), Tol); //-- NYI etc BUG PAS BEAU En attendant l acces a rejected
1736     //-- le resultat est TopAbs_OUT;
1737   }
1738 }