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