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