1 // Copyright (C) 2007-2008 CEA/DEN, EDF R&D
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : BLSURFPlugin_BLSURF.cxx
21 // Authors : Francis KLOSS (OCC) & Patrick LAUG (INRIA) & Lioka RAZAFINDRAZAKA (CEA)
22 // & Aurelien ALLEAUME (DISTENE)
23 // Size maps developement: Nicolas GEIMER (OCC) & Gilles DAVID (EURIWARE)
26 #include "BLSURFPlugin_BLSURF.hxx"
27 #include "BLSURFPlugin_Hypothesis.hxx"
29 #include <structmember.h>
32 #include <SMESH_Gen.hxx>
33 #include <SMESH_Mesh.hxx>
34 #include <SMESH_ControlsDef.hxx>
36 #include <utilities.h>
43 #include <BRep_Tool.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <NCollection_Map.hxx>
47 #include <Standard_ErrorHandler.hxx>
49 #include <Geom_Surface.hxx>
50 #include <Handle_Geom_Surface.hxx>
51 #include <Geom2d_Curve.hxx>
52 #include <Handle_Geom2d_Curve.hxx>
53 #include <Geom_Curve.hxx>
54 #include <Handle_Geom_Curve.hxx>
55 #include <gp_Pnt2d.hxx>
56 #include <TopTools_IndexedMapOfShape.hxx>
57 #include <BRepTools.hxx>
58 #include <TopTools_DataMapOfShapeInteger.hxx>
59 #include <GProp_GProps.hxx>
60 #include <BRepGProp.hxx>
66 #include <GeomAPI_ProjectPointOnCurve.hxx>
67 #include <GeomAPI_ProjectPointOnSurf.hxx>
71 /* ==================================
72 * =========== PYTHON ==============
73 * ==================================*/
82 PyStdOut_dealloc(PyStdOut *self)
88 PyStdOut_write(PyStdOut *self, PyObject *args)
92 if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
96 *(self->out)=*(self->out)+c;
102 static PyMethodDef PyStdOut_methods[] = {
103 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
104 PyDoc_STR("write(string) -> None")},
105 {NULL, NULL} /* sentinel */
108 static PyMemberDef PyStdOut_memberlist[] = {
109 {"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
110 "flag indicating that a space needs to be printed; used by print"},
111 {NULL} /* Sentinel */
114 static PyTypeObject PyStdOut_Type = {
115 /* The ob_type field must be initialized in the module init function
116 * to be portable to Windows without using C++. */
117 PyObject_HEAD_INIT(NULL)
120 sizeof(PyStdOut), /*tp_basicsize*/
123 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
130 0, /*tp_as_sequence*/
135 PyObject_GenericGetAttr, /*tp_getattro*/
136 /* softspace is writable: we must supply tp_setattro */
137 PyObject_GenericSetAttr, /* tp_setattro */
139 Py_TPFLAGS_DEFAULT, /*tp_flags*/
143 0, /*tp_richcompare*/
144 0, /*tp_weaklistoffset*/
147 PyStdOut_methods, /*tp_methods*/
148 PyStdOut_memberlist, /*tp_members*/
162 PyObject * newPyStdOut( std::string& out )
165 self = PyObject_New(PyStdOut, &PyStdOut_Type);
170 return (PyObject*)self;
174 ////////////////////////END PYTHON///////////////////////////
176 //////////////////MY MAPS////////////////////////////////////////
177 std::map<int,string> FaceId2SizeMap;
178 std::map<int,string> EdgeId2SizeMap;
179 std::map<int,string> VertexId2SizeMap;
180 std::map<int,PyObject*> FaceId2PythonSmp;
181 std::map<int,PyObject*> EdgeId2PythonSmp;
182 std::map<int,PyObject*> VertexId2PythonSmp;
185 bool HasSizeMapOnFace=false;
186 bool HasSizeMapOnEdge=false;
187 bool HasSizeMapOnVertex=false;
189 //=============================================================================
193 //=============================================================================
195 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
197 : SMESH_2D_Algo(hypId, studyId, gen)
199 MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
202 _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
203 _compatibleHypothesis.push_back("BLSURF_Parameters");
204 _requireDescretBoundary = false;
205 _onlyUnaryInput = false;
208 smeshGen_i = SMESH_Gen_i::GetSMESHGen();
209 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
210 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
212 MESSAGE("studyid = " << _studyId);
215 myStudy = aStudyMgr->GetStudyByID(_studyId);
216 MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
218 /* Initialize the Python interpreter */
219 assert(Py_IsInitialized());
220 PyGILState_STATE gstate;
221 gstate = PyGILState_Ensure();
224 main_mod = PyImport_AddModule("__main__");
227 main_dict = PyModule_GetDict(main_mod);
229 PyRun_SimpleString("from math import *");
230 PyGILState_Release(gstate);
232 FaceId2SizeMap.clear();
233 EdgeId2SizeMap.clear();
234 VertexId2SizeMap.clear();
235 FaceId2PythonSmp.clear();
236 EdgeId2PythonSmp.clear();
237 VertexId2PythonSmp.clear();
240 //=============================================================================
244 //=============================================================================
246 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
248 MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
252 //=============================================================================
256 //=============================================================================
258 bool BLSURFPlugin_BLSURF::CheckHypothesis
260 const TopoDS_Shape& aShape,
261 SMESH_Hypothesis::Hypothesis_Status& aStatus)
265 list<const SMESHDS_Hypothesis*>::const_iterator itl;
266 const SMESHDS_Hypothesis* theHyp;
268 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
269 int nbHyp = hyps.size();
272 aStatus = SMESH_Hypothesis::HYP_OK;
273 return true; // can work with no hypothesis
277 theHyp = (*itl); // use only the first hypothesis
279 string hypName = theHyp->GetName();
281 if (hypName == "BLSURF_Parameters")
283 _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
285 if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
286 _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
287 // hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
288 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
290 aStatus = SMESH_Hypothesis::HYP_OK;
293 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
295 return aStatus == SMESH_Hypothesis::HYP_OK;
298 //=============================================================================
300 * Pass parameters to BLSURF
302 //=============================================================================
304 inline std::string to_string(double d)
306 std::ostringstream o;
311 inline std::string to_string(int i)
313 std::ostringstream o;
318 double _smp_phy_size;
319 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
320 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
321 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
323 double my_u_min=1e6,my_v_min=1e6,my_u_max=-1e6,my_v_max=-1e6;
325 /////////////////////////////////////////////////////////
326 gp_XY getUV(const TopoDS_Face& face, const gp_XYZ& point)
328 Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
329 GeomAPI_ProjectPointOnSurf projector( point, surface );
330 if ( !projector.IsDone() || projector.NbPoints()==0 )
331 throw "Can't project";
333 Quantity_Parameter u,v;
334 projector.LowerDistanceParameters(u,v);
337 /////////////////////////////////////////////////////////
339 /////////////////////////////////////////////////////////
340 double getT(const TopoDS_Edge& edge, const gp_XYZ& point)
343 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
344 GeomAPI_ProjectPointOnCurve projector( point, curve);
345 if ( projector.NbPoints() == 0 )
347 return projector.LowerDistanceParameter();
350 /////////////////////////////////////////////////////////
351 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
353 MESSAGE("BLSURFPlugin_BLSURF::entryToShape"<<entry );
354 TopoDS_Shape S = TopoDS_Shape();
355 SALOMEDS::SObject_var aSO = myStudy->FindObjectID(entry.c_str());
356 SALOMEDS::GenericAttribute_var anAttr;
357 if (!aSO->_is_nil()){
358 SALOMEDS::SObject_var aRefSObj;
359 GEOM::GEOM_Object_var aShape;
360 SALOMEDS::AttributeIOR_var myAttribute;
361 CORBA::String_var myAttrValue;
362 CORBA::Object_var myCorbaObj;
363 // If selected object is a reference
364 if ( aSO->ReferencedObject( aRefSObj ))
366 SALOMEDS::SComponent_var myFatherCpnt = aSO->GetFatherComponent();
367 CORBA::String_var myFatherCpntDataType = myFatherCpnt->ComponentDataType();
368 if ( strcmp(myFatherCpntDataType,"GEOM")==0) {
369 MESSAGE("aSO father component is GEOM");
370 if (!aSO->FindAttribute(anAttr, "AttributeIOR")) return S;
371 myAttribute=SALOMEDS::AttributeIOR::_narrow(anAttr);
372 myAttrValue=myAttribute->Value();
373 MESSAGE("aSO IOR: "<< myAttrValue);
374 myCorbaObj=smeshGen_i->GetORB()->string_to_object(myAttrValue);
375 aShape = GEOM::GEOM_Object::_narrow(myCorbaObj);
377 if ( !aShape->_is_nil() )
378 S=smeshGen_i->GeomObjectToShape( aShape.in() );
382 /////////////////////////////////////////////////////////
384 void BLSURFPlugin_BLSURF::SetParameters(const BLSURFPlugin_Hypothesis* hyp, blsurf_session_t *bls)
386 int _topology = BLSURFPlugin_Hypothesis::GetDefaultTopology();
387 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
388 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
389 int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
390 double _angleMeshS = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
391 double _angleMeshC = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
392 double _gradation = BLSURFPlugin_Hypothesis::GetDefaultGradation();
393 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
394 bool _decimesh = BLSURFPlugin_Hypothesis::GetDefaultDecimesh();
395 int _verb = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
398 MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
399 _topology = (int) hyp->GetTopology();
400 _physicalMesh = (int) hyp->GetPhysicalMesh();
401 _phySize = hyp->GetPhySize();
402 _geometricMesh = (int) hyp->GetGeometricMesh();
403 _angleMeshS = hyp->GetAngleMeshS();
404 _angleMeshC = hyp->GetAngleMeshC();
405 _gradation = hyp->GetGradation();
406 _quadAllowed = hyp->GetQuadAllowed();
407 _decimesh = hyp->GetDecimesh();
408 _verb = hyp->GetVerbosity();
410 if ( hyp->GetPhyMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
411 blsurf_set_param(bls, "hphymin", to_string(hyp->GetPhyMin()).c_str());
412 if ( hyp->GetPhyMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
413 blsurf_set_param(bls, "hphymax", to_string(hyp->GetPhyMax()).c_str());
414 if ( hyp->GetGeoMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
415 blsurf_set_param(bls, "hgeomin", to_string(hyp->GetGeoMin()).c_str());
416 if ( hyp->GetGeoMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
417 blsurf_set_param(bls, "hgeomax", to_string(hyp->GetGeoMax()).c_str());
419 const BLSURFPlugin_Hypothesis::TOptionValues & opts = hyp->GetOptionValues();
420 BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
421 for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
422 if ( !opIt->second.empty() ) {
423 MESSAGE("blsurf_set_param(): " << opIt->first << " = " << opIt->second);
424 blsurf_set_param(bls, opIt->first.c_str(), opIt->second.c_str());
428 MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
430 _smp_phy_size = _phySize;
431 blsurf_set_param(bls, "topo_points", _topology > 0 ? "1" : "0");
432 blsurf_set_param(bls, "topo_curves", _topology > 0 ? "1" : "0");
433 blsurf_set_param(bls, "topo_project", _topology > 0 ? "1" : "0");
434 blsurf_set_param(bls, "clean_boundary", _topology > 1 ? "1" : "0");
435 blsurf_set_param(bls, "close_boundary", _topology > 1 ? "1" : "0");
436 blsurf_set_param(bls, "hphy_flag", to_string(_physicalMesh).c_str());
437 // blsurf_set_param(bls, "hphy_flag", "2");
438 if ((to_string(_physicalMesh))=="2"){
440 TopoDS_Shape GeomShape;
441 TopAbs_ShapeEnum GeomType;
443 // Standard Size Maps
445 MESSAGE("Setting a Size Map");
446 const BLSURFPlugin_Hypothesis::TSizeMap & sizeMaps = hyp->GetSizeMapEntries();
447 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt;
448 for ( smIt = sizeMaps.begin(); smIt != sizeMaps.end(); ++smIt ) {
449 if ( !smIt->second.empty() ) {
450 MESSAGE("blsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
451 GeomShape = entryToShape(smIt->first);
452 GeomType = GeomShape.ShapeType();
453 if (GeomType == TopAbs_FACE){
454 HasSizeMapOnFace = true;
455 FaceId2SizeMap[TopoDS::Face(GeomShape).HashCode(471662)] = smIt->second;
457 if (GeomType == TopAbs_EDGE){
458 HasSizeMapOnEdge = true;
459 HasSizeMapOnFace = true;
460 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(471662)] = smIt->second;
462 if (GeomType == TopAbs_VERTEX){
463 HasSizeMapOnVertex = true;
464 HasSizeMapOnEdge = true;
465 HasSizeMapOnFace = true;
466 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(471662)] = smIt->second;
474 MESSAGE("Setting Attractors");
475 const BLSURFPlugin_Hypothesis::TSizeMap & attractors = hyp->GetAttractorEntries();
476 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt;
477 for ( atIt = attractors.begin(); atIt != attractors.end(); ++atIt ) {
478 if ( !atIt->second.empty() ) {
479 MESSAGE("blsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
480 GeomShape = entryToShape(atIt->first);
481 GeomType = GeomShape.ShapeType();
483 if (GeomType == TopAbs_FACE){
484 HasSizeMapOnFace = true;
486 double xa, ya, za; // Coordinates of attractor point
487 double a, b; // Attractor parameter
489 // atIt->second has the following pattern:
490 // ATTRACTOR(xa;ya;za;a;b)
492 // xa;ya;za : coordinates of attractor
493 // a : desired size on attractor
494 // b : distance of influence of attractor
496 // We search the parameters in the string
497 pos1 = atIt->second.find(";");
498 xa = atof(atIt->second.substr(10, pos1-10).c_str());
499 pos2 = atIt->second.find(";", pos1+1);
500 ya = atof(atIt->second.substr(pos1+1, pos2-pos1-1).c_str());
502 pos2 = atIt->second.find(";", pos1+1);
503 za = atof(atIt->second.substr(pos1+1, pos2-pos1-1).c_str());
505 pos2 = atIt->second.find(";", pos1+1);
506 a = atof(atIt->second.substr(pos1+1, pos2-pos1-1).c_str());
508 pos2 = atIt->second.find(")");
509 b = atof(atIt->second.substr(pos1+1, pos2-pos1-1).c_str());
511 // Get the (u,v) values of the attractor on the face
512 gp_XY uvPoint = getUV(TopoDS::Face(GeomShape),gp_XYZ(xa,ya,za));
513 Standard_Real u0 = uvPoint.X();
514 Standard_Real v0 = uvPoint.Y();
515 // We construct the python function
516 ostringstream attractorFunction;
517 attractorFunction << "def f(u,v): return ";
518 attractorFunction << _smp_phy_size << "-(" << _smp_phy_size <<"-" << a << ")";
519 attractorFunction << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
521 MESSAGE("Python function for attractor:" << std::endl << attractorFunction.str());
523 FaceId2SizeMap[TopoDS::Face(GeomShape).HashCode(471662)] =attractorFunction.str();
526 if (GeomType == TopAbs_EDGE){
527 HasSizeMapOnEdge = true;
528 HasSizeMapOnFace = true;
529 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(471662)] = atIt->second;
531 if (GeomType == TopAbs_VERTEX){
532 HasSizeMapOnVertex = true;
533 HasSizeMapOnEdge = true;
534 HasSizeMapOnFace = true;
535 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(471662)] = atIt->second;
542 // if (HasSizeMapOnFace){
543 // In all size map cases (hphy_flag = 2), at least map on face must be defined
544 MESSAGE("Setting Size Map on FACES ");
545 blsurf_data_set_sizemap_iso_cad_face(bls, size_on_surface, &_smp_phy_size);
548 if (HasSizeMapOnEdge){
549 MESSAGE("Setting Size Map on EDGES ");
550 blsurf_data_set_sizemap_iso_cad_edge(bls, size_on_edge, &_smp_phy_size);
552 if (HasSizeMapOnVertex){
553 MESSAGE("Setting Size Map on VERTICES ");
554 blsurf_data_set_sizemap_iso_cad_point(bls, size_on_vertex, &_smp_phy_size);
557 blsurf_set_param(bls, "hphydef", to_string(_phySize).c_str());
558 blsurf_set_param(bls, "hgeo_flag", to_string(_geometricMesh).c_str());
559 blsurf_set_param(bls, "relax_size", _decimesh ? "0": to_string(_geometricMesh).c_str());
560 blsurf_set_param(bls, "angle_meshs", to_string(_angleMeshS).c_str());
561 blsurf_set_param(bls, "angle_meshc", to_string(_angleMeshC).c_str());
562 blsurf_set_param(bls, "gradation", to_string(_gradation).c_str());
563 blsurf_set_param(bls, "patch_independent", _decimesh ? "1" : "0");
564 blsurf_set_param(bls, "element", _quadAllowed ? "q1.0" : "p1");
565 blsurf_set_param(bls, "verb", to_string(_verb).c_str());
568 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
569 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
570 real *duu, real *duv, real *dvv, void *user_data);
571 status_t message_callback(message_t *msg, void *user_data);
573 //=============================================================================
577 //=============================================================================
579 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
581 MESSAGE("BLSURFPlugin_BLSURF::Compute");
583 if (aShape.ShapeType() == TopAbs_COMPOUND) {
584 MESSAGE(" the shape is a COMPOUND");
587 MESSAGE(" the shape is UNKNOWN");
590 context_t *ctx = context_new();
591 context_set_message_callback(ctx, message_callback, &_comment);
593 cad_t *c = cad_new(ctx);
595 blsurf_session_t *bls = blsurf_session_new(ctx);
598 SetParameters(_hypothesis, bls);
600 TopTools_IndexedMapOfShape fmap;
601 TopTools_IndexedMapOfShape emap;
602 TopTools_IndexedMapOfShape pmap;
603 vector<Handle(Geom2d_Curve)> curves;
604 vector<Handle(Geom_Surface)> surfaces;
609 FaceId2PythonSmp.clear();
611 EdgeId2PythonSmp.clear();
613 VertexId2PythonSmp.clear();
617 assert(Py_IsInitialized());
618 PyGILState_STATE gstate;
619 gstate = PyGILState_Ensure();
627 string bad_end = "return";
628 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next()) {
629 TopoDS_Face f=TopoDS::Face(face_iter.Current());
630 if (fmap.FindIndex(f) > 0)
635 surfaces.push_back(BRep_Tool::Surface(f));
636 // Get bound values of uv surface
637 //BRep_Tool::Surface(f)->Bounds(u_min,u_max,v_min,v_max);
638 //MESSAGE("BRep_Tool::Surface(f)->Bounds(u_min,u_max,v_min,v_max): " << u_min << ", " << u_max << ", " << v_min << ", " << v_max);
640 if ((HasSizeMapOnFace) && FaceId2SizeMap.find(f.HashCode(471662))!=FaceId2SizeMap.end()){
641 MESSAGE("FaceId2SizeMap[f.HashCode(471662)].find(bad_end): " << FaceId2SizeMap[f.HashCode(471662)].find(bad_end));
642 MESSAGE("FaceId2SizeMap[f.HashCode(471662)].size(): " << FaceId2SizeMap[f.HashCode(471662)].size());
643 MESSAGE("bad_end.size(): " << bad_end.size());
644 // check if function ends with "return"
645 if (FaceId2SizeMap[f.HashCode(471662)].find(bad_end) == (FaceId2SizeMap[f.HashCode(471662)].size()-bad_end.size()-1))
647 // Expr To Python function, verification is performed at validation in GUI
648 PyObject * obj = NULL;
649 obj= PyRun_String(FaceId2SizeMap[f.HashCode(471662)].c_str(), Py_file_input, main_dict, NULL);
651 PyObject * func = NULL;
652 func = PyObject_GetAttrString(main_mod, "f");
653 FaceId2PythonSmp[iface]=func;
654 FaceId2SizeMap.erase(f.HashCode(471662));
656 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
657 cad_face_set_tag(fce, iface);
658 if(f.Orientation() != TopAbs_FORWARD){
659 cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
661 cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
664 for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next()) {
665 TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
666 int ic = emap.FindIndex(e);
671 curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
672 if ((HasSizeMapOnEdge) && EdgeId2SizeMap.find(e.HashCode(471662))!=EdgeId2SizeMap.end()){
673 if (EdgeId2SizeMap[e.HashCode(471662)].find(bad_end) == (EdgeId2SizeMap[e.HashCode(471662)].size()-bad_end.size()-1))
675 // Expr To Python function, verification is performed at validation in GUI
676 PyObject * obj = NULL;
677 obj= PyRun_String(EdgeId2SizeMap[e.HashCode(471662)].c_str(), Py_file_input, main_dict, NULL);
679 PyObject * func = NULL;
680 func = PyObject_GetAttrString(main_mod, "f");
681 EdgeId2PythonSmp[ic]=func;
682 EdgeId2SizeMap.erase(e.HashCode(471662));
684 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
685 cad_edge_set_tag(edg, ic);
686 cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
687 if (e.Orientation() == TopAbs_INTERNAL)
688 cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
692 gp_Pnt2d e0 = curves.back()->Value(tmin);
693 gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
694 Standard_Real d1=0,d2=0;
695 for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
696 TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
700 d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
703 d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
705 *ip = pmap.FindIndex(v);
708 if ((HasSizeMapOnVertex) && VertexId2SizeMap.find(v.HashCode(471662))!=VertexId2SizeMap.end()){
709 if (VertexId2SizeMap[v.HashCode(471662)].find(bad_end) == (VertexId2SizeMap[v.HashCode(471662)].size()-bad_end.size()-1))
711 // Expr To Python function, verification is performed at validation in GUI
712 PyObject * obj = NULL;
713 obj= PyRun_String(VertexId2SizeMap[v.HashCode(471662)].c_str(), Py_file_input, main_dict, NULL);
715 PyObject * func = NULL;
716 func = PyObject_GetAttrString(main_mod, "f");
717 VertexId2PythonSmp[*ip]=func;
718 VertexId2SizeMap.erase(v.HashCode(471662));
723 MESSAGE("An edge does not have 2 extremities.");
726 cad_edge_set_extremities(edg, ip1, ip2);
728 cad_edge_set_extremities(edg, ip2, ip1);
734 PyGILState_Release(gstate);
736 blsurf_data_set_cad(bls, c);
738 std::cout << std::endl;
739 std::cout << "Beginning of Surface Mesh generation" << std::endl;
740 std::cout << std::endl;
742 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
744 feclearexcept( FE_ALL_EXCEPT );
745 int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
748 status_t status = STATUS_ERROR;
753 status = blsurf_compute_mesh(bls);
756 catch ( std::exception& exc ) {
757 _comment += exc.what();
759 catch (Standard_Failure& ex) {
760 _comment += ex.DynamicType()->Name();
761 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
763 _comment += ex.GetMessageString();
767 if ( _comment.empty() )
768 _comment = "Exception in blsurf_compute_mesh()";
770 if ( status != STATUS_OK) {
771 blsurf_session_delete(bls);
775 return error(_comment);
778 std::cout << std::endl;
779 std::cout << "End of Surface Mesh generation" << std::endl;
780 std::cout << std::endl;
783 blsurf_data_get_mesh(bls, &msh);
785 blsurf_session_delete(bls);
789 return error(_comment);
793 integer nv, ne, nt, nq, vtx[4], tag;
796 mesh_get_vertex_count(msh, &nv);
797 mesh_get_edge_count(msh, &ne);
798 mesh_get_triangle_count(msh, &nt);
799 mesh_get_quadrangle_count(msh, &nq);
802 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
803 SMDS_MeshNode** nodes = new SMDS_MeshNode*[nv+1];
804 bool* tags = new bool[nv+1];
806 for(int iv=1;iv<=nv;iv++) {
807 mesh_get_vertex_coordinates(msh, iv, xyz);
808 mesh_get_vertex_tag(msh, iv, &tag);
809 nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
810 // internal point are tagged to zero
812 meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
819 for(int it=1;it<=ne;it++) {
820 mesh_get_edge_vertices(msh, it, vtx);
821 SMDS_MeshEdge* edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
822 mesh_get_edge_tag(msh, it, &tag);
825 Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
826 tags[vtx[0]] = false;
829 Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
830 tags[vtx[1]] = false;
832 meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
836 for(int it=1;it<=nt;it++) {
837 mesh_get_triangle_vertices(msh, it, vtx);
838 SMDS_MeshFace* tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
839 mesh_get_triangle_tag(msh, it, &tag);
840 meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
842 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
843 tags[vtx[0]] = false;
846 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
847 tags[vtx[1]] = false;
850 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
851 tags[vtx[2]] = false;
855 for(int it=1;it<=nq;it++) {
856 mesh_get_quadrangle_vertices(msh, it, vtx);
857 SMDS_MeshFace* quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
858 mesh_get_quadrangle_tag(msh, it, &tag);
859 meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
861 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
862 tags[vtx[0]] = false;
865 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
866 tags[vtx[1]] = false;
869 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
870 tags[vtx[2]] = false;
873 meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
874 tags[vtx[3]] = false;
880 /* release the mesh object */
881 blsurf_data_regain_mesh(bls, msh);
883 /* clean up everything */
884 blsurf_session_delete(bls);
889 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
891 if ( oldFEFlags > 0 )
892 feenableexcept( oldFEFlags );
893 feclearexcept( FE_ALL_EXCEPT );
899 //=============================================================================
903 //=============================================================================
905 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* node, const TopoDS_Shape& ed) {
906 const TopoDS_Edge edge = TopoDS::Edge(ed);
908 gp_Pnt pnt(node->X(), node->Y(), node->Z());
910 Standard_Real p0 = 0.0;
911 Standard_Real p1 = 1.0;
912 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, p0, p1);
914 GeomAPI_ProjectPointOnCurve proj(pnt, curve);
916 double pa = (double)proj.Parameter(1);
919 BRepGProp::LinearProperties(ed, LProps);
920 double lg = (double)LProps.Mass();
922 meshDS->SetNodeOnEdge(node, edge, pa);
925 //=============================================================================
929 //=============================================================================
931 ostream & BLSURFPlugin_BLSURF::SaveTo(ostream & save)
936 //=============================================================================
940 //=============================================================================
942 istream & BLSURFPlugin_BLSURF::LoadFrom(istream & load)
947 //=============================================================================
951 //=============================================================================
953 ostream & operator << (ostream & save, BLSURFPlugin_BLSURF & hyp)
955 return hyp.SaveTo( save );
958 //=============================================================================
962 //=============================================================================
964 istream & operator >> (istream & load, BLSURFPlugin_BLSURF & hyp)
966 return hyp.LoadFrom( load );
969 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
971 const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
976 uv[0]=P.X(); uv[1]=P.Y();
982 dt[0]=V1.X(); dt[1]=V1.Y();
988 dtt[0]=V2.X(); dtt[1]=V2.Y();
994 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
995 real *duu, real *duv, real *dvv, void *user_data)
997 const Geom_Surface* geometry = (const Geom_Surface*) user_data;
1001 P=geometry->Value(uv[0],uv[1]); // S.D0(U,V,P);
1002 xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
1009 geometry->D1(uv[0],uv[1],P,D1U,D1V);
1010 du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
1011 dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
1014 if(duu && duv && dvv){
1017 gp_Vec D2U,D2V,D2UV;
1019 geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
1020 duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
1021 duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
1022 dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
1029 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
1032 if (my_u_min > uv[0]) {
1035 if (my_v_min > uv[1]) {
1038 if (my_u_max < uv[0]) {
1041 if (my_v_max < uv[1]) {
1046 if (FaceId2PythonSmp.count(face_id) != 0){
1047 PyObject * pyresult = NULL;
1048 PyObject* new_stderr = NULL;
1049 assert(Py_IsInitialized());
1050 PyGILState_STATE gstate;
1051 gstate = PyGILState_Ensure();
1052 pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],"(f,f)",uv[0],uv[1]);
1054 if ( pyresult == NULL){
1056 string err_description="";
1057 new_stderr = newPyStdOut(err_description);
1058 PySys_SetObject("stderr", new_stderr);
1060 PySys_SetObject("stderr", PySys_GetObject("__stderr__"));
1061 Py_DECREF(new_stderr);
1062 MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
1063 result = *((double*)user_data);
1066 result = PyFloat_AsDouble(pyresult);
1067 Py_DECREF(pyresult);
1070 //MESSAGE("f(" << uv[0] << "," << uv[1] << ")" << " = " << result);
1071 PyGILState_Release(gstate);
1074 *size = *((double*)user_data);
1079 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
1081 if (EdgeId2PythonSmp.count(edge_id) != 0){
1082 PyObject * pyresult = NULL;
1083 PyObject* new_stderr = NULL;
1084 assert(Py_IsInitialized());
1085 PyGILState_STATE gstate;
1086 gstate = PyGILState_Ensure();
1087 pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],"(f)",t);
1089 if ( pyresult == NULL){
1091 string err_description="";
1092 new_stderr = newPyStdOut(err_description);
1093 PySys_SetObject("stderr", new_stderr);
1095 PySys_SetObject("stderr", PySys_GetObject("__stderr__"));
1096 Py_DECREF(new_stderr);
1097 MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
1098 result = *((double*)user_data);
1101 result = PyFloat_AsDouble(pyresult);
1102 Py_DECREF(pyresult);
1105 PyGILState_Release(gstate);
1108 *size = *((double*)user_data);
1113 status_t size_on_vertex(integer point_id, real *size, void *user_data)
1115 if (VertexId2PythonSmp.count(point_id) != 0){
1116 PyObject * pyresult = NULL;
1117 PyObject* new_stderr = NULL;
1118 assert(Py_IsInitialized());
1119 PyGILState_STATE gstate;
1120 gstate = PyGILState_Ensure();
1121 pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],"");
1123 if ( pyresult == NULL){
1125 string err_description="";
1126 new_stderr = newPyStdOut(err_description);
1127 PySys_SetObject("stderr", new_stderr);
1129 PySys_SetObject("stderr", PySys_GetObject("__stderr__"));
1130 Py_DECREF(new_stderr);
1131 MESSAGE("Can't evaluate f()" << " error is " << err_description);
1132 result = *((double*)user_data);
1135 result = PyFloat_AsDouble(pyresult);
1136 Py_DECREF(pyresult);
1139 PyGILState_Release(gstate);
1142 *size = *((double*)user_data);
1147 status_t message_callback(message_t *msg, void *user_data)
1149 integer errnumber = 0;
1151 message_get_number(msg, &errnumber);
1152 message_get_description(msg, &desc);
1153 if ( errnumber < 0 ) {
1154 string * error = (string*)user_data;
1155 // if ( !error->empty() )
1157 // remove ^A from the tail
1158 int len = strlen( desc );
1159 while (len > 0 && desc[len-1] != '\n')
1161 error->append( desc, len );
1164 std::cout << desc << std::endl;
1170 //=============================================================================
1174 //=============================================================================
1175 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
1176 const TopoDS_Shape& aShape,
1177 MapShapeNbElems& aResMap)
1179 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
1180 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
1181 //int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
1182 //double _angleMeshS = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
1183 double _angleMeshC = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
1185 _physicalMesh = (int) _hypothesis->GetPhysicalMesh();
1186 _phySize = _hypothesis->GetPhySize();
1187 //_geometricMesh = (int) hyp->GetGeometricMesh();
1188 //_angleMeshS = hyp->GetAngleMeshS();
1189 _angleMeshC = _hypothesis->GetAngleMeshC();
1192 bool IsQuadratic = false;
1197 TopTools_DataMapOfShapeInteger EdgesMap;
1198 double fullLen = 0.0;
1199 double fullNbSeg = 0;
1200 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
1201 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
1202 if( EdgesMap.IsBound(E) )
1204 SMESH_subMesh *sm = aMesh.GetSubMesh(E);
1205 double aLen = SMESH_Algo::EdgeLength(E);
1208 if(_physicalMesh==1) {
1209 nb1d = (int)( aLen/_phySize + 1 );
1214 Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
1215 double fullAng = 0.0;
1216 double dp = (l-f)/200;
1221 for(int j=2; j<=200; j++) {
1224 fullAng += fabs(V1.Angle(V2));
1228 nb1d = (int)( fullAng/_angleMeshC + 1 );
1231 std::vector<int> aVec(SMDSEntity_Last);
1232 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1233 if( IsQuadratic > 0 ) {
1234 aVec[SMDSEntity_Node] = 2*nb1d - 1;
1235 aVec[SMDSEntity_Quad_Edge] = nb1d;
1238 aVec[SMDSEntity_Node] = nb1d - 1;
1239 aVec[SMDSEntity_Edge] = nb1d;
1241 aResMap.insert(std::make_pair(sm,aVec));
1242 EdgesMap.Bind(E,nb1d);
1244 double ELen = fullLen/fullNbSeg;
1248 // try to evaluate as in MEFISTO
1249 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
1250 TopoDS_Face F = TopoDS::Face( exp.Current() );
1251 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
1253 BRepGProp::SurfaceProperties(F,G);
1254 double anArea = G.Mass();
1256 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
1257 nb1d += EdgesMap.Find(exp1.Current());
1259 int nbFaces = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
1260 int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
1261 std::vector<int> aVec(SMDSEntity_Last);
1262 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1264 int nb1d_in = (nbFaces*3 - nb1d) / 2;
1265 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
1266 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
1269 aVec[SMDSEntity_Node] = nbNodes;
1270 aVec[SMDSEntity_Triangle] = nbFaces;
1272 aResMap.insert(std::make_pair(sm,aVec));
1279 BRepGProp::VolumeProperties(aShape,G);
1280 double aVolume = G.Mass();
1281 double tetrVol = 0.1179*ELen*ELen*ELen;
1282 int nbVols = (int)aVolume/tetrVol;
1283 int nb1d_in = (int) ( ( nbVols*6 - fullNbSeg ) / 6 );
1284 std::vector<int> aVec(SMDSEntity_Last);
1285 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1287 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
1288 aVec[SMDSEntity_Quad_Tetra] = nbVols;
1291 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
1292 aVec[SMDSEntity_Tetra] = nbVols;
1294 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1295 aResMap.insert(std::make_pair(sm,aVec));