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"
30 #include "distene/blsurf.h"
31 #include <distene/api.h>
34 #include <structmember.h>
37 #include <SMESH_Gen.hxx>
38 #include <SMESH_Mesh.hxx>
39 #include <SMESH_ControlsDef.hxx>
41 #include <utilities.h>
48 #include <BRep_Tool.hxx>
50 #include <TopExp_Explorer.hxx>
51 #include <NCollection_Map.hxx>
52 #include <Standard_ErrorHandler.hxx>
54 #include <Geom_Surface.hxx>
55 #include <Handle_Geom_Surface.hxx>
56 #include <Geom2d_Curve.hxx>
57 #include <Handle_Geom2d_Curve.hxx>
58 #include <Geom_Curve.hxx>
59 #include <Handle_Geom_Curve.hxx>
60 #include <gp_Pnt2d.hxx>
61 #include <TopTools_IndexedMapOfShape.hxx>
62 #include <BRepTools.hxx>
63 #include <TopTools_DataMapOfShapeInteger.hxx>
64 #include <GProp_GProps.hxx>
65 #include <BRepGProp.hxx>
71 #include <GeomAPI_ProjectPointOnCurve.hxx>
72 #include <GeomAPI_ProjectPointOnSurf.hxx>
76 /* ==================================
77 * =========== PYTHON ==============
78 * ==================================*/
87 PyStdOut_dealloc(PyStdOut *self)
93 PyStdOut_write(PyStdOut *self, PyObject *args)
97 if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
101 *(self->out)=*(self->out)+c;
107 static PyMethodDef PyStdOut_methods[] = {
108 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
109 PyDoc_STR("write(string) -> None")},
110 {NULL, NULL} /* sentinel */
113 static PyMemberDef PyStdOut_memberlist[] = {
114 {"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
115 "flag indicating that a space needs to be printed; used by print"},
116 {NULL} /* Sentinel */
119 static PyTypeObject PyStdOut_Type = {
120 /* The ob_type field must be initialized in the module init function
121 * to be portable to Windows without using C++. */
122 PyObject_HEAD_INIT(NULL)
125 sizeof(PyStdOut), /*tp_basicsize*/
128 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
135 0, /*tp_as_sequence*/
140 PyObject_GenericGetAttr, /*tp_getattro*/
141 /* softspace is writable: we must supply tp_setattro */
142 PyObject_GenericSetAttr, /* tp_setattro */
144 Py_TPFLAGS_DEFAULT, /*tp_flags*/
148 0, /*tp_richcompare*/
149 0, /*tp_weaklistoffset*/
152 PyStdOut_methods, /*tp_methods*/
153 PyStdOut_memberlist, /*tp_members*/
167 PyObject * newPyStdOut( std::string& out )
170 self = PyObject_New(PyStdOut, &PyStdOut_Type);
175 return (PyObject*)self;
179 ////////////////////////END PYTHON///////////////////////////
181 //////////////////MY MAPS////////////////////////////////////////
182 std::map<int,string> FaceId2SizeMap;
183 std::map<int,string> EdgeId2SizeMap;
184 std::map<int,string> VertexId2SizeMap;
185 std::map<int,PyObject*> FaceId2PythonSmp;
186 std::map<int,PyObject*> EdgeId2PythonSmp;
187 std::map<int,PyObject*> VertexId2PythonSmp;
190 bool HasSizeMapOnFace=false;
191 bool HasSizeMapOnEdge=false;
192 bool HasSizeMapOnVertex=false;
194 //=============================================================================
198 //=============================================================================
200 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
202 : SMESH_2D_Algo(hypId, studyId, gen)
204 MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
207 _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
208 _compatibleHypothesis.push_back("BLSURF_Parameters");
209 _requireDescretBoundary = false;
210 _onlyUnaryInput = false;
213 smeshGen_i = SMESH_Gen_i::GetSMESHGen();
214 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
215 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
217 MESSAGE("studyid = " << _studyId);
220 myStudy = aStudyMgr->GetStudyByID(_studyId);
221 MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
223 /* Initialize the Python interpreter */
224 assert(Py_IsInitialized());
225 PyGILState_STATE gstate;
226 gstate = PyGILState_Ensure();
229 main_mod = PyImport_AddModule("__main__");
232 main_dict = PyModule_GetDict(main_mod);
234 PyRun_SimpleString("from math import *");
235 PyGILState_Release(gstate);
237 FaceId2SizeMap.clear();
238 EdgeId2SizeMap.clear();
239 VertexId2SizeMap.clear();
240 FaceId2PythonSmp.clear();
241 EdgeId2PythonSmp.clear();
242 VertexId2PythonSmp.clear();
245 //=============================================================================
249 //=============================================================================
251 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
253 MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
257 //=============================================================================
261 //=============================================================================
263 bool BLSURFPlugin_BLSURF::CheckHypothesis
265 const TopoDS_Shape& aShape,
266 SMESH_Hypothesis::Hypothesis_Status& aStatus)
270 list<const SMESHDS_Hypothesis*>::const_iterator itl;
271 const SMESHDS_Hypothesis* theHyp;
273 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
274 int nbHyp = hyps.size();
277 aStatus = SMESH_Hypothesis::HYP_OK;
278 return true; // can work with no hypothesis
282 theHyp = (*itl); // use only the first hypothesis
284 string hypName = theHyp->GetName();
286 if (hypName == "BLSURF_Parameters")
288 _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
290 if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
291 _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
292 // hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
293 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
295 aStatus = SMESH_Hypothesis::HYP_OK;
298 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
300 return aStatus == SMESH_Hypothesis::HYP_OK;
303 //=============================================================================
305 * Pass parameters to BLSURF
307 //=============================================================================
309 inline std::string to_string(double d)
311 std::ostringstream o;
316 inline std::string to_string(int i)
318 std::ostringstream o;
323 double _smp_phy_size;
324 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
325 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
326 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
328 double my_u_min=1e6,my_v_min=1e6,my_u_max=-1e6,my_v_max=-1e6;
330 /////////////////////////////////////////////////////////
331 gp_XY getUV(const TopoDS_Face& face, const gp_XYZ& point)
333 Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
334 GeomAPI_ProjectPointOnSurf projector( point, surface );
335 if ( !projector.IsDone() || projector.NbPoints()==0 )
336 throw "Can't project";
338 Quantity_Parameter u,v;
339 projector.LowerDistanceParameters(u,v);
342 /////////////////////////////////////////////////////////
344 /////////////////////////////////////////////////////////
345 double getT(const TopoDS_Edge& edge, const gp_XYZ& point)
348 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
349 GeomAPI_ProjectPointOnCurve projector( point, curve);
350 if ( projector.NbPoints() == 0 )
352 return projector.LowerDistanceParameter();
355 /////////////////////////////////////////////////////////
356 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
358 MESSAGE("BLSURFPlugin_BLSURF::entryToShape"<<entry );
359 TopoDS_Shape S = TopoDS_Shape();
360 SALOMEDS::SObject_var aSO = myStudy->FindObjectID(entry.c_str());
361 SALOMEDS::GenericAttribute_var anAttr;
362 if (!aSO->_is_nil()){
363 SALOMEDS::SObject_var aRefSObj;
364 GEOM::GEOM_Object_var aShape;
365 SALOMEDS::AttributeIOR_var myAttribute;
366 CORBA::String_var myAttrValue;
367 CORBA::Object_var myCorbaObj;
368 // If selected object is a reference
369 if ( aSO->ReferencedObject( aRefSObj ))
371 SALOMEDS::SComponent_var myFatherCpnt = aSO->GetFatherComponent();
372 CORBA::String_var myFatherCpntDataType = myFatherCpnt->ComponentDataType();
373 if ( strcmp(myFatherCpntDataType,"GEOM")==0) {
374 MESSAGE("aSO father component is GEOM");
375 if (!aSO->FindAttribute(anAttr, "AttributeIOR")) return S;
376 myAttribute=SALOMEDS::AttributeIOR::_narrow(anAttr);
377 myAttrValue=myAttribute->Value();
378 MESSAGE("aSO IOR: "<< myAttrValue);
379 myCorbaObj=smeshGen_i->GetORB()->string_to_object(myAttrValue);
380 aShape = GEOM::GEOM_Object::_narrow(myCorbaObj);
382 if ( !aShape->_is_nil() )
383 S=smeshGen_i->GeomObjectToShape( aShape.in() );
387 /////////////////////////////////////////////////////////
389 void BLSURFPlugin_BLSURF::SetParameters(const BLSURFPlugin_Hypothesis* hyp, blsurf_session_t *bls)
391 int _topology = BLSURFPlugin_Hypothesis::GetDefaultTopology();
392 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
393 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
394 int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
395 double _angleMeshS = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
396 double _angleMeshC = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
397 double _gradation = BLSURFPlugin_Hypothesis::GetDefaultGradation();
398 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
399 bool _decimesh = BLSURFPlugin_Hypothesis::GetDefaultDecimesh();
400 int _verb = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
403 MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
404 _topology = (int) hyp->GetTopology();
405 _physicalMesh = (int) hyp->GetPhysicalMesh();
406 _phySize = hyp->GetPhySize();
407 _geometricMesh = (int) hyp->GetGeometricMesh();
408 _angleMeshS = hyp->GetAngleMeshS();
409 _angleMeshC = hyp->GetAngleMeshC();
410 _gradation = hyp->GetGradation();
411 _quadAllowed = hyp->GetQuadAllowed();
412 _decimesh = hyp->GetDecimesh();
413 _verb = hyp->GetVerbosity();
415 if ( hyp->GetPhyMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
416 blsurf_set_param(bls, "hphymin", to_string(hyp->GetPhyMin()).c_str());
417 if ( hyp->GetPhyMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
418 blsurf_set_param(bls, "hphymax", to_string(hyp->GetPhyMax()).c_str());
419 if ( hyp->GetGeoMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
420 blsurf_set_param(bls, "hgeomin", to_string(hyp->GetGeoMin()).c_str());
421 if ( hyp->GetGeoMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
422 blsurf_set_param(bls, "hgeomax", to_string(hyp->GetGeoMax()).c_str());
424 const BLSURFPlugin_Hypothesis::TOptionValues & opts = hyp->GetOptionValues();
425 BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
426 for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
427 if ( !opIt->second.empty() ) {
428 MESSAGE("blsurf_set_param(): " << opIt->first << " = " << opIt->second);
429 blsurf_set_param(bls, opIt->first.c_str(), opIt->second.c_str());
433 MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
435 _smp_phy_size = _phySize;
436 blsurf_set_param(bls, "topo_points", _topology > 0 ? "1" : "0");
437 blsurf_set_param(bls, "topo_curves", _topology > 0 ? "1" : "0");
438 blsurf_set_param(bls, "topo_project", _topology > 0 ? "1" : "0");
439 blsurf_set_param(bls, "clean_boundary", _topology > 1 ? "1" : "0");
440 blsurf_set_param(bls, "close_boundary", _topology > 1 ? "1" : "0");
441 blsurf_set_param(bls, "hphy_flag", to_string(_physicalMesh).c_str());
442 // blsurf_set_param(bls, "hphy_flag", "2");
443 if ((to_string(_physicalMesh))=="2"){
445 TopoDS_Shape GeomShape;
446 TopAbs_ShapeEnum GeomType;
448 // Standard Size Maps
450 MESSAGE("Setting a Size Map");
451 const BLSURFPlugin_Hypothesis::TSizeMap & sizeMaps = hyp->GetSizeMapEntries();
452 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt;
453 for ( smIt = sizeMaps.begin(); smIt != sizeMaps.end(); ++smIt ) {
454 if ( !smIt->second.empty() ) {
455 MESSAGE("blsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
456 GeomShape = entryToShape(smIt->first);
457 GeomType = GeomShape.ShapeType();
458 if (GeomType == TopAbs_FACE){
459 HasSizeMapOnFace = true;
460 FaceId2SizeMap[TopoDS::Face(GeomShape).HashCode(471662)] = smIt->second;
462 if (GeomType == TopAbs_EDGE){
463 HasSizeMapOnEdge = true;
464 HasSizeMapOnFace = true;
465 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(471662)] = smIt->second;
467 if (GeomType == TopAbs_VERTEX){
468 HasSizeMapOnVertex = true;
469 HasSizeMapOnEdge = true;
470 HasSizeMapOnFace = true;
471 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(471662)] = smIt->second;
479 MESSAGE("Setting Attractors");
480 const BLSURFPlugin_Hypothesis::TSizeMap & attractors = hyp->GetAttractorEntries();
481 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt;
482 for ( atIt = attractors.begin(); atIt != attractors.end(); ++atIt ) {
483 if ( !atIt->second.empty() ) {
484 MESSAGE("blsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
485 GeomShape = entryToShape(atIt->first);
486 GeomType = GeomShape.ShapeType();
488 if (GeomType == TopAbs_FACE){
489 HasSizeMapOnFace = true;
491 double xa, ya, za; // Coordinates of attractor point
492 double a, b; // Attractor parameter
494 // atIt->second has the following pattern:
495 // ATTRACTOR(xa;ya;za;a;b)
497 // xa;ya;za : coordinates of attractor
498 // a : desired size on attractor
499 // b : distance of influence of attractor
501 // We search the parameters in the string
502 pos1 = atIt->second.find(";");
503 xa = atof(atIt->second.substr(10, pos1-10).c_str());
504 pos2 = atIt->second.find(";", pos1+1);
505 ya = atof(atIt->second.substr(pos1+1, pos2-pos1-1).c_str());
507 pos2 = atIt->second.find(";", pos1+1);
508 za = atof(atIt->second.substr(pos1+1, pos2-pos1-1).c_str());
510 pos2 = atIt->second.find(";", pos1+1);
511 a = atof(atIt->second.substr(pos1+1, pos2-pos1-1).c_str());
513 pos2 = atIt->second.find(")");
514 b = atof(atIt->second.substr(pos1+1, pos2-pos1-1).c_str());
516 // Get the (u,v) values of the attractor on the face
517 gp_XY uvPoint = getUV(TopoDS::Face(GeomShape),gp_XYZ(xa,ya,za));
518 Standard_Real u0 = uvPoint.X();
519 Standard_Real v0 = uvPoint.Y();
520 // We construct the python function
521 ostringstream attractorFunction;
522 attractorFunction << "def f(u,v): return ";
523 attractorFunction << _smp_phy_size << "-(" << _smp_phy_size <<"-" << a << ")";
524 attractorFunction << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
526 MESSAGE("Python function for attractor:" << std::endl << attractorFunction.str());
528 FaceId2SizeMap[TopoDS::Face(GeomShape).HashCode(471662)] =attractorFunction.str();
531 if (GeomType == TopAbs_EDGE){
532 HasSizeMapOnEdge = true;
533 HasSizeMapOnFace = true;
534 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(471662)] = atIt->second;
536 if (GeomType == TopAbs_VERTEX){
537 HasSizeMapOnVertex = true;
538 HasSizeMapOnEdge = true;
539 HasSizeMapOnFace = true;
540 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(471662)] = atIt->second;
547 // if (HasSizeMapOnFace){
548 // In all size map cases (hphy_flag = 2), at least map on face must be defined
549 MESSAGE("Setting Size Map on FACES ");
550 blsurf_data_set_sizemap_iso_cad_face(bls, size_on_surface, &_smp_phy_size);
553 if (HasSizeMapOnEdge){
554 MESSAGE("Setting Size Map on EDGES ");
555 blsurf_data_set_sizemap_iso_cad_edge(bls, size_on_edge, &_smp_phy_size);
557 if (HasSizeMapOnVertex){
558 MESSAGE("Setting Size Map on VERTICES ");
559 blsurf_data_set_sizemap_iso_cad_point(bls, size_on_vertex, &_smp_phy_size);
562 blsurf_set_param(bls, "hphydef", to_string(_phySize).c_str());
563 blsurf_set_param(bls, "hgeo_flag", to_string(_geometricMesh).c_str());
564 blsurf_set_param(bls, "relax_size", _decimesh ? "0": to_string(_geometricMesh).c_str());
565 blsurf_set_param(bls, "angle_meshs", to_string(_angleMeshS).c_str());
566 blsurf_set_param(bls, "angle_meshc", to_string(_angleMeshC).c_str());
567 blsurf_set_param(bls, "gradation", to_string(_gradation).c_str());
568 blsurf_set_param(bls, "patch_independent", _decimesh ? "1" : "0");
569 blsurf_set_param(bls, "element", _quadAllowed ? "q1.0" : "p1");
570 blsurf_set_param(bls, "verb", to_string(_verb).c_str());
573 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
574 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
575 real *duu, real *duv, real *dvv, void *user_data);
576 status_t message_callback(message_t *msg, void *user_data);
578 //=============================================================================
582 //=============================================================================
584 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
586 MESSAGE("BLSURFPlugin_BLSURF::Compute");
588 if (aShape.ShapeType() == TopAbs_COMPOUND) {
589 MESSAGE(" the shape is a COMPOUND");
592 MESSAGE(" the shape is UNKNOWN");
595 context_t *ctx = context_new();
596 context_set_message_callback(ctx, message_callback, &_comment);
598 cad_t *c = cad_new(ctx);
600 blsurf_session_t *bls = blsurf_session_new(ctx);
603 SetParameters(_hypothesis, bls);
605 TopTools_IndexedMapOfShape fmap;
606 TopTools_IndexedMapOfShape emap;
607 TopTools_IndexedMapOfShape pmap;
608 vector<Handle(Geom2d_Curve)> curves;
609 vector<Handle(Geom_Surface)> surfaces;
614 FaceId2PythonSmp.clear();
616 EdgeId2PythonSmp.clear();
618 VertexId2PythonSmp.clear();
622 assert(Py_IsInitialized());
623 PyGILState_STATE gstate;
624 gstate = PyGILState_Ensure();
632 string bad_end = "return";
633 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next()) {
634 TopoDS_Face f=TopoDS::Face(face_iter.Current());
635 if (fmap.FindIndex(f) > 0)
640 surfaces.push_back(BRep_Tool::Surface(f));
641 // Get bound values of uv surface
642 //BRep_Tool::Surface(f)->Bounds(u_min,u_max,v_min,v_max);
643 //MESSAGE("BRep_Tool::Surface(f)->Bounds(u_min,u_max,v_min,v_max): " << u_min << ", " << u_max << ", " << v_min << ", " << v_max);
645 if ((HasSizeMapOnFace) && FaceId2SizeMap.find(f.HashCode(471662))!=FaceId2SizeMap.end()){
646 MESSAGE("FaceId2SizeMap[f.HashCode(471662)].find(bad_end): " << FaceId2SizeMap[f.HashCode(471662)].find(bad_end));
647 MESSAGE("FaceId2SizeMap[f.HashCode(471662)].size(): " << FaceId2SizeMap[f.HashCode(471662)].size());
648 MESSAGE("bad_end.size(): " << bad_end.size());
649 // check if function ends with "return"
650 if (FaceId2SizeMap[f.HashCode(471662)].find(bad_end) == (FaceId2SizeMap[f.HashCode(471662)].size()-bad_end.size()-1))
652 // Expr To Python function, verification is performed at validation in GUI
653 PyObject * obj = NULL;
654 obj= PyRun_String(FaceId2SizeMap[f.HashCode(471662)].c_str(), Py_file_input, main_dict, NULL);
656 PyObject * func = NULL;
657 func = PyObject_GetAttrString(main_mod, "f");
658 FaceId2PythonSmp[iface]=func;
659 FaceId2SizeMap.erase(f.HashCode(471662));
661 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
662 cad_face_set_tag(fce, iface);
663 if(f.Orientation() != TopAbs_FORWARD){
664 cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
666 cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
669 for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next()) {
670 TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
671 int ic = emap.FindIndex(e);
676 curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
677 if ((HasSizeMapOnEdge) && EdgeId2SizeMap.find(e.HashCode(471662))!=EdgeId2SizeMap.end()){
678 if (EdgeId2SizeMap[e.HashCode(471662)].find(bad_end) == (EdgeId2SizeMap[e.HashCode(471662)].size()-bad_end.size()-1))
680 // Expr To Python function, verification is performed at validation in GUI
681 PyObject * obj = NULL;
682 obj= PyRun_String(EdgeId2SizeMap[e.HashCode(471662)].c_str(), Py_file_input, main_dict, NULL);
684 PyObject * func = NULL;
685 func = PyObject_GetAttrString(main_mod, "f");
686 EdgeId2PythonSmp[ic]=func;
687 EdgeId2SizeMap.erase(e.HashCode(471662));
689 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
690 cad_edge_set_tag(edg, ic);
691 cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
692 if (e.Orientation() == TopAbs_INTERNAL)
693 cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
697 gp_Pnt2d e0 = curves.back()->Value(tmin);
698 gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
699 Standard_Real d1=0,d2=0;
700 for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
701 TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
705 d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
708 d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
710 *ip = pmap.FindIndex(v);
713 if ((HasSizeMapOnVertex) && VertexId2SizeMap.find(v.HashCode(471662))!=VertexId2SizeMap.end()){
714 if (VertexId2SizeMap[v.HashCode(471662)].find(bad_end) == (VertexId2SizeMap[v.HashCode(471662)].size()-bad_end.size()-1))
716 // Expr To Python function, verification is performed at validation in GUI
717 PyObject * obj = NULL;
718 obj= PyRun_String(VertexId2SizeMap[v.HashCode(471662)].c_str(), Py_file_input, main_dict, NULL);
720 PyObject * func = NULL;
721 func = PyObject_GetAttrString(main_mod, "f");
722 VertexId2PythonSmp[*ip]=func;
723 VertexId2SizeMap.erase(v.HashCode(471662));
728 MESSAGE("An edge does not have 2 extremities.");
731 cad_edge_set_extremities(edg, ip1, ip2);
733 cad_edge_set_extremities(edg, ip2, ip1);
739 PyGILState_Release(gstate);
741 blsurf_data_set_cad(bls, c);
743 std::cout << std::endl;
744 std::cout << "Beginning of Surface Mesh generation" << std::endl;
745 std::cout << std::endl;
747 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
749 feclearexcept( FE_ALL_EXCEPT );
750 int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
753 status_t status = STATUS_ERROR;
758 status = blsurf_compute_mesh(bls);
761 catch ( std::exception& exc ) {
762 _comment += exc.what();
764 catch (Standard_Failure& ex) {
765 _comment += ex.DynamicType()->Name();
766 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
768 _comment += ex.GetMessageString();
772 if ( _comment.empty() )
773 _comment = "Exception in blsurf_compute_mesh()";
775 if ( status != STATUS_OK) {
776 blsurf_session_delete(bls);
780 return error(_comment);
783 std::cout << std::endl;
784 std::cout << "End of Surface Mesh generation" << std::endl;
785 std::cout << std::endl;
788 blsurf_data_get_mesh(bls, &msh);
790 blsurf_session_delete(bls);
794 return error(_comment);
798 integer nv, ne, nt, nq, vtx[4], tag;
801 mesh_get_vertex_count(msh, &nv);
802 mesh_get_edge_count(msh, &ne);
803 mesh_get_triangle_count(msh, &nt);
804 mesh_get_quadrangle_count(msh, &nq);
807 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
808 SMDS_MeshNode** nodes = new SMDS_MeshNode*[nv+1];
809 bool* tags = new bool[nv+1];
811 for(int iv=1;iv<=nv;iv++) {
812 mesh_get_vertex_coordinates(msh, iv, xyz);
813 mesh_get_vertex_tag(msh, iv, &tag);
814 nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
815 // internal point are tagged to zero
817 meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
824 for(int it=1;it<=ne;it++) {
825 mesh_get_edge_vertices(msh, it, vtx);
826 SMDS_MeshEdge* edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
827 mesh_get_edge_tag(msh, it, &tag);
830 Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
831 tags[vtx[0]] = false;
834 Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
835 tags[vtx[1]] = false;
837 meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
841 for(int it=1;it<=nt;it++) {
842 mesh_get_triangle_vertices(msh, it, vtx);
843 SMDS_MeshFace* tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
844 mesh_get_triangle_tag(msh, it, &tag);
845 meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
847 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
848 tags[vtx[0]] = false;
851 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
852 tags[vtx[1]] = false;
855 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
856 tags[vtx[2]] = false;
860 for(int it=1;it<=nq;it++) {
861 mesh_get_quadrangle_vertices(msh, it, vtx);
862 SMDS_MeshFace* quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
863 mesh_get_quadrangle_tag(msh, it, &tag);
864 meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
866 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
867 tags[vtx[0]] = false;
870 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
871 tags[vtx[1]] = false;
874 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
875 tags[vtx[2]] = false;
878 meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
879 tags[vtx[3]] = false;
885 /* release the mesh object */
886 blsurf_data_regain_mesh(bls, msh);
888 /* clean up everything */
889 blsurf_session_delete(bls);
894 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
896 if ( oldFEFlags > 0 )
897 feenableexcept( oldFEFlags );
898 feclearexcept( FE_ALL_EXCEPT );
904 //=============================================================================
908 //=============================================================================
910 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* node, const TopoDS_Shape& ed) {
911 const TopoDS_Edge edge = TopoDS::Edge(ed);
913 gp_Pnt pnt(node->X(), node->Y(), node->Z());
915 Standard_Real p0 = 0.0;
916 Standard_Real p1 = 1.0;
917 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, p0, p1);
919 GeomAPI_ProjectPointOnCurve proj(pnt, curve);
921 double pa = (double)proj.Parameter(1);
924 BRepGProp::LinearProperties(ed, LProps);
925 double lg = (double)LProps.Mass();
927 meshDS->SetNodeOnEdge(node, edge, pa);
930 //=============================================================================
934 //=============================================================================
936 ostream & BLSURFPlugin_BLSURF::SaveTo(ostream & save)
941 //=============================================================================
945 //=============================================================================
947 istream & BLSURFPlugin_BLSURF::LoadFrom(istream & load)
952 //=============================================================================
956 //=============================================================================
958 ostream & operator << (ostream & save, BLSURFPlugin_BLSURF & hyp)
960 return hyp.SaveTo( save );
963 //=============================================================================
967 //=============================================================================
969 istream & operator >> (istream & load, BLSURFPlugin_BLSURF & hyp)
971 return hyp.LoadFrom( load );
974 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
976 const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
981 uv[0]=P.X(); uv[1]=P.Y();
987 dt[0]=V1.X(); dt[1]=V1.Y();
993 dtt[0]=V2.X(); dtt[1]=V2.Y();
999 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1000 real *duu, real *duv, real *dvv, void *user_data)
1002 const Geom_Surface* geometry = (const Geom_Surface*) user_data;
1006 P=geometry->Value(uv[0],uv[1]); // S.D0(U,V,P);
1007 xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
1014 geometry->D1(uv[0],uv[1],P,D1U,D1V);
1015 du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
1016 dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
1019 if(duu && duv && dvv){
1022 gp_Vec D2U,D2V,D2UV;
1024 geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
1025 duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
1026 duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
1027 dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
1034 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
1037 if (my_u_min > uv[0]) {
1040 if (my_v_min > uv[1]) {
1043 if (my_u_max < uv[0]) {
1046 if (my_v_max < uv[1]) {
1051 if (FaceId2PythonSmp.count(face_id) != 0){
1052 PyObject * pyresult = NULL;
1053 PyObject* new_stderr = NULL;
1054 assert(Py_IsInitialized());
1055 PyGILState_STATE gstate;
1056 gstate = PyGILState_Ensure();
1057 pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],"(f,f)",uv[0],uv[1]);
1059 if ( pyresult == NULL){
1061 string err_description="";
1062 new_stderr = newPyStdOut(err_description);
1063 PySys_SetObject("stderr", new_stderr);
1065 PySys_SetObject("stderr", PySys_GetObject("__stderr__"));
1066 Py_DECREF(new_stderr);
1067 MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
1068 result = *((double*)user_data);
1071 result = PyFloat_AsDouble(pyresult);
1072 Py_DECREF(pyresult);
1075 //MESSAGE("f(" << uv[0] << "," << uv[1] << ")" << " = " << result);
1076 PyGILState_Release(gstate);
1079 *size = *((double*)user_data);
1084 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
1086 if (EdgeId2PythonSmp.count(edge_id) != 0){
1087 PyObject * pyresult = NULL;
1088 PyObject* new_stderr = NULL;
1089 assert(Py_IsInitialized());
1090 PyGILState_STATE gstate;
1091 gstate = PyGILState_Ensure();
1092 pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],"(f)",t);
1094 if ( pyresult == NULL){
1096 string err_description="";
1097 new_stderr = newPyStdOut(err_description);
1098 PySys_SetObject("stderr", new_stderr);
1100 PySys_SetObject("stderr", PySys_GetObject("__stderr__"));
1101 Py_DECREF(new_stderr);
1102 MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
1103 result = *((double*)user_data);
1106 result = PyFloat_AsDouble(pyresult);
1107 Py_DECREF(pyresult);
1110 PyGILState_Release(gstate);
1113 *size = *((double*)user_data);
1118 status_t size_on_vertex(integer point_id, real *size, void *user_data)
1120 if (VertexId2PythonSmp.count(point_id) != 0){
1121 PyObject * pyresult = NULL;
1122 PyObject* new_stderr = NULL;
1123 assert(Py_IsInitialized());
1124 PyGILState_STATE gstate;
1125 gstate = PyGILState_Ensure();
1126 pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],"");
1128 if ( pyresult == NULL){
1130 string err_description="";
1131 new_stderr = newPyStdOut(err_description);
1132 PySys_SetObject("stderr", new_stderr);
1134 PySys_SetObject("stderr", PySys_GetObject("__stderr__"));
1135 Py_DECREF(new_stderr);
1136 MESSAGE("Can't evaluate f()" << " error is " << err_description);
1137 result = *((double*)user_data);
1140 result = PyFloat_AsDouble(pyresult);
1141 Py_DECREF(pyresult);
1144 PyGILState_Release(gstate);
1147 *size = *((double*)user_data);
1152 status_t message_callback(message_t *msg, void *user_data)
1154 integer errnumber = 0;
1156 message_get_number(msg, &errnumber);
1157 message_get_description(msg, &desc);
1158 if ( errnumber < 0 ) {
1159 string * error = (string*)user_data;
1160 // if ( !error->empty() )
1162 // remove ^A from the tail
1163 int len = strlen( desc );
1164 while (len > 0 && desc[len-1] != '\n')
1166 error->append( desc, len );
1169 std::cout << desc << std::endl;
1175 //=============================================================================
1179 //=============================================================================
1180 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
1181 const TopoDS_Shape& aShape,
1182 MapShapeNbElems& aResMap)
1184 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
1185 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
1186 //int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
1187 //double _angleMeshS = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
1188 double _angleMeshC = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
1190 _physicalMesh = (int) _hypothesis->GetPhysicalMesh();
1191 _phySize = _hypothesis->GetPhySize();
1192 //_geometricMesh = (int) hyp->GetGeometricMesh();
1193 //_angleMeshS = hyp->GetAngleMeshS();
1194 _angleMeshC = _hypothesis->GetAngleMeshC();
1197 bool IsQuadratic = false;
1202 TopTools_DataMapOfShapeInteger EdgesMap;
1203 double fullLen = 0.0;
1204 double fullNbSeg = 0;
1205 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
1206 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
1207 if( EdgesMap.IsBound(E) )
1209 SMESH_subMesh *sm = aMesh.GetSubMesh(E);
1210 double aLen = SMESH_Algo::EdgeLength(E);
1213 if(_physicalMesh==1) {
1214 nb1d = (int)( aLen/_phySize + 1 );
1219 Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
1220 double fullAng = 0.0;
1221 double dp = (l-f)/200;
1226 for(int j=2; j<=200; j++) {
1229 fullAng += fabs(V1.Angle(V2));
1233 nb1d = (int)( fullAng/_angleMeshC + 1 );
1236 std::vector<int> aVec(SMDSEntity_Last);
1237 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1238 if( IsQuadratic > 0 ) {
1239 aVec[SMDSEntity_Node] = 2*nb1d - 1;
1240 aVec[SMDSEntity_Quad_Edge] = nb1d;
1243 aVec[SMDSEntity_Node] = nb1d - 1;
1244 aVec[SMDSEntity_Edge] = nb1d;
1246 aResMap.insert(std::make_pair(sm,aVec));
1247 EdgesMap.Bind(E,nb1d);
1249 double ELen = fullLen/fullNbSeg;
1253 // try to evaluate as in MEFISTO
1254 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
1255 TopoDS_Face F = TopoDS::Face( exp.Current() );
1256 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
1258 BRepGProp::SurfaceProperties(F,G);
1259 double anArea = G.Mass();
1261 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
1262 nb1d += EdgesMap.Find(exp1.Current());
1264 int nbFaces = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
1265 int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
1266 std::vector<int> aVec(SMDSEntity_Last);
1267 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1269 int nb1d_in = (nbFaces*3 - nb1d) / 2;
1270 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
1271 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
1274 aVec[SMDSEntity_Node] = nbNodes;
1275 aVec[SMDSEntity_Triangle] = nbFaces;
1277 aResMap.insert(std::make_pair(sm,aVec));
1284 BRepGProp::VolumeProperties(aShape,G);
1285 double aVolume = G.Mass();
1286 double tetrVol = 0.1179*ELen*ELen*ELen;
1287 int nbVols = (int)aVolume/tetrVol;
1288 int nb1d_in = (int) ( ( nbVols*6 - fullNbSeg ) / 6 );
1289 std::vector<int> aVec(SMDSEntity_Last);
1290 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1292 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
1293 aVec[SMDSEntity_Quad_Tetra] = nbVols;
1296 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
1297 aVec[SMDSEntity_Tetra] = nbVols;
1299 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1300 aResMap.insert(std::make_pair(sm,aVec));