]> SALOME platform Git repositories - plugins/blsurfplugin.git/blob - src/BLSURFPlugin/BLSURFPlugin_BLSURF.cxx
Salome HOME
89a2dc85763eca659744b6722bda3cdc4fa4575c
[plugins/blsurfplugin.git] / src / BLSURFPlugin / BLSURFPlugin_BLSURF.cxx
1 // Copyright (C) 2007-2011  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 #include "BLSURFPlugin_Attractor.hxx"
29
30 extern "C"{
31 #include <distene/api.h>
32 #include <distene/blsurf.h>
33 #include <distene/precad.h>
34 }
35
36 #include <structmember.h>
37
38
39 #include <Basics_Utils.hxx>
40 #include <Basics_OCCTVersion.hxx>
41
42 #include <SMESH_Gen.hxx>
43 #include <SMESH_Mesh.hxx>
44 #include <SMESH_ControlsDef.hxx>
45 #include <SMDSAbs_ElementType.hxx>
46 #include "SMESHDS_Group.hxx"
47 #include "SMESH_Group.hxx"
48
49 #include <utilities.h>
50
51 #include <limits>
52 #include <list>
53 #include <vector>
54 #include <set>
55 #include <cstdlib>
56
57 // OPENCASCADE includes
58 #include <BRep_Tool.hxx>
59 #include <TopExp.hxx>
60 #include <TopExp_Explorer.hxx>
61 #include <TopoDS.hxx>
62 #include <NCollection_Map.hxx>
63
64 #include <Geom_Surface.hxx>
65 #include <Handle_Geom_Surface.hxx>
66 #include <Geom2d_Curve.hxx>
67 #include <Handle_Geom2d_Curve.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Handle_Geom_Curve.hxx>
70 #include <Handle_AIS_InteractiveObject.hxx>
71 #include <TopoDS_Vertex.hxx>
72 #include <TopoDS_Edge.hxx>
73 #include <TopoDS_Wire.hxx>
74 #include <TopoDS_Face.hxx>
75
76 #include <gp_Pnt2d.hxx>
77 #include <gp_Pnt.hxx>
78 #include <TopTools_IndexedMapOfShape.hxx>
79 #include <TopoDS_Shape.hxx>
80 #include <BRep_Builder.hxx>
81 #include <BRepBuilderAPI_MakeVertex.hxx>
82 #include <BRepTools.hxx>
83
84 #include <TopTools_DataMapOfShapeInteger.hxx>
85 #include <GProp_GProps.hxx>
86 #include <BRepGProp.hxx>
87
88 #ifndef WNT
89 #include <fenv.h>
90 #endif
91
92 #include <Standard_ErrorHandler.hxx>
93 #include <GeomAPI_ProjectPointOnCurve.hxx>
94 #include <GeomAPI_ProjectPointOnSurf.hxx>
95 #include <gp_XY.hxx>
96 #include <gp_XYZ.hxx>
97 // #include <BRepClass_FaceClassifier.hxx>
98 #include <TopTools_MapOfShape.hxx>
99
100 /* ==================================
101  * ===========  PYTHON ==============
102  * ==================================*/
103
104 typedef struct {
105   PyObject_HEAD
106   int softspace;
107   std::string *out;
108   } PyStdOut;
109
110 static void
111 PyStdOut_dealloc(PyStdOut *self)
112 {
113   PyObject_Del(self);
114 }
115
116 static PyObject *
117 PyStdOut_write(PyStdOut *self, PyObject *args)
118 {
119   char *c;
120   int l;
121   if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
122     return NULL;
123
124   //std::cerr << c ;
125   *(self->out)=*(self->out)+c;
126
127   Py_INCREF(Py_None);
128   return Py_None;
129 }
130
131 static PyMethodDef PyStdOut_methods[] = {
132   {"write",  (PyCFunction)PyStdOut_write,  METH_VARARGS,
133     PyDoc_STR("write(string) -> None")},
134   {NULL,    NULL}   /* sentinel */
135 };
136
137 static PyMemberDef PyStdOut_memberlist[] = {
138   {(char*)"softspace", T_INT,  offsetof(PyStdOut, softspace), 0,
139    (char*)"flag indicating that a space needs to be printed; used by print"},
140   {NULL} /* Sentinel */
141 };
142
143 static PyTypeObject PyStdOut_Type = {
144   /* The ob_type field must be initialized in the module init function
145    * to be portable to Windows without using C++. */
146   PyObject_HEAD_INIT(NULL)
147   0,                            /*ob_size*/
148   "PyOut",                      /*tp_name*/
149   sizeof(PyStdOut),             /*tp_basicsize*/
150   0,                            /*tp_itemsize*/
151   /* methods */
152   (destructor)PyStdOut_dealloc, /*tp_dealloc*/
153   0,                            /*tp_print*/
154   0,                            /*tp_getattr*/
155   0,                            /*tp_setattr*/
156   0,                            /*tp_compare*/
157   0,                            /*tp_repr*/
158   0,                            /*tp_as_number*/
159   0,                            /*tp_as_sequence*/
160   0,                            /*tp_as_mapping*/
161   0,                            /*tp_hash*/
162   0,                            /*tp_call*/
163   0,                            /*tp_str*/
164   PyObject_GenericGetAttr,      /*tp_getattro*/
165   /* softspace is writable:  we must supply tp_setattro */
166   PyObject_GenericSetAttr,      /* tp_setattro */
167   0,                            /*tp_as_buffer*/
168   Py_TPFLAGS_DEFAULT,           /*tp_flags*/
169   0,                            /*tp_doc*/
170   0,                            /*tp_traverse*/
171   0,                            /*tp_clear*/
172   0,                            /*tp_richcompare*/
173   0,                            /*tp_weaklistoffset*/
174   0,                            /*tp_iter*/
175   0,                            /*tp_iternext*/
176   PyStdOut_methods,             /*tp_methods*/
177   PyStdOut_memberlist,          /*tp_members*/
178   0,                            /*tp_getset*/
179   0,                            /*tp_base*/
180   0,                            /*tp_dict*/
181   0,                            /*tp_descr_get*/
182   0,                            /*tp_descr_set*/
183   0,                            /*tp_dictoffset*/
184   0,                            /*tp_init*/
185   0,                            /*tp_alloc*/
186   0,                            /*tp_new*/
187   0,                            /*tp_free*/
188   0,                            /*tp_is_gc*/
189 };
190
191 PyObject * newPyStdOut( std::string& out )
192 {
193   PyStdOut *self;
194   self = PyObject_New(PyStdOut, &PyStdOut_Type);
195   if (self == NULL)
196     return NULL;
197   self->softspace = 0;
198   self->out=&out;
199   return (PyObject*)self;
200 }
201
202
203 ////////////////////////END PYTHON///////////////////////////
204
205 //////////////////MY MAPS////////////////////////////////////////
206 TopTools_IndexedMapOfShape FacesWithSizeMap;
207 std::map<int,string> FaceId2SizeMap;
208 TopTools_IndexedMapOfShape EdgesWithSizeMap;
209 std::map<int,string> EdgeId2SizeMap;
210 TopTools_IndexedMapOfShape VerticesWithSizeMap;
211 std::map<int,string> VertexId2SizeMap;
212
213 std::map<int,PyObject*> FaceId2PythonSmp;
214 std::map<int,PyObject*> EdgeId2PythonSmp;
215 std::map<int,PyObject*> VertexId2PythonSmp;
216
217 std::map<int,std::vector<double> > FaceId2AttractorCoords;
218 std::map<int,BLSURFPlugin_Attractor*> FaceId2ClassAttractor;
219 std::map<int,BLSURFPlugin_Attractor*> FaceIndex2ClassAttractor;
220
221 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
222 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
223 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
224 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
225
226 bool HasSizeMapOnFace=false;
227 bool HasSizeMapOnEdge=false;
228 bool HasSizeMapOnVertex=false;
229 //bool HasAttractorOnFace=false;
230
231 //=============================================================================
232 /*!
233  *
234  */
235 //=============================================================================
236
237 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
238                                                SMESH_Gen* gen)
239   : SMESH_2D_Algo(hypId, studyId, gen)
240 {
241   MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
242
243   _name = "BLSURF";
244   _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
245   _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
246   _requireDiscreteBoundary = false;
247   _onlyUnaryInput = false;
248   _hypothesis = NULL;
249   _supportSubmeshes = true;
250
251   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
252   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
253   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
254
255   MESSAGE("studyid = " << _studyId);
256
257   myStudy = NULL;
258   myStudy = aStudyMgr->GetStudyByID(_studyId);
259   if (myStudy)
260     MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
261
262   /* Initialize the Python interpreter */
263   assert(Py_IsInitialized());
264   PyGILState_STATE gstate;
265   gstate = PyGILState_Ensure();
266
267   main_mod = NULL;
268   main_mod = PyImport_AddModule("__main__");
269
270   main_dict = NULL;
271   main_dict = PyModule_GetDict(main_mod);
272
273   PyRun_SimpleString("from math import *");
274   PyGILState_Release(gstate);
275
276   FacesWithSizeMap.Clear();
277   FaceId2SizeMap.clear();
278   EdgesWithSizeMap.Clear();
279   EdgeId2SizeMap.clear();
280   VerticesWithSizeMap.Clear();
281   VertexId2SizeMap.clear();
282   FaceId2PythonSmp.clear();
283   EdgeId2PythonSmp.clear();
284   VertexId2PythonSmp.clear();
285   FaceId2AttractorCoords.clear();
286   FaceId2ClassAttractor.clear();
287   FaceIndex2ClassAttractor.clear();
288   FacesWithEnforcedVertices.Clear();
289   FaceId2EnforcedVertexCoords.clear();
290   EnfVertexCoords2ProjVertex.clear();
291   EnfVertexCoords2EnfVertexList.clear();
292
293 #ifdef WITH_SMESH_CANCEL_COMPUTE
294   _compute_canceled = false;
295 #endif
296 }
297
298 //=============================================================================
299 /*!
300  *
301  */
302 //=============================================================================
303
304 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
305 {
306   MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
307 }
308
309
310 //=============================================================================
311 /*!
312  *
313  */
314 //=============================================================================
315
316 bool BLSURFPlugin_BLSURF::CheckHypothesis
317                          (SMESH_Mesh&                          aMesh,
318                           const TopoDS_Shape&                  aShape,
319                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
320 {
321   _hypothesis = NULL;
322
323   list<const SMESHDS_Hypothesis*>::const_iterator itl;
324   const SMESHDS_Hypothesis* theHyp;
325
326   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
327   int nbHyp = hyps.size();
328   if (!nbHyp)
329   {
330     aStatus = SMESH_Hypothesis::HYP_OK;
331     return true;  // can work with no hypothesis
332   }
333
334   itl = hyps.begin();
335   theHyp = (*itl); // use only the first hypothesis
336
337   string hypName = theHyp->GetName();
338
339   if (hypName == "BLSURF_Parameters")
340   {
341     _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
342     ASSERT(_hypothesis);
343     if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
344          _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
345       //  hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
346       aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
347     else
348       aStatus = SMESH_Hypothesis::HYP_OK;
349   }
350   else
351     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
352
353   return aStatus == SMESH_Hypothesis::HYP_OK;
354 }
355
356 //=============================================================================
357 /*!
358  * Pass parameters to BLSURF
359  */
360 //=============================================================================
361
362 inline std::string to_string(double d)
363 {
364    std::ostringstream o;
365    o << d;
366    return o.str();
367 }
368
369 inline std::string to_string(int i)
370 {
371    std::ostringstream o;
372    o << i;
373    return o.str();
374 }
375
376 double _smp_phy_size;
377 // #if BLSURF_VERSION_LONG >= "3.1.1"
378 // //   sizemap_t *geo_sizemap_e, *geo_sizemap_f;
379 //   sizemap_t *iso_sizemap_p, *iso_sizemap_e, *iso_sizemap_f;
380 // //   sizemap_t *clean_geo_sizemap_e, *clean_geo_sizemap_f;
381 //   sizemap_t *clean_iso_sizemap_p, *clean_iso_sizemap_e, *clean_iso_sizemap_f;
382 // #endif
383 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
384 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
385 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
386
387 double my_u_min=1e6,my_v_min=1e6,my_u_max=-1e6,my_v_max=-1e6;
388
389 typedef struct {
390         gp_XY uv;
391         gp_XYZ xyz;
392 } projectionPoint;
393 /////////////////////////////////////////////////////////
394 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_Pnt& point)
395 {
396   projectionPoint myPoint;
397   Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
398   GeomAPI_ProjectPointOnSurf projector( point, surface );
399   if ( !projector.IsDone() || projector.NbPoints()==0 )
400     throw "getProjectionPoint: Can't project";
401
402   Quantity_Parameter u,v;
403   projector.LowerDistanceParameters(u,v);
404   myPoint.uv = gp_XY(u,v);
405   gp_Pnt aPnt = projector.NearestPoint();
406   myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
407   //return gp_XY(u,v);
408   return myPoint;
409 }
410 /////////////////////////////////////////////////////////
411
412 /////////////////////////////////////////////////////////
413 double getT(const TopoDS_Edge& edge, const gp_Pnt& point)
414 {
415   Standard_Real f,l;
416   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
417   GeomAPI_ProjectPointOnCurve projector( point, curve);
418   if ( projector.NbPoints() == 0 )
419     throw;
420   return projector.LowerDistanceParameter();
421 }
422
423 /////////////////////////////////////////////////////////
424 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
425 {
426   MESSAGE("BLSURFPlugin_BLSURF::entryToShape "<<entry );
427   GEOM::GEOM_Object_var aGeomObj;
428   TopoDS_Shape S = TopoDS_Shape();
429   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
430   SALOMEDS::GenericAttribute_var anAttr;
431
432   if (!aSObj->_is_nil() && aSObj->FindAttribute(anAttr, "AttributeIOR")) {
433     SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
434     CORBA::String_var aVal = anIOR->Value();
435     CORBA::Object_var obj = myStudy->ConvertIORToObject(aVal);
436     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
437   }
438   if ( !aGeomObj->_is_nil() )
439     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
440   return S;
441 }
442
443 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
444 {
445   BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
446   enf_coords.clear();
447   coords.clear();
448   s_coords.clear();
449
450   // Get the (u,v) values of the enforced vertex on the face
451   projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
452
453   MESSAGE("Enforced Vertex: " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z());
454   MESSAGE("Projected Vertex: " << myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z());
455   MESSAGE("Parametric coordinates: " << myPoint.uv.X() << ", " << myPoint.uv.Y() );
456
457   enf_coords.push_back(aPnt.X());
458   enf_coords.push_back(aPnt.Y());
459   enf_coords.push_back(aPnt.Z());
460
461   coords.push_back(myPoint.uv.X());
462   coords.push_back(myPoint.uv.Y());
463   coords.push_back(myPoint.xyz.X());
464   coords.push_back(myPoint.xyz.Y());
465   coords.push_back(myPoint.xyz.Z());
466
467   s_coords.push_back(myPoint.xyz.X());
468   s_coords.push_back(myPoint.xyz.Y());
469   s_coords.push_back(myPoint.xyz.Z());
470
471   // Save pair projected vertex / enf vertex
472   MESSAGE("Storing pair projected vertex / enf vertex:");
473   MESSAGE("("<< myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z() <<") / (" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z()<<")");
474   EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
475   MESSAGE("Group name is: \"" << enfVertex->grpName << "\"");
476   pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
477   BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
478   ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
479   if (ret.second == false) {
480     it = ret.first;
481     (*it)->grpName = enfVertex->grpName;
482   }
483
484   int key = 0;
485   if (! FacesWithEnforcedVertices.Contains(faceShape)) {
486     key = FacesWithEnforcedVertices.Add(faceShape);
487   }
488   else {
489     key = FacesWithEnforcedVertices.FindIndex(faceShape);
490   }
491
492   // If a node is already created by an attractor, do not create enforced vertex
493   int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
494   bool sameAttractor = false;
495   if (attractorKey >= 0)
496     if (FaceId2AttractorCoords.count(attractorKey) > 0)
497       if (FaceId2AttractorCoords[attractorKey] == coords)
498         sameAttractor = true;
499
500   if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
501     MESSAGE("Map of enf. vertex has key " << key)
502     MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
503     if (! sameAttractor)
504       FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
505     else
506       MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
507     MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
508   }
509   else {
510     MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
511     if (! sameAttractor) {
512       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
513       ens.insert(coords);
514       FaceId2EnforcedVertexCoords[key] = ens;
515     }
516     else
517       MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
518   }
519 }
520
521 /////////////////////////////////////////////////////////
522 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
523 {
524   BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
525   gp_Pnt aPnt;
526
527   BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
528
529   for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
530     enfVertex = *enfVertexListIt;
531     // Case of manual coords
532     if (enfVertex->coords.size() != 0) {
533       aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
534       _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
535     }
536
537     // Case of geom vertex coords
538     if (enfVertex->geomEntry != "") {
539       TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
540       TopAbs_ShapeEnum GeomType  = GeomShape.ShapeType();
541        if (GeomType == TopAbs_VERTEX){
542          aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
543          _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
544        }
545        // Group Management
546        if (GeomType == TopAbs_COMPOUND){
547          for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
548            if (it.Value().ShapeType() == TopAbs_VERTEX){
549              aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
550              _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
551            }
552          }
553        }
554     }
555   }
556 }
557
558 /////////////////////////////////////////////////////////
559 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction)
560 {
561   MESSAGE("Attractor function: "<< AttractorFunction);
562   double xa, ya, za; // Coordinates of attractor point
563   double a, b;       // Attractor parameter
564   double d = 0.;
565   bool createNode=false; // To create a node on attractor projection
566   int pos1, pos2;
567   const char *sep = ";";
568   // atIt->second has the following pattern:
569   // ATTRACTOR(xa;ya;za;a;b;True|False;d)
570   // where:
571   // xa;ya;za : coordinates of  attractor
572   // a        : desired size on attractor
573   // b        : distance of influence of attractor
574   // d        : distance until which the size remains constant
575   //
576   // We search the parameters in the string
577   // xa
578   pos1 = AttractorFunction.find(sep);
579   if (pos1!=string::npos)
580   xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
581   // ya
582   pos2 = AttractorFunction.find(sep, pos1+1);
583   if (pos2!=string::npos) {
584   ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
585   pos1 = pos2;
586   }
587   // za
588   pos2 = AttractorFunction.find(sep, pos1+1);
589   if (pos2!=string::npos) {
590   za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
591   pos1 = pos2;
592   }
593   // a
594   pos2 = AttractorFunction.find(sep, pos1+1);
595   if (pos2!=string::npos) {
596   a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
597   pos1 = pos2;
598   }
599   // b
600   pos2 = AttractorFunction.find(sep, pos1+1);
601   if (pos2!=string::npos) {
602   b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
603   pos1 = pos2;
604   }
605   // createNode
606   pos2 = AttractorFunction.find(sep, pos1+1);
607   if (pos2!=string::npos) {
608     string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
609     MESSAGE("createNode: " << createNodeStr);
610     createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
611     pos1=pos2;
612   }
613   // d
614   pos2 = AttractorFunction.find(")");
615   if (pos2!=string::npos) {
616   d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
617   }
618
619   // Get the (u,v) values of the attractor on the face
620   projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
621   gp_XY uvPoint = myPoint.uv;
622   gp_XYZ xyzPoint = myPoint.xyz;
623   Standard_Real u0 = uvPoint.X();
624   Standard_Real v0 = uvPoint.Y();
625   Standard_Real x0 = xyzPoint.X();
626   Standard_Real y0 = xyzPoint.Y();
627   Standard_Real z0 = xyzPoint.Z();
628   std::vector<double> coords;
629   coords.push_back(u0);
630   coords.push_back(v0);
631   coords.push_back(x0);
632   coords.push_back(y0);
633   coords.push_back(z0);
634   // We construct the python function
635   ostringstream attractorFunctionStream;
636   attractorFunctionStream << "def f(u,v): return ";
637   attractorFunctionStream << _smp_phy_size << "-(" << _smp_phy_size <<"-" << a << ")";
638   //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
639   // rnc: make possible to keep the size constant until
640   // a defined distance. Distance is expressed as the positiv part
641   // of r-d where r is the distance to (u0,v0)
642   attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
643
644   MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
645
646   int key;
647   if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
648     key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
649   }
650   else {
651     key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
652   }
653   FaceId2SizeMap[key] =attractorFunctionStream.str();
654   if (createNode) {
655     MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
656     FaceId2AttractorCoords[key] = coords;
657   }
658 //   // Test for new attractors
659 //   gp_Pnt myP(xyzPoint);
660 //   TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
661 //   BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
662 //   myAttractor.SetParameters(a, _smp_phy_size, b, d);
663 //   myAttractor.SetType(1);
664 //   FaceId2ClassAttractor[key] = myAttractor;
665 //   if(FaceId2ClassAttractor[key].GetFace().IsNull()){
666 //     MESSAGE("face nulle ");
667 //   }
668 //   else
669 //     MESSAGE("face OK");
670 //
671 //   if (FaceId2ClassAttractor[key].GetAttractorShape().IsNull()){
672 //     MESSAGE("pas de point");
673 //   }
674 //   else
675 //     MESSAGE("point OK");
676 }
677
678 /////////////////////////////////////////////////////////
679
680 void BLSURFPlugin_BLSURF::SetParameters(
681 // #if BLSURF_VERSION_LONG >= "3.1.1"
682 //                                         cad_t *                          c,
683 // #endif
684                                         const BLSURFPlugin_Hypothesis* hyp,
685                                         blsurf_session_t *             bls,
686                                         precad_session_t *             pcs,
687                                         SMESH_Mesh&                   mesh,
688                                         bool *                  use_precad
689                                        )
690 {
691   int    _topology      = BLSURFPlugin_Hypothesis::GetDefaultTopology();
692   int    _physicalMesh  = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
693   double _phySize       = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
694   int    _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
695   double _angleMeshS    = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
696   double _angleMeshC    = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
697   double _gradation     = BLSURFPlugin_Hypothesis::GetDefaultGradation();
698   bool   _quadAllowed   = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
699   bool   _decimesh      = BLSURFPlugin_Hypothesis::GetDefaultDecimesh();
700   int    _verb          = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
701
702   // PreCAD
703   int _precadMergeEdges      = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
704   int _precadRemoveNanoEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveNanoEdges();
705   int _precadDiscardInput    = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
706   double _precadEpsNano      = BLSURFPlugin_Hypothesis::GetDefaultPreCADEpsNano();
707
708
709   if (hyp) {
710     MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
711     _topology      = (int) hyp->GetTopology();
712     _physicalMesh  = (int) hyp->GetPhysicalMesh();
713     _phySize       = hyp->GetPhySize();
714     _geometricMesh = (int) hyp->GetGeometricMesh();
715     _angleMeshS    = hyp->GetAngleMeshS();
716     _angleMeshC    = hyp->GetAngleMeshC();
717     _gradation     = hyp->GetGradation();
718     _quadAllowed   = hyp->GetQuadAllowed();
719     _decimesh      = hyp->GetDecimesh();
720     _verb          = hyp->GetVerbosity();
721     if ( hyp->GetPhyMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
722       blsurf_set_param(bls, "hphymin", to_string(hyp->GetPhyMin()).c_str());
723     if ( hyp->GetPhyMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
724       blsurf_set_param(bls, "hphymax", to_string(hyp->GetPhyMax()).c_str());
725     if ( hyp->GetGeoMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
726       blsurf_set_param(bls, "hgeomin", to_string(hyp->GetGeoMin()).c_str());
727     if ( hyp->GetGeoMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
728       blsurf_set_param(bls, "hgeomax", to_string(hyp->GetGeoMax()).c_str());
729
730     const BLSURFPlugin_Hypothesis::TOptionValues & opts = hyp->GetOptionValues();
731     BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
732     for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
733       if ( !opIt->second.empty() ) {
734         MESSAGE("blsurf_set_param(): " << opIt->first << " = " << opIt->second);
735         blsurf_set_param(bls, opIt->first.c_str(), opIt->second.c_str());
736       }
737       
738     const BLSURFPlugin_Hypothesis::TOptionValues & preCADopts = hyp->GetPreCADOptionValues();
739     for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
740       if ( !opIt->second.empty() ) {
741         if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
742           MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
743           blsurf_set_param(bls, opIt->first.c_str(), opIt->second.c_str());
744         }
745       }
746
747     // PreCAD
748     _precadMergeEdges = hyp->GetPreCADMergeEdges();
749     _precadRemoveNanoEdges = hyp->GetPreCADRemoveNanoEdges();
750     _precadDiscardInput = hyp->GetPreCADDiscardInput();
751     _precadEpsNano = hyp->GetPreCADEpsNano();
752
753   } else {
754     //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
755     // GetDefaultPhySize() sometimes leads to computation failure
756     _phySize = mesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
757     MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
758   }
759
760   // PreCAD
761   if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
762     *use_precad = true;
763     precad_set_param(pcs, "verbose",                to_string(_verb).c_str());
764     precad_set_param(pcs, "merge_edges",            _precadMergeEdges ? "1" : "0");
765     precad_set_param(pcs, "remove_nano_edges",      _precadRemoveNanoEdges ? "1" : "0");
766     precad_set_param(pcs, "discard_input_topology", _precadDiscardInput ? "1" : "0");
767     if ( _precadEpsNano != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
768       precad_set_param(pcs, "eps_nano",               to_string(_precadEpsNano).c_str());
769   }
770
771   _smp_phy_size = _phySize;
772   blsurf_set_param(bls, "topo_points",       _topology == BLSURFPlugin_Hypothesis::Process || _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
773   blsurf_set_param(bls, "topo_curves",       _topology == BLSURFPlugin_Hypothesis::Process || _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
774   blsurf_set_param(bls, "topo_project",      _topology == BLSURFPlugin_Hypothesis::Process || _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
775   blsurf_set_param(bls, "clean_boundary",    _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
776   blsurf_set_param(bls, "close_boundary",    _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
777   blsurf_set_param(bls, "hphy_flag",         to_string(_physicalMesh).c_str());
778   blsurf_set_param(bls, "hphydef",           to_string(_phySize).c_str());
779   blsurf_set_param(bls, "hgeo_flag",         to_string(_geometricMesh).c_str());
780   blsurf_set_param(bls, "relax_size",        _decimesh ? "0": to_string(_geometricMesh).c_str());
781   blsurf_set_param(bls, "angle_meshs",       to_string(_angleMeshS).c_str());
782   blsurf_set_param(bls, "angle_meshc",       to_string(_angleMeshC).c_str());
783   blsurf_set_param(bls, "gradation",         to_string(_gradation).c_str());
784   blsurf_set_param(bls, "patch_independent", _decimesh ? "1" : "0");
785   blsurf_set_param(bls, "element",           _quadAllowed ? "q1.0" : "p1");
786   blsurf_set_param(bls, "verb",              to_string(_verb).c_str());
787   
788   if (_physicalMesh == BLSURFPlugin_Hypothesis::SizeMap){
789     TopoDS_Shape GeomShape;
790     TopoDS_Shape AttShape;
791     TopAbs_ShapeEnum GeomType;
792     //
793     // Standard Size Maps
794     //
795     MESSAGE("Setting a Size Map");
796     const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
797     BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
798     for ( ; smIt != sizeMaps.end(); ++smIt ) {
799       if ( !smIt->second.empty() ) {
800         MESSAGE("blsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
801         GeomShape = entryToShape(smIt->first);
802         GeomType  = GeomShape.ShapeType();
803         MESSAGE("Geomtype is " << GeomType);
804         int key = -1;
805         // Group Management
806         if (GeomType == TopAbs_COMPOUND){
807           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
808             // Group of faces
809             if (it.Value().ShapeType() == TopAbs_FACE){
810               HasSizeMapOnFace = true;
811               if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
812                 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
813               }
814               else {
815                 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
816 //                 MESSAGE("Face with key " << key << " already in map");
817               }
818               FaceId2SizeMap[key] = smIt->second;
819             }
820             // Group of edges
821             if (it.Value().ShapeType() == TopAbs_EDGE){
822               HasSizeMapOnEdge = true;
823               HasSizeMapOnFace = true;
824               if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
825                 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
826               }
827               else {
828                 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
829 //                 MESSAGE("Edge with key " << key << " already in map");
830               }
831               EdgeId2SizeMap[key] = smIt->second;
832             }
833             // Group of vertices
834             if (it.Value().ShapeType() == TopAbs_VERTEX){
835               HasSizeMapOnVertex = true;
836               HasSizeMapOnEdge = true;
837               HasSizeMapOnFace = true;
838               if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
839                 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
840               }
841               else {
842                 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
843                 MESSAGE("Group of vertices with key " << key << " already in map");
844               }
845               MESSAGE("Group of vertices with key " << key << " has a size map: " << smIt->second);
846               VertexId2SizeMap[key] = smIt->second;
847             }
848           }
849         }
850         // Single face
851         if (GeomType == TopAbs_FACE){
852           HasSizeMapOnFace = true;
853           if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
854             key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
855           }
856           else {
857             key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
858 //             MESSAGE("Face with key " << key << " already in map");
859           }
860           FaceId2SizeMap[key] = smIt->second;
861         }
862         // Single edge
863         if (GeomType == TopAbs_EDGE){
864           HasSizeMapOnEdge = true;
865           HasSizeMapOnFace = true;
866           if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
867             key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
868           }
869           else {
870             key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
871 //             MESSAGE("Edge with key " << key << " already in map");
872           }
873           EdgeId2SizeMap[key] = smIt->second;
874         }
875         // Single vertex
876         if (GeomType == TopAbs_VERTEX){
877           HasSizeMapOnVertex = true;
878           HasSizeMapOnEdge   = true;
879           HasSizeMapOnFace   = true;
880           if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
881             key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
882           }
883           else {
884             key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
885              MESSAGE("Vertex with key " << key << " already in map");
886           }
887           MESSAGE("Vertex with key " << key << " has a size map: " << smIt->second);
888           VertexId2SizeMap[key] = smIt->second;
889         }
890       }
891     }
892
893     //
894     // Attractors
895     //
896     // TODO appeler le constructeur des attracteurs directement ici
897     MESSAGE("Setting Attractors");
898     const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
899     BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
900     for ( ; atIt != attractors.end(); ++atIt ) {
901       if ( !atIt->second.empty() ) {
902         MESSAGE("blsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
903         GeomShape = entryToShape(atIt->first);
904         GeomType  = GeomShape.ShapeType();
905         // Group Management
906         if (GeomType == TopAbs_COMPOUND){
907           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
908             if (it.Value().ShapeType() == TopAbs_FACE){
909               HasSizeMapOnFace = true;
910               createAttractorOnFace(it.Value(), atIt->second);
911             }
912           }
913         }
914
915         if (GeomType == TopAbs_FACE){
916           HasSizeMapOnFace = true;
917           createAttractorOnFace(GeomShape, atIt->second);
918         }
919 /*
920         if (GeomType == TopAbs_EDGE){
921           HasSizeMapOnEdge = true;
922           HasSizeMapOnFace = true;
923         EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
924         }
925         if (GeomType == TopAbs_VERTEX){
926           HasSizeMapOnVertex = true;
927           HasSizeMapOnEdge   = true;
928           HasSizeMapOnFace   = true;
929         VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
930         }
931 */
932       }
933     }
934
935     // Class Attractors
936     // temporary commented out for testing
937     // TODO
938     //  - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
939     //  - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
940     //  - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
941     //  OR, even better:
942     //  - Construct the attractors with an empty dist. map in the hypothesis
943     //  - build the map here for each face with an attractor set and only if the attractor shape as changed since the last call to _buildmap()
944     //  -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap()  OK
945
946     const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
947     int key=-1;
948     BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
949     for ( ; AtIt != class_attractors.end(); ++AtIt ) {
950       if ( !AtIt->second->Empty() ) {
951        // MESSAGE("blsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
952         GeomShape = entryToShape(AtIt->first);
953         AttShape = AtIt->second->GetAttractorShape();
954         GeomType  = GeomShape.ShapeType();
955         // Group Management
956 //         if (GeomType == TopAbs_COMPOUND){
957 //           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
958 //             if (it.Value().ShapeType() == TopAbs_FACE){
959 //               HasAttractorOnFace = true;
960 //               myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
961 //             }
962 //           }
963 //         }
964
965         if (GeomType == TopAbs_FACE
966           && (AttShape.ShapeType() == TopAbs_VERTEX
967            || AttShape.ShapeType() == TopAbs_EDGE
968            || AttShape.ShapeType() == TopAbs_WIRE
969            || AttShape.ShapeType() == TopAbs_COMPOUND) ){
970             HasSizeMapOnFace = true;
971
972             if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape)) ) {
973                 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
974             }
975             else {
976               key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
977 //                 MESSAGE("Face with key " << key << " already in map");
978             }
979
980             FaceId2ClassAttractor[key] = AtIt->second;
981         }
982         else{
983           MESSAGE("Wrong shape type !!")
984         }
985
986       }
987     }
988
989
990     //
991     // Enforced Vertices
992     //
993     MESSAGE("Setting Enforced Vertices");
994     const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
995     BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
996     for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
997       if ( !enfIt->second.empty() ) {
998         GeomShape = entryToShape(enfIt->first);
999         GeomType  = GeomShape.ShapeType();
1000         // Group Management
1001         if (GeomType == TopAbs_COMPOUND){
1002           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1003             if (it.Value().ShapeType() == TopAbs_FACE){
1004               HasSizeMapOnFace = true;
1005               createEnforcedVertexOnFace(it.Value(), enfIt->second);
1006             }
1007           }
1008         }
1009
1010         if (GeomType == TopAbs_FACE){
1011           HasSizeMapOnFace = true;
1012           createEnforcedVertexOnFace(GeomShape, enfIt->second);
1013         }
1014       }
1015     }
1016
1017     // Internal vertices
1018     bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1019     if (useInternalVertexAllFaces) {
1020       std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1021       MESSAGE("Setting Internal Enforced Vertices");
1022       GeomShape = mesh.GetShapeToMesh();
1023       gp_Pnt aPnt;
1024       TopExp_Explorer exp (GeomShape, TopAbs_FACE);
1025       for (; exp.More(); exp.Next()){
1026         MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
1027         TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX);
1028         for (; exp_face.More(); exp_face.Next())
1029         {
1030           // Get coords of vertex
1031           // Check if current coords is already in enfVertexList
1032           // If coords not in enfVertexList, add new enfVertex
1033           aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1034           MESSAGE("Found vertex on face at " << aPnt.X() <<", "<<aPnt.Y()<<", "<<aPnt.Z());
1035           BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1036           enfVertex->coords.push_back(aPnt.X());
1037           enfVertex->coords.push_back(aPnt.Y());
1038           enfVertex->coords.push_back(aPnt.Z());
1039           enfVertex->name = "";
1040           enfVertex->faceEntries.clear();
1041           enfVertex->geomEntry = "";
1042           enfVertex->grpName = grpName;
1043           _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()),  aPnt, enfVertex);
1044           HasSizeMapOnFace = true;
1045         }
1046       }
1047     }
1048
1049     MESSAGE("Setting Size Map on FACES ");
1050 // #if BLSURF_VERSION_LONG < "3.1.1"
1051     blsurf_data_set_sizemap_iso_cad_face(bls, size_on_surface, &_smp_phy_size);
1052 // #else
1053 //     if (*use_precad)
1054 //       iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1055 //     else
1056 //       clean_iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1057 // #endif
1058
1059     if (HasSizeMapOnEdge){
1060       MESSAGE("Setting Size Map on EDGES ");
1061 // #if BLSURF_VERSION_LONG < "3.1.1"
1062       blsurf_data_set_sizemap_iso_cad_edge(bls, size_on_edge, &_smp_phy_size);
1063 // #else
1064 //       if (*use_precad)
1065 //         iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1066 //       else
1067 //         clean_iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1068 // #endif
1069     }
1070     if (HasSizeMapOnVertex){
1071       MESSAGE("Setting Size Map on VERTICES ");
1072 // #if BLSURF_VERSION_LONG < "3.1.1"
1073       blsurf_data_set_sizemap_iso_cad_point(bls, size_on_vertex, &_smp_phy_size);
1074 // #else
1075 //       if (*use_precad)
1076 //         iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1077 //       else
1078 //         clean_iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1079 // #endif
1080     }
1081   }
1082 }
1083
1084 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1085 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1086                   real *duu, real *duv, real *dvv, void *user_data);
1087 status_t message_cb(message_t *msg, void *user_data);
1088 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1089
1090 //=============================================================================
1091 /*!
1092  *
1093  */
1094 //=============================================================================
1095
1096 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1097
1098   MESSAGE("BLSURFPlugin_BLSURF::Compute");
1099
1100   // Fix problem with locales
1101   Kernel_Utils::Localizer aLocalizer;
1102
1103   /* create a distene context (generic object) */
1104   status_t status = STATUS_ERROR;
1105
1106   context_t *ctx =  context_new();
1107
1108   /* Set the message callback in the working context */
1109   context_set_message_callback(ctx, message_cb, &_comment);
1110 #ifdef WITH_SMESH_CANCEL_COMPUTE
1111   _compute_canceled = false;
1112   context_set_interrupt_callback(ctx, interrupt_cb, this);
1113 #else
1114   context_set_interrupt_callback(ctx, interrupt_cb, NULL);
1115 #endif
1116
1117   /* create the CAD object we will work on. It is associated to the context ctx. */
1118   cad_t *c = cad_new(ctx);
1119
1120   FacesWithSizeMap.Clear();
1121   FaceId2SizeMap.clear();
1122   FaceId2ClassAttractor.clear();
1123   FaceIndex2ClassAttractor.clear();
1124   EdgesWithSizeMap.Clear();
1125   EdgeId2SizeMap.clear();
1126   VerticesWithSizeMap.Clear();
1127   VertexId2SizeMap.clear();
1128
1129
1130   /* Now fill the CAD object with data from your CAD
1131    * environement. This is the most complex part of a successfull
1132    * integration.
1133    */
1134
1135   // PreCAD
1136   // If user requests it, send the CAD through Distene preprocessor : PreCAD
1137   cad_t *cleanc = NULL;
1138   precad_session_t *pcs = precad_session_new(ctx);
1139   precad_data_set_cad(pcs, c);
1140
1141   blsurf_session_t *bls = blsurf_session_new(ctx);
1142
1143   MESSAGE("BEGIN SetParameters");
1144   bool use_precad = false;
1145   SetParameters(
1146 // #if BLSURF_VERSION_LONG >= "3.1.1"
1147 //     c,
1148 // #endif
1149     _hypothesis, bls, pcs, aMesh, &use_precad);
1150   MESSAGE("END SetParameters");
1151
1152   // needed to prevent the opencascade memory managmement from freeing things
1153   vector<Handle(Geom2d_Curve)> curves;
1154   vector<Handle(Geom_Surface)> surfaces;
1155
1156   surfaces.resize(0);
1157   curves.resize(0);
1158
1159   TopTools_IndexedMapOfShape fmap;
1160   TopTools_IndexedMapOfShape emap;
1161   TopTools_IndexedMapOfShape pmap;
1162
1163   fmap.Clear();
1164   FaceId2PythonSmp.clear();
1165   emap.Clear();
1166   EdgeId2PythonSmp.clear();
1167   pmap.Clear();
1168   VertexId2PythonSmp.clear();
1169
1170   assert(Py_IsInitialized());
1171   PyGILState_STATE gstate;
1172   gstate = PyGILState_Ensure();
1173
1174   string theSizeMapStr;
1175
1176   /****************************************************************************************
1177                                   FACES
1178   *****************************************************************************************/
1179   int iface = 0;
1180   string bad_end = "return";
1181   int faceKey = -1;
1182   TopTools_IndexedMapOfShape _map;
1183   TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
1184   int ienf = _map.Extent();
1185
1186   for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next()) {
1187     TopoDS_Face f=TopoDS::Face(face_iter.Current());
1188
1189     // make INTERNAL face oriented FORWARD (issue 0020993)
1190     if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
1191       f.Orientation(TopAbs_FORWARD);
1192
1193     if (fmap.FindIndex(f) > 0)
1194       continue;
1195
1196     fmap.Add(f);
1197     iface++;
1198     surfaces.push_back(BRep_Tool::Surface(f));
1199
1200     /* create an object representing the face for blsurf */
1201     /* where face_id is an integer identifying the face.
1202      * surf_function is the function that defines the surface
1203      * (For this face, it will be called by blsurf with your_face_object_ptr
1204      * as last parameter.
1205      */
1206     cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
1207
1208     /* by default a face has no tag (color). The following call sets it to the same value as the face_id : */
1209     cad_face_set_tag(fce, iface);
1210
1211     /* Set face orientation (optional if you want a well oriented output mesh)*/
1212     if(f.Orientation() != TopAbs_FORWARD){
1213       cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
1214     } else {
1215       cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
1216     }
1217
1218     if (HasSizeMapOnFace && !use_precad){
1219 //       MESSAGE("A size map is defined on a face")
1220 //       std::cout << "A size map is defined on a face" << std::endl;
1221       // Classic size map
1222       faceKey = FacesWithSizeMap.FindIndex(f);
1223
1224
1225       if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()){
1226         MESSAGE("A size map is defined on face :"<<faceKey)
1227         theSizeMapStr = FaceId2SizeMap[faceKey];
1228         // check if function ends with "return"
1229         if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1230           continue;
1231         // Expr To Python function, verification is performed at validation in GUI
1232         PyObject * obj = NULL;
1233         obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1234         Py_DECREF(obj);
1235         PyObject * func = NULL;
1236         func = PyObject_GetAttrString(main_mod, "f");
1237         FaceId2PythonSmp[iface]=func;
1238         FaceId2SizeMap.erase(faceKey);
1239       }
1240
1241       // Specific size map = Attractor
1242       std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
1243
1244       for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
1245         if (attractor_iter->first == faceKey) {
1246           MESSAGE("Face indice: " << iface);
1247           MESSAGE("Adding attractor");
1248
1249           double xyzCoords[3]  = {attractor_iter->second[2],
1250                                   attractor_iter->second[3],
1251                                   attractor_iter->second[4]};
1252
1253           MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1254           gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1255           BRepClass_FaceClassifier scl(f,P,1e-7);
1256           // scl.Perform() is bugged. The function was rewritten
1257 //          scl.Perform();
1258           BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1259           TopAbs_State result = scl.State();
1260           MESSAGE("Position of point on face: "<<result);
1261           if ( result == TopAbs_OUT )
1262               MESSAGE("Point is out of face: node is not created");
1263           if ( result == TopAbs_UNKNOWN )
1264               MESSAGE("Point position on face is unknown: node is not created");
1265           if ( result == TopAbs_ON )
1266               MESSAGE("Point is on border of face: node is not created");
1267           if ( result == TopAbs_IN )
1268           {
1269             // Point is inside face and not on border
1270             MESSAGE("Point is in face: node is created");
1271             double uvCoords[2]   = {attractor_iter->second[0],attractor_iter->second[1]};
1272             ienf++;
1273             MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
1274             cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
1275             cad_point_set_tag(point_p, ienf);
1276           }
1277           FaceId2AttractorCoords.erase(faceKey);
1278         }
1279       }
1280
1281       // Class Attractors
1282       std::map<int,BLSURFPlugin_Attractor* >::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
1283       if (clAttractor_iter != FaceId2ClassAttractor.end()){
1284           MESSAGE("Face indice: " << iface);
1285           MESSAGE("Adding attractor");
1286           FaceIndex2ClassAttractor[iface]=clAttractor_iter->second;
1287           FaceId2ClassAttractor.erase(clAttractor_iter);
1288         }
1289       }
1290
1291       // Enforced Vertices
1292       faceKey = FacesWithEnforcedVertices.FindIndex(f);
1293       std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
1294       if (evmIt != FaceId2EnforcedVertexCoords.end()) {
1295         MESSAGE("Some enforced vertices are defined");
1296         BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
1297         MESSAGE("Face indice: " << iface);
1298         MESSAGE("Adding enforced vertices");
1299         evl = evmIt->second;
1300         MESSAGE("Number of vertices to add: "<< evl.size());
1301         BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
1302         for (; evlIt != evl.end(); ++evlIt) {
1303           BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
1304           xyzCoords.push_back(evlIt->at(2));
1305           xyzCoords.push_back(evlIt->at(3));
1306           xyzCoords.push_back(evlIt->at(4));
1307           MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1308           gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1309           BRepClass_FaceClassifier scl(f,P,1e-7);
1310           // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
1311 //          BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1312           // OCC 6.5.2: scl.Perform() is not bugged anymore
1313           scl.Perform(f, P, 1e-7);
1314           TopAbs_State result = scl.State();
1315           MESSAGE("Position of point on face: "<<result);
1316           if ( result == TopAbs_OUT ) {
1317             MESSAGE("Point is out of face: node is not created");
1318             if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1319               EnfVertexCoords2ProjVertex.erase(xyzCoords);
1320               EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1321             }
1322           }
1323           if ( result == TopAbs_UNKNOWN ) {
1324             MESSAGE("Point position on face is unknown: node is not created");
1325             if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1326               EnfVertexCoords2ProjVertex.erase(xyzCoords);
1327               EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1328             }
1329           }
1330           if ( result == TopAbs_ON ) {
1331             MESSAGE("Point is on border of face: node is not created");
1332             if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1333               EnfVertexCoords2ProjVertex.erase(xyzCoords);
1334               EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1335             }
1336           }
1337           if ( result == TopAbs_IN )
1338           {
1339             // Point is inside face and not on border
1340             MESSAGE("Point is in face: node is created");
1341             double uvCoords[2]   = {evlIt->at(0),evlIt->at(1)};
1342             ienf++;
1343             MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
1344             cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
1345             cad_point_set_tag(point_p, ienf);
1346           }
1347         }
1348         FaceId2EnforcedVertexCoords.erase(faceKey);
1349       }
1350 //       else
1351 //         std::cout << "No enforced vertex defined" << std::endl;
1352 //     }
1353
1354
1355     /****************************************************************************************
1356                                     EDGES
1357                    now create the edges associated to this face
1358     *****************************************************************************************/
1359     int edgeKey = -1;
1360     for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next()) {
1361       TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
1362       int ic = emap.FindIndex(e);
1363       if (ic <= 0)
1364         ic = emap.Add(e);
1365
1366       double tmin,tmax;
1367       curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
1368
1369       if (HasSizeMapOnEdge){
1370         edgeKey = EdgesWithSizeMap.FindIndex(e);
1371         if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
1372           MESSAGE("Sizemap defined on edge with index " << edgeKey);
1373           theSizeMapStr = EdgeId2SizeMap[edgeKey];
1374           if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1375             continue;
1376           // Expr To Python function, verification is performed at validation in GUI
1377           PyObject * obj = NULL;
1378           obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1379           Py_DECREF(obj);
1380           PyObject * func = NULL;
1381           func = PyObject_GetAttrString(main_mod, "f");
1382           EdgeId2PythonSmp[ic]=func;
1383           EdgeId2SizeMap.erase(edgeKey);
1384         }
1385       }
1386
1387       /* attach the edge to the current blsurf face */
1388       cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
1389
1390       /* by default an edge has no tag (color). The following call sets it to the same value as the edge_id : */
1391       cad_edge_set_tag(edg, ic);
1392
1393       /* by default, an edge does not necessalry appear in the resulting mesh,
1394      unless the following property is set :
1395       */
1396       cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
1397
1398       /* by default an edge is a boundary edge */
1399       if (e.Orientation() == TopAbs_INTERNAL)
1400         cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
1401
1402       int npts = 0;
1403       int ip1, ip2, *ip;
1404       gp_Pnt2d e0 = curves.back()->Value(tmin);
1405       gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
1406       Standard_Real d1=0,d2=0;
1407
1408
1409       /****************************************************************************************
1410                                       VERTICES
1411       *****************************************************************************************/
1412       int vertexKey = -1;
1413       for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
1414         TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
1415         ++npts;
1416         if (npts == 1){
1417           ip = &ip1;
1418           d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
1419         } else {
1420           ip = &ip2;
1421           d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
1422         }
1423         *ip = pmap.FindIndex(v);
1424         if(*ip <= 0)
1425           *ip = pmap.Add(v);
1426
1427         if (HasSizeMapOnVertex){
1428           vertexKey = VerticesWithSizeMap.FindIndex(v);
1429           if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
1430             theSizeMapStr = VertexId2SizeMap[vertexKey];
1431             //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
1432             if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1433               continue;
1434             // Expr To Python function, verification is performed at validation in GUI
1435             PyObject * obj = NULL;
1436             obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1437             Py_DECREF(obj);
1438             PyObject * func = NULL;
1439             func = PyObject_GetAttrString(main_mod, "f");
1440             VertexId2PythonSmp[*ip]=func;
1441             VertexId2SizeMap.erase(vertexKey);   // do not erase if using a vector
1442           }
1443         }
1444       }
1445       if (npts != 2) {
1446         // should not happen
1447         MESSAGE("An edge does not have 2 extremities.");
1448       } else {
1449         if (d1 < d2) {
1450           // This defines the curves extremity connectivity
1451           cad_edge_set_extremities(edg, ip1, ip2);
1452           /* set the tag (color) to the same value as the extremity id : */
1453           cad_edge_set_extremities_tag(edg, ip1, ip2);
1454         }
1455         else {
1456           cad_edge_set_extremities(edg, ip2, ip1);
1457           cad_edge_set_extremities_tag(edg, ip2, ip1);
1458         }
1459       }
1460     } // for edge
1461   } //for face
1462
1463
1464   PyGILState_Release(gstate);
1465
1466   if (use_precad){
1467     /* Now launch the PreCAD process */
1468     status = precad_process(pcs);
1469     if(status != STATUS_OK){
1470       cout << "PreCAD processing failed with error code " << status << "\n";
1471       // Now we can delete the PreCAD session
1472       precad_session_delete(pcs);
1473     }
1474     else {
1475       // retrieve the pre-processed CAD object
1476       cleanc = precad_new_cad(pcs);
1477       if(!cleanc){
1478         cout << "Unable to retrieve PreCAD result \n";
1479       }
1480       cout << "PreCAD processing successfull \n";
1481
1482 // #if BLSURF_VERSION_LONG >= "3.1.1"
1483 //       /* We can now get the updated sizemaps (if any) */
1484 // //       if(geo_sizemap_e)
1485 // //         clean_geo_sizemap_e = precad_new_sizemap(pcs, geo_sizemap_e);
1486 // // 
1487 // //       if(geo_sizemap_f)
1488 // //         clean_geo_sizemap_f = precad_new_sizemap(pcs, geo_sizemap_f);
1489 // 
1490 //       if(iso_sizemap_p)
1491 //         clean_iso_sizemap_p = precad_new_sizemap(pcs, iso_sizemap_p);
1492 // 
1493 //       if(iso_sizemap_e)
1494 //         clean_iso_sizemap_e = precad_new_sizemap(pcs, iso_sizemap_e);
1495 // 
1496 //       if(iso_sizemap_f)
1497 //         clean_iso_sizemap_f = precad_new_sizemap(pcs, iso_sizemap_f);
1498 // #endif
1499       
1500       // Now we can delete the PreCAD session 
1501       precad_session_delete(pcs);
1502     }
1503   }
1504
1505   if (cleanc) {
1506     // Give the pre-processed CAD object to the current BLSurf session
1507     blsurf_data_set_cad(bls, cleanc);
1508   }
1509   else {
1510     // Use the original one
1511     blsurf_data_set_cad(bls, c);
1512   }
1513
1514 // #if BLSURF_VERSION_LONG >= "3.1.1"
1515 //   blsurf_data_set_sizemap(bls, clean_iso_sizemap_p);
1516 //   blsurf_data_set_sizemap(bls, clean_iso_sizemap_e);
1517 //   blsurf_data_set_sizemap(bls, clean_iso_sizemap_f);
1518 // #endif
1519
1520   std::cout << std::endl;
1521   std::cout << "Beginning of Surface Mesh generation" << std::endl;
1522   std::cout << std::endl;
1523
1524   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1525 #ifndef WNT
1526   feclearexcept( FE_ALL_EXCEPT );
1527   int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1528 #endif
1529
1530   try {
1531     OCC_CATCH_SIGNALS;
1532
1533     status = blsurf_compute_mesh(bls);
1534
1535   }
1536   catch ( std::exception& exc ) {
1537     _comment += exc.what();
1538   }
1539   catch (Standard_Failure& ex) {
1540     _comment += ex.DynamicType()->Name();
1541     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
1542       _comment += ": ";
1543       _comment += ex.GetMessageString();
1544     }
1545   }
1546   catch (...) {
1547     if ( _comment.empty() )
1548       _comment = "Exception in blsurf_compute_mesh()";
1549   }
1550   if ( status != STATUS_OK) {
1551     // There was an error while meshing
1552     blsurf_session_delete(bls);
1553
1554 // #if BLSURF_VERSION_LONG >= "3.1.1"
1555 // //     if(geo_sizemap_e)
1556 // //       distene_sizemap_delete(geo_sizemap_e);
1557 // //     if(geo_sizemap_f)
1558 // //       distene_sizemap_delete(geo_sizemap_f);
1559 //     if(iso_sizemap_p)
1560 //       distene_sizemap_delete(iso_sizemap_p);
1561 //     if(iso_sizemap_e)
1562 //       distene_sizemap_delete(iso_sizemap_e);
1563 //     if(iso_sizemap_f)
1564 //       distene_sizemap_delete(iso_sizemap_f);
1565 // 
1566 // //     if(clean_geo_sizemap_e)
1567 // //       distene_sizemap_delete(clean_geo_sizemap_e);
1568 // //     if(clean_geo_sizemap_f)
1569 // //       distene_sizemap_delete(clean_geo_sizemap_f);
1570 //     if(clean_iso_sizemap_p)
1571 //       distene_sizemap_delete(clean_iso_sizemap_p);
1572 //     if(clean_iso_sizemap_e)
1573 //       distene_sizemap_delete(clean_iso_sizemap_e);
1574 //     if(clean_iso_sizemap_f)
1575 //       distene_sizemap_delete(clean_iso_sizemap_f);
1576 // #endif
1577       
1578     cad_delete(c);
1579     context_delete(ctx);
1580
1581     return error(_comment);
1582   }
1583
1584   std::cout << std::endl;
1585   std::cout << "End of Surface Mesh generation" << std::endl;
1586   std::cout << std::endl;
1587
1588   mesh_t *msh = NULL;
1589   blsurf_data_get_mesh(bls, &msh);
1590   if(!msh){
1591     /* release the mesh object */
1592     blsurf_data_regain_mesh(bls, msh);
1593     /* clean up everything */
1594     blsurf_session_delete(bls);
1595
1596 // #if BLSURF_VERSION_LONG >= "3.1.1"
1597 // //     if(geo_sizemap_e)
1598 // //       distene_sizemap_delete(geo_sizemap_e);
1599 // //     if(geo_sizemap_f)
1600 // //       distene_sizemap_delete(geo_sizemap_f);
1601 //     if(iso_sizemap_p)
1602 //       distene_sizemap_delete(iso_sizemap_p);
1603 //     if(iso_sizemap_e)
1604 //       distene_sizemap_delete(iso_sizemap_e);
1605 //     if(iso_sizemap_f)
1606 //       distene_sizemap_delete(iso_sizemap_f);
1607 // 
1608 // //     if(clean_geo_sizemap_e)
1609 // //       distene_sizemap_delete(clean_geo_sizemap_e);
1610 // //     if(clean_geo_sizemap_f)
1611 // //       distene_sizemap_delete(clean_geo_sizemap_f);
1612 //     if(clean_iso_sizemap_p)
1613 //       distene_sizemap_delete(clean_iso_sizemap_p);
1614 //     if(clean_iso_sizemap_e)
1615 //       distene_sizemap_delete(clean_iso_sizemap_e);
1616 //     if(clean_iso_sizemap_f)
1617 //       distene_sizemap_delete(clean_iso_sizemap_f);
1618 // #endif
1619       
1620     cad_delete(c);
1621     context_delete(ctx);
1622
1623     return error(_comment);
1624     //return false;
1625   }
1626
1627   std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
1628   if (_hypothesis)
1629     GMFFileName = _hypothesis->GetGMFFile();
1630   if (GMFFileName != "") {
1631 //     bool GMFFileMode = _hypothesis->GetGMFFileMode();
1632     bool asciiFound = (GMFFileName.find(".mesh",GMFFileName.length()-5) != std::string::npos);
1633     bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
1634     if (!asciiFound && !binaryFound)
1635       GMFFileName.append(".mesh");
1636     /*
1637     if (GMFFileMode) {
1638       if (!binaryFound) {
1639         if (asciiFound)
1640           GMFFileName.append("b");
1641         else
1642           GMFFileName.append(".meshb");
1643       }
1644     }
1645     else {
1646       if (!asciiFound)
1647         GMFFileName.append(".mesh");
1648     }
1649     */
1650     mesh_write_mesh(msh, GMFFileName.c_str());
1651   }
1652
1653   /* retrieve mesh data (see distene/mesh.h) */
1654   integer nv, ne, nt, nq, vtx[4], tag;
1655   real xyz[3];
1656
1657   mesh_get_vertex_count(msh, &nv);
1658   mesh_get_edge_count(msh, &ne);
1659   mesh_get_triangle_count(msh, &nt);
1660   mesh_get_quadrangle_count(msh, &nq);
1661
1662
1663   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1664   SMDS_MeshNode** nodes = new SMDS_MeshNode*[nv+1];
1665   bool* tags = new bool[nv+1];
1666
1667   /* enumerated vertices */
1668   for(int iv=1;iv<=nv;iv++) {
1669     mesh_get_vertex_coordinates(msh, iv, xyz);
1670     mesh_get_vertex_tag(msh, iv, &tag);
1671     // Issue 0020656. Use vertex coordinates
1672     if ( tag > 0 && tag <= pmap.Extent() ) {
1673       TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
1674       double tol = BRep_Tool::Tolerance( v );
1675       gp_Pnt p = BRep_Tool::Pnt( v );
1676       if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
1677         xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
1678       else
1679         tag = 0; // enforced or attracted vertex
1680     }
1681     nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
1682
1683     // Create group of enforced vertices if requested
1684     BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
1685     projVertex.clear();
1686     projVertex.push_back((double)xyz[0]);
1687     projVertex.push_back((double)xyz[1]);
1688     projVertex.push_back((double)xyz[2]);
1689     std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
1690     if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
1691       MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
1692       BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
1693       BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
1694       for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
1695         currentEnfVertex = (*enfListIt);
1696         if (currentEnfVertex->grpName != "") {
1697           bool groupDone = false;
1698           SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
1699           MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
1700           MESSAGE("Parsing the groups of the mesh");
1701           while (grIt->more()) {
1702             SMESH_Group * group = grIt->next();
1703             if ( !group ) continue;
1704             MESSAGE("Group: " << group->GetName());
1705             SMESHDS_GroupBase* groupDS = group->GetGroupDS();
1706             if ( !groupDS ) continue;
1707             MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
1708             MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
1709             MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
1710             if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
1711               SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
1712               aGroupDS->SMDSGroup().Add(nodes[iv]);
1713               MESSAGE("Node ID: " << nodes[iv]->GetID());
1714               // How can I inform the hypothesis ?
1715 //                 _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
1716               groupDone = true;
1717               MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
1718               break;
1719             }
1720           }
1721           if (!groupDone)
1722           {
1723             int groupId;
1724             SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
1725             aGroup->SetName( currentEnfVertex->grpName.c_str() );
1726             SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
1727             aGroupDS->SMDSGroup().Add(nodes[iv]);
1728             MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
1729             groupDone = true;
1730           }
1731           if (!groupDone)
1732             throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
1733         }
1734         else
1735           MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
1736       }
1737     }
1738
1739
1740     // internal point are tagged to zero
1741     if(tag > 0 && tag <= pmap.Extent() ){
1742       meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
1743       tags[iv] = false;
1744     } else {
1745       tags[iv] = true;
1746     }
1747   }
1748
1749   /* enumerate edges */
1750   for(int it=1;it<=ne;it++) {
1751     mesh_get_edge_vertices(msh, it, vtx);
1752     SMDS_MeshEdge* edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
1753     mesh_get_edge_tag(msh, it, &tag);
1754
1755     if (tags[vtx[0]]) {
1756       Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
1757       tags[vtx[0]] = false;
1758     };
1759     if (tags[vtx[1]]) {
1760       Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
1761       tags[vtx[1]] = false;
1762     };
1763     meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
1764
1765   }
1766
1767   /* enumerate triangles */
1768   for(int it=1;it<=nt;it++) {
1769     mesh_get_triangle_vertices(msh, it, vtx);
1770     SMDS_MeshFace* tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
1771     mesh_get_triangle_tag(msh, it, &tag);
1772     meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
1773     if (tags[vtx[0]]) {
1774       meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
1775       tags[vtx[0]] = false;
1776     };
1777     if (tags[vtx[1]]) {
1778       meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
1779       tags[vtx[1]] = false;
1780     };
1781     if (tags[vtx[2]]) {
1782       meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
1783       tags[vtx[2]] = false;
1784     };
1785   }
1786
1787   /* enumerate quadrangles */
1788   for(int it=1;it<=nq;it++) {
1789     mesh_get_quadrangle_vertices(msh, it, vtx);
1790     SMDS_MeshFace* quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
1791     mesh_get_quadrangle_tag(msh, it, &tag);
1792     meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
1793     if (tags[vtx[0]]) {
1794       meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
1795       tags[vtx[0]] = false;
1796     };
1797     if (tags[vtx[1]]) {
1798       meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
1799       tags[vtx[1]] = false;
1800     };
1801     if (tags[vtx[2]]) {
1802       meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
1803       tags[vtx[2]] = false;
1804     };
1805     if (tags[vtx[3]]) {
1806       meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
1807       tags[vtx[3]] = false;
1808     };
1809   }
1810
1811   // SetIsAlwaysComputed( true ) to sub-meshes of degenerated EDGEs
1812   TopLoc_Location loc; double f,l;
1813   for (int i = 1; i <= emap.Extent(); i++)
1814     if ( BRep_Tool::Curve(TopoDS::Edge( emap( i )), loc, f,l).IsNull() )
1815       if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
1816         sm->SetIsAlwaysComputed( true );
1817   for (int i = 1; i <= pmap.Extent(); i++)
1818       if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
1819         if ( !sm->IsMeshComputed() )
1820           sm->SetIsAlwaysComputed( true );
1821
1822   delete [] nodes;
1823
1824   /* release the mesh object */
1825   blsurf_data_regain_mesh(bls, msh);
1826
1827   /* clean up everything */
1828   blsurf_session_delete(bls);
1829   
1830 // #if BLSURF_VERSION_LONG >= "3.1.1"
1831 // //     if(geo_sizemap_e)
1832 // //       distene_sizemap_delete(geo_sizemap_e);
1833 // //     if(geo_sizemap_f)
1834 // //       distene_sizemap_delete(geo_sizemap_f);
1835 //     if(iso_sizemap_p)
1836 //       distene_sizemap_delete(iso_sizemap_p);
1837 //     if(iso_sizemap_e)
1838 //       distene_sizemap_delete(iso_sizemap_e);
1839 //     if(iso_sizemap_f)
1840 //       distene_sizemap_delete(iso_sizemap_f);
1841 // 
1842 // //     if(clean_geo_sizemap_e)
1843 // //       distene_sizemap_delete(clean_geo_sizemap_e);
1844 // //     if(clean_geo_sizemap_f)
1845 // //       distene_sizemap_delete(clean_geo_sizemap_f);
1846 //     if(clean_iso_sizemap_p)
1847 //       distene_sizemap_delete(clean_iso_sizemap_p);
1848 //     if(clean_iso_sizemap_e)
1849 //       distene_sizemap_delete(clean_iso_sizemap_e);
1850 //     if(clean_iso_sizemap_f)
1851 //       distene_sizemap_delete(clean_iso_sizemap_f);
1852 // #endif
1853       
1854   cad_delete(c);
1855
1856   context_delete(ctx);
1857
1858   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1859 #ifndef WNT
1860   if ( oldFEFlags > 0 )
1861     feenableexcept( oldFEFlags );
1862   feclearexcept( FE_ALL_EXCEPT );
1863 #endif
1864
1865   /*
1866   std::cout << "FacesWithSizeMap" << std::endl;
1867   FacesWithSizeMap.Statistics(std::cout);
1868   std::cout << "EdgesWithSizeMap" << std::endl;
1869   EdgesWithSizeMap.Statistics(std::cout);
1870   std::cout << "VerticesWithSizeMap" << std::endl;
1871   VerticesWithSizeMap.Statistics(std::cout);
1872   std::cout << "FacesWithEnforcedVertices" << std::endl;
1873   FacesWithEnforcedVertices.Statistics(std::cout);
1874   */
1875
1876   MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
1877   return true;
1878 }
1879
1880 #ifdef WITH_SMESH_CANCEL_COMPUTE
1881 void BLSURFPlugin_BLSURF::CancelCompute()
1882 {
1883   _compute_canceled = true;
1884 }
1885 #endif
1886
1887 //=============================================================================
1888 /*!
1889  *  SetNodeOnEdge
1890  */
1891 //=============================================================================
1892
1893 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* node, const TopoDS_Shape& ed) {
1894   const TopoDS_Edge edge = TopoDS::Edge(ed);
1895
1896   gp_Pnt pnt(node->X(), node->Y(), node->Z());
1897
1898   Standard_Real p0 = 0.0;
1899   Standard_Real p1 = 1.0;
1900   TopLoc_Location loc;
1901   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
1902
1903   if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
1904   GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
1905
1906   double pa = 0.;
1907   if ( proj.NbPoints() > 0 )
1908   {
1909     pa = (double)proj.LowerDistanceParameter();
1910     // Issue 0020656. Move node if it is too far from edge
1911     gp_Pnt curve_pnt = curve->Value( pa );
1912     double dist2 = pnt.SquareDistance( curve_pnt );
1913     double tol = BRep_Tool::Tolerance( edge );
1914     if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
1915     {
1916       curve_pnt.Transform( loc );
1917       meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
1918     }
1919   }
1920 //   GProp_GProps LProps;
1921 //   BRepGProp::LinearProperties(ed, LProps);
1922 //   double lg = (double)LProps.Mass();
1923
1924   meshDS->SetNodeOnEdge(node, edge, pa);
1925 }
1926
1927 //=============================================================================
1928 /*!
1929  *
1930  */
1931 //=============================================================================
1932
1933 ostream & BLSURFPlugin_BLSURF::SaveTo(ostream & save)
1934 {
1935   return save;
1936 }
1937
1938 //=============================================================================
1939 /*!
1940  *
1941  */
1942 //=============================================================================
1943
1944 istream & BLSURFPlugin_BLSURF::LoadFrom(istream & load)
1945 {
1946   return load;
1947 }
1948
1949 //=============================================================================
1950 /*!
1951  *
1952  */
1953 //=============================================================================
1954
1955 ostream & operator << (ostream & save, BLSURFPlugin_BLSURF & hyp)
1956 {
1957   return hyp.SaveTo( save );
1958 }
1959
1960 //=============================================================================
1961 /*!
1962  *
1963  */
1964 //=============================================================================
1965
1966 istream & operator >> (istream & load, BLSURFPlugin_BLSURF & hyp)
1967 {
1968   return hyp.LoadFrom( load );
1969 }
1970
1971 /* Curve definition function See cad_curv_t in file distene/cad.h for
1972  * more information.
1973  * NOTE : if when your CAD systems evaluates second
1974  * order derivatives it also computes first order derivatives and
1975  * function evaluation, you can optimize this example by making only
1976  * one CAD call and filling the necessary uv, dt, dtt arrays.
1977  */
1978 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
1979 {
1980   /* t is given. It contains the t (time) 1D parametric coordintaes
1981      of the point PreCAD/BLSurf is querying on the curve */
1982
1983   /* user_data identifies the edge PreCAD/BLSurf is querying
1984    * (see cad_edge_new later in this example) */
1985   const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
1986
1987   if (uv){
1988    /* BLSurf is querying the function evaluation */
1989     gp_Pnt2d P;
1990     P=pargeo->Value(t);
1991     uv[0]=P.X(); uv[1]=P.Y();
1992   }
1993
1994   if(dt) {
1995    /* query for the first order derivatives */
1996     gp_Vec2d V1;
1997     V1=pargeo->DN(t,1);
1998     dt[0]=V1.X(); dt[1]=V1.Y();
1999   }
2000
2001   if(dtt){
2002     /* query for the second order derivatives */
2003     gp_Vec2d V2;
2004     V2=pargeo->DN(t,2);
2005     dtt[0]=V2.X(); dtt[1]=V2.Y();
2006   }
2007
2008   return STATUS_OK;
2009 }
2010
2011 /* Surface definition function.
2012  * See cad_surf_t in file distene/cad.h for more information.
2013  * NOTE : if when your CAD systems evaluates second order derivatives it also
2014  * computes first order derivatives and function evaluation, you can optimize
2015  * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
2016  * arrays.
2017  */
2018 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
2019                   real *duu, real *duv, real *dvv, void *user_data)
2020 {
2021   /* uv[2] is given. It contains the u,v coordinates of the point
2022    * PreCAD/BLSurf is querying on the surface */
2023
2024   /* user_data identifies the face PreCAD/BLSurf is querying (see
2025    * cad_face_new later in this example)*/
2026   const Geom_Surface* geometry = (const Geom_Surface*) user_data;
2027
2028   if(xyz){
2029    gp_Pnt P;
2030    P=geometry->Value(uv[0],uv[1]);   // S.D0(U,V,P);
2031    xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
2032   }
2033
2034   if(du && dv){
2035     gp_Pnt P;
2036     gp_Vec D1U,D1V;
2037
2038     geometry->D1(uv[0],uv[1],P,D1U,D1V);
2039     du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
2040     dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
2041   }
2042
2043   if(duu && duv && dvv){
2044
2045     gp_Pnt P;
2046     gp_Vec D1U,D1V;
2047     gp_Vec D2U,D2V,D2UV;
2048
2049     geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
2050     duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
2051     duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
2052     dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
2053   }
2054
2055   return STATUS_OK;
2056 }
2057
2058
2059 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
2060 {
2061   if (face_id == 1) {
2062     if (my_u_min > uv[0]) {
2063       my_u_min = uv[0];
2064     }
2065     if (my_v_min > uv[1]) {
2066       my_v_min = uv[1];
2067     }
2068     if (my_u_max < uv[0]) {
2069       my_u_max = uv[0];
2070     }
2071     if (my_v_max < uv[1]) {
2072       my_v_max = uv[1];
2073     }
2074   }
2075   //MESSAGE("size_on_surface")
2076   if (FaceId2PythonSmp.count(face_id) != 0){
2077     //MESSAGE("A size map is used to calculate size on face : "<<face_id)
2078     PyObject * pyresult = NULL;
2079     PyObject* new_stderr = NULL;
2080     assert(Py_IsInitialized());
2081     PyGILState_STATE gstate;
2082     gstate = PyGILState_Ensure();
2083     pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
2084     double result;
2085     if ( pyresult == NULL){
2086       fflush(stderr);
2087       string err_description="";
2088       new_stderr = newPyStdOut(err_description);
2089       PySys_SetObject((char*)"stderr", new_stderr);
2090       PyErr_Print();
2091       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2092       Py_DECREF(new_stderr);
2093       MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
2094       result = *((double*)user_data);
2095       }
2096     else {
2097       result = PyFloat_AsDouble(pyresult);
2098       Py_DECREF(pyresult);
2099     }
2100    // MESSAGE("f(" << uv[0] << "," << uv[1] << ")" << " = " << result);
2101     *size = result;
2102     PyGILState_Release(gstate);
2103   }
2104   else if (FaceIndex2ClassAttractor.count(face_id) !=0 && !FaceIndex2ClassAttractor[face_id]->Empty()){
2105 //    MESSAGE("attractor used on face :"<<face_id)
2106     // MESSAGE("List of attractor is not empty")
2107     // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
2108     double result = FaceIndex2ClassAttractor[face_id]->GetSize(uv[0],uv[1]);
2109     *size = result;
2110    // MESSAGE("f(" << uv[0] << "," << uv[1] << ")" << " = " << result);
2111   }
2112   else {
2113     // MESSAGE("List of attractor is empty !!!")
2114     *size = *((double*)user_data);
2115   }
2116   return STATUS_OK;
2117 }
2118
2119 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
2120 {
2121   if (EdgeId2PythonSmp.count(edge_id) != 0){
2122     PyObject * pyresult = NULL;
2123     PyObject* new_stderr = NULL;
2124     assert(Py_IsInitialized());
2125     PyGILState_STATE gstate;
2126     gstate = PyGILState_Ensure();
2127     pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
2128     double result;
2129     if ( pyresult == NULL){
2130       fflush(stderr);
2131       string err_description="";
2132       new_stderr = newPyStdOut(err_description);
2133       PySys_SetObject((char*)"stderr", new_stderr);
2134       PyErr_Print();
2135       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2136       Py_DECREF(new_stderr);
2137       MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
2138       result = *((double*)user_data);
2139       }
2140     else {
2141       result = PyFloat_AsDouble(pyresult);
2142       Py_DECREF(pyresult);
2143     }
2144     *size = result;
2145     PyGILState_Release(gstate);
2146   }
2147   else {
2148     *size = *((double*)user_data);
2149   }
2150   return STATUS_OK;
2151 }
2152
2153 status_t size_on_vertex(integer point_id, real *size, void *user_data)
2154 {
2155   if (VertexId2PythonSmp.count(point_id) != 0){
2156     PyObject * pyresult = NULL;
2157     PyObject* new_stderr = NULL;
2158     assert(Py_IsInitialized());
2159     PyGILState_STATE gstate;
2160     gstate = PyGILState_Ensure();
2161     pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
2162     double result;
2163     if ( pyresult == NULL){
2164       fflush(stderr);
2165       string err_description="";
2166       new_stderr = newPyStdOut(err_description);
2167       PySys_SetObject((char*)"stderr", new_stderr);
2168       PyErr_Print();
2169       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2170       Py_DECREF(new_stderr);
2171       MESSAGE("Can't evaluate f()" << " error is " << err_description);
2172       result = *((double*)user_data);
2173       }
2174     else {
2175       result = PyFloat_AsDouble(pyresult);
2176       Py_DECREF(pyresult);
2177     }
2178     *size = result;
2179     PyGILState_Release(gstate);
2180   }
2181   else {
2182     *size = *((double*)user_data);
2183   }
2184  return STATUS_OK;
2185 }
2186
2187 /*
2188  * The following function will be called for PreCAD/BLSurf message
2189  * printing.  See context_set_message_callback (later in this
2190  * template) for how to set user_data.
2191  */
2192 status_t message_cb(message_t *msg, void *user_data)
2193 {
2194   integer errnumber = 0;
2195   char *desc;
2196   message_get_number(msg, &errnumber);
2197   message_get_description(msg, &desc);
2198   string err( desc );
2199   if ( errnumber < 0 || err.find("license") != string::npos ) {
2200     string * error = (string*)user_data;
2201 //   if ( !error->empty() )
2202 //     *error += "\n";
2203     // remove ^A from the tail
2204     int len = strlen( desc );
2205     while (len > 0 && desc[len-1] != '\n')
2206       len--;
2207     error->append( desc, len );
2208   }
2209   else {
2210       std::cout << desc << std::endl;
2211   }
2212   return STATUS_OK;
2213 }
2214
2215 /* This is the interrupt callback. PreCAD/BLSurf will call this
2216  * function regularily. See the file distene/interrupt.h
2217  */
2218 status_t interrupt_cb(integer *interrupt_status, void *user_data)
2219 {
2220   integer you_want_to_continue = 1;
2221 #ifdef WITH_SMESH_CANCEL_COMPUTE
2222   BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
2223   you_want_to_continue = !tmp->computeCanceled();
2224 #endif
2225
2226   if(you_want_to_continue)
2227   {
2228     *interrupt_status = INTERRUPT_CONTINUE;
2229     return STATUS_OK;
2230   }
2231   else /* you want to stop BLSurf */
2232   {
2233     *interrupt_status = INTERRUPT_STOP;
2234     return STATUS_ERROR;
2235   }
2236 }
2237
2238 //=============================================================================
2239 /*!
2240  *
2241  */
2242 //=============================================================================
2243 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh&         aMesh,
2244                                    const TopoDS_Shape& aShape,
2245                                    MapShapeNbElems&    aResMap)
2246 {
2247   int    _physicalMesh  = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
2248   double _phySize       = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
2249   //int    _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
2250   //double _angleMeshS    = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
2251   double _angleMeshC    = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
2252   bool   _quadAllowed   = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
2253   if(_hypothesis) {
2254     _physicalMesh  = (int) _hypothesis->GetPhysicalMesh();
2255     _phySize       = _hypothesis->GetPhySize();
2256     //_geometricMesh = (int) hyp->GetGeometricMesh();
2257     //_angleMeshS    = hyp->GetAngleMeshS();
2258     _angleMeshC    = _hypothesis->GetAngleMeshC();
2259     _quadAllowed   = _hypothesis->GetQuadAllowed();
2260   }
2261
2262   bool IsQuadratic = false;
2263
2264   // ----------------
2265   // evaluate 1D
2266   // ----------------
2267   TopTools_DataMapOfShapeInteger EdgesMap;
2268   double fullLen = 0.0;
2269   double fullNbSeg = 0;
2270   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
2271     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2272     if( EdgesMap.IsBound(E) )
2273       continue;
2274     SMESH_subMesh *sm = aMesh.GetSubMesh(E);
2275     double aLen = SMESH_Algo::EdgeLength(E);
2276     fullLen += aLen;
2277     int nb1d = 0;
2278     if(_physicalMesh==1) {
2279        nb1d = (int)( aLen/_phySize + 1 );
2280     }
2281     else {
2282       // use geometry
2283       double f,l;
2284       Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
2285       double fullAng = 0.0;
2286       double dp = (l-f)/200;
2287       gp_Pnt P1,P2,P3;
2288       C->D0(f,P1);
2289       C->D0(f+dp,P2);
2290       gp_Vec V1(P1,P2);
2291       for(int j=2; j<=200; j++) {
2292         C->D0(f+dp*j,P3);
2293         gp_Vec V2(P2,P3);
2294         fullAng += fabs(V1.Angle(V2));
2295         V1 = V2;
2296         P2 = P3;
2297       }
2298       nb1d = (int)( fullAng/_angleMeshC + 1 );
2299     }
2300     fullNbSeg += nb1d;
2301     std::vector<int> aVec(SMDSEntity_Last);
2302     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2303     if( IsQuadratic > 0 ) {
2304       aVec[SMDSEntity_Node] = 2*nb1d - 1;
2305       aVec[SMDSEntity_Quad_Edge] = nb1d;
2306     }
2307     else {
2308       aVec[SMDSEntity_Node] = nb1d - 1;
2309       aVec[SMDSEntity_Edge] = nb1d;
2310     }
2311     aResMap.insert(std::make_pair(sm,aVec));
2312     EdgesMap.Bind(E,nb1d);
2313   }
2314   double ELen = fullLen/fullNbSeg;
2315   // ----------------
2316   // evaluate 2D
2317   // ----------------
2318   // try to evaluate as in MEFISTO
2319   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
2320     TopoDS_Face F = TopoDS::Face( exp.Current() );
2321     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
2322     GProp_GProps G;
2323     BRepGProp::SurfaceProperties(F,G);
2324     double anArea = G.Mass();
2325     int nb1d = 0;
2326     std::vector<int> nb1dVec;
2327     for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
2328       int nbSeg = EdgesMap.Find(exp1.Current());
2329       nb1d += nbSeg;
2330       nb1dVec.push_back( nbSeg );
2331     }
2332     int nbQuad = 0;
2333     int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
2334     int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
2335     if ( _quadAllowed )
2336     {
2337       if ( nb1dVec.size() == 4 ) // quadrangle geom face
2338       {
2339         int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
2340         nbQuad = n1 * n2;
2341         nbNodes = (n1 + 1) * (n2 + 1);
2342         nbTria = 0;
2343       }
2344       else
2345       {
2346         nbTria = nbQuad = nbTria / 3 + 1;
2347       }
2348     }
2349     std::vector<int> aVec(SMDSEntity_Last,0);
2350     if( IsQuadratic ) {
2351       int nb1d_in = (nbTria*3 - nb1d) / 2;
2352       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
2353       aVec[SMDSEntity_Quad_Triangle] = nbTria;
2354       aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
2355     }
2356     else {
2357       aVec[SMDSEntity_Node] = nbNodes;
2358       aVec[SMDSEntity_Triangle] = nbTria;
2359       aVec[SMDSEntity_Quadrangle] = nbQuad;
2360     }
2361     aResMap.insert(std::make_pair(sm,aVec));
2362   }
2363
2364   // ----------------
2365   // evaluate 3D
2366   // ----------------
2367   GProp_GProps G;
2368   BRepGProp::VolumeProperties(aShape,G);
2369   double aVolume = G.Mass();
2370   double tetrVol = 0.1179*ELen*ELen*ELen;
2371   int nbVols  = int(aVolume/tetrVol);
2372   int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
2373   std::vector<int> aVec(SMDSEntity_Last);
2374   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2375   if( IsQuadratic ) {
2376     aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
2377     aVec[SMDSEntity_Quad_Tetra] = nbVols;
2378   }
2379   else {
2380     aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
2381     aVec[SMDSEntity_Tetra] = nbVols;
2382   }
2383   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
2384   aResMap.insert(std::make_pair(sm,aVec));
2385
2386   return true;
2387 }
2388
2389 //=============================================================================
2390 /*!
2391  *  Rewritting of the BRepClass_FaceClassifier::Perform function which is bugged (CAS 6.3sp6)
2392  *  Following line was added:
2393  *        myExtrem.Perform(P);
2394  */
2395 //=============================================================================
2396 void  BLSURFPlugin_BLSURF::BRepClass_FaceClassifierPerform(BRepClass_FaceClassifier* fc,
2397                     const TopoDS_Face& face,
2398                     const gp_Pnt& P,
2399                     const Standard_Real Tol)
2400 {
2401   //-- Voir BRepExtrema_ExtPF.cxx
2402   BRepAdaptor_Surface Surf(face);
2403   Standard_Real U1, U2, V1, V2;
2404   BRepTools::UVBounds(face, U1, U2, V1, V2);
2405   Extrema_ExtPS myExtrem;
2406   myExtrem.Initialize(Surf, U1, U2, V1, V2, Tol, Tol);
2407   myExtrem.Perform(P);
2408   //----------------------------------------------------------
2409   //-- On cherche le point le plus proche , PUIS
2410   //-- On le classifie.
2411   Standard_Integer nbv    = 0; // xpu
2412   Standard_Real MaxDist   =  RealLast();
2413   Standard_Integer indice = 0;
2414   if (myExtrem.IsDone()) {
2415     nbv = myExtrem.NbExt();
2416     for (Standard_Integer i = 1; i <= nbv; i++) {
2417 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
2418       Standard_Real d = myExtrem.SquareDistance(i);
2419 #else
2420       Standard_Real d = myExtrem.Value(i);
2421       d = Abs(d);
2422 #endif
2423       if (d <= MaxDist) {
2424         MaxDist = d;
2425         indice = i;
2426       }
2427     }
2428   }
2429   if (indice) {
2430     gp_Pnt2d Puv;
2431     Standard_Real U1,U2;
2432     myExtrem.Point(indice).Parameter(U1, U2);
2433     Puv.SetCoord(U1, U2);
2434     fc->Perform(face, Puv, Tol);
2435   }
2436   else {
2437     fc->Perform(face, gp_Pnt2d(U1-1.0,V1 - 1.0), Tol); //-- NYI etc BUG PAS BEAU En attendant l acces a rejected
2438     //-- le resultat est TopAbs_OUT;
2439   }
2440 }