Salome HOME
Compute Progress bar
[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     double *      _progress;
1557   };
1558
1559
1560 } // namespace
1561
1562 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1563 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1564                   real *duu, real *duv, real *dvv, void *user_data);
1565 status_t message_cb(message_t *msg, void *user_data);
1566 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1567
1568 //=============================================================================
1569 /*!
1570  *
1571  */
1572 //=============================================================================
1573
1574 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1575
1576   MESSAGE("BLSURFPlugin_BLSURF::Compute");
1577
1578   // Fix problem with locales
1579   Kernel_Utils::Localizer aLocalizer;
1580
1581   if ( !compute( aMesh, aShape ))
1582     return false;
1583
1584   if ( _haveViscousLayers )
1585   {
1586     // Compute viscous layers
1587
1588     TopTools_MapOfShape map;
1589     for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1590     {
1591       const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1592       if ( !map.Add( F )) continue;
1593       SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1594       if ( !viscousMesh )
1595         return false; // error in StdMeshers_ViscousLayers2D::Compute()
1596
1597       // Compute BLSURF mesh on viscous layers
1598
1599       if ( viscousMesh->NbProxySubMeshes() > 0 )
1600       {
1601         TmpMesh tmpMesh;
1602         const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1603         if ( !compute( tmpMesh, proxyFace ))
1604           return false;
1605         tmpMesh.FillInOrigMesh( aMesh, F );
1606       }
1607     }
1608
1609     // Re-compute BLSURF mesh on the rest faces if the mesh was cleared
1610
1611     for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1612     {
1613       const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1614       SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1615       if ( fSM->IsMeshComputed() ) continue;
1616
1617       if ( !compute( aMesh, aShape ))
1618         return false;
1619       break;
1620     }
1621   }
1622   return true;
1623 }
1624
1625 //=============================================================================
1626 /*!
1627  *
1628  */
1629 //=============================================================================
1630
1631 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
1632                                   const TopoDS_Shape& aShape)
1633 {
1634   /* create a distene context (generic object) */
1635   status_t status = STATUS_ERROR;
1636
1637   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1638   SMESH_MesherHelper helper( aMesh );
1639   // do not call helper.IsQuadraticSubMesh() because sub-meshes
1640   // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1641   bool haveQuadraticSubMesh = SMESH_MesherHelper( aMesh ).IsQuadraticSubMesh( aShape );
1642   bool quadraticSubMeshAndViscousLayer = false;
1643   bool needMerge = false;
1644   typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1645   TSubMeshSet edgeSubmeshes;
1646   TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1647
1648   TopTools_IndexedMapOfShape fmap;
1649   TopTools_IndexedMapOfShape emap;
1650   TopTools_IndexedMapOfShape pmap;
1651
1652   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1653 #ifndef WNT
1654   feclearexcept( FE_ALL_EXCEPT );
1655   int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1656 #endif
1657
1658   context_t *ctx =  context_new();
1659
1660   /* Set the message callback in the working context */
1661   message_cb_user_data mcud;
1662   mcud._error     = & this->SMESH_Algo::_comment;
1663   mcud._progress  = & this->SMESH_Algo::_progress;
1664   mcud._verbosity =
1665     _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
1666   context_set_message_callback(ctx, message_cb, &mcud);
1667
1668   /* set the interruption callback */
1669   _compute_canceled = false;
1670   context_set_interrupt_callback(ctx, interrupt_cb, this);
1671
1672   /* create the CAD object we will work on. It is associated to the context ctx. */
1673   cad_t *c     = cad_new(ctx);
1674   dcad_t *dcad = dcad_new(c);
1675
1676   FacesWithSizeMap.Clear();
1677   FaceId2SizeMap.clear();
1678   FaceId2ClassAttractor.clear();
1679   FaceIndex2ClassAttractor.clear();
1680   EdgesWithSizeMap.Clear();
1681   EdgeId2SizeMap.clear();
1682   VerticesWithSizeMap.Clear();
1683   VertexId2SizeMap.clear();
1684
1685   /* Now fill the CAD object with data from your CAD
1686    * environement. This is the most complex part of a successfull
1687    * integration.
1688    */
1689
1690   // PreCAD
1691   // If user requests it, send the CAD through Distene preprocessor : PreCAD
1692   cad_t *cleanc = NULL; // preprocessed cad
1693   precad_session_t *pcs = precad_session_new(ctx);
1694   precad_data_set_cad(pcs, c);
1695
1696   cadsurf_session_t *css = cadsurf_session_new(ctx);
1697
1698   // an object that correctly deletes all cadsurf objects at destruction
1699   BLSURF_Cleaner cleaner( ctx,css,c,dcad );
1700
1701   MESSAGE("BEGIN SetParameters");
1702   bool use_precad = false;
1703   SetParameters(
1704                 // #if BLSURF_VERSION_LONG >= "3.1.1"
1705                 //     c,
1706                 // #endif
1707                 _hypothesis, css, pcs, aShape, &use_precad);
1708   MESSAGE("END SetParameters");
1709
1710   haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
1711   helper.SetIsQuadratic( haveQuadraticSubMesh );
1712
1713   // To remove as soon as quadratic mesh is allowed - BEGIN
1714   // GDD: Viscous layer is not allowed with quadratic mesh
1715   if (_haveViscousLayers && haveQuadraticSubMesh ) {
1716     quadraticSubMeshAndViscousLayer = true;
1717     _haveViscousLayers = !haveQuadraticSubMesh;
1718     _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
1719     error(COMPERR_WARNING, _comment);
1720   }
1721   // To remove as soon as quadratic mesh is allowed - END
1722
1723   // needed to prevent the opencascade memory managmement from freeing things
1724   vector<Handle(Geom2d_Curve)> curves;
1725   vector<Handle(Geom_Surface)> surfaces;
1726
1727   fmap.Clear();
1728   emap.Clear();
1729   pmap.Clear();
1730   FaceId2PythonSmp.clear();
1731   EdgeId2PythonSmp.clear();
1732   VertexId2PythonSmp.clear();
1733
1734   /****************************************************************************************
1735                                           FACES
1736   *****************************************************************************************/
1737   int iface = 0;
1738   string bad_end = "return";
1739   int faceKey = -1;
1740   TopTools_IndexedMapOfShape _map;
1741   TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
1742   int ienf = _map.Extent();
1743
1744   assert(Py_IsInitialized());
1745   PyGILState_STATE gstate;
1746
1747   string theSizeMapStr;
1748
1749   for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1750   {
1751     TopoDS_Face f = TopoDS::Face(face_iter.Current());
1752
1753     // make INTERNAL face oriented FORWARD (issue 0020993)
1754     if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
1755       f.Orientation(TopAbs_FORWARD);
1756
1757     if (fmap.FindIndex(f) > 0)
1758       continue;
1759     iface = fmap.Add(f);
1760
1761     surfaces.push_back(BRep_Tool::Surface(f));
1762
1763     /* create an object representing the face for cadsurf */
1764     /* where face_id is an integer identifying the face.
1765      * surf_function is the function that defines the surface
1766      * (For this face, it will be called by cadsurf with your_face_object_ptr
1767      * as last parameter.
1768      */
1769     cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
1770
1771     /* by default a face has no tag (color).
1772        The following call sets it to the same value as the face_id : */
1773     cad_face_set_tag(fce, iface);
1774
1775     /* Set face orientation (optional if you want a well oriented output mesh)*/
1776     if(f.Orientation() != TopAbs_FORWARD)
1777       cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
1778     else
1779       cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
1780
1781     if (HasSizeMapOnFace && !use_precad)
1782     {
1783       // -----------------
1784       // Classic size map
1785       // -----------------
1786       faceKey = FacesWithSizeMap.FindIndex(f);
1787
1788
1789       if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()) {
1790         MESSAGE("A size map is defined on face :"<<faceKey)
1791           theSizeMapStr = FaceId2SizeMap[faceKey];
1792         // check if function ends with "return"
1793         if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1794           continue;
1795         // Expr To Python function, verification is performed at validation in GUI
1796         gstate = PyGILState_Ensure();
1797         PyObject * obj = NULL;
1798         obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1799         Py_DECREF(obj);
1800         PyObject * func = NULL;
1801         func = PyObject_GetAttrString(main_mod, "f");
1802         FaceId2PythonSmp[iface]=func;
1803         FaceId2SizeMap.erase(faceKey);
1804         PyGILState_Release(gstate);
1805       }
1806
1807       // Specific size map = Attractor
1808       std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
1809
1810       for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
1811         if (attractor_iter->first == faceKey) {
1812           MESSAGE("Face indice: " << iface);
1813           MESSAGE("Adding attractor");
1814
1815           double xyzCoords[3]  = {attractor_iter->second[2],
1816                                   attractor_iter->second[3],
1817                                   attractor_iter->second[4]};
1818
1819           MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1820           gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1821           BRepClass_FaceClassifier scl(f,P,1e-7);
1822           // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
1823           // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1824           // OCC 6.5.2: scl.Perform() is not bugged anymore
1825           scl.Perform(f, P, 1e-7);
1826           TopAbs_State result = scl.State();
1827           MESSAGE("Position of point on face: "<<result);
1828           if ( result == TopAbs_OUT )
1829             MESSAGE("Point is out of face: node is not created");
1830           if ( result == TopAbs_UNKNOWN )
1831             MESSAGE("Point position on face is unknown: node is not created");
1832           if ( result == TopAbs_ON )
1833             MESSAGE("Point is on border of face: node is not created");
1834           if ( result == TopAbs_IN )
1835           {
1836             // Point is inside face and not on border
1837             MESSAGE("Point is in face: node is created");
1838             double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
1839             ienf++;
1840             MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
1841             cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
1842             cad_point_set_tag(point_p, ienf);
1843           }
1844           FaceId2AttractorCoords.erase(faceKey);
1845         }
1846       }
1847
1848       // -----------------
1849       // Class Attractors
1850       // -----------------
1851       std::map<int,BLSURFPlugin_Attractor* >::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
1852       if (clAttractor_iter != FaceId2ClassAttractor.end()){
1853         MESSAGE("Face indice: " << iface);
1854         MESSAGE("Adding attractor");
1855         FaceIndex2ClassAttractor[iface]=clAttractor_iter->second;
1856         FaceId2ClassAttractor.erase(clAttractor_iter);
1857       }
1858     } // if (HasSizeMapOnFace && !use_precad)
1859
1860       // ------------------
1861       // Enforced Vertices
1862       // ------------------
1863     faceKey = FacesWithEnforcedVertices.FindIndex(f);
1864     std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
1865     if (evmIt != FaceId2EnforcedVertexCoords.end()) {
1866       MESSAGE("Some enforced vertices are defined");
1867       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
1868       MESSAGE("Face indice: " << iface);
1869       MESSAGE("Adding enforced vertices");
1870       evl = evmIt->second;
1871       MESSAGE("Number of vertices to add: "<< evl.size());
1872       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
1873       for (; evlIt != evl.end(); ++evlIt) {
1874         BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
1875         xyzCoords.push_back(evlIt->at(2));
1876         xyzCoords.push_back(evlIt->at(3));
1877         xyzCoords.push_back(evlIt->at(4));
1878         MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1879         gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1880         BRepClass_FaceClassifier scl(f,P,1e-7);
1881         // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
1882         // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1883         // OCC 6.5.2: scl.Perform() is not bugged anymore
1884         scl.Perform(f, P, 1e-7);
1885         TopAbs_State result = scl.State();
1886         MESSAGE("Position of point on face: "<<result);
1887         if ( result == TopAbs_OUT ) {
1888           MESSAGE("Point is out of face: node is not created");
1889           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1890             EnfVertexCoords2ProjVertex.erase(xyzCoords);
1891             EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1892           }
1893         }
1894         if ( result == TopAbs_UNKNOWN ) {
1895           MESSAGE("Point position on face is unknown: node is not created");
1896           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1897             EnfVertexCoords2ProjVertex.erase(xyzCoords);
1898             EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1899           }
1900         }
1901         if ( result == TopAbs_ON ) {
1902           MESSAGE("Point is on border of face: node is not created");
1903           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1904             EnfVertexCoords2ProjVertex.erase(xyzCoords);
1905             EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1906           }
1907         }
1908         if ( result == TopAbs_IN )
1909         {
1910           // Point is inside face and not on border
1911           MESSAGE("Point is in face: node is created");
1912           double uvCoords[2]   = {evlIt->at(0),evlIt->at(1)};
1913           ienf++;
1914           MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
1915           cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
1916           int tag = 0;
1917           std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
1918           if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
1919               !enfCoordsIt->second.empty() )
1920           {
1921             // to merge nodes of an INTERNAL vertex belonging to several faces
1922             TopoDS_Vertex     v = (*enfCoordsIt->second.begin())->vertex;
1923             if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
1924             if ( !v.IsNull() ) {
1925               tag = pmap.Add( v );
1926               SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
1927               vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1928               mergeSubmeshes.insert( vSM->GetSubMeshDS() );
1929               //if ( tag != pmap.Extent() )
1930               needMerge = true;
1931             }
1932           }
1933           if ( tag == 0 ) tag = ienf;
1934           cad_point_set_tag(point_p, tag);
1935         }
1936       }
1937       FaceId2EnforcedVertexCoords.erase(faceKey);
1938
1939     }
1940
1941     /****************************************************************************************
1942                                            EDGES
1943                         now create the edges associated to this face
1944     *****************************************************************************************/
1945     int edgeKey = -1;
1946     for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next())
1947     {
1948       TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
1949       int ic = emap.FindIndex(e);
1950       if (ic <= 0)
1951         ic = emap.Add(e);
1952
1953       double tmin,tmax;
1954       curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
1955
1956       if (HasSizeMapOnEdge){
1957         edgeKey = EdgesWithSizeMap.FindIndex(e);
1958         if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
1959           MESSAGE("Sizemap defined on edge with index " << edgeKey);
1960           theSizeMapStr = EdgeId2SizeMap[edgeKey];
1961           if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1962             continue;
1963           // Expr To Python function, verification is performed at validation in GUI
1964           gstate = PyGILState_Ensure();
1965           PyObject * obj = NULL;
1966           obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1967           Py_DECREF(obj);
1968           PyObject * func = NULL;
1969           func = PyObject_GetAttrString(main_mod, "f");
1970           EdgeId2PythonSmp[ic]=func;
1971           EdgeId2SizeMap.erase(edgeKey);
1972           PyGILState_Release(gstate);
1973         }
1974       }
1975       /* data of nodes existing on the edge */
1976       StdMeshers_FaceSidePtr nodeData;
1977       SMESH_subMesh* sm = aMesh.GetSubMesh( e );
1978       if ( !sm->IsEmpty() )
1979       {
1980         SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
1981                                                                      /*complexFirst=*/false);
1982         while ( subsmIt->more() )
1983           edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
1984
1985         nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
1986                                                  /*ignoreMedium=*/haveQuadraticSubMesh));
1987         if ( nodeData->MissVertexNode() )
1988           return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
1989
1990         const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
1991         if ( !nodeDataVec.empty() )
1992         {
1993           if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
1994           {
1995             nodeData->Reverse();
1996             nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
1997           }
1998           // tmin and tmax can change in case of viscous layer on an adjacent edge
1999           tmin = nodeDataVec.front().param;
2000           tmax = nodeDataVec.back().param;
2001         }
2002         else
2003         {
2004           cout << "---------------- Invalid nodeData" << endl;
2005           nodeData.reset();
2006         }
2007       }
2008
2009       /* attach the edge to the current cadsurf face */
2010       cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
2011
2012       /* by default an edge has no tag (color).
2013          The following call sets it to the same value as the edge_id : */
2014       cad_edge_set_tag(edg, ic);
2015
2016       /* by default, an edge does not necessalry appear in the resulting mesh,
2017          unless the following property is set :
2018       */
2019       cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2020
2021       /* by default an edge is a boundary edge */
2022       if (e.Orientation() == TopAbs_INTERNAL)
2023         cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2024
2025       // pass existing nodes of sub-meshes to BLSURF
2026       if ( nodeData )
2027       {
2028         const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2029         const int                      nbNodes     = nodeDataVec.size();
2030
2031         dcad_edge_discretization_t *dedge;
2032         dcad_get_edge_discretization(dcad, edg, &dedge);
2033         dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2034
2035         // cout << endl << " EDGE " << ic << endl;
2036         // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2037         for ( int iN = 0; iN < nbNodes; ++iN )
2038         {
2039           const UVPtStruct& nData = nodeDataVec[ iN ];
2040           double t                = nData.param;
2041           real uv[2]              = { nData.u, nData.v };
2042           SMESH_TNodeXYZ nXYZ( nData.node );
2043           // cout << "\tt = " << t
2044           //      << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2045           //      << "\t u = " << nData.param
2046           //      << "\t ID = " << nData.node->GetID() << endl;
2047           dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ._xyz );
2048         }
2049         dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2050       }
2051
2052       /****************************************************************************************
2053                                       VERTICES
2054       *****************************************************************************************/
2055
2056       int npts = 0;
2057       int ip1, ip2, *ip;
2058       gp_Pnt2d e0 = curves.back()->Value(tmin);
2059       gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
2060       Standard_Real d1=0,d2=0;
2061
2062       int vertexKey = -1;
2063       for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
2064         TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
2065         ++npts;
2066         if (npts == 1){
2067           ip = &ip1;
2068           d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2069         } else {
2070           ip = &ip2;
2071           d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2072         }
2073         *ip = pmap.FindIndex(v);
2074         if(*ip <= 0) {
2075           *ip = pmap.Add(v);
2076           SMESH_subMesh* sm = aMesh.GetSubMesh(v);
2077           if ( sm->IsMeshComputed() )
2078             edgeSubmeshes.insert( sm->GetSubMeshDS() );
2079         }
2080         if (HasSizeMapOnVertex){
2081           vertexKey = VerticesWithSizeMap.FindIndex(v);
2082           if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
2083             theSizeMapStr = VertexId2SizeMap[vertexKey];
2084             //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
2085             if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2086               continue;
2087             // Expr To Python function, verification is performed at validation in GUI
2088             PyObject * obj = NULL;
2089             obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2090             Py_DECREF(obj);
2091             PyObject * func = NULL;
2092             func = PyObject_GetAttrString(main_mod, "f");
2093             VertexId2PythonSmp[*ip]=func;
2094             VertexId2SizeMap.erase(vertexKey);   // do not erase if using a vector
2095           }
2096         }
2097       }
2098       if (npts != 2) {
2099         // should not happen
2100         MESSAGE("An edge does not have 2 extremities.");
2101       } else {
2102         if (d1 < d2) {
2103           // This defines the curves extremity connectivity
2104           cad_edge_set_extremities(edg, ip1, ip2);
2105           /* set the tag (color) to the same value as the extremity id : */
2106           cad_edge_set_extremities_tag(edg, ip1, ip2);
2107         }
2108         else {
2109           cad_edge_set_extremities(edg, ip2, ip1);
2110           cad_edge_set_extremities_tag(edg, ip2, ip1);
2111         }
2112       }
2113     } // for edge
2114   } //for face
2115
2116   // Clear mesh from already meshed edges if possible else
2117   // remember that merge is needed
2118   TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2119   for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2120   {
2121     SMESHDS_SubMesh* smDS = *smIt;
2122     if ( !smDS ) continue;
2123     SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2124     if ( nIt->more() )
2125     {
2126       const SMDS_MeshNode* n = nIt->next();
2127       if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2128       {
2129         needMerge = true;
2130         // add existing medium nodes to helper
2131         if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2132         {
2133           SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2134           while ( edgeIt->more() )
2135             helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2136         }
2137         continue;
2138       }
2139     }
2140     {
2141       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2142       while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), smDS );
2143       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2144       while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), smDS );
2145     }
2146   }
2147
2148
2149   if (use_precad) {
2150     /* Now launch the PreCAD process */
2151     status = precad_process(pcs);
2152     if(status != STATUS_OK){
2153       cout << "PreCAD processing failed with error code " << status << "\n";
2154     }
2155     else {
2156       // retrieve the pre-processed CAD object
2157       cleanc = precad_new_cad(pcs);
2158       if(!cleanc){
2159         cout << "Unable to retrieve PreCAD result \n";
2160       }
2161       cout << "PreCAD processing successfull \n";
2162
2163       // #if BLSURF_VERSION_LONG >= "3.1.1"
2164       //       /* We can now get the updated sizemaps (if any) */
2165       // //       if(geo_sizemap_e)
2166       // //         clean_geo_sizemap_e = precad_new_sizemap(pcs, geo_sizemap_e);
2167       // // 
2168       // //       if(geo_sizemap_f)
2169       // //         clean_geo_sizemap_f = precad_new_sizemap(pcs, geo_sizemap_f);
2170       //
2171       //       if(iso_sizemap_p)
2172       //         clean_iso_sizemap_p = precad_new_sizemap(pcs, iso_sizemap_p);
2173       //
2174       //       if(iso_sizemap_e)
2175       //         clean_iso_sizemap_e = precad_new_sizemap(pcs, iso_sizemap_e);
2176       //
2177       //       if(iso_sizemap_f)
2178       //         clean_iso_sizemap_f = precad_new_sizemap(pcs, iso_sizemap_f);
2179       // #endif
2180     }
2181     // Now we can delete the PreCAD session
2182     precad_session_delete(pcs);
2183   }
2184
2185   cadsurf_data_set_dcad(css, dcad);
2186   if (cleanc) {
2187     // Give the pre-processed CAD object to the current BLSurf session
2188     cadsurf_data_set_cad(css, cleanc);
2189   }
2190   else {
2191     // Use the original one
2192     cadsurf_data_set_cad(css, c);
2193   }
2194
2195   std::cout << std::endl;
2196   std::cout << "Beginning of Surface Mesh generation" << std::endl;
2197   std::cout << std::endl;
2198
2199   try {
2200     OCC_CATCH_SIGNALS;
2201
2202     status = cadsurf_compute_mesh(css);
2203
2204   }
2205   catch ( std::exception& exc ) {
2206     _comment += exc.what();
2207   }
2208   catch (Standard_Failure& ex) {
2209     _comment += ex.DynamicType()->Name();
2210     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2211       _comment += ": ";
2212       _comment += ex.GetMessageString();
2213     }
2214   }
2215   catch (...) {
2216     if ( _comment.empty() )
2217       _comment = "Exception in cadsurf_compute_mesh()";
2218   }
2219   if ( status != STATUS_OK) {
2220     // There was an error while meshing
2221     error(_comment);
2222   }
2223
2224   std::cout << std::endl;
2225   std::cout << "End of Surface Mesh generation" << std::endl;
2226   std::cout << std::endl;
2227
2228   mesh_t *msh = NULL;
2229   cadsurf_data_get_mesh(css, &msh);
2230   if(!msh){
2231     /* release the mesh object */
2232     cadsurf_data_regain_mesh(css, msh);
2233     return error(_comment);
2234   }
2235
2236   std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2237   if (_hypothesis)
2238     GMFFileName = _hypothesis->GetGMFFile();
2239   if (GMFFileName != "") {
2240     //     bool GMFFileMode = _hypothesis->GetGMFFileMode();
2241     bool asciiFound = (GMFFileName.find(".mesh",GMFFileName.length()-5) != std::string::npos);
2242     bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2243     if (!asciiFound && !binaryFound)
2244       GMFFileName.append(".mesh");
2245     mesh_write_mesh(msh, GMFFileName.c_str());
2246   }
2247
2248   /* retrieve mesh data (see meshgems/mesh.h) */
2249   integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2250   integer *evedg, *evtri, *evquad, *tags_buff, type;
2251   real xyz[3];
2252
2253   mesh_get_vertex_count(msh, &nv);
2254   mesh_get_edge_count(msh, &ne);
2255   mesh_get_triangle_count(msh, &nt);
2256   mesh_get_quadrangle_count(msh, &nq);
2257
2258   evedg  = (integer *)mesh_calloc_generic_buffer(msh);
2259   evtri  = (integer *)mesh_calloc_generic_buffer(msh);
2260   evquad = (integer *)mesh_calloc_generic_buffer(msh);
2261   tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
2262
2263   SMDS_MeshNode** nodes = new SMDS_MeshNode*[nv+1];
2264   bool* tags = new bool[nv+1];
2265
2266   /* enumerated vertices */
2267   for(int iv=1;iv<=nv;iv++) {
2268     mesh_get_vertex_coordinates(msh, iv, xyz);
2269     mesh_get_vertex_tag(msh, iv, &tag);
2270     // Issue 0020656. Use vertex coordinates
2271     if ( tag > 0 && tag <= pmap.Extent() ) {
2272       TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2273       double tol = BRep_Tool::Tolerance( v );
2274       gp_Pnt p = BRep_Tool::Pnt( v );
2275       if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
2276         xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2277       else
2278         tag = 0; // enforced or attracted vertex
2279     }
2280     nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2281
2282     // Create group of enforced vertices if requested
2283     BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2284     projVertex.clear();
2285     projVertex.push_back((double)xyz[0]);
2286     projVertex.push_back((double)xyz[1]);
2287     projVertex.push_back((double)xyz[2]);
2288     std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
2289     if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
2290       MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
2291       BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
2292       BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
2293       for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
2294         currentEnfVertex = (*enfListIt);
2295         if (currentEnfVertex->grpName != "") {
2296           bool groupDone = false;
2297           SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
2298           MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
2299           MESSAGE("Parsing the groups of the mesh");
2300           while (grIt->more()) {
2301             SMESH_Group * group = grIt->next();
2302             if ( !group ) continue;
2303             MESSAGE("Group: " << group->GetName());
2304             SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2305             if ( !groupDS ) continue;
2306             MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
2307             MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
2308             MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
2309             if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
2310               SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
2311               aGroupDS->SMDSGroup().Add(nodes[iv]);
2312               MESSAGE("Node ID: " << nodes[iv]->GetID());
2313               // How can I inform the hypothesis ?
2314               //                 _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
2315               groupDone = true;
2316               MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
2317               break;
2318             }
2319           }
2320           if (!groupDone)
2321           {
2322             int groupId;
2323             SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
2324             aGroup->SetName( currentEnfVertex->grpName.c_str() );
2325             SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2326             aGroupDS->SMDSGroup().Add(nodes[iv]);
2327             MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
2328             groupDone = true;
2329           }
2330           if (!groupDone)
2331             throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
2332         }
2333         else
2334           MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
2335       }
2336     }
2337
2338     // internal points are tagged to zero
2339     if(tag > 0 && tag <= pmap.Extent() ){
2340       meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2341       tags[iv] = false;
2342     } else {
2343       tags[iv] = true;
2344     }
2345   }
2346
2347   /* enumerate edges */
2348   for(int it=1;it<=ne;it++) {
2349     SMDS_MeshEdge* edg;
2350     mesh_get_edge_vertices(msh, it, vtx);
2351     mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2352     mesh_get_edge_tag(msh, it, &tag);
2353
2354     // If PreCAD performed some cleaning operations (remove tiny edges,
2355     // merge edges ...) an output tag can indeed represent several original tags.
2356     // Get the initial tags corresponding to the output tag and redefine the tag as 
2357     // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2358     mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2359     if(nb_tag > 1)  
2360       tag=tags_buff[nb_tag-1]; 
2361
2362     if (tags[vtx[0]]) {
2363       Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2364       tags[vtx[0]] = false;
2365     };
2366     if (tags[vtx[1]]) {
2367       Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2368       tags[vtx[1]] = false;
2369     };
2370     if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2371       // QUADRATIC EDGE
2372       if (tags[evedg[0]]) {
2373         Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2374         tags[evedg[0]] = false;
2375       }
2376       edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2377     }
2378     else {
2379       edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2380     }
2381     meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2382   }
2383
2384   /* enumerate triangles */
2385   for(int it=1;it<=nt;it++) {
2386     SMDS_MeshFace* tri;
2387     mesh_get_triangle_vertices(msh, it, vtx);
2388     mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2389     mesh_get_triangle_tag(msh, it, &tag);
2390     if (tags[vtx[0]]) {
2391       meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
2392       tags[vtx[0]] = false;
2393     };
2394     if (tags[vtx[1]]) {
2395       meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
2396       tags[vtx[1]] = false;
2397     };
2398     if (tags[vtx[2]]) {
2399       meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
2400       tags[vtx[2]] = false;
2401     };
2402     if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2403       // QUADRATIC TRIANGLE
2404       if (tags[evtri[0]]) {
2405         meshDS->SetNodeOnFace(nodes[evtri[0]], TopoDS::Face(fmap(tag)));
2406         tags[evtri[0]] = false;
2407       }
2408       if (tags[evtri[1]]) {
2409         meshDS->SetNodeOnFace(nodes[evtri[1]], TopoDS::Face(fmap(tag)));
2410         tags[evtri[1]] = false;
2411       }
2412       if (tags[evtri[2]]) {
2413         meshDS->SetNodeOnFace(nodes[evtri[2]], TopoDS::Face(fmap(tag)));
2414         tags[evtri[2]] = false;
2415       }
2416       tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2417                             nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2418     }
2419     else {
2420       tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2421     }
2422     meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
2423   }
2424
2425   /* enumerate quadrangles */
2426   for(int it=1;it<=nq;it++) {
2427     SMDS_MeshFace* quad;
2428     mesh_get_quadrangle_vertices(msh, it, vtx);
2429     mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2430     mesh_get_quadrangle_tag(msh, it, &tag);
2431     if (tags[vtx[0]]) {
2432       meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
2433       tags[vtx[0]] = false;
2434     };
2435     if (tags[vtx[1]]) {
2436       meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
2437       tags[vtx[1]] = false;
2438     };
2439     if (tags[vtx[2]]) {
2440       meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
2441       tags[vtx[2]] = false;
2442     };
2443     if (tags[vtx[3]]) {
2444       meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
2445       tags[vtx[3]] = false;
2446     };
2447     if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
2448       // QUADRATIC QUADRANGLE
2449       std::cout << "This is a quadratic quadrangle" << std::endl;
2450       if (tags[evquad[0]]) {
2451         meshDS->SetNodeOnFace(nodes[evquad[0]], TopoDS::Face(fmap(tag)));
2452         tags[evquad[0]] = false;
2453       }
2454       if (tags[evquad[1]]) {
2455         meshDS->SetNodeOnFace(nodes[evquad[1]], TopoDS::Face(fmap(tag)));
2456         tags[evquad[1]] = false;
2457       }
2458       if (tags[evquad[2]]) {
2459         meshDS->SetNodeOnFace(nodes[evquad[2]], TopoDS::Face(fmap(tag)));
2460         tags[evquad[2]] = false;
2461       }
2462       if (tags[evquad[3]]) {
2463         meshDS->SetNodeOnFace(nodes[evquad[3]], TopoDS::Face(fmap(tag)));
2464         tags[evquad[3]] = false;
2465       }
2466       if (tags[evquad[4]]) {
2467         meshDS->SetNodeOnFace(nodes[evquad[4]], TopoDS::Face(fmap(tag)));
2468         tags[evquad[4]] = false;
2469       }
2470       quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
2471                              nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
2472                              nodes[evquad[4]]);
2473     }
2474     else {
2475       quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
2476     }
2477     meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
2478   }
2479
2480   /* release the mesh object, the rest is released by cleaner */
2481   cadsurf_data_regain_mesh(css, msh);
2482
2483   delete [] nodes;
2484   delete [] tags;
2485
2486   if ( needMerge ) // sew mesh computed by BLSURF with pre-existing mesh
2487   {
2488     SMESH_MeshEditor editor( &aMesh );
2489     SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
2490     TIDSortedElemSet segementsOnEdge;
2491     TIDSortedNodeSet nodesOnEdge;
2492     TSubMeshSet::iterator smIt;
2493     SMESHDS_SubMesh* smDS;
2494     typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_NodeIteratorPtr > TNodeIterator;
2495     double tol;
2496
2497     // merge nodes on EDGE's with ones computed by BLSURF
2498     for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
2499     {
2500       if (! (smDS = *smIt) ) continue;
2501       getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
2502
2503       SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2504       while ( segIt->more() )
2505         segementsOnEdge.insert( segIt->next() );
2506     }
2507     // merge nodes
2508     editor.MergeNodes( nodeGroupsToMerge );
2509
2510     // merge segments
2511     SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
2512     editor.FindEqualElements( segementsOnEdge, equalSegments );
2513     editor.MergeElements( equalSegments );
2514
2515     // remove excess segments created on the boundary of viscous layers
2516     const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
2517     for ( int i = 1; i <= emap.Extent(); ++i )
2518     {
2519       if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
2520       {
2521         SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2522         while ( segIt->more() )
2523         {
2524           const SMDS_MeshElement* seg = segIt->next();
2525           if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
2526                seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
2527             meshDS->RemoveFreeElement( seg, smDS );
2528         }
2529       }
2530     }
2531   }
2532
2533   // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
2534   TopLoc_Location loc; double f,l;
2535   for (int i = 1; i <= emap.Extent(); i++)
2536     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
2537       sm->SetIsAlwaysComputed( true );
2538   for (int i = 1; i <= pmap.Extent(); i++)
2539     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
2540       if ( !sm->IsMeshComputed() )
2541         sm->SetIsAlwaysComputed( true );
2542
2543   // Set error to FACE's w/o elements
2544   for ( int i = 1; i <= fmap.Extent(); ++i )
2545   {
2546     SMESH_subMesh* sm = aMesh.GetSubMesh( fmap(i) );
2547     if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
2548       sm->GetComputeError().reset
2549         ( new SMESH_ComputeError( COMPERR_ALGO_FAILED, _comment, this ));
2550   }
2551
2552   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
2553 #ifndef WNT
2554   if ( oldFEFlags > 0 )
2555     feenableexcept( oldFEFlags );
2556   feclearexcept( FE_ALL_EXCEPT );
2557 #endif
2558
2559   /*
2560     std::cout << "FacesWithSizeMap" << std::endl;
2561     FacesWithSizeMap.Statistics(std::cout);
2562     std::cout << "EdgesWithSizeMap" << std::endl;
2563     EdgesWithSizeMap.Statistics(std::cout);
2564     std::cout << "VerticesWithSizeMap" << std::endl;
2565     VerticesWithSizeMap.Statistics(std::cout);
2566     std::cout << "FacesWithEnforcedVertices" << std::endl;
2567     FacesWithEnforcedVertices.Statistics(std::cout);
2568   */
2569
2570   MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
2571   return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
2572 }
2573
2574 //================================================================================
2575 /*!
2576  * \brief Terminates computation
2577  */
2578 //================================================================================
2579
2580 #ifdef WITH_SMESH_CANCEL_COMPUTE
2581 void BLSURFPlugin_BLSURF::CancelCompute()
2582 {
2583   _compute_canceled = true;
2584 }
2585 #endif
2586
2587 //=============================================================================
2588 /*!
2589  *  SetNodeOnEdge
2590  */
2591 //=============================================================================
2592
2593 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* node, const TopoDS_Shape& ed) {
2594   const TopoDS_Edge edge = TopoDS::Edge(ed);
2595
2596   gp_Pnt pnt(node->X(), node->Y(), node->Z());
2597
2598   Standard_Real p0 = 0.0;
2599   Standard_Real p1 = 1.0;
2600   TopLoc_Location loc;
2601   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
2602
2603   if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
2604   GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
2605
2606   double pa = 0.;
2607   if ( proj.NbPoints() > 0 )
2608   {
2609     pa = (double)proj.LowerDistanceParameter();
2610     // Issue 0020656. Move node if it is too far from edge
2611     gp_Pnt curve_pnt = curve->Value( pa );
2612     double dist2     = pnt.SquareDistance( curve_pnt );
2613     double tol       = BRep_Tool::Tolerance( edge );
2614     if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
2615     {
2616       curve_pnt.Transform( loc );
2617       meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
2618     }
2619   }
2620 //   GProp_GProps LProps;
2621 //   BRepGProp::LinearProperties(ed, LProps);
2622 //   double lg = (double)LProps.Mass();
2623
2624   meshDS->SetNodeOnEdge(node, edge, pa);
2625 }
2626
2627 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
2628  * more information.
2629  * NOTE : if when your CAD systems evaluates second
2630  * order derivatives it also computes first order derivatives and
2631  * function evaluation, you can optimize this example by making only
2632  * one CAD call and filling the necessary uv, dt, dtt arrays.
2633  */
2634 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
2635 {
2636   /* t is given. It contains the t (time) 1D parametric coordintaes
2637      of the point PreCAD/BLSurf is querying on the curve */
2638
2639   /* user_data identifies the edge PreCAD/BLSurf is querying
2640    * (see cad_edge_new later in this example) */
2641   const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
2642
2643   if (uv){
2644    /* BLSurf is querying the function evaluation */
2645     gp_Pnt2d P;
2646     P=pargeo->Value(t);
2647     uv[0]=P.X(); uv[1]=P.Y();
2648   }
2649
2650   if(dt) {
2651    /* query for the first order derivatives */
2652     gp_Vec2d V1;
2653     V1=pargeo->DN(t,1);
2654     dt[0]=V1.X(); dt[1]=V1.Y();
2655   }
2656
2657   if(dtt){
2658     /* query for the second order derivatives */
2659     gp_Vec2d V2;
2660     V2=pargeo->DN(t,2);
2661     dtt[0]=V2.X(); dtt[1]=V2.Y();
2662   }
2663
2664   return STATUS_OK;
2665 }
2666
2667 /* Surface definition function.
2668  * See cad_surf_t in file meshgems/cad.h for more information.
2669  * NOTE : if when your CAD systems evaluates second order derivatives it also
2670  * computes first order derivatives and function evaluation, you can optimize
2671  * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
2672  * arrays.
2673  */
2674 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
2675                   real *duu, real *duv, real *dvv, void *user_data)
2676 {
2677   /* uv[2] is given. It contains the u,v coordinates of the point
2678    * PreCAD/BLSurf is querying on the surface */
2679
2680   /* user_data identifies the face PreCAD/BLSurf is querying (see
2681    * cad_face_new later in this example)*/
2682   const Geom_Surface* geometry = (const Geom_Surface*) user_data;
2683
2684   if(xyz){
2685    gp_Pnt P;
2686    P=geometry->Value(uv[0],uv[1]);   // S.D0(U,V,P);
2687    xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
2688   }
2689
2690   if(du && dv){
2691     gp_Pnt P;
2692     gp_Vec D1U,D1V;
2693
2694     geometry->D1(uv[0],uv[1],P,D1U,D1V);
2695     du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
2696     dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
2697   }
2698
2699   if(duu && duv && dvv){
2700
2701     gp_Pnt P;
2702     gp_Vec D1U,D1V;
2703     gp_Vec D2U,D2V,D2UV;
2704
2705     geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
2706     duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
2707     duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
2708     dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
2709   }
2710
2711   return STATUS_OK;
2712 }
2713
2714
2715 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
2716 {
2717   //MESSAGE("size_on_surface")
2718   if (FaceId2PythonSmp.count(face_id) != 0){
2719     //MESSAGE("A size map is used to calculate size on face : "<<face_id)
2720     PyObject * pyresult = NULL;
2721     PyObject* new_stderr = NULL;
2722     assert(Py_IsInitialized());
2723     PyGILState_STATE gstate;
2724     gstate = PyGILState_Ensure();
2725     pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
2726     real result;
2727     if ( pyresult != NULL) {
2728       result = PyFloat_AsDouble(pyresult);
2729       Py_DECREF(pyresult);
2730 //       *size = result;
2731     }
2732     else{
2733       fflush(stderr);
2734       string err_description="";
2735       new_stderr = newPyStdOut(err_description);
2736       PySys_SetObject((char*)"stderr", new_stderr);
2737       PyErr_Print();
2738       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2739       Py_DECREF(new_stderr);
2740       MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
2741       result = *((real*)user_data);
2742     }
2743     *size = result;
2744     PyGILState_Release(gstate);
2745   }
2746   else if (FaceIndex2ClassAttractor.count(face_id) !=0 && !FaceIndex2ClassAttractor[face_id]->Empty()){
2747 //    MESSAGE("attractor used on face :"<<face_id)
2748     // MESSAGE("List of attractor is not empty")
2749     // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
2750     real result = FaceIndex2ClassAttractor[face_id]->GetSize(uv[0],uv[1]);
2751     *size = result;
2752   }
2753   else {
2754     // MESSAGE("List of attractor is empty !!!")
2755     *size = *((real*)user_data);
2756   }
2757 //   std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
2758   return STATUS_OK;
2759 }
2760
2761 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
2762 {
2763   if (EdgeId2PythonSmp.count(edge_id) != 0){
2764     PyObject * pyresult = NULL;
2765     PyObject* new_stderr = NULL;
2766     assert(Py_IsInitialized());
2767     PyGILState_STATE gstate;
2768     gstate = PyGILState_Ensure();
2769     pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
2770     real result;
2771     if ( pyresult != NULL) {
2772       result = PyFloat_AsDouble(pyresult);
2773       Py_DECREF(pyresult);
2774 //       *size = result;
2775     }
2776     else{
2777       fflush(stderr);
2778       string err_description="";
2779       new_stderr = newPyStdOut(err_description);
2780       PySys_SetObject((char*)"stderr", new_stderr);
2781       PyErr_Print();
2782       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2783       Py_DECREF(new_stderr);
2784       MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
2785       result = *((real*)user_data);
2786     }
2787     *size = result;
2788     PyGILState_Release(gstate);
2789   }
2790   else {
2791     *size = *((real*)user_data);
2792   }
2793   return STATUS_OK;
2794 }
2795
2796 status_t size_on_vertex(integer point_id, real *size, void *user_data)
2797 {
2798   if (VertexId2PythonSmp.count(point_id) != 0){
2799     PyObject * pyresult = NULL;
2800     PyObject* new_stderr = NULL;
2801     assert(Py_IsInitialized());
2802     PyGILState_STATE gstate;
2803     gstate = PyGILState_Ensure();
2804     pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
2805     real result;
2806     if ( pyresult != NULL) {
2807       result = PyFloat_AsDouble(pyresult);
2808       Py_DECREF(pyresult);
2809 //       *size = result;
2810     }
2811     else {
2812       fflush(stderr);
2813       string err_description="";
2814       new_stderr = newPyStdOut(err_description);
2815       PySys_SetObject((char*)"stderr", new_stderr);
2816       PyErr_Print();
2817       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2818       Py_DECREF(new_stderr);
2819       MESSAGE("Can't evaluate f()" << " error is " << err_description);
2820       result = *((real*)user_data);
2821     }
2822     *size = result;
2823     PyGILState_Release(gstate);
2824   }
2825   else {
2826     *size = *((real*)user_data);
2827   }
2828  return STATUS_OK;
2829 }
2830
2831 /*
2832  * The following function will be called for PreCAD/BLSurf message
2833  * printing.  See context_set_message_callback (later in this
2834  * template) for how to set user_data.
2835  */
2836 status_t message_cb(message_t *msg, void *user_data)
2837 {
2838   integer errnumber = 0;
2839   char *desc;
2840   message_get_number(msg, &errnumber);
2841   message_get_description(msg, &desc);
2842   string err( desc );
2843   message_cb_user_data * mcud = (message_cb_user_data*)user_data;
2844   if ( errnumber < 0 || err.find("license") != string::npos ) {
2845     // remove ^A from the tail
2846     int len = strlen( desc );
2847     while (len > 0 && desc[len-1] != '\n')
2848       len--;
2849     mcud->_error->append( desc, len );
2850   }
2851   else {
2852     if ( errnumber == 3009001 )
2853       * mcud->_progress = atof( desc + 11 ) / 100.;
2854     if ( mcud->_verbosity > 0 )
2855       std::cout << desc << std::endl;
2856   }
2857   return STATUS_OK;
2858 }
2859
2860 /* This is the interrupt callback. PreCAD/BLSurf will call this
2861  * function regularily. See the file meshgems/interrupt.h
2862  */
2863 status_t interrupt_cb(integer *interrupt_status, void *user_data)
2864 {
2865   integer you_want_to_continue = 1;
2866 #ifdef WITH_SMESH_CANCEL_COMPUTE
2867   BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
2868   you_want_to_continue = !tmp->computeCanceled();
2869 #endif
2870
2871   if(you_want_to_continue)
2872   {
2873     *interrupt_status = INTERRUPT_CONTINUE;
2874     return STATUS_OK;
2875   }
2876   else /* you want to stop BLSurf */
2877   {
2878     *interrupt_status = INTERRUPT_STOP;
2879     return STATUS_ERROR;
2880   }
2881 }
2882
2883 //=============================================================================
2884 /*!
2885  *
2886  */
2887 //=============================================================================
2888 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh&         aMesh,
2889                                    const TopoDS_Shape& aShape,
2890                                    MapShapeNbElems&    aResMap)
2891 {
2892   double diagonal       = aMesh.GetShapeDiagonalSize();
2893   double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
2894   int    _physicalMesh  = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
2895   double _phySize       = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
2896   bool   _phySizeRel    = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
2897   //int    _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
2898   double _angleMesh     = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
2899   bool   _quadAllowed   = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
2900   if(_hypothesis) {
2901     _physicalMesh  = (int) _hypothesis->GetPhysicalMesh();
2902     _phySizeRel         = _hypothesis->IsPhySizeRel();
2903     if ( _hypothesis->GetPhySize() > 0)
2904       _phySize          = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
2905     //_geometricMesh = (int) hyp->GetGeometricMesh();
2906     if (_hypothesis->GetAngleMesh() > 0)
2907       _angleMesh        = _hypothesis->GetAngleMesh();
2908     _quadAllowed        = _hypothesis->GetQuadAllowed();
2909   } else {
2910     //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
2911     // GetDefaultPhySize() sometimes leads to computation failure
2912     _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
2913     MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
2914   }
2915
2916   bool IsQuadratic = _quadraticMesh;
2917
2918   // ----------------
2919   // evaluate 1D
2920   // ----------------
2921   TopTools_DataMapOfShapeInteger EdgesMap;
2922   double fullLen = 0.0;
2923   double fullNbSeg = 0;
2924   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
2925     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2926     if( EdgesMap.IsBound(E) )
2927       continue;
2928     SMESH_subMesh *sm = aMesh.GetSubMesh(E);
2929     double aLen = SMESH_Algo::EdgeLength(E);
2930     fullLen += aLen;
2931     int nb1d = 0;
2932     if(_physicalMesh==1) {
2933        nb1d = (int)( aLen/_phySize + 1 );
2934     }
2935     else {
2936       // use geometry
2937       double f,l;
2938       Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
2939       double fullAng = 0.0;
2940       double dp = (l-f)/200;
2941       gp_Pnt P1,P2,P3;
2942       C->D0(f,P1);
2943       C->D0(f+dp,P2);
2944       gp_Vec V1(P1,P2);
2945       for(int j=2; j<=200; j++) {
2946         C->D0(f+dp*j,P3);
2947         gp_Vec V2(P2,P3);
2948         fullAng += fabs(V1.Angle(V2));
2949         V1 = V2;
2950         P2 = P3;
2951       }
2952       nb1d = (int)( fullAng/_angleMesh + 1 );
2953     }
2954     fullNbSeg += nb1d;
2955     std::vector<int> aVec(SMDSEntity_Last);
2956     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2957     if( IsQuadratic > 0 ) {
2958       aVec[SMDSEntity_Node] = 2*nb1d - 1;
2959       aVec[SMDSEntity_Quad_Edge] = nb1d;
2960     }
2961     else {
2962       aVec[SMDSEntity_Node] = nb1d - 1;
2963       aVec[SMDSEntity_Edge] = nb1d;
2964     }
2965     aResMap.insert(std::make_pair(sm,aVec));
2966     EdgesMap.Bind(E,nb1d);
2967   }
2968   double ELen = fullLen/fullNbSeg;
2969   // ----------------
2970   // evaluate 2D
2971   // ----------------
2972   // try to evaluate as in MEFISTO
2973   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
2974     TopoDS_Face F = TopoDS::Face( exp.Current() );
2975     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
2976     GProp_GProps G;
2977     BRepGProp::SurfaceProperties(F,G);
2978     double anArea = G.Mass();
2979     int nb1d = 0;
2980     std::vector<int> nb1dVec;
2981     for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
2982       int nbSeg = EdgesMap.Find(exp1.Current());
2983       nb1d += nbSeg;
2984       nb1dVec.push_back( nbSeg );
2985     }
2986     int nbQuad = 0;
2987     int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
2988     int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
2989     if ( _quadAllowed )
2990     {
2991       if ( nb1dVec.size() == 4 ) // quadrangle geom face
2992       {
2993         int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
2994         nbQuad = n1 * n2;
2995         nbNodes = (n1 + 1) * (n2 + 1);
2996         nbTria = 0;
2997       }
2998       else
2999       {
3000         nbTria = nbQuad = nbTria / 3 + 1;
3001       }
3002     }
3003     std::vector<int> aVec(SMDSEntity_Last,0);
3004     if( IsQuadratic ) {
3005       int nb1d_in = (nbTria*3 - nb1d) / 2;
3006       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3007       aVec[SMDSEntity_Quad_Triangle] = nbTria;
3008       aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3009     }
3010     else {
3011       aVec[SMDSEntity_Node] = nbNodes;
3012       aVec[SMDSEntity_Triangle] = nbTria;
3013       aVec[SMDSEntity_Quadrangle] = nbQuad;
3014     }
3015     aResMap.insert(std::make_pair(sm,aVec));
3016   }
3017
3018   // ----------------
3019   // evaluate 3D
3020   // ----------------
3021   GProp_GProps G;
3022   BRepGProp::VolumeProperties(aShape,G);
3023   double aVolume = G.Mass();
3024   double tetrVol = 0.1179*ELen*ELen*ELen;
3025   int nbVols  = int(aVolume/tetrVol);
3026   int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3027   std::vector<int> aVec(SMDSEntity_Last);
3028   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3029   if( IsQuadratic ) {
3030     aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3031     aVec[SMDSEntity_Quad_Tetra] = nbVols;
3032   }
3033   else {
3034     aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3035     aVec[SMDSEntity_Tetra] = nbVols;
3036   }
3037   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3038   aResMap.insert(std::make_pair(sm,aVec));
3039
3040   return true;
3041 }