Salome HOME
Merge from V6_main 01/04/2013
[plugins/blsurfplugin.git] / src / BLSURFPlugin / BLSURFPlugin_BLSURF.cxx
1 // Copyright (C) 2007-2013  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 // ---
21 // File    : BLSURFPlugin_BLSURF.cxx
22 // Authors : Francis KLOSS (OCC) & Patrick LAUG (INRIA) & Lioka RAZAFINDRAZAKA (CEA)
23 //           & Aurelien ALLEAUME (DISTENE)
24 //           Size maps developement: Nicolas GEIMER (OCC) & Gilles DAVID (EURIWARE)
25 // ---
26
27 #include "BLSURFPlugin_BLSURF.hxx"
28 #include "BLSURFPlugin_Hypothesis.hxx"
29 #include "BLSURFPlugin_Attractor.hxx"
30
31 extern "C"{
32 #include <meshgems/meshgems.h>
33 #include <meshgems/cadsurf.h>
34 #include <meshgems/precad.h>
35 }
36
37 #include <structmember.h>
38
39
40 #include <Basics_Utils.hxx>
41 #include <Basics_OCCTVersion.hxx>
42
43 #include <SMDS_EdgePosition.hxx>
44 #include <SMESHDS_Group.hxx>
45 #include <SMESH_Gen.hxx>
46 #include <SMESH_Group.hxx>
47 #include <SMESH_Mesh.hxx>
48 #include <SMESH_MeshEditor.hxx>
49 #include <SMESH_MesherHelper.hxx>
50 #include <StdMeshers_FaceSide.hxx>
51 #include <StdMeshers_ViscousLayers2D.hxx>
52
53 #include <utilities.h>
54
55 #include <limits>
56 #include <list>
57 #include <vector>
58 #include <set>
59 #include <cstdlib>
60
61 // OPENCASCADE includes
62 #include <BRepBuilderAPI_MakeFace.hxx>
63 #include <BRepBuilderAPI_MakePolygon.hxx>
64 //#include <BRepBuilderAPI_MakeVertex.hxx>
65 #include <BRepGProp.hxx>
66 #include <BRepTools.hxx>
67 #include <BRep_Builder.hxx>
68 #include <BRep_Tool.hxx>
69 #include <GProp_GProps.hxx>
70 #include <Geom2d_Curve.hxx>
71 #include <GeomAPI_ProjectPointOnCurve.hxx>
72 #include <GeomAPI_ProjectPointOnSurf.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Surface.hxx>
75 #include <NCollection_Map.hxx>
76 #include <Standard_ErrorHandler.hxx>
77 #include <TopExp.hxx>
78 #include <TopExp_Explorer.hxx>
79 #include <TopTools_DataMapOfShapeInteger.hxx>
80 #include <TopTools_IndexedMapOfShape.hxx>
81 #include <TopTools_MapOfShape.hxx>
82 #include <TopoDS.hxx>
83 #include <TopoDS_Compound.hxx>
84 #include <TopoDS_Edge.hxx>
85 #include <TopoDS_Face.hxx>
86 #include <TopoDS_Shape.hxx>
87 #include <TopoDS_Vertex.hxx>
88 #include <TopoDS_Wire.hxx>
89 #include <gp_Pnt.hxx>
90 #include <gp_Pnt2d.hxx>
91 #include <gp_XY.hxx>
92 #include <gp_XYZ.hxx>
93
94 #ifndef WNT
95 #include <fenv.h>
96 #endif
97
98 /* ==================================
99  * ===========  PYTHON ==============
100  * ==================================*/
101
102 typedef struct {
103   PyObject_HEAD
104   int softspace;
105   std::string *out;
106   } PyStdOut;
107
108 static void
109 PyStdOut_dealloc(PyStdOut *self)
110 {
111   PyObject_Del(self);
112 }
113
114 static PyObject *
115 PyStdOut_write(PyStdOut *self, PyObject *args)
116 {
117   char *c;
118   int l;
119   if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
120     return NULL;
121
122   //std::cerr << c ;
123   *(self->out)=*(self->out)+c;
124
125   Py_INCREF(Py_None);
126   return Py_None;
127 }
128
129 static PyMethodDef PyStdOut_methods[] = {
130   {"write",  (PyCFunction)PyStdOut_write,  METH_VARARGS,
131     PyDoc_STR("write(string) -> None")},
132   {NULL,    NULL}   /* sentinel */
133 };
134
135 static PyMemberDef PyStdOut_memberlist[] = {
136   {(char*)"softspace", T_INT,  offsetof(PyStdOut, softspace), 0,
137    (char*)"flag indicating that a space needs to be printed; used by print"},
138   {NULL} /* Sentinel */
139 };
140
141 static PyTypeObject PyStdOut_Type = {
142   /* The ob_type field must be initialized in the module init function
143    * to be portable to Windows without using C++. */
144   PyObject_HEAD_INIT(NULL)
145   0,                            /*ob_size*/
146   "PyOut",                      /*tp_name*/
147   sizeof(PyStdOut),             /*tp_basicsize*/
148   0,                            /*tp_itemsize*/
149   /* methods */
150   (destructor)PyStdOut_dealloc, /*tp_dealloc*/
151   0,                            /*tp_print*/
152   0,                            /*tp_getattr*/
153   0,                            /*tp_setattr*/
154   0,                            /*tp_compare*/
155   0,                            /*tp_repr*/
156   0,                            /*tp_as_number*/
157   0,                            /*tp_as_sequence*/
158   0,                            /*tp_as_mapping*/
159   0,                            /*tp_hash*/
160   0,                            /*tp_call*/
161   0,                            /*tp_str*/
162   PyObject_GenericGetAttr,      /*tp_getattro*/
163   /* softspace is writable:  we must supply tp_setattro */
164   PyObject_GenericSetAttr,      /* tp_setattro */
165   0,                            /*tp_as_buffer*/
166   Py_TPFLAGS_DEFAULT,           /*tp_flags*/
167   0,                            /*tp_doc*/
168   0,                            /*tp_traverse*/
169   0,                            /*tp_clear*/
170   0,                            /*tp_richcompare*/
171   0,                            /*tp_weaklistoffset*/
172   0,                            /*tp_iter*/
173   0,                            /*tp_iternext*/
174   PyStdOut_methods,             /*tp_methods*/
175   PyStdOut_memberlist,          /*tp_members*/
176   0,                            /*tp_getset*/
177   0,                            /*tp_base*/
178   0,                            /*tp_dict*/
179   0,                            /*tp_descr_get*/
180   0,                            /*tp_descr_set*/
181   0,                            /*tp_dictoffset*/
182   0,                            /*tp_init*/
183   0,                            /*tp_alloc*/
184   0,                            /*tp_new*/
185   0,                            /*tp_free*/
186   0,                            /*tp_is_gc*/
187 };
188
189 PyObject * newPyStdOut( std::string& out )
190 {
191   PyStdOut *self;
192   self = PyObject_New(PyStdOut, &PyStdOut_Type);
193   if (self == NULL)
194     return NULL;
195   self->softspace = 0;
196   self->out=&out;
197   return (PyObject*)self;
198 }
199
200
201 ////////////////////////END PYTHON///////////////////////////
202
203 //////////////////MY MAPS////////////////////////////////////////
204 TopTools_IndexedMapOfShape FacesWithSizeMap;
205 std::map<int,string> FaceId2SizeMap;
206 TopTools_IndexedMapOfShape EdgesWithSizeMap;
207 std::map<int,string> EdgeId2SizeMap;
208 TopTools_IndexedMapOfShape VerticesWithSizeMap;
209 std::map<int,string> VertexId2SizeMap;
210
211 std::map<int,PyObject*> FaceId2PythonSmp;
212 std::map<int,PyObject*> EdgeId2PythonSmp;
213 std::map<int,PyObject*> VertexId2PythonSmp;
214
215 std::map<int,std::vector<double> > FaceId2AttractorCoords;
216 std::map<int,BLSURFPlugin_Attractor*> FaceId2ClassAttractor;
217 std::map<int,BLSURFPlugin_Attractor*> FaceIndex2ClassAttractor;
218
219 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
220 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
221 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
222 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
223
224 bool HasSizeMapOnFace=false;
225 bool HasSizeMapOnEdge=false;
226 bool HasSizeMapOnVertex=false;
227 //bool HasAttractorOnFace=false;
228
229 //=============================================================================
230 /*!
231  *
232  */
233 //=============================================================================
234
235 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
236                                                SMESH_Gen* gen)
237   : SMESH_2D_Algo(hypId, studyId, gen)
238 {
239   MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
240
241   _name = "BLSURF";
242   _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
243   _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
244   _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
245   _requireDiscreteBoundary = false;
246   _onlyUnaryInput = false;
247   _hypothesis = NULL;
248   _supportSubmeshes = true;
249
250   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
251   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
252   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
253
254   MESSAGE("studyid = " << _studyId);
255
256   myStudy = NULL;
257   myStudy = aStudyMgr->GetStudyByID(_studyId);
258   if (myStudy)
259     MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
260
261   /* Initialize the Python interpreter */
262   assert(Py_IsInitialized());
263   PyGILState_STATE gstate;
264   gstate = PyGILState_Ensure();
265
266   main_mod = NULL;
267   main_mod = PyImport_AddModule("__main__");
268
269   main_dict = NULL;
270   main_dict = PyModule_GetDict(main_mod);
271
272   PyRun_SimpleString("from math import *");
273   PyGILState_Release(gstate);
274
275   FacesWithSizeMap.Clear();
276   FaceId2SizeMap.clear();
277   EdgesWithSizeMap.Clear();
278   EdgeId2SizeMap.clear();
279   VerticesWithSizeMap.Clear();
280   VertexId2SizeMap.clear();
281   FaceId2PythonSmp.clear();
282   EdgeId2PythonSmp.clear();
283   VertexId2PythonSmp.clear();
284   FaceId2AttractorCoords.clear();
285   FaceId2ClassAttractor.clear();
286   FaceIndex2ClassAttractor.clear();
287   FacesWithEnforcedVertices.Clear();
288   FaceId2EnforcedVertexCoords.clear();
289   EnfVertexCoords2ProjVertex.clear();
290   EnfVertexCoords2EnfVertexList.clear();
291
292 #ifdef WITH_SMESH_CANCEL_COMPUTE
293   _compute_canceled = false;
294 #endif
295 }
296
297 //=============================================================================
298 /*!
299  *
300  */
301 //=============================================================================
302
303 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
304 {
305   MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
306 }
307
308
309 //=============================================================================
310 /*!
311  *
312  */
313 //=============================================================================
314
315 bool BLSURFPlugin_BLSURF::CheckHypothesis
316                          (SMESH_Mesh&                          aMesh,
317                           const TopoDS_Shape&                  aShape,
318                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
319 {
320   _hypothesis        = NULL;
321   _haveViscousLayers = false;
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                                                                   /*ignoreAuxiliary=*/false);
328   aStatus = SMESH_Hypothesis::HYP_OK;
329   if ( hyps.empty() )
330   {
331     return true;  // can work with no hypothesis
332   }
333
334   for ( itl = hyps.begin(); itl != hyps.end(); ++itl )
335   {
336     theHyp = *itl;
337     string hypName = theHyp->GetName();
338     if ( hypName == BLSURFPlugin_Hypothesis::GetHypType() )
339     {
340       _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
341       ASSERT(_hypothesis);
342       if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
343            _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
344         //  hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
345         aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
346     }
347     else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
348     {
349       _haveViscousLayers = true;
350     }
351     else
352     {
353       aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
354     }
355   }
356   return aStatus == SMESH_Hypothesis::HYP_OK;
357 }
358
359 //=============================================================================
360 /*!
361  * Pass parameters to BLSURF
362  */
363 //=============================================================================
364
365 inline std::string to_string(double d)
366 {
367    std::ostringstream o;
368    o << d;
369    return o.str();
370 }
371
372 inline std::string to_string_rel(double d)
373 {
374    std::ostringstream o;
375    o << d;
376    o << 'r';
377    return o.str();
378 }
379
380 inline std::string to_string(int i)
381 {
382    std::ostringstream o;
383    o << i;
384    return o.str();
385 }
386
387 inline std::string to_string_rel(int i)
388 {
389    std::ostringstream o;
390    o << i;
391    o << 'r';
392    return o.str();
393 }
394
395 double _smp_phy_size;
396 // #if BLSURF_VERSION_LONG >= "3.1.1"
397 // //   sizemap_t *geo_sizemap_e, *geo_sizemap_f;
398 //   sizemap_t *iso_sizemap_p, *iso_sizemap_e, *iso_sizemap_f;
399 // //   sizemap_t *clean_geo_sizemap_e, *clean_geo_sizemap_f;
400 //   sizemap_t *clean_iso_sizemap_p, *clean_iso_sizemap_e, *clean_iso_sizemap_f;
401 // #endif
402 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
403 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
404 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
405
406 typedef struct {
407         gp_XY uv;
408         gp_XYZ xyz;
409 } projectionPoint;
410 /////////////////////////////////////////////////////////
411 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_Pnt& point)
412 {
413   projectionPoint myPoint;
414   Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
415   GeomAPI_ProjectPointOnSurf projector( point, surface );
416   if ( !projector.IsDone() || projector.NbPoints()==0 )
417     throw "getProjectionPoint: Can't project";
418
419   Quantity_Parameter u,v;
420   projector.LowerDistanceParameters(u,v);
421   myPoint.uv = gp_XY(u,v);
422   gp_Pnt aPnt = projector.NearestPoint();
423   myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
424   //return gp_XY(u,v);
425   return myPoint;
426 }
427 /////////////////////////////////////////////////////////
428
429 /////////////////////////////////////////////////////////
430 double getT(const TopoDS_Edge& edge, const gp_Pnt& point)
431 {
432   Standard_Real f,l;
433   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
434   GeomAPI_ProjectPointOnCurve projector( point, curve);
435   if ( projector.NbPoints() == 0 )
436     throw;
437   return projector.LowerDistanceParameter();
438 }
439
440 /////////////////////////////////////////////////////////
441 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
442 {
443   MESSAGE("BLSURFPlugin_BLSURF::entryToShape "<<entry );
444   GEOM::GEOM_Object_var aGeomObj;
445   TopoDS_Shape S = TopoDS_Shape();
446   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
447   if (!aSObj->_is_nil()) {
448     CORBA::Object_var obj = aSObj->GetObject();
449     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
450     aSObj->UnRegister();
451   }
452   if ( !aGeomObj->_is_nil() )
453     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
454   return S;
455 }
456
457 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
458 {
459   BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
460   enf_coords.clear();
461   coords.clear();
462   s_coords.clear();
463
464   // Get the (u,v) values of the enforced vertex on the face
465   projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
466
467   MESSAGE("Enforced Vertex: " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z());
468   MESSAGE("Projected Vertex: " << myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z());
469   MESSAGE("Parametric coordinates: " << myPoint.uv.X() << ", " << myPoint.uv.Y() );
470
471   enf_coords.push_back(aPnt.X());
472   enf_coords.push_back(aPnt.Y());
473   enf_coords.push_back(aPnt.Z());
474
475   coords.push_back(myPoint.uv.X());
476   coords.push_back(myPoint.uv.Y());
477   coords.push_back(myPoint.xyz.X());
478   coords.push_back(myPoint.xyz.Y());
479   coords.push_back(myPoint.xyz.Z());
480
481   s_coords.push_back(myPoint.xyz.X());
482   s_coords.push_back(myPoint.xyz.Y());
483   s_coords.push_back(myPoint.xyz.Z());
484
485   // Save pair projected vertex / enf vertex
486   MESSAGE("Storing pair projected vertex / enf vertex:");
487   MESSAGE("("<< myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z() <<") / (" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z()<<")");
488   EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
489   MESSAGE("Group name is: \"" << enfVertex->grpName << "\"");
490   pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
491   BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
492   ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
493   if (ret.second == false) {
494     it = ret.first;
495     (*it)->grpName = enfVertex->grpName;
496   }
497
498   int key = 0;
499   if (! FacesWithEnforcedVertices.Contains(faceShape)) {
500     key = FacesWithEnforcedVertices.Add(faceShape);
501   }
502   else {
503     key = FacesWithEnforcedVertices.FindIndex(faceShape);
504   }
505
506   // If a node is already created by an attractor, do not create enforced vertex
507   int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
508   bool sameAttractor = false;
509   if (attractorKey >= 0)
510     if (FaceId2AttractorCoords.count(attractorKey) > 0)
511       if (FaceId2AttractorCoords[attractorKey] == coords)
512         sameAttractor = true;
513
514   if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
515     MESSAGE("Map of enf. vertex has key " << key)
516     MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
517     if (! sameAttractor)
518       FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
519     else
520       MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
521     MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
522   }
523   else {
524     MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
525     if (! sameAttractor) {
526       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
527       ens.insert(coords);
528       FaceId2EnforcedVertexCoords[key] = ens;
529     }
530     else
531       MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
532   }
533 }
534
535 /////////////////////////////////////////////////////////
536 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
537 {
538   BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
539   gp_Pnt aPnt;
540
541   BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
542
543   for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
544     enfVertex = *enfVertexListIt;
545     // Case of manual coords
546     if (enfVertex->coords.size() != 0) {
547       aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
548       _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
549     }
550
551     // Case of geom vertex coords
552     if (enfVertex->geomEntry != "") {
553       TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
554       TopAbs_ShapeEnum GeomType  = GeomShape.ShapeType();
555        if (GeomType == TopAbs_VERTEX){
556          aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
557          _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
558        }
559        // Group Management
560        if (GeomType == TopAbs_COMPOUND){
561          for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
562            if (it.Value().ShapeType() == TopAbs_VERTEX){
563              aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
564              _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
565            }
566          }
567        }
568     }
569   }
570 }
571
572 /////////////////////////////////////////////////////////
573 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction, double defaultSize)
574 {
575   MESSAGE("Attractor function: "<< AttractorFunction);
576   double xa, ya, za; // Coordinates of attractor point
577   double a, b;       // Attractor parameter
578   double d = 0.;
579   bool createNode=false; // To create a node on attractor projection
580   int pos1, pos2;
581   const char *sep = ";";
582   // atIt->second has the following pattern:
583   // ATTRACTOR(xa;ya;za;a;b;True|False;d)
584   // where:
585   // xa;ya;za : coordinates of  attractor
586   // a        : desired size on attractor
587   // b        : distance of influence of attractor
588   // d        : distance until which the size remains constant
589   //
590   // We search the parameters in the string
591   // xa
592   pos1 = AttractorFunction.find(sep);
593   if (pos1!=string::npos)
594   xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
595   // ya
596   pos2 = AttractorFunction.find(sep, pos1+1);
597   if (pos2!=string::npos) {
598   ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
599   pos1 = pos2;
600   }
601   // za
602   pos2 = AttractorFunction.find(sep, pos1+1);
603   if (pos2!=string::npos) {
604   za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
605   pos1 = pos2;
606   }
607   // a
608   pos2 = AttractorFunction.find(sep, pos1+1);
609   if (pos2!=string::npos) {
610   a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
611   pos1 = pos2;
612   }
613   // b
614   pos2 = AttractorFunction.find(sep, pos1+1);
615   if (pos2!=string::npos) {
616   b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
617   pos1 = pos2;
618   }
619   // createNode
620   pos2 = AttractorFunction.find(sep, pos1+1);
621   if (pos2!=string::npos) {
622     string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
623     MESSAGE("createNode: " << createNodeStr);
624     createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
625     pos1=pos2;
626   }
627   // d
628   pos2 = AttractorFunction.find(")");
629   if (pos2!=string::npos) {
630   d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
631   }
632
633   // Get the (u,v) values of the attractor on the face
634   projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
635   gp_XY uvPoint = myPoint.uv;
636   gp_XYZ xyzPoint = myPoint.xyz;
637   Standard_Real u0 = uvPoint.X();
638   Standard_Real v0 = uvPoint.Y();
639   Standard_Real x0 = xyzPoint.X();
640   Standard_Real y0 = xyzPoint.Y();
641   Standard_Real z0 = xyzPoint.Z();
642   std::vector<double> coords;
643   coords.push_back(u0);
644   coords.push_back(v0);
645   coords.push_back(x0);
646   coords.push_back(y0);
647   coords.push_back(z0);
648   // We construct the python function
649   ostringstream attractorFunctionStream;
650   attractorFunctionStream << "def f(u,v): return ";
651   attractorFunctionStream << defaultSize << "-(" << defaultSize <<"-" << a << ")";
652   //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
653   // rnc: make possible to keep the size constant until
654   // a defined distance. Distance is expressed as the positiv part
655   // of r-d where r is the distance to (u0,v0)
656   attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
657
658   MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
659
660   int key;
661   if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
662     key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
663   }
664   else {
665     key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
666   }
667   FaceId2SizeMap[key] =attractorFunctionStream.str();
668   if (createNode) {
669     MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
670     FaceId2AttractorCoords[key] = coords;
671   }
672 //   // Test for new attractors
673 //   gp_Pnt myP(xyzPoint);
674 //   TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
675 //   BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
676 //   myAttractor.SetParameters(a, defaultSize, b, d);
677 //   myAttractor.SetType(1);
678 //   FaceId2ClassAttractor[key] = myAttractor;
679 //   if(FaceId2ClassAttractor[key].GetFace().IsNull()){
680 //     MESSAGE("face nulle ");
681 //   }
682 //   else
683 //     MESSAGE("face OK");
684 //
685 //   if (FaceId2ClassAttractor[key].GetAttractorShape().IsNull()){
686 //     MESSAGE("pas de point");
687 //   }
688 //   else
689 //     MESSAGE("point OK");
690 }
691
692 /////////////////////////////////////////////////////////
693
694 void BLSURFPlugin_BLSURF::SetParameters(
695 // #if BLSURF_VERSION_LONG >= "3.1.1"
696 //                                         cad_t *                          c,
697 // #endif
698                                         const BLSURFPlugin_Hypothesis* hyp,
699                                         cadsurf_session_t *            css,
700                                         precad_session_t *             pcs,
701                                         const TopoDS_Shape&            theGeomShape,
702                                         bool *                  use_precad
703                                        )
704 {
705   // rnc : Bug 1457
706   // Clear map so that it is not stored in the algorithm with old enforced vertices in it
707   EnfVertexCoords2EnfVertexList.clear();
708   
709    double diagonal               = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
710    double bbSegmentation         = _gen->GetBoundaryBoxSegmentation();
711    int    _physicalMesh          = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
712    int    _geometricMesh         = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
713    double _phySize               = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
714    bool   _phySizeRel            = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
715    double _minSize               = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
716    bool   _minSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
717    double _maxSize               = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
718    bool   _maxSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
719    double _gradation             = BLSURFPlugin_Hypothesis::GetDefaultGradation();
720    bool   _quadAllowed           = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
721    double _angleMesh             = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
722    double _chordalError          = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
723    bool   _anisotropic           = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
724    double _anisotropicRatio      = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
725    bool   _removeTinyEdges       = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
726    double _tinyEdgeLength        = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
727    bool   _badElementRemoval     = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
728    double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
729    bool   _optimizeMesh          = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
730    bool   _quadraticMesh         = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
731    int    _verb                  = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
732    int    _topology              = BLSURFPlugin_Hypothesis::GetDefaultTopology();
733
734   // PreCAD
735    int _precadMergeEdges         = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
736    int _precadProcess3DTopology  = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
737    int _precadDiscardInput       = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
738
739
740   if (hyp) {
741     MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
742     _physicalMesh  = (int) hyp->GetPhysicalMesh();
743     _geometricMesh = (int) hyp->GetGeometricMesh();
744     if (hyp->GetPhySize() > 0) {
745       _phySize       = hyp->GetPhySize();
746       // if user size is not explicitly specified, "relative" flag is ignored
747       _phySizeRel    = hyp->IsPhySizeRel();
748     }
749     if (hyp->GetMinSize() > 0) {
750       _minSize       = hyp->GetMinSize();
751       // if min size is not explicitly specified, "relative" flag is ignored
752       _minSizeRel    = hyp->IsMinSizeRel();
753     }
754     if (hyp->GetMaxSize() > 0) {
755       _maxSize       = hyp->GetMaxSize();
756       // if max size is not explicitly specified, "relative" flag is ignored
757       _maxSizeRel    = hyp->IsMaxSizeRel();
758     }
759     if (hyp->GetGradation() > 0)
760       _gradation     = hyp->GetGradation();
761     _quadAllowed   = hyp->GetQuadAllowed();
762      if (hyp->GetAngleMesh() > 0)
763      _angleMesh     = hyp->GetAngleMesh();
764      if (hyp->GetChordalError() > 0)
765        _chordalError           = hyp->GetChordalError();
766      _anisotropic            = hyp->GetAnisotropic();
767      if (hyp->GetAnisotropicRatio() >= 0)
768        _anisotropicRatio       = hyp->GetAnisotropicRatio();
769      _removeTinyEdges        = hyp->GetRemoveTinyEdges();
770      if (hyp->GetTinyEdgeLength() > 0)
771        _tinyEdgeLength         = hyp->GetTinyEdgeLength();
772      _badElementRemoval      = hyp->GetBadElementRemoval();
773      if (hyp->GetBadElementAspectRatio() >= 0)
774        _badElementAspectRatio  = hyp->GetBadElementAspectRatio();
775      _optimizeMesh  = hyp->GetOptimizeMesh();
776      _quadraticMesh = hyp->GetQuadraticMesh();
777     _verb          = hyp->GetVerbosity();
778      _topology      = (int) hyp->GetTopology();
779      // PreCAD
780      _precadMergeEdges = hyp->GetPreCADMergeEdges();
781      _precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
782      _precadDiscardInput = hyp->GetPreCADDiscardInput();
783
784     const BLSURFPlugin_Hypothesis::TOptionValues & opts = hyp->GetOptionValues();
785     BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
786     for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
787       if ( !opIt->second.empty() ) {
788         MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
789         set_param(css, opIt->first.c_str(), opIt->second.c_str());
790       }
791       
792     const BLSURFPlugin_Hypothesis::TOptionValues & preCADopts = hyp->GetPreCADOptionValues();
793     for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
794       if ( !opIt->second.empty() ) {
795         if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
796           MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
797           precad_set_param(pcs, opIt->first.c_str(), opIt->second.c_str());
798         }
799       }
800   }
801 //   else {
802 //     //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
803 //     // GetDefaultPhySize() sometimes leads to computation failure
804 //     // GDD 26/07/2012 From Distene documentation, global physical size default value = diag/100
805 //     _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal);
806 //     _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
807 //     _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
808 //     _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
809 //     _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
810 //     MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
811 //   }
812
813   // PreCAD
814   if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
815     *use_precad = true;
816     precad_set_param(pcs, "verbose",                to_string(_verb).c_str());
817     precad_set_param(pcs, "merge_edges",            _precadMergeEdges ? "1" : "0");
818     precad_set_param(pcs, "process_3d_topology",    _precadProcess3DTopology ? "1" : "0");
819     precad_set_param(pcs, "discard_input_topology", _precadDiscardInput ? "1" : "0");
820   }
821   
822    bool useGradation = false;
823    switch (_physicalMesh)
824    {
825      case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
826        set_param(css, "physical_size_mode", "global");
827        set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
828        break;
829      case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
830        set_param(css, "physical_size_mode", "local");
831        set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
832        useGradation = true;
833        break;
834      default:
835        set_param(css, "physical_size_mode", "none");
836    }
837
838    switch (_geometricMesh)
839    {
840      case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
841        set_param(css, "geometric_size_mode", "global");
842        set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
843        set_param(css, "chordal_error", to_string(_chordalError).c_str());
844        useGradation = true;
845        break;
846      case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
847        set_param(css, "geometric_size_mode", "local");
848        set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
849        set_param(css, "chordal_error", to_string(_chordalError).c_str());
850        useGradation = true;
851        break;
852      default:
853        set_param(css, "geometric_size_mode", "none");
854    }
855
856    if ( hyp && hyp->GetPhySize() > 0 ) {
857      // user size is explicitly specified via hypothesis parameters
858      // min and max sizes should be compared with explicitly specified user size
859      // - compute absolute min size
860      double mins = _minSizeRel ? _minSize * diagonal : _minSize;
861      // - min size should not be greater than user size
862      if ( _phySize < mins )
863        set_param(css, "min_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
864      else
865        set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
866      // - compute absolute max size
867      double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
868      // - max size should not be less than user size
869      if ( _phySize > maxs )
870        set_param(css, "max_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
871      else
872        set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
873    }
874    else {
875      // user size is not explicitly specified
876      // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
877      set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
878      // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
879      set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
880    }
881   
882   if ( useGradation )
883      set_param(css, "gradation",                         to_string(_gradation).c_str());
884    set_param(css, "element_generation",                _quadAllowed ? "quad_dominant" : "triangle");
885
886
887    set_param(css, "metric",                            _anisotropic ? "anisotropic" : "isotropic");
888    if ( _anisotropic )
889      set_param(css, "anisotropic_ratio",                 to_string(_anisotropicRatio).c_str());
890    set_param(css, "remove_tiny_edges",                 _removeTinyEdges ? "1" : "0");
891    if ( _removeTinyEdges )
892      set_param(css, "tiny_edge_length",                  to_string(_tinyEdgeLength).c_str());
893    set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
894    if ( _badElementRemoval )
895      set_param(css, "bad_surface_element_aspect_ratio",  to_string(_badElementAspectRatio).c_str());
896    set_param(css, "optimisation",                      _optimizeMesh ? "yes" : "no");
897    set_param(css, "element_order",                     _quadraticMesh ? "quadratic" : "linear");
898    set_param(css, "verbose",                           to_string(_verb).c_str());
899
900    _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
901    if ( _verb > 0 )
902      std::cout << "_smp_phy_size = " << _smp_phy_size << std::endl;
903
904    if (_physicalMesh == BLSURFPlugin_Hypothesis::PhysicalLocalSize){
905     TopoDS_Shape GeomShape;
906     TopoDS_Shape AttShape;
907     TopAbs_ShapeEnum GeomType;
908     //
909     // Standard Size Maps
910     //
911     MESSAGE("Setting a Size Map");
912     const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
913     BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
914     for ( ; smIt != sizeMaps.end(); ++smIt ) {
915       if ( !smIt->second.empty() ) {
916         MESSAGE("cadsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
917         GeomShape = entryToShape(smIt->first);
918         GeomType  = GeomShape.ShapeType();
919         MESSAGE("Geomtype is " << GeomType);
920         int key = -1;
921         // Group Management
922         if (GeomType == TopAbs_COMPOUND){
923           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
924             // Group of faces
925             if (it.Value().ShapeType() == TopAbs_FACE){
926               HasSizeMapOnFace = true;
927               if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
928                 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
929               }
930               else {
931                 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
932 //                 MESSAGE("Face with key " << key << " already in map");
933               }
934               FaceId2SizeMap[key] = smIt->second;
935             }
936             // Group of edges
937             if (it.Value().ShapeType() == TopAbs_EDGE){
938               HasSizeMapOnEdge = true;
939               HasSizeMapOnFace = true;
940               if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
941                 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
942               }
943               else {
944                 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
945 //                 MESSAGE("Edge with key " << key << " already in map");
946               }
947               EdgeId2SizeMap[key] = smIt->second;
948             }
949             // Group of vertices
950             if (it.Value().ShapeType() == TopAbs_VERTEX){
951               HasSizeMapOnVertex = true;
952               HasSizeMapOnEdge = true;
953               HasSizeMapOnFace = true;
954               if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
955                 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
956               }
957               else {
958                 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
959                 MESSAGE("Group of vertices with key " << key << " already in map");
960               }
961               MESSAGE("Group of vertices with key " << key << " has a size map: " << smIt->second);
962               VertexId2SizeMap[key] = smIt->second;
963             }
964           }
965         }
966         // Single face
967         if (GeomType == TopAbs_FACE){
968           HasSizeMapOnFace = true;
969           if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
970             key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
971           }
972           else {
973             key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
974 //             MESSAGE("Face with key " << key << " already in map");
975           }
976           FaceId2SizeMap[key] = smIt->second;
977         }
978         // Single edge
979         if (GeomType == TopAbs_EDGE){
980           HasSizeMapOnEdge = true;
981           HasSizeMapOnFace = true;
982           if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
983             key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
984           }
985           else {
986             key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
987 //             MESSAGE("Edge with key " << key << " already in map");
988           }
989           EdgeId2SizeMap[key] = smIt->second;
990         }
991         // Single vertex
992         if (GeomType == TopAbs_VERTEX){
993           HasSizeMapOnVertex = true;
994           HasSizeMapOnEdge   = true;
995           HasSizeMapOnFace   = true;
996           if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
997             key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
998           }
999           else {
1000             key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
1001              MESSAGE("Vertex with key " << key << " already in map");
1002           }
1003           MESSAGE("Vertex with key " << key << " has a size map: " << smIt->second);
1004           VertexId2SizeMap[key] = smIt->second;
1005         }
1006       }
1007     }
1008
1009     //
1010     // Attractors
1011     //
1012     // TODO appeler le constructeur des attracteurs directement ici
1013     MESSAGE("Setting Attractors");
1014 //     if ( !_phySizeRel ) {
1015       const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
1016       BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
1017       for ( ; atIt != attractors.end(); ++atIt ) {
1018         if ( !atIt->second.empty() ) {
1019           MESSAGE("cadsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
1020           GeomShape = entryToShape(atIt->first);
1021           GeomType  = GeomShape.ShapeType();
1022           // Group Management
1023           if (GeomType == TopAbs_COMPOUND){
1024             for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1025               if (it.Value().ShapeType() == TopAbs_FACE){
1026                 HasSizeMapOnFace = true;
1027                 createAttractorOnFace(it.Value(), atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1028               }
1029             }
1030           }
1031
1032           if (GeomType == TopAbs_FACE){
1033             HasSizeMapOnFace = true;
1034             createAttractorOnFace(GeomShape, atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1035           }
1036   /*
1037           if (GeomType == TopAbs_EDGE){
1038             HasSizeMapOnEdge = true;
1039             HasSizeMapOnFace = true;
1040           EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
1041           }
1042           if (GeomType == TopAbs_VERTEX){
1043             HasSizeMapOnVertex = true;
1044             HasSizeMapOnEdge   = true;
1045             HasSizeMapOnFace   = true;
1046           VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
1047           }
1048   */
1049         }
1050       }
1051 //     }
1052 //     else
1053 //       MESSAGE("Impossible to create the attractors when the physical size is relative");
1054
1055     // Class Attractors
1056     // temporary commented out for testing
1057     // TODO
1058     //  - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
1059     //  - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
1060     //  - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
1061     //  OR, even better:
1062     //  - Construct the attractors with an empty dist. map in the hypothesis
1063     //  - 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()
1064     //  -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap()  OK
1065
1066     const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
1067     int key=-1;
1068     BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
1069     for ( ; AtIt != class_attractors.end(); ++AtIt ) {
1070       if ( !AtIt->second->Empty() ) {
1071        // MESSAGE("cadsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
1072         GeomShape = entryToShape(AtIt->first);
1073         AttShape = AtIt->second->GetAttractorShape();
1074         GeomType  = GeomShape.ShapeType();
1075         // Group Management
1076 //         if (GeomType == TopAbs_COMPOUND){
1077 //           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1078 //             if (it.Value().ShapeType() == TopAbs_FACE){
1079 //               HasAttractorOnFace = true;
1080 //               myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
1081 //             }
1082 //           }
1083 //         }
1084
1085         if (GeomType == TopAbs_FACE
1086           && (AttShape.ShapeType() == TopAbs_VERTEX
1087            || AttShape.ShapeType() == TopAbs_EDGE
1088            || AttShape.ShapeType() == TopAbs_WIRE
1089            || AttShape.ShapeType() == TopAbs_COMPOUND) ){
1090             HasSizeMapOnFace = true;
1091
1092             if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape)) ) {
1093                 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
1094             }
1095             else {
1096               key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1097 //                 MESSAGE("Face with key " << key << " already in map");
1098             }
1099
1100             FaceId2ClassAttractor[key] = AtIt->second;
1101         }
1102         else{
1103           MESSAGE("Wrong shape type !!")
1104         }
1105
1106       }
1107     }
1108
1109
1110     //
1111     // Enforced Vertices
1112     //
1113     MESSAGE("Setting Enforced Vertices");
1114     const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
1115     BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
1116     for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
1117       if ( !enfIt->second.empty() ) {
1118         GeomShape = entryToShape(enfIt->first);
1119         GeomType  = GeomShape.ShapeType();
1120         // Group Management
1121         if (GeomType == TopAbs_COMPOUND){
1122           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1123             if (it.Value().ShapeType() == TopAbs_FACE){
1124               HasSizeMapOnFace = true;
1125               createEnforcedVertexOnFace(it.Value(), enfIt->second);
1126             }
1127           }
1128         }
1129
1130         if (GeomType == TopAbs_FACE){
1131           HasSizeMapOnFace = true;
1132           createEnforcedVertexOnFace(GeomShape, enfIt->second);
1133         }
1134       }
1135     }
1136
1137     // Internal vertices
1138     bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1139     if (useInternalVertexAllFaces) {
1140       std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1141       MESSAGE("Setting Internal Enforced Vertices");
1142       gp_Pnt aPnt;
1143       TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
1144       for (; exp.More(); exp.Next()){
1145         MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
1146         TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
1147         for (; exp_face.More(); exp_face.Next())
1148         {
1149           // Get coords of vertex
1150           // Check if current coords is already in enfVertexList
1151           // If coords not in enfVertexList, add new enfVertex
1152           aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1153           MESSAGE("Found vertex on face at " << aPnt.X() <<", "<<aPnt.Y()<<", "<<aPnt.Z());
1154           BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1155           enfVertex->coords.push_back(aPnt.X());
1156           enfVertex->coords.push_back(aPnt.Y());
1157           enfVertex->coords.push_back(aPnt.Z());
1158           enfVertex->name = "";
1159           enfVertex->faceEntries.clear();
1160           enfVertex->geomEntry = "";
1161           enfVertex->grpName = grpName;
1162           enfVertex->vertex = TopoDS::Vertex( exp_face.Current() );
1163           _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()),  aPnt, enfVertex);
1164           HasSizeMapOnFace = true;
1165         }
1166       }
1167     }
1168
1169     MESSAGE("Setting Size Map on FACES ");
1170 // #if BLSURF_VERSION_LONG < "3.1.1"
1171     cadsurf_data_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
1172 // #else
1173 //     if (*use_precad)
1174 //       iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1175 //     else
1176 //       clean_iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1177 // #endif
1178
1179     if (HasSizeMapOnEdge){
1180       MESSAGE("Setting Size Map on EDGES ");
1181 // #if BLSURF_VERSION_LONG < "3.1.1"
1182       cadsurf_data_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
1183 // #else
1184 //       if (*use_precad)
1185 //         iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1186 //       else
1187 //         clean_iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1188 // #endif
1189     }
1190     if (HasSizeMapOnVertex){
1191       MESSAGE("Setting Size Map on VERTICES ");
1192 // #if BLSURF_VERSION_LONG < "3.1.1"
1193       cadsurf_data_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
1194 // #else
1195 //       if (*use_precad)
1196 //         iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1197 //       else
1198 //         clean_iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1199 // #endif
1200     }
1201   }
1202 }
1203
1204 //================================================================================
1205 /*!
1206  * \brief Throws an exception if a parameter name is wrong
1207  */
1208 //================================================================================
1209
1210 void BLSURFPlugin_BLSURF::set_param(cadsurf_session_t *css,
1211                                     const char *       option_name,
1212                                     const char *       option_value)
1213 {
1214   status_t status = cadsurf_set_param(css, option_name, option_value );
1215   if ( status != MESHGEMS_STATUS_OK )
1216   {
1217     if ( status == MESHGEMS_STATUS_UNKNOWN_PARAMETER ) {
1218       throw SALOME_Exception
1219         ( SMESH_Comment("Invalid name of CADSURF parameter: ") << option_name );
1220     }
1221     else if ( status == MESHGEMS_STATUS_NOLICENSE )
1222       throw SALOME_Exception
1223         ( "No valid license available" );
1224     else
1225       throw SALOME_Exception
1226         ( SMESH_Comment("Unacceptable value of CADSURF parameter '")
1227           << option_name << "': " << option_value);
1228   }
1229 }
1230
1231 namespace
1232 {
1233   // --------------------------------------------------------------------------
1234   /*!
1235    * \brief Class correctly terminating usage of BLSURF library at destruction
1236    */
1237   class BLSURF_Cleaner
1238   {
1239     context_t *       _ctx;
1240     cadsurf_session_t* _css;
1241     cad_t *           _cad;
1242     dcad_t *          _dcad;
1243   public:
1244     BLSURF_Cleaner(context_t *       ctx,
1245                    cadsurf_session_t* css,
1246                    cad_t *           cad,
1247                    dcad_t *          dcad)
1248       : _ctx ( ctx  ),
1249         _css ( css  ),
1250         _cad ( cad  ),
1251         _dcad( dcad )
1252     {
1253     }
1254     ~BLSURF_Cleaner()
1255     {
1256       Clean( /*exceptContext=*/false );
1257     }
1258     void Clean(const bool exceptContext)
1259     {
1260       if ( _css )
1261       {
1262         cadsurf_session_delete(_css); _css = 0;
1263
1264         // #if BLSURF_VERSION_LONG >= "3.1.1"
1265         // //     if(geo_sizemap_e)
1266         // //       distene_sizemap_delete(geo_sizemap_e);
1267         // //     if(geo_sizemap_f)
1268         // //       distene_sizemap_delete(geo_sizemap_f);
1269         //     if(iso_sizemap_p)
1270         //       distene_sizemap_delete(iso_sizemap_p);
1271         //     if(iso_sizemap_e)
1272         //       distene_sizemap_delete(iso_sizemap_e);
1273         //     if(iso_sizemap_f)
1274         //       distene_sizemap_delete(iso_sizemap_f);
1275         // 
1276         // //     if(clean_geo_sizemap_e)
1277         // //       distene_sizemap_delete(clean_geo_sizemap_e);
1278         // //     if(clean_geo_sizemap_f)
1279         // //       distene_sizemap_delete(clean_geo_sizemap_f);
1280         //     if(clean_iso_sizemap_p)
1281         //       distene_sizemap_delete(clean_iso_sizemap_p);
1282         //     if(clean_iso_sizemap_e)
1283         //       distene_sizemap_delete(clean_iso_sizemap_e);
1284         //     if(clean_iso_sizemap_f)
1285         //       distene_sizemap_delete(clean_iso_sizemap_f);
1286         // #endif
1287
1288         cad_delete(_cad); _cad = 0;
1289         dcad_delete(_dcad); _dcad = 0;
1290         if ( !exceptContext )
1291         {
1292           context_delete(_ctx); _ctx = 0;
1293         }
1294       }
1295     }
1296   };
1297
1298   // --------------------------------------------------------------------------
1299   // comparator to sort nodes and sub-meshes
1300   struct ShapeTypeCompare
1301   {
1302     // sort nodes by position in the following order:
1303     // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
1304     int operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
1305     {
1306       SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
1307       SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
1308       if ( pos1 == pos2 ) return 0;
1309       if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
1310       return -1;
1311     }
1312     // sort sub-meshes in order: EDGE, VERTEX
1313     bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
1314     {
1315       int isVertex1 = ( s1 && s1->NbElements() == 0 );
1316       int isVertex2 = ( s2 && s2->NbElements() == 0 );
1317       if ( isVertex1 == isVertex2 )
1318         return s1 < s2;
1319       return isVertex1 < isVertex2;
1320     }
1321   };
1322
1323   //================================================================================
1324   /*!
1325    * \brief Fills groups on nodes to be merged
1326    */
1327   //================================================================================
1328
1329   void getNodeGroupsToMerge( const SMESHDS_SubMesh*                smDS,
1330                              const TopoDS_Shape&                   shape,
1331                              SMESH_MeshEditor::TListOfListOfNodes& nodeGroupsToMerge)
1332   {
1333     SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1334     switch ( shape.ShapeType() )
1335     {
1336     case TopAbs_VERTEX: {
1337       std::list< const SMDS_MeshNode* > nodes;
1338       while ( nIt->more() )
1339         nodes.push_back( nIt->next() );
1340       if ( nodes.size() > 1 )
1341         nodeGroupsToMerge.push_back( nodes );
1342       break;
1343     }
1344     case TopAbs_EDGE: {
1345       std::multimap< double, const SMDS_MeshNode* > u2node;
1346       const SMDS_EdgePosition* ePos;
1347       while ( nIt->more() )
1348       {
1349         const SMDS_MeshNode* n = nIt->next();
1350         if (( ePos = dynamic_cast< const SMDS_EdgePosition* >( n->GetPosition() )))
1351           u2node.insert( make_pair( ePos->GetUParameter(), n ));
1352       }
1353       if ( u2node.size() < 2 ) return;
1354
1355       double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
1356       std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
1357       for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
1358       {
1359         if (( un2->first - un1->first ) <= tol )
1360         {
1361           std::list< const SMDS_MeshNode* > nodes;
1362           nodes.push_back( un1->second );
1363           while (( un2->first - un1->first ) <= tol )
1364           {
1365             nodes.push_back( un2->second );
1366             if ( ++un2 == u2node.end()) {
1367               --un2;
1368               break;
1369             }
1370           }
1371           // make nodes created on the boundary of viscous layer replace nodes created
1372           // by BLSURF as their SMDS_Position is more correct
1373           nodes.sort( ShapeTypeCompare() );
1374           nodeGroupsToMerge.push_back( nodes );
1375         }
1376       }
1377       break;
1378     }
1379     default: ;
1380     }
1381     // SMESH_MeshEditor::TListOfListOfNodes::const_iterator nll = nodeGroupsToMerge.begin();
1382     // for ( ; nll != nodeGroupsToMerge.end(); ++nll )
1383     // {
1384     //   cout << "Merge ";
1385     //   const std::list< const SMDS_MeshNode* >& nl = *nll;
1386     //   std::list< const SMDS_MeshNode* >::const_iterator nIt = nl.begin();
1387     //   for ( ; nIt != nl.end(); ++nIt )
1388     //     cout << (*nIt) << " ";
1389     //   cout << endl;
1390     // }
1391     // cout << endl;
1392   }
1393
1394   //================================================================================
1395   /*!
1396    * \brief A temporary mesh used to compute mesh on a proxy FACE
1397    */
1398   //================================================================================
1399
1400   struct TmpMesh: public SMESH_Mesh
1401   {
1402     typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
1403     TN2NMap     _tmp2origNN;
1404     TopoDS_Face _proxyFace;
1405
1406     TmpMesh()
1407     {
1408       _myMeshDS = new SMESHDS_Mesh( _id, true );
1409     }
1410     //--------------------------------------------------------------------------------
1411     /*!
1412      * \brief Creates a FACE bound by viscous layers and mesh each its EDGE with 1 segment
1413      */
1414     //--------------------------------------------------------------------------------
1415
1416     const TopoDS_Face& makeProxyFace( SMESH_ProxyMesh::Ptr& viscousMesh,
1417                                       const TopoDS_Face&    origFace)
1418     {
1419       // get data of nodes on inner boundary of viscous layers
1420       SMESH_Mesh* origMesh = viscousMesh->GetMesh();
1421       TError err;
1422       TSideVector wireVec = StdMeshers_FaceSide::GetFaceWires(origFace, *origMesh,
1423                                                               /*skipMediumNodes = */true,
1424                                                               err, viscousMesh );
1425       if ( err && err->IsKO() )
1426         throw *err.get(); // it should be caught at SMESH_subMesh
1427
1428       // proxy nodes and corresponding tmp VERTEXes
1429       std::vector<const SMDS_MeshNode*> origNodes;
1430       std::vector<TopoDS_Vertex>        tmpVertex;
1431
1432       // create a proxy FACE
1433       TopoDS_Shape origFaceCopy = origFace.EmptyCopied();
1434       BRepBuilderAPI_MakeFace newFace( TopoDS::Face( origFaceCopy ));
1435       for ( size_t iW = 0; iW != wireVec.size(); ++iW )
1436       {
1437         StdMeshers_FaceSidePtr& wireData = wireVec[iW];
1438         const UVPtStructVec& wirePoints = wireData->GetUVPtStruct();
1439         if ( wirePoints.size() < 3 )
1440           continue;
1441
1442         BRepBuilderAPI_MakePolygon wire;
1443         for ( size_t iN = 1; iN < wirePoints.size(); ++iN )
1444         {
1445           wire.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
1446           origNodes.push_back( wirePoints[ iN ].node );
1447           tmpVertex.push_back( wire.LastVertex() );
1448         }
1449         tmpVertex[0] = wire.FirstVertex();
1450         wire.Close();
1451         if ( !wire.IsDone() )
1452           throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
1453         newFace.Add( wire );
1454       }
1455       _proxyFace = newFace;
1456
1457       // set a new shape to mesh
1458       TopoDS_Compound auxCompoundToMesh;
1459       BRep_Builder shapeBuilder;
1460       shapeBuilder.MakeCompound( auxCompoundToMesh );
1461       shapeBuilder.Add( auxCompoundToMesh, _proxyFace );
1462       shapeBuilder.Add( auxCompoundToMesh, origMesh->GetShapeToMesh() );
1463
1464       ShapeToMesh( auxCompoundToMesh );
1465
1466       //TopExp_Explorer fExp( auxCompoundToMesh, TopAbs_FACE );
1467       //_proxyFace = TopoDS::Face( fExp.Current() );
1468
1469
1470       // Make input mesh for BLSURF: segments on EDGE's of newFace
1471
1472       // make nodes and fill in _tmp2origNN
1473       //
1474       SMESHDS_Mesh* tmpMeshDS = GetMeshDS();
1475       for ( size_t i = 0; i < origNodes.size(); ++i )
1476       {
1477         GetSubMesh( tmpVertex[i] )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1478         if ( const SMDS_MeshNode* tmpN = SMESH_Algo::VertexNode( tmpVertex[i], tmpMeshDS ))
1479           _tmp2origNN.insert( _tmp2origNN.end(), make_pair( tmpN, origNodes[i] ));
1480         else
1481           throw SALOME_Exception("BLSURFPlugin_BLSURF: a proxy vertex not meshed");
1482       }
1483
1484       // make segments
1485       TopoDS_Vertex v1, v2;
1486       for ( TopExp_Explorer edge( _proxyFace, TopAbs_EDGE ); edge.More(); edge.Next() )
1487       {
1488         const TopoDS_Edge& E = TopoDS::Edge( edge.Current() );
1489         TopExp::Vertices( E, v1, v2 );
1490         const SMDS_MeshNode* n1 = SMESH_Algo::VertexNode( v1, tmpMeshDS );
1491         const SMDS_MeshNode* n2 = SMESH_Algo::VertexNode( v2, tmpMeshDS );
1492
1493         if ( SMDS_MeshElement* seg = tmpMeshDS->AddEdge( n1, n2 ))
1494           tmpMeshDS->SetMeshElementOnShape( seg, E );
1495       }
1496
1497       return _proxyFace;
1498     }
1499
1500     //--------------------------------------------------------------------------------
1501     /*!
1502      * \brief Fill in the origMesh with faces computed by BLSURF in this tmp mesh
1503      */
1504     //--------------------------------------------------------------------------------
1505
1506     void FillInOrigMesh( SMESH_Mesh&        origMesh,
1507                          const TopoDS_Face& origFace )
1508     {
1509       SMESH_MesherHelper helper( origMesh );
1510       helper.SetSubShape( origFace );
1511       helper.SetElementsOnShape( true );
1512
1513       // iterate over tmp faces and copy them in origMesh
1514       const SMDS_MeshNode* nodes[27];
1515       const SMDS_MeshNode* nullNode = 0;
1516       double xyz[3];
1517       SMDS_FaceIteratorPtr fIt = GetMeshDS()->facesIterator(/*idInceasingOrder=*/true);
1518       while ( fIt->more() )
1519       {
1520         const SMDS_MeshElement* f = fIt->next();
1521         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
1522         int nbN = 0;
1523         for ( ; nIt->more(); ++nbN )
1524         {
1525           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
1526           TN2NMap::iterator n2nIt = 
1527             _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
1528           if ( !n2nIt->second ) {
1529             n->GetXYZ( xyz );
1530             gp_XY uv = helper.GetNodeUV( _proxyFace, n );
1531             n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], uv.X(), uv.Y() );
1532           }
1533           nodes[ nbN ] = n2nIt->second;
1534         }
1535         switch( nbN ) {
1536         case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
1537         // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
1538         //                         nodes[3], nodes[4], nodes[5]); break;
1539         case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
1540         // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1541         //                         nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
1542         // case 8: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1543         //                         nodes[4], nodes[5], nodes[6], nodes[7]); break;
1544         }
1545       }
1546     }
1547   };
1548
1549   /*!
1550    * \brief A structure holding an error description and a verbisity level
1551    */
1552   struct message_cb_user_data
1553   {
1554     std::string * _error;
1555     int           _verbosity;
1556   };
1557
1558
1559 } // namespace
1560
1561 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1562 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1563                   real *duu, real *duv, real *dvv, void *user_data);
1564 status_t message_cb(message_t *msg, void *user_data);
1565 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1566
1567 //=============================================================================
1568 /*!
1569  *
1570  */
1571 //=============================================================================
1572
1573 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1574
1575   MESSAGE("BLSURFPlugin_BLSURF::Compute");
1576
1577   // Fix problem with locales
1578   Kernel_Utils::Localizer aLocalizer;
1579
1580   if ( !compute( aMesh, aShape ))
1581     return false;
1582
1583   if ( _haveViscousLayers )
1584   {
1585     // Compute viscous layers
1586
1587     TopTools_MapOfShape map;
1588     for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1589     {
1590       const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1591       if ( !map.Add( F )) continue;
1592       SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1593       if ( !viscousMesh )
1594         return false; // error in StdMeshers_ViscousLayers2D::Compute()
1595
1596       // Compute BLSURF mesh on viscous layers
1597
1598       if ( viscousMesh->NbProxySubMeshes() > 0 )
1599       {
1600         TmpMesh tmpMesh;
1601         const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1602         if ( !compute( tmpMesh, proxyFace ))
1603           return false;
1604         tmpMesh.FillInOrigMesh( aMesh, F );
1605       }
1606     }
1607
1608     // Re-compute BLSURF mesh on the rest faces if the mesh was cleared
1609
1610     for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1611     {
1612       const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1613       SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1614       if ( fSM->IsMeshComputed() ) continue;
1615
1616       if ( !compute( aMesh, aShape ))
1617         return false;
1618       break;
1619     }
1620   }
1621   return true;
1622 }
1623
1624 //=============================================================================
1625 /*!
1626  *
1627  */
1628 //=============================================================================
1629
1630 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
1631                                   const TopoDS_Shape& aShape)
1632 {
1633   /* create a distene context (generic object) */
1634   status_t status = STATUS_ERROR;
1635
1636   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1637   SMESH_MesherHelper helper( aMesh );
1638   // do not call helper.IsQuadraticSubMesh() because sub-meshes
1639   // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1640   bool haveQuadraticSubMesh = SMESH_MesherHelper( aMesh ).IsQuadraticSubMesh( aShape );
1641   bool quadraticSubMeshAndViscousLayer = false;
1642   bool needMerge = false;
1643   typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1644   TSubMeshSet edgeSubmeshes;
1645   TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1646
1647   TopTools_IndexedMapOfShape fmap;
1648   TopTools_IndexedMapOfShape emap;
1649   TopTools_IndexedMapOfShape pmap;
1650
1651   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1652 #ifndef WNT
1653   feclearexcept( FE_ALL_EXCEPT );
1654   int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1655 #endif
1656
1657   context_t *ctx =  context_new();
1658
1659   /* Set the message callback in the working context */
1660   message_cb_user_data mcud;
1661   mcud._error     = & this->SMESH_Algo::_comment;
1662   mcud._verbosity =
1663     _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
1664   context_set_message_callback(ctx, message_cb, &mcud);
1665
1666   /* set the interruption callback */
1667   _compute_canceled = false;
1668   context_set_interrupt_callback(ctx, interrupt_cb, this);
1669
1670   /* create the CAD object we will work on. It is associated to the context ctx. */
1671   cad_t *c     = cad_new(ctx);
1672   dcad_t *dcad = dcad_new(c);
1673
1674   FacesWithSizeMap.Clear();
1675   FaceId2SizeMap.clear();
1676   FaceId2ClassAttractor.clear();
1677   FaceIndex2ClassAttractor.clear();
1678   EdgesWithSizeMap.Clear();
1679   EdgeId2SizeMap.clear();
1680   VerticesWithSizeMap.Clear();
1681   VertexId2SizeMap.clear();
1682
1683   /* Now fill the CAD object with data from your CAD
1684    * environement. This is the most complex part of a successfull
1685    * integration.
1686    */
1687
1688   // PreCAD
1689   // If user requests it, send the CAD through Distene preprocessor : PreCAD
1690   cad_t *cleanc = NULL; // preprocessed cad
1691   precad_session_t *pcs = precad_session_new(ctx);
1692   precad_data_set_cad(pcs, c);
1693
1694   cadsurf_session_t *css = cadsurf_session_new(ctx);
1695
1696   // an object that correctly deletes all cadsurf objects at destruction
1697   BLSURF_Cleaner cleaner( ctx,css,c,dcad );
1698
1699   MESSAGE("BEGIN SetParameters");
1700   bool use_precad = false;
1701   SetParameters(
1702                 // #if BLSURF_VERSION_LONG >= "3.1.1"
1703                 //     c,
1704                 // #endif
1705                 _hypothesis, css, pcs, aShape, &use_precad);
1706   MESSAGE("END SetParameters");
1707
1708   haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
1709   helper.SetIsQuadratic( haveQuadraticSubMesh );
1710
1711   // To remove as soon as quadratic mesh is allowed - BEGIN
1712   // GDD: Viscous layer is not allowed with quadratic mesh
1713   if (_haveViscousLayers && haveQuadraticSubMesh ) {
1714     quadraticSubMeshAndViscousLayer = true;
1715     _haveViscousLayers = !haveQuadraticSubMesh;
1716     _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
1717     error(COMPERR_WARNING, _comment);
1718   }
1719   // To remove as soon as quadratic mesh is allowed - END
1720
1721   // needed to prevent the opencascade memory managmement from freeing things
1722   vector<Handle(Geom2d_Curve)> curves;
1723   vector<Handle(Geom_Surface)> surfaces;
1724
1725   fmap.Clear();
1726   emap.Clear();
1727   pmap.Clear();
1728   FaceId2PythonSmp.clear();
1729   EdgeId2PythonSmp.clear();
1730   VertexId2PythonSmp.clear();
1731
1732   /****************************************************************************************
1733                                           FACES
1734   *****************************************************************************************/
1735   int iface = 0;
1736   string bad_end = "return";
1737   int faceKey = -1;
1738   TopTools_IndexedMapOfShape _map;
1739   TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
1740   int ienf = _map.Extent();
1741
1742   assert(Py_IsInitialized());
1743   PyGILState_STATE gstate;
1744   gstate = PyGILState_Ensure();
1745
1746   string theSizeMapStr;
1747
1748   for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1749   {
1750     TopoDS_Face f = TopoDS::Face(face_iter.Current());
1751
1752     // make INTERNAL face oriented FORWARD (issue 0020993)
1753     if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
1754       f.Orientation(TopAbs_FORWARD);
1755
1756     if (fmap.FindIndex(f) > 0)
1757       continue;
1758     iface = fmap.Add(f);
1759
1760     surfaces.push_back(BRep_Tool::Surface(f));
1761
1762     /* create an object representing the face for cadsurf */
1763     /* where face_id is an integer identifying the face.
1764      * surf_function is the function that defines the surface
1765      * (For this face, it will be called by cadsurf with your_face_object_ptr
1766      * as last parameter.
1767      */
1768     cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
1769
1770     /* by default a face has no tag (color).
1771        The following call sets it to the same value as the face_id : */
1772     cad_face_set_tag(fce, iface);
1773
1774     /* Set face orientation (optional if you want a well oriented output mesh)*/
1775     if(f.Orientation() != TopAbs_FORWARD)
1776       cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
1777     else
1778       cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
1779
1780     if (HasSizeMapOnFace && !use_precad)
1781     {
1782       // -----------------
1783       // Classic size map
1784       // -----------------
1785       faceKey = FacesWithSizeMap.FindIndex(f);
1786
1787
1788       if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()) {
1789         MESSAGE("A size map is defined on face :"<<faceKey)
1790           theSizeMapStr = FaceId2SizeMap[faceKey];
1791         // check if function ends with "return"
1792         if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1793           continue;
1794         // Expr To Python function, verification is performed at validation in GUI
1795         PyObject * obj = NULL;
1796         obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1797         Py_DECREF(obj);
1798         PyObject * func = NULL;
1799         func = PyObject_GetAttrString(main_mod, "f");
1800         FaceId2PythonSmp[iface]=func;
1801         FaceId2SizeMap.erase(faceKey);
1802       }
1803
1804       // Specific size map = Attractor
1805       std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
1806
1807       for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
1808         if (attractor_iter->first == faceKey) {
1809           MESSAGE("Face indice: " << iface);
1810           MESSAGE("Adding attractor");
1811
1812           double xyzCoords[3]  = {attractor_iter->second[2],
1813                                   attractor_iter->second[3],
1814                                   attractor_iter->second[4]};
1815
1816           MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1817           gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1818           BRepClass_FaceClassifier scl(f,P,1e-7);
1819           // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
1820           // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1821           // OCC 6.5.2: scl.Perform() is not bugged anymore
1822           scl.Perform(f, P, 1e-7);
1823           TopAbs_State result = scl.State();
1824           MESSAGE("Position of point on face: "<<result);
1825           if ( result == TopAbs_OUT )
1826             MESSAGE("Point is out of face: node is not created");
1827           if ( result == TopAbs_UNKNOWN )
1828             MESSAGE("Point position on face is unknown: node is not created");
1829           if ( result == TopAbs_ON )
1830             MESSAGE("Point is on border of face: node is not created");
1831           if ( result == TopAbs_IN )
1832           {
1833             // Point is inside face and not on border
1834             MESSAGE("Point is in face: node is created");
1835             double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
1836             ienf++;
1837             MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
1838             cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
1839             cad_point_set_tag(point_p, ienf);
1840           }
1841           FaceId2AttractorCoords.erase(faceKey);
1842         }
1843       }
1844
1845       // -----------------
1846       // Class Attractors
1847       // -----------------
1848       std::map<int,BLSURFPlugin_Attractor* >::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
1849       if (clAttractor_iter != FaceId2ClassAttractor.end()){
1850         MESSAGE("Face indice: " << iface);
1851         MESSAGE("Adding attractor");
1852         FaceIndex2ClassAttractor[iface]=clAttractor_iter->second;
1853         FaceId2ClassAttractor.erase(clAttractor_iter);
1854       }
1855     } // if (HasSizeMapOnFace && !use_precad)
1856
1857       // ------------------
1858       // Enforced Vertices
1859       // ------------------
1860     faceKey = FacesWithEnforcedVertices.FindIndex(f);
1861     std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
1862     if (evmIt != FaceId2EnforcedVertexCoords.end()) {
1863       MESSAGE("Some enforced vertices are defined");
1864       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
1865       MESSAGE("Face indice: " << iface);
1866       MESSAGE("Adding enforced vertices");
1867       evl = evmIt->second;
1868       MESSAGE("Number of vertices to add: "<< evl.size());
1869       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
1870       for (; evlIt != evl.end(); ++evlIt) {
1871         BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
1872         xyzCoords.push_back(evlIt->at(2));
1873         xyzCoords.push_back(evlIt->at(3));
1874         xyzCoords.push_back(evlIt->at(4));
1875         MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1876         gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1877         BRepClass_FaceClassifier scl(f,P,1e-7);
1878         // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
1879         // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1880         // OCC 6.5.2: scl.Perform() is not bugged anymore
1881         scl.Perform(f, P, 1e-7);
1882         TopAbs_State result = scl.State();
1883         MESSAGE("Position of point on face: "<<result);
1884         if ( result == TopAbs_OUT ) {
1885           MESSAGE("Point is out of face: node is not created");
1886           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1887             EnfVertexCoords2ProjVertex.erase(xyzCoords);
1888             EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1889           }
1890         }
1891         if ( result == TopAbs_UNKNOWN ) {
1892           MESSAGE("Point position on face is unknown: node is not created");
1893           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1894             EnfVertexCoords2ProjVertex.erase(xyzCoords);
1895             EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1896           }
1897         }
1898         if ( result == TopAbs_ON ) {
1899           MESSAGE("Point is on border of face: node is not created");
1900           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1901             EnfVertexCoords2ProjVertex.erase(xyzCoords);
1902             EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1903           }
1904         }
1905         if ( result == TopAbs_IN )
1906         {
1907           // Point is inside face and not on border
1908           MESSAGE("Point is in face: node is created");
1909           double uvCoords[2]   = {evlIt->at(0),evlIt->at(1)};
1910           ienf++;
1911           MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
1912           cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
1913           int tag = 0;
1914           std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
1915           if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
1916               !enfCoordsIt->second.empty() )
1917           {
1918             // to merge nodes of an INTERNAL vertex belonging to several faces
1919             TopoDS_Vertex     v = (*enfCoordsIt->second.begin())->vertex;
1920             if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
1921             if ( !v.IsNull() ) {
1922               tag = pmap.Add( v );
1923               SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
1924               vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1925               mergeSubmeshes.insert( vSM->GetSubMeshDS() );
1926               //if ( tag != pmap.Extent() )
1927               needMerge = true;
1928             }
1929           }
1930           if ( tag == 0 ) tag = ienf;
1931           cad_point_set_tag(point_p, tag);
1932         }
1933       }
1934       FaceId2EnforcedVertexCoords.erase(faceKey);
1935
1936     }
1937
1938     /****************************************************************************************
1939                                            EDGES
1940                         now create the edges associated to this face
1941     *****************************************************************************************/
1942     int edgeKey = -1;
1943     for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next())
1944     {
1945       TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
1946       int ic = emap.FindIndex(e);
1947       if (ic <= 0)
1948         ic = emap.Add(e);
1949
1950       double tmin,tmax;
1951       curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
1952
1953       if (HasSizeMapOnEdge){
1954         edgeKey = EdgesWithSizeMap.FindIndex(e);
1955         if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
1956           MESSAGE("Sizemap defined on edge with index " << edgeKey);
1957           theSizeMapStr = EdgeId2SizeMap[edgeKey];
1958           if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1959             continue;
1960           // Expr To Python function, verification is performed at validation in GUI
1961           PyObject * obj = NULL;
1962           obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1963           Py_DECREF(obj);
1964           PyObject * func = NULL;
1965           func = PyObject_GetAttrString(main_mod, "f");
1966           EdgeId2PythonSmp[ic]=func;
1967           EdgeId2SizeMap.erase(edgeKey);
1968         }
1969       }
1970       /* data of nodes existing on the edge */
1971       StdMeshers_FaceSidePtr nodeData;
1972       SMESH_subMesh* sm = aMesh.GetSubMesh( e );
1973       if ( !sm->IsEmpty() )
1974       {
1975         SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
1976                                                                      /*complexFirst=*/false);
1977         while ( subsmIt->more() )
1978           edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
1979
1980         nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
1981                                                  /*ignoreMedium=*/haveQuadraticSubMesh));
1982         if ( nodeData->MissVertexNode() )
1983           return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
1984
1985         const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
1986         if ( !nodeDataVec.empty() )
1987         {
1988           if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
1989           {
1990             nodeData->Reverse();
1991             nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
1992           }
1993           // tmin and tmax can change in case of viscous layer on an adjacent edge
1994           tmin = nodeDataVec.front().param;
1995           tmax = nodeDataVec.back().param;
1996         }
1997         else
1998         {
1999           cout << "---------------- Invalid nodeData" << endl;
2000           nodeData.reset();
2001         }
2002       }
2003
2004       /* attach the edge to the current cadsurf face */
2005       cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
2006
2007       /* by default an edge has no tag (color).
2008          The following call sets it to the same value as the edge_id : */
2009       cad_edge_set_tag(edg, ic);
2010
2011       /* by default, an edge does not necessalry appear in the resulting mesh,
2012          unless the following property is set :
2013       */
2014       cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2015
2016       /* by default an edge is a boundary edge */
2017       if (e.Orientation() == TopAbs_INTERNAL)
2018         cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2019
2020       // pass existing nodes of sub-meshes to BLSURF
2021       if ( nodeData )
2022       {
2023         const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2024         const int                      nbNodes     = nodeDataVec.size();
2025
2026         dcad_edge_discretization_t *dedge;
2027         dcad_get_edge_discretization(dcad, edg, &dedge);
2028         dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2029
2030         // cout << endl << " EDGE " << ic << endl;
2031         // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2032         for ( int iN = 0; iN < nbNodes; ++iN )
2033         {
2034           const UVPtStruct& nData = nodeDataVec[ iN ];
2035           double t                = nData.param;
2036           real uv[2]              = { nData.u, nData.v };
2037           SMESH_TNodeXYZ nXYZ( nData.node );
2038           // cout << "\tt = " << t
2039           //      << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2040           //      << "\t u = " << nData.param
2041           //      << "\t ID = " << nData.node->GetID() << endl;
2042           dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ._xyz );
2043         }
2044         dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2045       }
2046
2047       /****************************************************************************************
2048                                       VERTICES
2049       *****************************************************************************************/
2050
2051       int npts = 0;
2052       int ip1, ip2, *ip;
2053       gp_Pnt2d e0 = curves.back()->Value(tmin);
2054       gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
2055       Standard_Real d1=0,d2=0;
2056
2057       int vertexKey = -1;
2058       for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
2059         TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
2060         ++npts;
2061         if (npts == 1){
2062           ip = &ip1;
2063           d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2064         } else {
2065           ip = &ip2;
2066           d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2067         }
2068         *ip = pmap.FindIndex(v);
2069         if(*ip <= 0) {
2070           *ip = pmap.Add(v);
2071           SMESH_subMesh* sm = aMesh.GetSubMesh(v);
2072           if ( sm->IsMeshComputed() )
2073             edgeSubmeshes.insert( sm->GetSubMeshDS() );
2074         }
2075         if (HasSizeMapOnVertex){
2076           vertexKey = VerticesWithSizeMap.FindIndex(v);
2077           if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
2078             theSizeMapStr = VertexId2SizeMap[vertexKey];
2079             //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
2080             if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2081               continue;
2082             // Expr To Python function, verification is performed at validation in GUI
2083             PyObject * obj = NULL;
2084             obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2085             Py_DECREF(obj);
2086             PyObject * func = NULL;
2087             func = PyObject_GetAttrString(main_mod, "f");
2088             VertexId2PythonSmp[*ip]=func;
2089             VertexId2SizeMap.erase(vertexKey);   // do not erase if using a vector
2090           }
2091         }
2092       }
2093       if (npts != 2) {
2094         // should not happen
2095         MESSAGE("An edge does not have 2 extremities.");
2096       } else {
2097         if (d1 < d2) {
2098           // This defines the curves extremity connectivity
2099           cad_edge_set_extremities(edg, ip1, ip2);
2100           /* set the tag (color) to the same value as the extremity id : */
2101           cad_edge_set_extremities_tag(edg, ip1, ip2);
2102         }
2103         else {
2104           cad_edge_set_extremities(edg, ip2, ip1);
2105           cad_edge_set_extremities_tag(edg, ip2, ip1);
2106         }
2107       }
2108     } // for edge
2109   } //for face
2110
2111   // Clear mesh from already meshed edges if possible else
2112   // remember that merge is needed
2113   TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2114   for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2115   {
2116     SMESHDS_SubMesh* smDS = *smIt;
2117     if ( !smDS ) continue;
2118     SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2119     if ( nIt->more() )
2120     {
2121       const SMDS_MeshNode* n = nIt->next();
2122       if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2123       {
2124         needMerge = true;
2125         // add existing medium nodes to helper
2126         if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2127         {
2128           SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2129           while ( edgeIt->more() )
2130             helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2131         }
2132         continue;
2133       }
2134     }
2135     {
2136       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2137       while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), smDS );
2138       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2139       while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), smDS );
2140     }
2141   }
2142
2143
2144   if (use_precad) {
2145     /* Now launch the PreCAD process */
2146     status = precad_process(pcs);
2147     if(status != STATUS_OK){
2148       cout << "PreCAD processing failed with error code " << status << "\n";
2149     }
2150     else {
2151       // retrieve the pre-processed CAD object
2152       cleanc = precad_new_cad(pcs);
2153       if(!cleanc){
2154         cout << "Unable to retrieve PreCAD result \n";
2155       }
2156       cout << "PreCAD processing successfull \n";
2157
2158       // #if BLSURF_VERSION_LONG >= "3.1.1"
2159       //       /* We can now get the updated sizemaps (if any) */
2160       // //       if(geo_sizemap_e)
2161       // //         clean_geo_sizemap_e = precad_new_sizemap(pcs, geo_sizemap_e);
2162       // // 
2163       // //       if(geo_sizemap_f)
2164       // //         clean_geo_sizemap_f = precad_new_sizemap(pcs, geo_sizemap_f);
2165       //
2166       //       if(iso_sizemap_p)
2167       //         clean_iso_sizemap_p = precad_new_sizemap(pcs, iso_sizemap_p);
2168       //
2169       //       if(iso_sizemap_e)
2170       //         clean_iso_sizemap_e = precad_new_sizemap(pcs, iso_sizemap_e);
2171       //
2172       //       if(iso_sizemap_f)
2173       //         clean_iso_sizemap_f = precad_new_sizemap(pcs, iso_sizemap_f);
2174       // #endif
2175     }
2176     // Now we can delete the PreCAD session
2177     precad_session_delete(pcs);
2178   }
2179
2180   cadsurf_data_set_dcad(css, dcad);
2181   if (cleanc) {
2182     // Give the pre-processed CAD object to the current BLSurf session
2183     cadsurf_data_set_cad(css, cleanc);
2184   }
2185   else {
2186     // Use the original one
2187     cadsurf_data_set_cad(css, c);
2188   }
2189
2190   std::cout << std::endl;
2191   std::cout << "Beginning of Surface Mesh generation" << std::endl;
2192   std::cout << std::endl;
2193
2194   try {
2195     OCC_CATCH_SIGNALS;
2196
2197     status = cadsurf_compute_mesh(css);
2198
2199   }
2200   catch ( std::exception& exc ) {
2201     _comment += exc.what();
2202   }
2203   catch (Standard_Failure& ex) {
2204     _comment += ex.DynamicType()->Name();
2205     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2206       _comment += ": ";
2207       _comment += ex.GetMessageString();
2208     }
2209   }
2210   catch (...) {
2211     if ( _comment.empty() )
2212       _comment = "Exception in cadsurf_compute_mesh()";
2213   }
2214   if ( status != STATUS_OK) {
2215     // There was an error while meshing
2216     error(_comment);
2217   }
2218
2219   PyGILState_Release(gstate);
2220
2221   std::cout << std::endl;
2222   std::cout << "End of Surface Mesh generation" << std::endl;
2223   std::cout << std::endl;
2224
2225   mesh_t *msh = NULL;
2226   cadsurf_data_get_mesh(css, &msh);
2227   if(!msh){
2228     /* release the mesh object */
2229     cadsurf_data_regain_mesh(css, msh);
2230     return error(_comment);
2231   }
2232
2233   std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2234   if (_hypothesis)
2235     GMFFileName = _hypothesis->GetGMFFile();
2236   if (GMFFileName != "") {
2237     //     bool GMFFileMode = _hypothesis->GetGMFFileMode();
2238     bool asciiFound = (GMFFileName.find(".mesh",GMFFileName.length()-5) != std::string::npos);
2239     bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2240     if (!asciiFound && !binaryFound)
2241       GMFFileName.append(".mesh");
2242     mesh_write_mesh(msh, GMFFileName.c_str());
2243   }
2244
2245   /* retrieve mesh data (see meshgems/mesh.h) */
2246   integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2247   integer *evedg, *evtri, *evquad, *tags_buff, type;
2248   real xyz[3];
2249
2250   mesh_get_vertex_count(msh, &nv);
2251   mesh_get_edge_count(msh, &ne);
2252   mesh_get_triangle_count(msh, &nt);
2253   mesh_get_quadrangle_count(msh, &nq);
2254
2255   evedg  = (integer *)mesh_calloc_generic_buffer(msh);
2256   evtri  = (integer *)mesh_calloc_generic_buffer(msh);
2257   evquad = (integer *)mesh_calloc_generic_buffer(msh);
2258   tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
2259
2260   SMDS_MeshNode** nodes = new SMDS_MeshNode*[nv+1];
2261   bool* tags = new bool[nv+1];
2262
2263   /* enumerated vertices */
2264   for(int iv=1;iv<=nv;iv++) {
2265     mesh_get_vertex_coordinates(msh, iv, xyz);
2266     mesh_get_vertex_tag(msh, iv, &tag);
2267     // Issue 0020656. Use vertex coordinates
2268     if ( tag > 0 && tag <= pmap.Extent() ) {
2269       TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2270       double tol = BRep_Tool::Tolerance( v );
2271       gp_Pnt p = BRep_Tool::Pnt( v );
2272       if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
2273         xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2274       else
2275         tag = 0; // enforced or attracted vertex
2276     }
2277     nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2278
2279     // Create group of enforced vertices if requested
2280     BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2281     projVertex.clear();
2282     projVertex.push_back((double)xyz[0]);
2283     projVertex.push_back((double)xyz[1]);
2284     projVertex.push_back((double)xyz[2]);
2285     std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
2286     if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
2287       MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
2288       BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
2289       BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
2290       for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
2291         currentEnfVertex = (*enfListIt);
2292         if (currentEnfVertex->grpName != "") {
2293           bool groupDone = false;
2294           SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
2295           MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
2296           MESSAGE("Parsing the groups of the mesh");
2297           while (grIt->more()) {
2298             SMESH_Group * group = grIt->next();
2299             if ( !group ) continue;
2300             MESSAGE("Group: " << group->GetName());
2301             SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2302             if ( !groupDS ) continue;
2303             MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
2304             MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
2305             MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
2306             if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
2307               SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
2308               aGroupDS->SMDSGroup().Add(nodes[iv]);
2309               MESSAGE("Node ID: " << nodes[iv]->GetID());
2310               // How can I inform the hypothesis ?
2311               //                 _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
2312               groupDone = true;
2313               MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
2314               break;
2315             }
2316           }
2317           if (!groupDone)
2318           {
2319             int groupId;
2320             SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
2321             aGroup->SetName( currentEnfVertex->grpName.c_str() );
2322             SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2323             aGroupDS->SMDSGroup().Add(nodes[iv]);
2324             MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
2325             groupDone = true;
2326           }
2327           if (!groupDone)
2328             throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
2329         }
2330         else
2331           MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
2332       }
2333     }
2334
2335     // internal points are tagged to zero
2336     if(tag > 0 && tag <= pmap.Extent() ){
2337       meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2338       tags[iv] = false;
2339     } else {
2340       tags[iv] = true;
2341     }
2342   }
2343
2344   /* enumerate edges */
2345   for(int it=1;it<=ne;it++) {
2346     SMDS_MeshEdge* edg;
2347     mesh_get_edge_vertices(msh, it, vtx);
2348     mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2349     mesh_get_edge_tag(msh, it, &tag);
2350
2351     // If PreCAD performed some cleaning operations (remove tiny edges,
2352     // merge edges ...) an output tag can indeed represent several original tags.
2353     // Get the initial tags corresponding to the output tag and redefine the tag as 
2354     // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2355     mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2356     if(nb_tag > 1)  
2357       tag=tags_buff[nb_tag-1]; 
2358
2359     if (tags[vtx[0]]) {
2360       Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2361       tags[vtx[0]] = false;
2362     };
2363     if (tags[vtx[1]]) {
2364       Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2365       tags[vtx[1]] = false;
2366     };
2367     if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2368       // QUADRATIC EDGE
2369       if (tags[evedg[0]]) {
2370         Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2371         tags[evedg[0]] = false;
2372       }
2373       edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2374     }
2375     else {
2376       edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2377     }
2378     meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2379   }
2380
2381   /* enumerate triangles */
2382   for(int it=1;it<=nt;it++) {
2383     SMDS_MeshFace* tri;
2384     mesh_get_triangle_vertices(msh, it, vtx);
2385     mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2386     mesh_get_triangle_tag(msh, it, &tag);
2387     if (tags[vtx[0]]) {
2388       meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
2389       tags[vtx[0]] = false;
2390     };
2391     if (tags[vtx[1]]) {
2392       meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
2393       tags[vtx[1]] = false;
2394     };
2395     if (tags[vtx[2]]) {
2396       meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
2397       tags[vtx[2]] = false;
2398     };
2399     if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2400       // QUADRATIC TRIANGLE
2401       if (tags[evtri[0]]) {
2402         meshDS->SetNodeOnFace(nodes[evtri[0]], TopoDS::Face(fmap(tag)));
2403         tags[evtri[0]] = false;
2404       }
2405       if (tags[evtri[1]]) {
2406         meshDS->SetNodeOnFace(nodes[evtri[1]], TopoDS::Face(fmap(tag)));
2407         tags[evtri[1]] = false;
2408       }
2409       if (tags[evtri[2]]) {
2410         meshDS->SetNodeOnFace(nodes[evtri[2]], TopoDS::Face(fmap(tag)));
2411         tags[evtri[2]] = false;
2412       }
2413       tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2414                             nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2415     }
2416     else {
2417       tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2418     }
2419     meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
2420   }
2421
2422   /* enumerate quadrangles */
2423   for(int it=1;it<=nq;it++) {
2424     SMDS_MeshFace* quad;
2425     mesh_get_quadrangle_vertices(msh, it, vtx);
2426     mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2427     mesh_get_quadrangle_tag(msh, it, &tag);
2428     if (tags[vtx[0]]) {
2429       meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
2430       tags[vtx[0]] = false;
2431     };
2432     if (tags[vtx[1]]) {
2433       meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
2434       tags[vtx[1]] = false;
2435     };
2436     if (tags[vtx[2]]) {
2437       meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
2438       tags[vtx[2]] = false;
2439     };
2440     if (tags[vtx[3]]) {
2441       meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
2442       tags[vtx[3]] = false;
2443     };
2444     if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
2445       // QUADRATIC QUADRANGLE
2446       std::cout << "This is a quadratic quadrangle" << std::endl;
2447       if (tags[evquad[0]]) {
2448         meshDS->SetNodeOnFace(nodes[evquad[0]], TopoDS::Face(fmap(tag)));
2449         tags[evquad[0]] = false;
2450       }
2451       if (tags[evquad[1]]) {
2452         meshDS->SetNodeOnFace(nodes[evquad[1]], TopoDS::Face(fmap(tag)));
2453         tags[evquad[1]] = false;
2454       }
2455       if (tags[evquad[2]]) {
2456         meshDS->SetNodeOnFace(nodes[evquad[2]], TopoDS::Face(fmap(tag)));
2457         tags[evquad[2]] = false;
2458       }
2459       if (tags[evquad[3]]) {
2460         meshDS->SetNodeOnFace(nodes[evquad[3]], TopoDS::Face(fmap(tag)));
2461         tags[evquad[3]] = false;
2462       }
2463       if (tags[evquad[4]]) {
2464         meshDS->SetNodeOnFace(nodes[evquad[4]], TopoDS::Face(fmap(tag)));
2465         tags[evquad[4]] = false;
2466       }
2467       quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
2468                              nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
2469                              nodes[evquad[4]]);
2470     }
2471     else {
2472       quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
2473     }
2474     meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
2475   }
2476
2477   /* release the mesh object, the rest is released by cleaner */
2478   cadsurf_data_regain_mesh(css, msh);
2479
2480   delete [] nodes;
2481   delete [] tags;
2482
2483   if ( needMerge ) // sew mesh computed by BLSURF with pre-existing mesh
2484   {
2485     SMESH_MeshEditor editor( &aMesh );
2486     SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
2487     TIDSortedElemSet segementsOnEdge;
2488     TIDSortedNodeSet nodesOnEdge;
2489     TSubMeshSet::iterator smIt;
2490     SMESHDS_SubMesh* smDS;
2491     typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_NodeIteratorPtr > TNodeIterator;
2492     double tol;
2493
2494     // merge nodes on EDGE's with ones computed by BLSURF
2495     for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
2496     {
2497       if (! (smDS = *smIt) ) continue;
2498       getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
2499
2500       SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2501       while ( segIt->more() )
2502         segementsOnEdge.insert( segIt->next() );
2503     }
2504     // merge nodes
2505     editor.MergeNodes( nodeGroupsToMerge );
2506
2507     // merge segments
2508     SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
2509     editor.FindEqualElements( segementsOnEdge, equalSegments );
2510     editor.MergeElements( equalSegments );
2511
2512     // remove excess segments created on the boundary of viscous layers
2513     const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
2514     for ( int i = 1; i <= emap.Extent(); ++i )
2515     {
2516       if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
2517       {
2518         SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2519         while ( segIt->more() )
2520         {
2521           const SMDS_MeshElement* seg = segIt->next();
2522           if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
2523                seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
2524             meshDS->RemoveFreeElement( seg, smDS );
2525         }
2526       }
2527     }
2528   }
2529
2530   // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
2531   TopLoc_Location loc; double f,l;
2532   for (int i = 1; i <= emap.Extent(); i++)
2533     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
2534       sm->SetIsAlwaysComputed( true );
2535   for (int i = 1; i <= pmap.Extent(); i++)
2536     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
2537       if ( !sm->IsMeshComputed() )
2538         sm->SetIsAlwaysComputed( true );
2539
2540   // Set error to FACE's w/o elements
2541   for ( int i = 1; i <= fmap.Extent(); ++i )
2542   {
2543     SMESH_subMesh* sm = aMesh.GetSubMesh( fmap(i) );
2544     if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
2545       sm->GetComputeError().reset
2546         ( new SMESH_ComputeError( COMPERR_ALGO_FAILED, _comment, this ));
2547   }
2548
2549   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
2550 #ifndef WNT
2551   if ( oldFEFlags > 0 )
2552     feenableexcept( oldFEFlags );
2553   feclearexcept( FE_ALL_EXCEPT );
2554 #endif
2555
2556   /*
2557     std::cout << "FacesWithSizeMap" << std::endl;
2558     FacesWithSizeMap.Statistics(std::cout);
2559     std::cout << "EdgesWithSizeMap" << std::endl;
2560     EdgesWithSizeMap.Statistics(std::cout);
2561     std::cout << "VerticesWithSizeMap" << std::endl;
2562     VerticesWithSizeMap.Statistics(std::cout);
2563     std::cout << "FacesWithEnforcedVertices" << std::endl;
2564     FacesWithEnforcedVertices.Statistics(std::cout);
2565   */
2566
2567   MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
2568   return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
2569 }
2570
2571 //================================================================================
2572 /*!
2573  * \brief Terminates computation
2574  */
2575 //================================================================================
2576
2577 #ifdef WITH_SMESH_CANCEL_COMPUTE
2578 void BLSURFPlugin_BLSURF::CancelCompute()
2579 {
2580   _compute_canceled = true;
2581 }
2582 #endif
2583
2584 //=============================================================================
2585 /*!
2586  *  SetNodeOnEdge
2587  */
2588 //=============================================================================
2589
2590 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* node, const TopoDS_Shape& ed) {
2591   const TopoDS_Edge edge = TopoDS::Edge(ed);
2592
2593   gp_Pnt pnt(node->X(), node->Y(), node->Z());
2594
2595   Standard_Real p0 = 0.0;
2596   Standard_Real p1 = 1.0;
2597   TopLoc_Location loc;
2598   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
2599
2600   if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
2601   GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
2602
2603   double pa = 0.;
2604   if ( proj.NbPoints() > 0 )
2605   {
2606     pa = (double)proj.LowerDistanceParameter();
2607     // Issue 0020656. Move node if it is too far from edge
2608     gp_Pnt curve_pnt = curve->Value( pa );
2609     double dist2     = pnt.SquareDistance( curve_pnt );
2610     double tol       = BRep_Tool::Tolerance( edge );
2611     if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
2612     {
2613       curve_pnt.Transform( loc );
2614       meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
2615     }
2616   }
2617 //   GProp_GProps LProps;
2618 //   BRepGProp::LinearProperties(ed, LProps);
2619 //   double lg = (double)LProps.Mass();
2620
2621   meshDS->SetNodeOnEdge(node, edge, pa);
2622 }
2623
2624 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
2625  * more information.
2626  * NOTE : if when your CAD systems evaluates second
2627  * order derivatives it also computes first order derivatives and
2628  * function evaluation, you can optimize this example by making only
2629  * one CAD call and filling the necessary uv, dt, dtt arrays.
2630  */
2631 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
2632 {
2633   /* t is given. It contains the t (time) 1D parametric coordintaes
2634      of the point PreCAD/BLSurf is querying on the curve */
2635
2636   /* user_data identifies the edge PreCAD/BLSurf is querying
2637    * (see cad_edge_new later in this example) */
2638   const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
2639
2640   if (uv){
2641    /* BLSurf is querying the function evaluation */
2642     gp_Pnt2d P;
2643     P=pargeo->Value(t);
2644     uv[0]=P.X(); uv[1]=P.Y();
2645   }
2646
2647   if(dt) {
2648    /* query for the first order derivatives */
2649     gp_Vec2d V1;
2650     V1=pargeo->DN(t,1);
2651     dt[0]=V1.X(); dt[1]=V1.Y();
2652   }
2653
2654   if(dtt){
2655     /* query for the second order derivatives */
2656     gp_Vec2d V2;
2657     V2=pargeo->DN(t,2);
2658     dtt[0]=V2.X(); dtt[1]=V2.Y();
2659   }
2660
2661   return STATUS_OK;
2662 }
2663
2664 /* Surface definition function.
2665  * See cad_surf_t in file meshgems/cad.h for more information.
2666  * NOTE : if when your CAD systems evaluates second order derivatives it also
2667  * computes first order derivatives and function evaluation, you can optimize
2668  * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
2669  * arrays.
2670  */
2671 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
2672                   real *duu, real *duv, real *dvv, void *user_data)
2673 {
2674   /* uv[2] is given. It contains the u,v coordinates of the point
2675    * PreCAD/BLSurf is querying on the surface */
2676
2677   /* user_data identifies the face PreCAD/BLSurf is querying (see
2678    * cad_face_new later in this example)*/
2679   const Geom_Surface* geometry = (const Geom_Surface*) user_data;
2680
2681   if(xyz){
2682    gp_Pnt P;
2683    P=geometry->Value(uv[0],uv[1]);   // S.D0(U,V,P);
2684    xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
2685   }
2686
2687   if(du && dv){
2688     gp_Pnt P;
2689     gp_Vec D1U,D1V;
2690
2691     geometry->D1(uv[0],uv[1],P,D1U,D1V);
2692     du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
2693     dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
2694   }
2695
2696   if(duu && duv && dvv){
2697
2698     gp_Pnt P;
2699     gp_Vec D1U,D1V;
2700     gp_Vec D2U,D2V,D2UV;
2701
2702     geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
2703     duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
2704     duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
2705     dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
2706   }
2707
2708   return STATUS_OK;
2709 }
2710
2711
2712 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
2713 {
2714   //MESSAGE("size_on_surface")
2715   if (FaceId2PythonSmp.count(face_id) != 0){
2716     //MESSAGE("A size map is used to calculate size on face : "<<face_id)
2717     PyObject * pyresult = NULL;
2718     PyObject* new_stderr = NULL;
2719     assert(Py_IsInitialized());
2720     PyGILState_STATE gstate;
2721     gstate = PyGILState_Ensure();
2722     pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
2723     real result;
2724     if ( pyresult != NULL) {
2725       result = PyFloat_AsDouble(pyresult);
2726       Py_DECREF(pyresult);
2727 //       *size = result;
2728     }
2729     else{
2730       fflush(stderr);
2731       string err_description="";
2732       new_stderr = newPyStdOut(err_description);
2733       PySys_SetObject((char*)"stderr", new_stderr);
2734       PyErr_Print();
2735       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2736       Py_DECREF(new_stderr);
2737       MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
2738       result = *((real*)user_data);
2739     }
2740     *size = result;
2741     PyGILState_Release(gstate);
2742   }
2743   else if (FaceIndex2ClassAttractor.count(face_id) !=0 && !FaceIndex2ClassAttractor[face_id]->Empty()){
2744 //    MESSAGE("attractor used on face :"<<face_id)
2745     // MESSAGE("List of attractor is not empty")
2746     // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
2747     real result = FaceIndex2ClassAttractor[face_id]->GetSize(uv[0],uv[1]);
2748     *size = result;
2749   }
2750   else {
2751     // MESSAGE("List of attractor is empty !!!")
2752     *size = *((real*)user_data);
2753   }
2754 //   std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
2755   return STATUS_OK;
2756 }
2757
2758 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
2759 {
2760   if (EdgeId2PythonSmp.count(edge_id) != 0){
2761     PyObject * pyresult = NULL;
2762     PyObject* new_stderr = NULL;
2763     assert(Py_IsInitialized());
2764     PyGILState_STATE gstate;
2765     gstate = PyGILState_Ensure();
2766     pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
2767     real result;
2768     if ( pyresult != NULL) {
2769       result = PyFloat_AsDouble(pyresult);
2770       Py_DECREF(pyresult);
2771 //       *size = result;
2772     }
2773     else{
2774       fflush(stderr);
2775       string err_description="";
2776       new_stderr = newPyStdOut(err_description);
2777       PySys_SetObject((char*)"stderr", new_stderr);
2778       PyErr_Print();
2779       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2780       Py_DECREF(new_stderr);
2781       MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
2782       result = *((real*)user_data);
2783     }
2784     *size = result;
2785     PyGILState_Release(gstate);
2786   }
2787   else {
2788     *size = *((real*)user_data);
2789   }
2790   return STATUS_OK;
2791 }
2792
2793 status_t size_on_vertex(integer point_id, real *size, void *user_data)
2794 {
2795   if (VertexId2PythonSmp.count(point_id) != 0){
2796     PyObject * pyresult = NULL;
2797     PyObject* new_stderr = NULL;
2798     assert(Py_IsInitialized());
2799     PyGILState_STATE gstate;
2800     gstate = PyGILState_Ensure();
2801     pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
2802     real result;
2803     if ( pyresult != NULL) {
2804       result = PyFloat_AsDouble(pyresult);
2805       Py_DECREF(pyresult);
2806 //       *size = result;
2807     }
2808     else {
2809       fflush(stderr);
2810       string err_description="";
2811       new_stderr = newPyStdOut(err_description);
2812       PySys_SetObject((char*)"stderr", new_stderr);
2813       PyErr_Print();
2814       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2815       Py_DECREF(new_stderr);
2816       MESSAGE("Can't evaluate f()" << " error is " << err_description);
2817       result = *((real*)user_data);
2818     }
2819     *size = result;
2820     PyGILState_Release(gstate);
2821   }
2822   else {
2823     *size = *((real*)user_data);
2824   }
2825  return STATUS_OK;
2826 }
2827
2828 /*
2829  * The following function will be called for PreCAD/BLSurf message
2830  * printing.  See context_set_message_callback (later in this
2831  * template) for how to set user_data.
2832  */
2833 status_t message_cb(message_t *msg, void *user_data)
2834 {
2835   integer errnumber = 0;
2836   char *desc;
2837   message_get_number(msg, &errnumber);
2838   message_get_description(msg, &desc);
2839   string err( desc );
2840   message_cb_user_data * mcud = (message_cb_user_data*)user_data;
2841   if ( errnumber < 0 || err.find("license") != string::npos ) {
2842     // remove ^A from the tail
2843     int len = strlen( desc );
2844     while (len > 0 && desc[len-1] != '\n')
2845       len--;
2846     mcud->_error->append( desc, len );
2847   }
2848   else if ( mcud->_verbosity > 0 ) {
2849     std::cout << desc << std::endl;
2850   }
2851   return STATUS_OK;
2852 }
2853
2854 /* This is the interrupt callback. PreCAD/BLSurf will call this
2855  * function regularily. See the file meshgems/interrupt.h
2856  */
2857 status_t interrupt_cb(integer *interrupt_status, void *user_data)
2858 {
2859   integer you_want_to_continue = 1;
2860 #ifdef WITH_SMESH_CANCEL_COMPUTE
2861   BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
2862   you_want_to_continue = !tmp->computeCanceled();
2863 #endif
2864
2865   if(you_want_to_continue)
2866   {
2867     *interrupt_status = INTERRUPT_CONTINUE;
2868     return STATUS_OK;
2869   }
2870   else /* you want to stop BLSurf */
2871   {
2872     *interrupt_status = INTERRUPT_STOP;
2873     return STATUS_ERROR;
2874   }
2875 }
2876
2877 //=============================================================================
2878 /*!
2879  *
2880  */
2881 //=============================================================================
2882 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh&         aMesh,
2883                                    const TopoDS_Shape& aShape,
2884                                    MapShapeNbElems&    aResMap)
2885 {
2886   double diagonal       = aMesh.GetShapeDiagonalSize();
2887   double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
2888   int    _physicalMesh  = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
2889   double _phySize       = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
2890   bool   _phySizeRel    = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
2891   //int    _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
2892   double _angleMesh     = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
2893   bool   _quadAllowed   = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
2894   if(_hypothesis) {
2895     _physicalMesh  = (int) _hypothesis->GetPhysicalMesh();
2896     _phySizeRel         = _hypothesis->IsPhySizeRel();
2897     if ( _hypothesis->GetPhySize() > 0)
2898       _phySize          = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
2899     //_geometricMesh = (int) hyp->GetGeometricMesh();
2900     if (_hypothesis->GetAngleMesh() > 0)
2901       _angleMesh        = _hypothesis->GetAngleMesh();
2902     _quadAllowed        = _hypothesis->GetQuadAllowed();
2903   } else {
2904     //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
2905     // GetDefaultPhySize() sometimes leads to computation failure
2906     _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
2907     MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
2908   }
2909
2910   bool IsQuadratic = _quadraticMesh;
2911
2912   // ----------------
2913   // evaluate 1D
2914   // ----------------
2915   TopTools_DataMapOfShapeInteger EdgesMap;
2916   double fullLen = 0.0;
2917   double fullNbSeg = 0;
2918   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
2919     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2920     if( EdgesMap.IsBound(E) )
2921       continue;
2922     SMESH_subMesh *sm = aMesh.GetSubMesh(E);
2923     double aLen = SMESH_Algo::EdgeLength(E);
2924     fullLen += aLen;
2925     int nb1d = 0;
2926     if(_physicalMesh==1) {
2927        nb1d = (int)( aLen/_phySize + 1 );
2928     }
2929     else {
2930       // use geometry
2931       double f,l;
2932       Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
2933       double fullAng = 0.0;
2934       double dp = (l-f)/200;
2935       gp_Pnt P1,P2,P3;
2936       C->D0(f,P1);
2937       C->D0(f+dp,P2);
2938       gp_Vec V1(P1,P2);
2939       for(int j=2; j<=200; j++) {
2940         C->D0(f+dp*j,P3);
2941         gp_Vec V2(P2,P3);
2942         fullAng += fabs(V1.Angle(V2));
2943         V1 = V2;
2944         P2 = P3;
2945       }
2946       nb1d = (int)( fullAng/_angleMesh + 1 );
2947     }
2948     fullNbSeg += nb1d;
2949     std::vector<int> aVec(SMDSEntity_Last);
2950     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2951     if( IsQuadratic > 0 ) {
2952       aVec[SMDSEntity_Node] = 2*nb1d - 1;
2953       aVec[SMDSEntity_Quad_Edge] = nb1d;
2954     }
2955     else {
2956       aVec[SMDSEntity_Node] = nb1d - 1;
2957       aVec[SMDSEntity_Edge] = nb1d;
2958     }
2959     aResMap.insert(std::make_pair(sm,aVec));
2960     EdgesMap.Bind(E,nb1d);
2961   }
2962   double ELen = fullLen/fullNbSeg;
2963   // ----------------
2964   // evaluate 2D
2965   // ----------------
2966   // try to evaluate as in MEFISTO
2967   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
2968     TopoDS_Face F = TopoDS::Face( exp.Current() );
2969     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
2970     GProp_GProps G;
2971     BRepGProp::SurfaceProperties(F,G);
2972     double anArea = G.Mass();
2973     int nb1d = 0;
2974     std::vector<int> nb1dVec;
2975     for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
2976       int nbSeg = EdgesMap.Find(exp1.Current());
2977       nb1d += nbSeg;
2978       nb1dVec.push_back( nbSeg );
2979     }
2980     int nbQuad = 0;
2981     int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
2982     int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
2983     if ( _quadAllowed )
2984     {
2985       if ( nb1dVec.size() == 4 ) // quadrangle geom face
2986       {
2987         int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
2988         nbQuad = n1 * n2;
2989         nbNodes = (n1 + 1) * (n2 + 1);
2990         nbTria = 0;
2991       }
2992       else
2993       {
2994         nbTria = nbQuad = nbTria / 3 + 1;
2995       }
2996     }
2997     std::vector<int> aVec(SMDSEntity_Last,0);
2998     if( IsQuadratic ) {
2999       int nb1d_in = (nbTria*3 - nb1d) / 2;
3000       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3001       aVec[SMDSEntity_Quad_Triangle] = nbTria;
3002       aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3003     }
3004     else {
3005       aVec[SMDSEntity_Node] = nbNodes;
3006       aVec[SMDSEntity_Triangle] = nbTria;
3007       aVec[SMDSEntity_Quadrangle] = nbQuad;
3008     }
3009     aResMap.insert(std::make_pair(sm,aVec));
3010   }
3011
3012   // ----------------
3013   // evaluate 3D
3014   // ----------------
3015   GProp_GProps G;
3016   BRepGProp::VolumeProperties(aShape,G);
3017   double aVolume = G.Mass();
3018   double tetrVol = 0.1179*ELen*ELen*ELen;
3019   int nbVols  = int(aVolume/tetrVol);
3020   int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3021   std::vector<int> aVec(SMDSEntity_Last);
3022   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3023   if( IsQuadratic ) {
3024     aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3025     aVec[SMDSEntity_Quad_Tetra] = nbVols;
3026   }
3027   else {
3028     aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3029     aVec[SMDSEntity_Tetra] = nbVols;
3030   }
3031   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3032   aResMap.insert(std::make_pair(sm,aVec));
3033
3034   return true;
3035 }