1 // Copyright (C) 2007-2015 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, or (at your option) any later version.
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
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)
27 #include "BLSURFPlugin_BLSURF.hxx"
28 #include "BLSURFPlugin_Hypothesis.hxx"
29 #include "BLSURFPlugin_Attractor.hxx"
32 #include <meshgems/meshgems.h>
33 #include <meshgems/cadsurf.h>
34 #include <meshgems/precad.h>
37 #include <structmember.h>
40 #include <Basics_Utils.hxx>
41 #include <Basics_OCCTVersion.hxx>
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 #include <SMESH_File.hxx>
54 #include <utilities.h>
62 // OPENCASCADE includes
63 #include <BRepBuilderAPI_MakeFace.hxx>
64 #include <BRepBuilderAPI_MakePolygon.hxx>
65 //#include <BRepBuilderAPI_MakeVertex.hxx>
66 #include <BRepGProp.hxx>
67 #include <BRepTools.hxx>
68 #include <BRep_Builder.hxx>
69 #include <BRep_Tool.hxx>
70 #include <GProp_GProps.hxx>
71 #include <Geom2d_Curve.hxx>
72 #include <GeomAPI_ProjectPointOnCurve.hxx>
73 #include <GeomAPI_ProjectPointOnSurf.hxx>
74 #include <Geom_Curve.hxx>
75 #include <Geom_Surface.hxx>
76 #include <NCollection_Map.hxx>
77 #include <Standard_ErrorHandler.hxx>
79 #include <TopExp_Explorer.hxx>
80 #include <TopTools_DataMapOfShapeInteger.hxx>
81 #include <TopTools_IndexedMapOfShape.hxx>
82 #include <TopTools_MapOfShape.hxx>
84 #include <TopoDS_Compound.hxx>
85 #include <TopoDS_Edge.hxx>
86 #include <TopoDS_Face.hxx>
87 #include <TopoDS_Shape.hxx>
88 #include <TopoDS_Vertex.hxx>
89 #include <TopoDS_Wire.hxx>
91 #include <gp_Pnt2d.hxx>
99 /* ==================================
100 * =========== PYTHON ==============
101 * ==================================*/
112 PyStdOut_dealloc(PyStdOut *self)
118 PyStdOut_write(PyStdOut *self, PyObject *args)
122 if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
125 *(self->out)=*(self->out)+c;
131 static PyMethodDef PyStdOut_methods[] = {
132 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
133 PyDoc_STR("write(string) -> None")},
134 {NULL, NULL} /* sentinel */
137 static PyMemberDef PyStdOut_memberlist[] = {
138 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
139 (char*)"flag indicating that a space needs to be printed; used by print"},
140 {NULL} /* Sentinel */
143 static PyTypeObject PyStdOut_Type = {
144 /* The ob_type field must be initialized in the module init function
145 * to be portable to Windows without using C++. */
146 PyObject_HEAD_INIT(NULL)
149 sizeof(PyStdOut), /*tp_basicsize*/
152 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
159 0, /*tp_as_sequence*/
164 PyObject_GenericGetAttr, /*tp_getattro*/
165 /* softspace is writable: we must supply tp_setattro */
166 PyObject_GenericSetAttr, /* tp_setattro */
168 Py_TPFLAGS_DEFAULT, /*tp_flags*/
172 0, /*tp_richcompare*/
173 0, /*tp_weaklistoffset*/
176 PyStdOut_methods, /*tp_methods*/
177 PyStdOut_memberlist, /*tp_members*/
191 PyObject * newPyStdOut( std::string& out )
193 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
198 return (PyObject*)self;
203 ////////////////////////END PYTHON///////////////////////////
205 //////////////////MY MAPS////////////////////////////////////////
207 TopTools_IndexedMapOfShape FacesWithSizeMap;
208 std::map<int,string> FaceId2SizeMap;
209 TopTools_IndexedMapOfShape EdgesWithSizeMap;
210 std::map<int,string> EdgeId2SizeMap;
211 TopTools_IndexedMapOfShape VerticesWithSizeMap;
212 std::map<int,string> VertexId2SizeMap;
214 std::map<int,PyObject*> FaceId2PythonSmp;
215 std::map<int,PyObject*> EdgeId2PythonSmp;
216 std::map<int,PyObject*> VertexId2PythonSmp;
218 typedef std::map<int, std::vector< BLSURFPlugin_Attractor* > > TId2ClsAttractorVec;
219 TId2ClsAttractorVec FaceId2ClassAttractor;
220 TId2ClsAttractorVec FaceIndex2ClassAttractor;
221 std::map<int,std::vector<double> > FaceId2AttractorCoords;
224 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
225 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
226 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
227 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
229 bool HasSizeMapOnFace=false;
230 bool HasSizeMapOnEdge=false;
231 bool HasSizeMapOnVertex=false;
232 //bool HasAttractorOnFace=false;
234 //=============================================================================
238 //=============================================================================
240 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
242 : SMESH_2D_Algo(hypId, studyId, gen)
244 MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
246 _name = "MG-CADSurf";//"BLSURF";
247 _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
248 _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
249 _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
250 _requireDiscreteBoundary = false;
251 _onlyUnaryInput = false;
253 _supportSubmeshes = true;
255 smeshGen_i = SMESH_Gen_i::GetSMESHGen();
256 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
257 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
259 MESSAGE("studyid = " << _studyId);
262 myStudy = aStudyMgr->GetStudyByID(_studyId);
263 if ( !myStudy->_is_nil() )
264 MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
266 /* Initialize the Python interpreter */
267 assert(Py_IsInitialized());
268 PyGILState_STATE gstate;
269 gstate = PyGILState_Ensure();
272 main_mod = PyImport_AddModule("__main__");
275 main_dict = PyModule_GetDict(main_mod);
277 PyRun_SimpleString("from math import *");
278 PyGILState_Release(gstate);
280 FacesWithSizeMap.Clear();
281 FaceId2SizeMap.clear();
282 EdgesWithSizeMap.Clear();
283 EdgeId2SizeMap.clear();
284 VerticesWithSizeMap.Clear();
285 VertexId2SizeMap.clear();
286 FaceId2PythonSmp.clear();
287 EdgeId2PythonSmp.clear();
288 VertexId2PythonSmp.clear();
289 FaceId2AttractorCoords.clear();
290 FaceId2ClassAttractor.clear();
291 FaceIndex2ClassAttractor.clear();
292 FacesWithEnforcedVertices.Clear();
293 FaceId2EnforcedVertexCoords.clear();
294 EnfVertexCoords2ProjVertex.clear();
295 EnfVertexCoords2EnfVertexList.clear();
297 _compute_canceled = false;
300 //=============================================================================
304 //=============================================================================
306 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
308 MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
312 //=============================================================================
316 //=============================================================================
318 bool BLSURFPlugin_BLSURF::CheckHypothesis
320 const TopoDS_Shape& aShape,
321 SMESH_Hypothesis::Hypothesis_Status& aStatus)
324 _haveViscousLayers = false;
326 list<const SMESHDS_Hypothesis*>::const_iterator itl;
327 const SMESHDS_Hypothesis* theHyp;
329 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape,
330 /*ignoreAuxiliary=*/false);
331 aStatus = SMESH_Hypothesis::HYP_OK;
334 return true; // can work with no hypothesis
337 for ( itl = hyps.begin(); itl != hyps.end() && ( aStatus == HYP_OK ); ++itl )
340 string hypName = theHyp->GetName();
341 if ( hypName == BLSURFPlugin_Hypothesis::GetHypType() )
343 _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
345 if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
346 _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
347 // hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
348 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
350 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
352 if ( !_haveViscousLayers )
354 if ( error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus )))
355 _haveViscousLayers = true;
360 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
363 return aStatus == SMESH_Hypothesis::HYP_OK;
366 //=============================================================================
368 * Pass parameters to MG-CADSurf
370 //=============================================================================
372 inline std::string val_to_string(double d)
374 std::ostringstream o;
379 inline std::string val_to_string_rel(double d)
381 std::ostringstream o;
387 inline std::string val_to_string(int i)
389 std::ostringstream o;
394 inline std::string val_to_string_rel(int i)
396 std::ostringstream o;
402 double _smp_phy_size;
403 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
404 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
405 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
411 /////////////////////////////////////////////////////////
412 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_Pnt& point)
414 projectionPoint myPoint;
415 Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
416 GeomAPI_ProjectPointOnSurf projector( point, surface );
417 if ( !projector.IsDone() || projector.NbPoints()==0 )
418 throw "getProjectionPoint: Can't project";
420 Quantity_Parameter u,v;
421 projector.LowerDistanceParameters(u,v);
422 myPoint.uv = gp_XY(u,v);
423 gp_Pnt aPnt = projector.NearestPoint();
424 myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
428 /////////////////////////////////////////////////////////
430 /////////////////////////////////////////////////////////
431 double getT(const TopoDS_Edge& edge, const gp_Pnt& point)
434 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
435 GeomAPI_ProjectPointOnCurve projector( point, curve);
436 if ( projector.NbPoints() == 0 )
438 return projector.LowerDistanceParameter();
441 /////////////////////////////////////////////////////////
442 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
444 MESSAGE("BLSURFPlugin_BLSURF::entryToShape "<<entry );
445 GEOM::GEOM_Object_var aGeomObj;
446 TopoDS_Shape S = TopoDS_Shape();
447 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
448 if (!aSObj->_is_nil()) {
449 CORBA::Object_var obj = aSObj->GetObject();
450 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
453 if ( !aGeomObj->_is_nil() )
454 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
458 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
460 BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
465 // Get the (u,v) values of the enforced vertex on the face
466 projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
468 MESSAGE("Enforced Vertex: " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z());
469 MESSAGE("Projected Vertex: " << myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z());
470 MESSAGE("Parametric coordinates: " << myPoint.uv.X() << ", " << myPoint.uv.Y() );
472 enf_coords.push_back(aPnt.X());
473 enf_coords.push_back(aPnt.Y());
474 enf_coords.push_back(aPnt.Z());
476 coords.push_back(myPoint.uv.X());
477 coords.push_back(myPoint.uv.Y());
478 coords.push_back(myPoint.xyz.X());
479 coords.push_back(myPoint.xyz.Y());
480 coords.push_back(myPoint.xyz.Z());
482 s_coords.push_back(myPoint.xyz.X());
483 s_coords.push_back(myPoint.xyz.Y());
484 s_coords.push_back(myPoint.xyz.Z());
486 // Save pair projected vertex / enf vertex
487 MESSAGE("Storing pair projected vertex / enf vertex:");
488 MESSAGE("("<< myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z() <<") / (" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z()<<")");
489 EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
490 MESSAGE("Group name is: \"" << enfVertex->grpName << "\"");
491 pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
492 BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
493 ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
494 if (ret.second == false) {
496 (*it)->grpName = enfVertex->grpName;
500 if (! FacesWithEnforcedVertices.Contains(faceShape)) {
501 key = FacesWithEnforcedVertices.Add(faceShape);
504 key = FacesWithEnforcedVertices.FindIndex(faceShape);
507 // If a node is already created by an attractor, do not create enforced vertex
508 int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
509 bool sameAttractor = false;
510 if (attractorKey >= 0)
511 if (FaceId2AttractorCoords.count(attractorKey) > 0)
512 if (FaceId2AttractorCoords[attractorKey] == coords)
513 sameAttractor = true;
515 if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
516 MESSAGE("Map of enf. vertex has key " << key)
517 MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
519 FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
521 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
522 MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
525 MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
526 if (! sameAttractor) {
527 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
529 FaceId2EnforcedVertexCoords[key] = ens;
532 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
536 /////////////////////////////////////////////////////////
537 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
539 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
542 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
544 for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
545 enfVertex = *enfVertexListIt;
546 // Case of manual coords
547 if (enfVertex->coords.size() != 0) {
548 aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
549 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
552 // Case of geom vertex coords
553 if (enfVertex->geomEntry != "") {
554 TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
555 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
556 if (GeomType == TopAbs_VERTEX){
557 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
558 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
561 if (GeomType == TopAbs_COMPOUND){
562 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
563 if (it.Value().ShapeType() == TopAbs_VERTEX){
564 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
565 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
573 /////////////////////////////////////////////////////////
574 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction, double defaultSize)
576 MESSAGE("Attractor function: "<< AttractorFunction);
577 double xa, ya, za; // Coordinates of attractor point
578 double a, b; // Attractor parameter
580 bool createNode=false; // To create a node on attractor projection
582 const char *sep = ";";
583 // atIt->second has the following pattern:
584 // ATTRACTOR(xa;ya;za;a;b;True|False;d)
586 // xa;ya;za : coordinates of attractor
587 // a : desired size on attractor
588 // b : distance of influence of attractor
589 // d : distance until which the size remains constant
591 // We search the parameters in the string
593 pos1 = AttractorFunction.find(sep);
594 if (pos1!=string::npos)
595 xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
597 pos2 = AttractorFunction.find(sep, pos1+1);
598 if (pos2!=string::npos) {
599 ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
603 pos2 = AttractorFunction.find(sep, pos1+1);
604 if (pos2!=string::npos) {
605 za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
609 pos2 = AttractorFunction.find(sep, pos1+1);
610 if (pos2!=string::npos) {
611 a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
615 pos2 = AttractorFunction.find(sep, pos1+1);
616 if (pos2!=string::npos) {
617 b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
621 pos2 = AttractorFunction.find(sep, pos1+1);
622 if (pos2!=string::npos) {
623 string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
624 MESSAGE("createNode: " << createNodeStr);
625 createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
629 pos2 = AttractorFunction.find(")");
630 if (pos2!=string::npos) {
631 d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
634 // Get the (u,v) values of the attractor on the face
635 projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
636 gp_XY uvPoint = myPoint.uv;
637 gp_XYZ xyzPoint = myPoint.xyz;
638 Standard_Real u0 = uvPoint.X();
639 Standard_Real v0 = uvPoint.Y();
640 Standard_Real x0 = xyzPoint.X();
641 Standard_Real y0 = xyzPoint.Y();
642 Standard_Real z0 = xyzPoint.Z();
643 std::vector<double> coords;
644 coords.push_back(u0);
645 coords.push_back(v0);
646 coords.push_back(x0);
647 coords.push_back(y0);
648 coords.push_back(z0);
649 // We construct the python function
650 ostringstream attractorFunctionStream;
651 attractorFunctionStream << "def f(u,v): return ";
652 attractorFunctionStream << defaultSize << "-(" << defaultSize <<"-" << a << ")";
653 //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
654 // rnc: make possible to keep the size constant until
655 // a defined distance. Distance is expressed as the positiv part
656 // of r-d where r is the distance to (u0,v0)
657 attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
659 MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
662 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
663 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
666 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
668 FaceId2SizeMap[key] =attractorFunctionStream.str();
670 MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
671 FaceId2AttractorCoords[key] = coords;
673 // // Test for new attractors
674 // gp_Pnt myP(xyzPoint);
675 // TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
676 // BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
677 // myAttractor.SetParameters(a, defaultSize, b, d);
678 // myAttractor.SetType(1);
679 // FaceId2ClassAttractor[key] = myAttractor;
680 // if(FaceId2ClassAttractor[key].GetFace().IsNull()){
681 // MESSAGE("face nulle ");
684 // MESSAGE("face OK");
686 // if (FaceId2ClassAttractor[key].GetAttractorShape().IsNull()){
687 // MESSAGE("pas de point");
690 // MESSAGE("point OK");
693 // One sub-shape to get ids from
694 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(TopoDS_Shape theMainShape, TopoDS_Shape theSubShape,
695 TopAbs_ShapeEnum theShapeType)
697 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
698 TopTools_IndexedMapOfShape anIndices;
700 TopExp::MapShapes(theMainShape, theShapeType, anIndices);
702 // Standard_Boolean result = BRepTools::Write(theMainShape,"main_shape.brep");
704 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
706 int face_id = anIndices.FindIndex(face_iter.Current());
708 throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
709 face_ids.push_back(face_id);
710 // std::ostringstream o;
711 // o << "face_" << face_id << ".brep";
712 // std::string face_name = o.str();
713 // const TopoDS_Face& face = TopoDS::Face(face_iter.Current());
714 // Standard_Boolean result = BRepTools::Write(face,face_name.c_str());
720 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(SMESH_Mesh* theMesh,
721 TopoDS_Shape theSubShape,
722 TopAbs_ShapeEnum theShapeType)
724 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
726 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
728 int face_id = theMesh->GetMeshDS()->ShapeToIndex(face_iter.Current());
730 throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
731 face_ids.push_back(face_id);
737 void BLSURFPlugin_BLSURF::addCoordsFromVertices(const std::vector<std::string> &theVerticesEntries, std::vector<double> &theVerticesCoords)
739 for (std::vector<std::string>::const_iterator it = theVerticesEntries.begin(); it != theVerticesEntries.end(); it++)
741 BLSURFPlugin_Hypothesis::TEntry theVertexEntry = *it;
742 MESSAGE("Vertex entry " << theVertexEntry);
743 addCoordsFromVertex(theVertexEntry, theVerticesCoords);
748 void BLSURFPlugin_BLSURF::addCoordsFromVertex(BLSURFPlugin_Hypothesis::TEntry theVertexEntry, std::vector<double> &theVerticesCoords)
750 if (theVertexEntry!="")
752 TopoDS_Shape aShape = entryToShape(theVertexEntry);
754 gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex( aShape ) );
755 double theX, theY, theZ;
760 theVerticesCoords.push_back(theX);
761 theVerticesCoords.push_back(theY);
762 theVerticesCoords.push_back(theZ);
766 /////////////////////////////////////////////////////////
767 void BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
769 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity");
771 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
772 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
774 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_FACE);
775 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_FACE);
777 TPreCadPeriodicityIDs preCadFacesPeriodicityIDs;
778 preCadFacesPeriodicityIDs.shape1IDs = theFace1_ids;
779 preCadFacesPeriodicityIDs.shape2IDs = theFace2_ids;
781 MESSAGE("preCadPeriodicity.theSourceVerticesEntries.size(): " << preCadPeriodicity.theSourceVerticesEntries.size());
782 MESSAGE("preCadPeriodicity.theTargetVerticesEntries.size(): " << preCadPeriodicity.theTargetVerticesEntries.size());
784 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadFacesPeriodicityIDs.theSourceVerticesCoords);
785 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadFacesPeriodicityIDs.theTargetVerticesCoords);
787 MESSAGE("preCadFacesPeriodicityIDs.theSourceVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theSourceVerticesCoords.size());
788 MESSAGE("preCadFacesPeriodicityIDs.theTargetVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theTargetVerticesCoords.size());
790 _preCadFacesIDsPeriodicityVector.push_back(preCadFacesPeriodicityIDs);
791 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
792 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity END");
796 /////////////////////////////////////////////////////////
797 void BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
799 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity");
801 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
802 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
804 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_EDGE);
805 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_EDGE);
807 TPreCadPeriodicityIDs preCadEdgesPeriodicityIDs;
808 preCadEdgesPeriodicityIDs.shape1IDs = theEdge1_ids;
809 preCadEdgesPeriodicityIDs.shape2IDs = theEdge2_ids;
811 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadEdgesPeriodicityIDs.theSourceVerticesCoords);
812 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadEdgesPeriodicityIDs.theTargetVerticesCoords);
814 _preCadEdgesIDsPeriodicityVector.push_back(preCadEdgesPeriodicityIDs);
815 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
816 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity END");
820 /////////////////////////////////////////////////////////
821 void BLSURFPlugin_BLSURF::createFacesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theFace1, BLSURFPlugin_Hypothesis::TEntry theFace2)
823 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity");
825 TopoDS_Shape GeomShape1 = entryToShape(theFace1);
826 TopoDS_Shape GeomShape2 = entryToShape(theFace2);
828 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomShape1, TopAbs_FACE);
829 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomShape2, TopAbs_FACE);
831 // Only one face id, since only a face can be selected
832 int theFace1_id = theFace1_ids[0];
833 int theFace2_id = theFace2_ids[0];
835 std::pair<int, int> pairOfFacesID = std::make_pair(theFace1_id, theFace2_id);
837 _facesIDsPeriodicityVector.push_back(pairOfFacesID);
838 MESSAGE("_facesIDsPeriodicityVector.size() = " << _facesIDsPeriodicityVector.size());
839 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity END");
844 /////////////////////////////////////////////////////////
845 void BLSURFPlugin_BLSURF::createEdgesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theFace1, BLSURFPlugin_Hypothesis::TEntry theEdge1,
846 BLSURFPlugin_Hypothesis::TEntry theFace2, BLSURFPlugin_Hypothesis::TEntry theEdge2, int edge_orientation)
848 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity");
850 TEdgePeriodicityIDs edgePeriodicityIDs;
854 TopoDS_Shape GeomFace1 = entryToShape(theFace1);
855 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomFace1, TopAbs_FACE);
856 // Only one face id, since only a face can be selected
857 edgePeriodicityIDs.theFace1ID = theFace1_ids[0];
860 edgePeriodicityIDs.theFace1ID = 0;
863 TopoDS_Shape GeomFace2 = entryToShape(theFace2);
864 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomFace2, TopAbs_FACE);
865 edgePeriodicityIDs.theFace2ID = theFace2_ids[0];
868 edgePeriodicityIDs.theFace2ID = 0;
870 TopoDS_Shape GeomEdge1 = entryToShape(theEdge1);
871 TopoDS_Shape GeomEdge2 = entryToShape(theEdge2);
873 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge1, TopAbs_EDGE);
874 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge2, TopAbs_EDGE);
876 if (edge_orientation == 0 && GeomEdge1.Closed())
878 // if edge is closed, we have to set its orientation
879 MESSAGE("GeomEdge1.Orientation() = " << GeomEdge1.Orientation());
880 MESSAGE("GeomEdge2.Orientation() = " << GeomEdge2.Orientation());
881 if(GeomEdge1.Orientation() == TopAbs_FORWARD)
882 edge_orientation = CAD_ORIENTATION_REVERSED;
884 edge_orientation = CAD_ORIENTATION_FORWARD;
887 // Only one edge id, since only a edge can be selected
888 edgePeriodicityIDs.theEdge1ID = theEdge1_ids[0];
889 edgePeriodicityIDs.theEdge2ID = theEdge2_ids[0];
890 edgePeriodicityIDs.edge_orientation = edge_orientation;
892 _edgesIDsPeriodicityVector.push_back(edgePeriodicityIDs);
893 MESSAGE("_edgesIDsPeriodicityVector.size() = " << _edgesIDsPeriodicityVector.size());
894 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity END");
899 /////////////////////////////////////////////////////////
900 void BLSURFPlugin_BLSURF::createVerticesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theEdge1, BLSURFPlugin_Hypothesis::TEntry theVertex1,
901 BLSURFPlugin_Hypothesis::TEntry theEdge2, BLSURFPlugin_Hypothesis::TEntry theVertex2)
903 MESSAGE("BLSURFPlugin_BLSURF::createVerticesPeriodicity");
905 TopoDS_Shape GeomEdge1 = entryToShape(theEdge1);
906 TopoDS_Shape GeomVertex1 = entryToShape(theVertex1);
907 TopoDS_Shape GeomEdge2 = entryToShape(theEdge2);
908 TopoDS_Shape GeomVertex2 = entryToShape(theVertex2);
910 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge1, TopAbs_EDGE);
911 TListOfIDs vertices1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomVertex1, TopAbs_VERTEX);
912 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge2, TopAbs_EDGE);
913 TListOfIDs vertices2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomVertex2, TopAbs_VERTEX);
915 // Only one vertex id, since only a vertex can be selected
916 TVertexPeriodicityIDs vertexPeriodicityIDs;
917 vertexPeriodicityIDs.theEdge1ID = theEdge1_ids[0];
918 vertexPeriodicityIDs.theVertex1ID = vertices1_ids[0];
919 vertexPeriodicityIDs.theEdge2ID = theEdge2_ids[0];
920 vertexPeriodicityIDs.theVertex2ID = vertices2_ids[0];
922 _verticesIDsPeriodicityVector.push_back(vertexPeriodicityIDs);
923 MESSAGE("_verticesIDsPeriodicityVector.size() = " << _verticesIDsPeriodicityVector.size());
924 MESSAGE("BLSURFPlugin_BLSURF::createVerticesPeriodicity END");
928 /////////////////////////////////////////////////////////
930 void BLSURFPlugin_BLSURF::SetParameters(const BLSURFPlugin_Hypothesis* hyp,
931 cadsurf_session_t * css,
932 precad_session_t * pcs,
933 const TopoDS_Shape& theGeomShape,
938 // Clear map so that it is not stored in the algorithm with old enforced vertices in it
939 EnfVertexCoords2EnfVertexList.clear();
941 double diagonal = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
942 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
943 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
944 int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
945 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
946 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
947 double _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
948 bool _minSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
949 double _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
950 bool _maxSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
951 double _gradation = BLSURFPlugin_Hypothesis::GetDefaultGradation();
952 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
953 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
954 double _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
955 bool _anisotropic = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
956 double _anisotropicRatio = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
957 bool _removeTinyEdges = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
958 double _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
959 bool _badElementRemoval = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
960 double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
961 bool _optimizeMesh = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
962 bool _quadraticMesh = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
963 int _verb = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
964 int _topology = BLSURFPlugin_Hypothesis::GetDefaultTopology();
967 int _precadMergeEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
968 int _precadProcess3DTopology = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
969 int _precadDiscardInput = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
973 MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
974 _physicalMesh = (int) hyp->GetPhysicalMesh();
975 _geometricMesh = (int) hyp->GetGeometricMesh();
976 if (hyp->GetPhySize() > 0) {
977 _phySize = hyp->GetPhySize();
978 // if user size is not explicitly specified, "relative" flag is ignored
979 _phySizeRel = hyp->IsPhySizeRel();
981 if (hyp->GetMinSize() > 0) {
982 _minSize = hyp->GetMinSize();
983 // if min size is not explicitly specified, "relative" flag is ignored
984 _minSizeRel = hyp->IsMinSizeRel();
986 if (hyp->GetMaxSize() > 0) {
987 _maxSize = hyp->GetMaxSize();
988 // if max size is not explicitly specified, "relative" flag is ignored
989 _maxSizeRel = hyp->IsMaxSizeRel();
991 if (hyp->GetGradation() > 0)
992 _gradation = hyp->GetGradation();
993 _quadAllowed = hyp->GetQuadAllowed();
994 if (hyp->GetAngleMesh() > 0)
995 _angleMesh = hyp->GetAngleMesh();
996 if (hyp->GetChordalError() > 0)
997 _chordalError = hyp->GetChordalError();
998 _anisotropic = hyp->GetAnisotropic();
999 if (hyp->GetAnisotropicRatio() >= 0)
1000 _anisotropicRatio = hyp->GetAnisotropicRatio();
1001 _removeTinyEdges = hyp->GetRemoveTinyEdges();
1002 if (hyp->GetTinyEdgeLength() > 0)
1003 _tinyEdgeLength = hyp->GetTinyEdgeLength();
1004 _badElementRemoval = hyp->GetBadElementRemoval();
1005 if (hyp->GetBadElementAspectRatio() >= 0)
1006 _badElementAspectRatio = hyp->GetBadElementAspectRatio();
1007 _optimizeMesh = hyp->GetOptimizeMesh();
1008 _quadraticMesh = hyp->GetQuadraticMesh();
1009 _verb = hyp->GetVerbosity();
1010 _topology = (int) hyp->GetTopology();
1012 _precadMergeEdges = hyp->GetPreCADMergeEdges();
1013 _precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
1014 _precadDiscardInput = hyp->GetPreCADDiscardInput();
1016 const BLSURFPlugin_Hypothesis::TOptionValues& opts = hyp->GetOptionValues();
1017 BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
1018 for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
1019 if ( !opIt->second.empty() ) {
1020 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
1021 set_param(css, opIt->first.c_str(), opIt->second.c_str());
1024 const BLSURFPlugin_Hypothesis::TOptionValues& custom_opts = hyp->GetCustomOptionValues();
1025 for ( opIt = custom_opts.begin(); opIt != custom_opts.end(); ++opIt )
1026 if ( !opIt->second.empty() ) {
1027 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
1028 set_param(css, opIt->first.c_str(), opIt->second.c_str());
1031 const BLSURFPlugin_Hypothesis::TOptionValues& preCADopts = hyp->GetPreCADOptionValues();
1032 for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
1033 if ( !opIt->second.empty() ) {
1035 MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
1036 precad_set_param(pcs, opIt->first.c_str(), opIt->second.c_str());
1039 const BLSURFPlugin_Hypothesis::TOptionValues& custom_preCADopts = hyp->GetCustomPreCADOptionValues();
1040 for ( opIt = custom_preCADopts.begin(); opIt != custom_preCADopts.end(); ++opIt )
1041 if ( !opIt->second.empty() ) {
1043 MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
1044 precad_set_param(pcs, opIt->first.c_str(), opIt->second.c_str());
1048 // //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
1049 // // GetDefaultPhySize() sometimes leads to computation failure
1050 // // GDD 26/07/2012 From Distene documentation, global physical size default value = diag/100
1051 // _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal);
1052 // _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
1053 // _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
1054 // _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
1055 // _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
1056 // MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
1060 if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
1062 precad_set_param(pcs, "verbose", val_to_string(_verb).c_str());
1063 precad_set_param(pcs, "merge_edges", _precadMergeEdges ? "1" : "0");
1064 precad_set_param(pcs, "process_3d_topology", _precadProcess3DTopology ? "1" : "0");
1065 precad_set_param(pcs, "discard_input_topology", _precadDiscardInput ? "1" : "0");
1067 // unlimit mesh size (issue 0022266)
1068 set_param(css, "max_number_of_points_per_patch", "1000000");
1070 bool useGradation = false;
1071 switch (_physicalMesh)
1073 case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
1074 set_param(css, "physical_size_mode", "global");
1075 set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1077 case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
1078 set_param(css, "physical_size_mode", "local");
1079 set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1080 useGradation = true;
1083 set_param(css, "physical_size_mode", "none");
1086 switch (_geometricMesh)
1088 case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
1089 set_param(css, "geometric_size_mode", "global");
1090 set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
1091 set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
1092 useGradation = true;
1094 case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
1095 set_param(css, "geometric_size_mode", "local");
1096 set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
1097 set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
1098 useGradation = true;
1101 set_param(css, "geometric_size_mode", "none");
1104 if ( hyp && hyp->GetPhySize() > 0 ) {
1105 // user size is explicitly specified via hypothesis parameters
1106 // min and max sizes should be compared with explicitly specified user size
1107 // - compute absolute min size
1108 double mins = _minSizeRel ? _minSize * diagonal : _minSize;
1109 // - min size should not be greater than user size
1110 if ( _phySize < mins )
1111 set_param(css, "min_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1113 set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
1114 // - compute absolute max size
1115 double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
1116 // - max size should not be less than user size
1117 if ( _phySize > maxs )
1118 set_param(css, "max_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1120 set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1123 // user size is not explicitly specified
1124 // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1125 set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
1126 // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1127 set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1129 // anisotropic and quadrangle mesh requires disabling gradation
1130 if ( _anisotropic && _quadAllowed )
1131 useGradation = false; // limitation of V1.3
1133 set_param(css, "gradation", val_to_string(_gradation).c_str());
1134 set_param(css, "element_generation", _quadAllowed ? "quad_dominant" : "triangle");
1137 set_param(css, "metric", _anisotropic ? "anisotropic" : "isotropic");
1139 set_param(css, "anisotropic_ratio", val_to_string(_anisotropicRatio).c_str());
1140 set_param(css, "remove_tiny_edges", _removeTinyEdges ? "1" : "0");
1141 if ( _removeTinyEdges )
1142 set_param(css, "tiny_edge_length", val_to_string(_tinyEdgeLength).c_str());
1143 set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
1144 if ( _badElementRemoval )
1145 set_param(css, "bad_surface_element_aspect_ratio", val_to_string(_badElementAspectRatio).c_str());
1146 set_param(css, "optimisation", _optimizeMesh ? "yes" : "no");
1147 set_param(css, "element_order", _quadraticMesh ? "quadratic" : "linear");
1148 set_param(css, "verbose", val_to_string(_verb).c_str());
1150 _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
1152 std::cout << "_smp_phy_size = " << _smp_phy_size << std::endl;
1154 if (_physicalMesh == BLSURFPlugin_Hypothesis::PhysicalLocalSize){
1155 TopoDS_Shape GeomShape;
1156 TopoDS_Shape AttShape;
1157 TopAbs_ShapeEnum GeomType;
1159 // Standard Size Maps
1161 MESSAGE("Setting a Size Map");
1162 const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
1163 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
1164 for ( ; smIt != sizeMaps.end(); ++smIt ) {
1165 if ( !smIt->second.empty() ) {
1166 MESSAGE("cadsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
1167 GeomShape = entryToShape(smIt->first);
1168 GeomType = GeomShape.ShapeType();
1169 MESSAGE("Geomtype is " << GeomType);
1172 if (GeomType == TopAbs_COMPOUND){
1173 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1175 if (it.Value().ShapeType() == TopAbs_FACE){
1176 HasSizeMapOnFace = true;
1177 if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
1178 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
1181 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
1182 // MESSAGE("Face with key " << key << " already in map");
1184 FaceId2SizeMap[key] = smIt->second;
1187 if (it.Value().ShapeType() == TopAbs_EDGE){
1188 HasSizeMapOnEdge = true;
1189 HasSizeMapOnFace = true;
1190 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
1191 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
1194 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
1195 // MESSAGE("Edge with key " << key << " already in map");
1197 EdgeId2SizeMap[key] = smIt->second;
1199 // Group of vertices
1200 if (it.Value().ShapeType() == TopAbs_VERTEX){
1201 HasSizeMapOnVertex = true;
1202 HasSizeMapOnEdge = true;
1203 HasSizeMapOnFace = true;
1204 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
1205 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
1208 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
1209 MESSAGE("Group of vertices with key " << key << " already in map");
1211 MESSAGE("Group of vertices with key " << key << " has a size map: " << smIt->second);
1212 VertexId2SizeMap[key] = smIt->second;
1217 if (GeomType == TopAbs_FACE){
1218 HasSizeMapOnFace = true;
1219 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
1220 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
1223 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1224 // MESSAGE("Face with key " << key << " already in map");
1226 FaceId2SizeMap[key] = smIt->second;
1229 if (GeomType == TopAbs_EDGE){
1230 HasSizeMapOnEdge = true;
1231 HasSizeMapOnFace = true;
1232 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
1233 key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
1236 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
1237 // MESSAGE("Edge with key " << key << " already in map");
1239 EdgeId2SizeMap[key] = smIt->second;
1242 if (GeomType == TopAbs_VERTEX){
1243 HasSizeMapOnVertex = true;
1244 HasSizeMapOnEdge = true;
1245 HasSizeMapOnFace = true;
1246 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
1247 key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
1250 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
1251 MESSAGE("Vertex with key " << key << " already in map");
1253 MESSAGE("Vertex with key " << key << " has a size map: " << smIt->second);
1254 VertexId2SizeMap[key] = smIt->second;
1262 // TODO appeler le constructeur des attracteurs directement ici
1263 MESSAGE("Setting Attractors");
1264 // if ( !_phySizeRel ) {
1265 const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
1266 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
1267 for ( ; atIt != attractors.end(); ++atIt ) {
1268 if ( !atIt->second.empty() ) {
1269 MESSAGE("cadsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
1270 GeomShape = entryToShape(atIt->first);
1271 GeomType = GeomShape.ShapeType();
1273 if (GeomType == TopAbs_COMPOUND){
1274 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1275 if (it.Value().ShapeType() == TopAbs_FACE){
1276 HasSizeMapOnFace = true;
1277 createAttractorOnFace(it.Value(), atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1282 if (GeomType == TopAbs_FACE){
1283 HasSizeMapOnFace = true;
1284 createAttractorOnFace(GeomShape, atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1287 if (GeomType == TopAbs_EDGE){
1288 HasSizeMapOnEdge = true;
1289 HasSizeMapOnFace = true;
1290 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
1292 if (GeomType == TopAbs_VERTEX){
1293 HasSizeMapOnVertex = true;
1294 HasSizeMapOnEdge = true;
1295 HasSizeMapOnFace = true;
1296 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
1303 // MESSAGE("Impossible to create the attractors when the physical size is relative");
1306 // temporary commented out for testing
1308 // - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
1309 // - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
1310 // - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
1312 // - Construct the attractors with an empty dist. map in the hypothesis
1313 // - 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()
1314 // -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap() OK
1316 theNbAttractors = 0;
1317 const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
1319 BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
1320 for ( ; AtIt != class_attractors.end(); ++AtIt ) {
1321 if ( !AtIt->second->Empty() ) {
1322 // MESSAGE("cadsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
1323 GeomShape = entryToShape(AtIt->first);
1324 if ( !SMESH_MesherHelper::IsSubShape( GeomShape, theGeomShape ))
1326 AttShape = AtIt->second->GetAttractorShape();
1327 GeomType = GeomShape.ShapeType();
1329 // if (GeomType == TopAbs_COMPOUND){
1330 // for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1331 // if (it.Value().ShapeType() == TopAbs_FACE){
1332 // HasAttractorOnFace = true;
1333 // myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
1338 if (GeomType == TopAbs_FACE
1339 && (AttShape.ShapeType() == TopAbs_VERTEX
1340 || AttShape.ShapeType() == TopAbs_EDGE
1341 || AttShape.ShapeType() == TopAbs_WIRE
1342 || AttShape.ShapeType() == TopAbs_COMPOUND) ){
1343 HasSizeMapOnFace = true;
1345 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
1347 FaceId2ClassAttractor[key].push_back( AtIt->second );
1351 MESSAGE("Wrong shape type !!")
1359 // Enforced Vertices
1361 MESSAGE("Setting Enforced Vertices");
1362 const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
1363 BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
1364 for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
1365 if ( !enfIt->second.empty() ) {
1366 GeomShape = entryToShape(enfIt->first);
1367 GeomType = GeomShape.ShapeType();
1369 if (GeomType == TopAbs_COMPOUND){
1370 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1371 if (it.Value().ShapeType() == TopAbs_FACE){
1372 HasSizeMapOnFace = true;
1373 createEnforcedVertexOnFace(it.Value(), enfIt->second);
1378 if (GeomType == TopAbs_FACE){
1379 HasSizeMapOnFace = true;
1380 createEnforcedVertexOnFace(GeomShape, enfIt->second);
1385 // Internal vertices
1386 bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1387 if (useInternalVertexAllFaces) {
1388 std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1389 MESSAGE("Setting Internal Enforced Vertices");
1391 TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
1392 for (; exp.More(); exp.Next()){
1393 MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
1394 TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
1395 for (; exp_face.More(); exp_face.Next())
1397 // Get coords of vertex
1398 // Check if current coords is already in enfVertexList
1399 // If coords not in enfVertexList, add new enfVertex
1400 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1401 MESSAGE("Found vertex on face at " << aPnt.X() <<", "<<aPnt.Y()<<", "<<aPnt.Z());
1402 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1403 enfVertex->coords.push_back(aPnt.X());
1404 enfVertex->coords.push_back(aPnt.Y());
1405 enfVertex->coords.push_back(aPnt.Z());
1406 enfVertex->name = "";
1407 enfVertex->faceEntries.clear();
1408 enfVertex->geomEntry = "";
1409 enfVertex->grpName = grpName;
1410 enfVertex->vertex = TopoDS::Vertex( exp_face.Current() );
1411 _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()), aPnt, enfVertex);
1412 HasSizeMapOnFace = true;
1417 MESSAGE("Setting Size Map on FACES ");
1418 // #if BLSURF_VERSION_LONG < "3.1.1"
1419 cadsurf_data_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
1422 // iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1424 // clean_iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1427 if (HasSizeMapOnEdge){
1428 MESSAGE("Setting Size Map on EDGES ");
1429 // #if BLSURF_VERSION_LONG < "3.1.1"
1430 cadsurf_data_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
1433 // iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1435 // clean_iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1438 if (HasSizeMapOnVertex){
1439 MESSAGE("Setting Size Map on VERTICES ");
1440 // #if BLSURF_VERSION_LONG < "3.1.1"
1441 cadsurf_data_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
1444 // iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1446 // clean_iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1454 _preCadFacesIDsPeriodicityVector.clear();
1455 _preCadEdgesIDsPeriodicityVector.clear();
1456 _facesIDsPeriodicityVector.clear();
1457 _edgesIDsPeriodicityVector.clear();
1458 _verticesIDsPeriodicityVector.clear();
1460 MESSAGE("SetParameters preCadFacesPeriodicityVector");
1461 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadFacesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadFacesPeriodicityVector(hyp);
1463 for (std::size_t i = 0; i<preCadFacesPeriodicityVector.size(); i++){
1464 MESSAGE("SetParameters preCadFacesPeriodicityVector[" << i << "]");
1465 createPreCadFacesPeriodicity(theGeomShape, preCadFacesPeriodicityVector[i]);
1467 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
1469 MESSAGE("SetParameters preCadEdgesPeriodicityVector");
1470 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadEdgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadEdgesPeriodicityVector(hyp);
1472 for (std::size_t i = 0; i<preCadEdgesPeriodicityVector.size(); i++){
1473 MESSAGE("SetParameters preCadEdgesPeriodicityVector[" << i << "]");
1474 createPreCadEdgesPeriodicity(theGeomShape, preCadEdgesPeriodicityVector[i]);
1476 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
1478 if ( _preCadFacesIDsPeriodicityVector.size() > 0 || _preCadEdgesIDsPeriodicityVector.size() > 0 )
1480 MESSAGE("USING PRECAD FOR PERIODICITY")
1482 precad_set_param(pcs, "verbose", val_to_string(_verb).c_str());
1485 MESSAGE("SetParameters facesPeriodicityVector");
1486 const BLSURFPlugin_Hypothesis::TFacesPeriodicityVector facesPeriodicityVector = BLSURFPlugin_Hypothesis::GetFacesPeriodicityVector(hyp);
1488 for (std::size_t i = 0; i<facesPeriodicityVector.size(); i++){
1489 MESSAGE("SetParameters facesPeriodicityVector[" << i << "]");
1490 createFacesPeriodicity(theGeomShape, facesPeriodicityVector[i].first, facesPeriodicityVector[i].second);
1492 MESSAGE("_facesIDsPeriodicityVector.size() = " << _facesIDsPeriodicityVector.size());
1495 MESSAGE("SetParameters edgesPeriodicityVector");
1496 const BLSURFPlugin_Hypothesis::TEdgesPeriodicityVector edgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetEdgesPeriodicityVector(hyp);
1498 for (std::size_t i = 0; i<edgesPeriodicityVector.size(); i++){
1499 MESSAGE("SetParameters edgesPeriodicityVector[" << i << "]");
1500 // TODO: passer directement en paramètre edgesPeriodicityVector[i] plutôt que tous ces attributs
1501 createEdgesPeriodicity(theGeomShape, edgesPeriodicityVector[i].theFace1Entry, edgesPeriodicityVector[i].theEdge1Entry,
1502 edgesPeriodicityVector[i].theFace2Entry, edgesPeriodicityVector[i].theEdge2Entry, edgesPeriodicityVector[i].edge_orientation);
1504 MESSAGE("_edgesIDsPeriodicityVector.size() = " << _edgesIDsPeriodicityVector.size());
1506 MESSAGE("SetParameters verticesPeriodicityVector");
1507 const BLSURFPlugin_Hypothesis::TVerticesPeriodicityVector verticesPeriodicityVector = BLSURFPlugin_Hypothesis::GetVerticesPeriodicityVector(hyp);
1509 for (std::size_t i = 0; i<verticesPeriodicityVector.size(); i++){
1510 MESSAGE("SetParameters verticesPeriodicityVector[" << i << "]");
1511 // TODO: passer directement en paramètre verticesPeriodicityVector[i] plutôt que tous ces attributs
1512 createVerticesPeriodicity(theGeomShape, verticesPeriodicityVector[i].theEdge1Entry, verticesPeriodicityVector[i].theVertex1Entry,
1513 verticesPeriodicityVector[i].theEdge2Entry, verticesPeriodicityVector[i].theVertex2Entry);
1515 MESSAGE("_verticesIDsPeriodicityVector.size() = " << _verticesIDsPeriodicityVector.size());
1518 //================================================================================
1520 * \brief Throws an exception if a parameter name is wrong
1522 //================================================================================
1524 void BLSURFPlugin_BLSURF::set_param(cadsurf_session_t *css,
1525 const char * option_name,
1526 const char * option_value)
1528 status_t status = cadsurf_set_param(css, option_name, option_value );
1529 if ( status != MESHGEMS_STATUS_OK )
1531 if ( status == MESHGEMS_STATUS_UNKNOWN_PARAMETER ) {
1532 throw SALOME_Exception
1533 ( SMESH_Comment("Invalid name of CADSURF parameter: ") << option_name );
1535 else if ( status == MESHGEMS_STATUS_NOLICENSE )
1536 throw SALOME_Exception
1537 ( "No valid license available" );
1539 throw SALOME_Exception
1540 ( SMESH_Comment("Unacceptable value of CADSURF parameter '")
1541 << option_name << "': " << option_value);
1547 // --------------------------------------------------------------------------
1549 * \brief Class correctly terminating usage of MG-CADSurf library at destruction
1551 class BLSURF_Cleaner
1554 cadsurf_session_t* _css;
1560 BLSURF_Cleaner(context_t * ctx,
1561 cadsurf_session_t* css,
1576 Clean( /*exceptContext=*/false );
1578 void Clean(const bool exceptContext)
1582 cadsurf_session_delete(_css); _css = 0;
1584 // #if BLSURF_VERSION_LONG >= "3.1.1"
1585 // // if(geo_sizemap_e)
1586 // // distene_sizemap_delete(geo_sizemap_e);
1587 // // if(geo_sizemap_f)
1588 // // distene_sizemap_delete(geo_sizemap_f);
1589 // if(iso_sizemap_p)
1590 // distene_sizemap_delete(iso_sizemap_p);
1591 // if(iso_sizemap_e)
1592 // distene_sizemap_delete(iso_sizemap_e);
1593 // if(iso_sizemap_f)
1594 // distene_sizemap_delete(iso_sizemap_f);
1596 // // if(clean_geo_sizemap_e)
1597 // // distene_sizemap_delete(clean_geo_sizemap_e);
1598 // // if(clean_geo_sizemap_f)
1599 // // distene_sizemap_delete(clean_geo_sizemap_f);
1600 // if(clean_iso_sizemap_p)
1601 // distene_sizemap_delete(clean_iso_sizemap_p);
1602 // if(clean_iso_sizemap_e)
1603 // distene_sizemap_delete(clean_iso_sizemap_e);
1604 // if(clean_iso_sizemap_f)
1605 // distene_sizemap_delete(clean_iso_sizemap_f);
1608 cad_delete(_cad); _cad = 0;
1609 dcad_delete(_dcad); _dcad = 0;
1610 cad_delete(_cleanc); _cleanc = 0;
1611 dcad_delete(_cleandc); _cleandc = 0;
1612 if ( !exceptContext )
1614 context_delete(_ctx); _ctx = 0;
1620 // --------------------------------------------------------------------------
1621 // comparator to sort nodes and sub-meshes
1622 struct ShapeTypeCompare
1624 // sort nodes by position in the following order:
1625 // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
1626 bool operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
1628 // NEW ORDER: nodes earlier added to sub-mesh are considered "less"
1629 return n1->getIdInShape() < n2->getIdInShape();
1630 // SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
1631 // SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
1632 // if ( pos1 == pos2 ) return 0;
1633 // if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
1636 // sort sub-meshes in order: EDGE, VERTEX
1637 bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
1639 int isVertex1 = ( s1 && s1->NbElements() == 0 );
1640 int isVertex2 = ( s2 && s2->NbElements() == 0 );
1641 if ( isVertex1 == isVertex2 )
1643 return isVertex1 < isVertex2;
1647 //================================================================================
1649 * \brief Fills groups of nodes to be merged
1651 //================================================================================
1653 void getNodeGroupsToMerge( const SMESHDS_SubMesh* smDS,
1654 const TopoDS_Shape& shape,
1655 SMESH_MeshEditor::TListOfListOfNodes& nodeGroupsToMerge)
1657 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1658 switch ( shape.ShapeType() )
1660 case TopAbs_VERTEX: {
1661 std::list< const SMDS_MeshNode* > nodes;
1662 while ( nIt->more() )
1663 nodes.push_back( nIt->next() );
1664 if ( nodes.size() > 1 )
1665 nodeGroupsToMerge.push_back( nodes );
1669 std::multimap< double, const SMDS_MeshNode* > u2node;
1670 const SMDS_EdgePosition* ePos;
1671 while ( nIt->more() )
1673 const SMDS_MeshNode* n = nIt->next();
1674 if (( ePos = dynamic_cast< const SMDS_EdgePosition* >( n->GetPosition() )))
1675 u2node.insert( make_pair( ePos->GetUParameter(), n ));
1677 if ( u2node.size() < 2 ) return;
1679 //double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
1681 BRep_Tool::Range( TopoDS::Edge( shape ), f,l );
1682 double tol = (( l - f ) / 20.) / u2node.size();
1684 std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
1685 for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
1687 if (( un2->first - un1->first ) <= tol )
1689 std::list< const SMDS_MeshNode* > nodes;
1690 nodes.push_back( un1->second );
1691 while (( un2->first - un1->first ) <= tol )
1693 nodes.push_back( un2->second );
1694 if ( ++un2 == u2node.end()) {
1699 // make nodes created on the boundary of viscous layer replace nodes created
1700 // by MG-CADSurf as their SMDS_Position is more correct
1701 nodes.sort( ShapeTypeCompare() );
1702 nodeGroupsToMerge.push_back( nodes );
1709 // SMESH_MeshEditor::TListOfListOfNodes::const_iterator nll = nodeGroupsToMerge.begin();
1710 // for ( ; nll != nodeGroupsToMerge.end(); ++nll )
1712 // cout << "Merge ";
1713 // const std::list< const SMDS_MeshNode* >& nl = *nll;
1714 // std::list< const SMDS_MeshNode* >::const_iterator nIt = nl.begin();
1715 // for ( ; nIt != nl.end(); ++nIt )
1716 // cout << (*nIt) << " ";
1722 //================================================================================
1724 * \brief A temporary mesh used to compute mesh on a proxy FACE
1726 //================================================================================
1728 struct TmpMesh: public SMESH_Mesh
1730 typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
1731 TN2NMap _tmp2origNN;
1732 TopoDS_Face _proxyFace;
1736 _myMeshDS = new SMESHDS_Mesh( _id, true );
1738 //--------------------------------------------------------------------------------
1740 * \brief Creates a FACE bound by viscous layers and mesh each its EDGE with 1 segment
1742 //--------------------------------------------------------------------------------
1744 const TopoDS_Face& makeProxyFace( SMESH_ProxyMesh::Ptr& viscousMesh,
1745 const TopoDS_Face& origFace)
1747 // get data of nodes on inner boundary of viscous layers
1748 SMESH_Mesh* origMesh = viscousMesh->GetMesh();
1750 TSideVector wireVec = StdMeshers_FaceSide::GetFaceWires(origFace, *origMesh,
1751 /*skipMediumNodes = */true,
1753 if ( err && err->IsKO() )
1754 throw *err.get(); // it should be caught at SMESH_subMesh
1756 // proxy nodes and corresponding tmp VERTEXes
1757 std::vector<const SMDS_MeshNode*> origNodes;
1758 std::vector<TopoDS_Vertex> tmpVertex;
1760 // create a proxy FACE
1761 TopoDS_Shape origFaceCopy = origFace.EmptyCopied();
1762 BRepBuilderAPI_MakeFace newFace( TopoDS::Face( origFaceCopy ));
1763 for ( size_t iW = 0; iW != wireVec.size(); ++iW )
1765 StdMeshers_FaceSidePtr& wireData = wireVec[iW];
1766 const UVPtStructVec& wirePoints = wireData->GetUVPtStruct();
1767 if ( wirePoints.size() < 3 )
1770 BRepBuilderAPI_MakePolygon wire;
1771 const size_t i0 = tmpVertex.size();
1772 for ( size_t iN = 1; iN < wirePoints.size(); ++iN )
1774 wire.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
1775 origNodes.push_back( wirePoints[ iN ].node );
1776 tmpVertex.push_back( wire.LastVertex() );
1778 tmpVertex[ i0 ] = wire.FirstVertex(); // wire.LastVertex()==NULL for 1 vertex in wire
1780 if ( !wire.IsDone() )
1781 throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
1782 newFace.Add( wire );
1784 _proxyFace = newFace;
1786 // set a new shape to mesh
1787 TopoDS_Compound auxCompoundToMesh;
1788 BRep_Builder shapeBuilder;
1789 shapeBuilder.MakeCompound( auxCompoundToMesh );
1790 shapeBuilder.Add( auxCompoundToMesh, _proxyFace );
1791 shapeBuilder.Add( auxCompoundToMesh, origMesh->GetShapeToMesh() );
1793 ShapeToMesh( auxCompoundToMesh );
1795 //TopExp_Explorer fExp( auxCompoundToMesh, TopAbs_FACE );
1796 //_proxyFace = TopoDS::Face( fExp.Current() );
1799 // Make input mesh for MG-CADSurf: segments on EDGE's of newFace
1801 // make nodes and fill in _tmp2origNN
1803 SMESHDS_Mesh* tmpMeshDS = GetMeshDS();
1804 for ( size_t i = 0; i < origNodes.size(); ++i )
1806 GetSubMesh( tmpVertex[i] )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1807 if ( const SMDS_MeshNode* tmpN = SMESH_Algo::VertexNode( tmpVertex[i], tmpMeshDS ))
1808 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( tmpN, origNodes[i] ));
1810 throw SALOME_Exception("BLSURFPlugin_BLSURF: a proxy vertex not meshed");
1814 TopoDS_Vertex v1, v2;
1815 for ( TopExp_Explorer edge( _proxyFace, TopAbs_EDGE ); edge.More(); edge.Next() )
1817 const TopoDS_Edge& E = TopoDS::Edge( edge.Current() );
1818 TopExp::Vertices( E, v1, v2 );
1819 const SMDS_MeshNode* n1 = SMESH_Algo::VertexNode( v1, tmpMeshDS );
1820 const SMDS_MeshNode* n2 = SMESH_Algo::VertexNode( v2, tmpMeshDS );
1822 if ( SMDS_MeshElement* seg = tmpMeshDS->AddEdge( n1, n2 ))
1823 tmpMeshDS->SetMeshElementOnShape( seg, E );
1829 //--------------------------------------------------------------------------------
1831 * \brief Fill in the origMesh with faces computed by MG-CADSurf in this tmp mesh
1833 //--------------------------------------------------------------------------------
1835 void FillInOrigMesh( SMESH_Mesh& origMesh,
1836 const TopoDS_Face& origFace )
1838 SMESH_MesherHelper helper( origMesh );
1839 helper.SetSubShape( origFace );
1840 helper.SetElementsOnShape( true );
1842 SMESH_MesherHelper tmpHelper( *this );
1843 tmpHelper.SetSubShape( _proxyFace );
1845 // iterate over tmp faces and copy them in origMesh
1846 const SMDS_MeshNode* nodes[27];
1847 const SMDS_MeshNode* nullNode = 0;
1849 SMDS_FaceIteratorPtr fIt = GetMeshDS()->facesIterator(/*idInceasingOrder=*/true);
1850 while ( fIt->more() )
1852 const SMDS_MeshElement* f = fIt->next();
1853 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
1855 for ( ; nIt->more(); ++nbN )
1857 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
1858 TN2NMap::iterator n2nIt =
1859 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
1860 if ( !n2nIt->second ) {
1862 gp_XY uv = tmpHelper.GetNodeUV( _proxyFace, n );
1863 n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], uv.X(), uv.Y() );
1865 nodes[ nbN ] = n2nIt->second;
1868 case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
1869 // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
1870 // nodes[3], nodes[4], nodes[5]); break;
1871 case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
1872 // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1873 // nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
1874 // case 8: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1875 // nodes[4], nodes[5], nodes[6], nodes[7]); break;
1882 * \brief A structure holding an error description and a verbisity level
1884 struct message_cb_user_data
1886 std::string * _error;
1894 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1895 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1896 real *duu, real *duv, real *dvv, void *user_data);
1897 status_t message_cb(message_t *msg, void *user_data);
1898 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1900 //=============================================================================
1904 //=============================================================================
1906 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1908 MESSAGE("BLSURFPlugin_BLSURF::Compute");
1910 // Fix problem with locales
1911 Kernel_Utils::Localizer aLocalizer;
1913 this->SMESH_Algo::_progress = 1e-3; // prevent progress advancment while computing attractors
1915 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1918 if ( _haveViscousLayers )
1920 // Compute viscous layers
1922 TopTools_MapOfShape map;
1923 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1925 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1926 if ( !map.Add( F )) continue;
1927 SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1929 return false; // error in StdMeshers_ViscousLayers2D::Compute()
1931 // Compute MG-CADSurf mesh on viscous layers
1933 if ( viscousMesh->NbProxySubMeshes() > 0 )
1936 const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1937 if ( !compute( tmpMesh, proxyFace, /*allowSubMeshClearing=*/false ))
1939 tmpMesh.FillInOrigMesh( aMesh, F );
1943 // Re-compute MG-CADSurf mesh on the rest faces if the mesh was cleared
1945 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1947 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1948 SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1949 if ( fSM->IsMeshComputed() ) continue;
1951 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1959 //=============================================================================
1963 //=============================================================================
1965 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh& aMesh,
1966 const TopoDS_Shape& aShape,
1967 bool allowSubMeshClearing)
1969 /* create a distene context (generic object) */
1970 status_t status = STATUS_ERROR;
1973 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1974 SMESH_MesherHelper helper( aMesh );
1975 // do not call helper.IsQuadraticSubMesh() because sub-meshes
1976 // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1977 bool haveQuadraticSubMesh = SMESH_MesherHelper( aMesh ).IsQuadraticSubMesh( aShape );
1978 bool quadraticSubMeshAndViscousLayer = false;
1979 bool needMerge = false;
1980 typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1981 TSubMeshSet edgeSubmeshes;
1982 TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1984 TopTools_IndexedMapOfShape pmap, emap, fmap;
1986 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1988 feclearexcept( FE_ALL_EXCEPT );
1989 int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1992 context_t *ctx = context_new();
1994 /* Set the message callback in the working context */
1995 message_cb_user_data mcud;
1996 mcud._error = & this->SMESH_Algo::_comment;
1997 mcud._progress = & this->SMESH_Algo::_progress;
1999 _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
2000 context_set_message_callback(ctx, message_cb, &mcud);
2002 /* set the interruption callback */
2003 _compute_canceled = false;
2004 context_set_interrupt_callback(ctx, interrupt_cb, this);
2006 /* create the CAD object we will work on. It is associated to the context ctx. */
2007 cad_t *c = cad_new(ctx);
2008 dcad_t *dcad = dcad_new(c);
2010 FacesWithSizeMap.Clear();
2011 FaceId2SizeMap.clear();
2012 FaceId2ClassAttractor.clear();
2013 FaceIndex2ClassAttractor.clear();
2014 EdgesWithSizeMap.Clear();
2015 EdgeId2SizeMap.clear();
2016 VerticesWithSizeMap.Clear();
2017 VertexId2SizeMap.clear();
2019 /* Now fill the CAD object with data from your CAD
2020 * environement. This is the most complex part of a successfull
2025 // If user requests it, send the CAD through Distene preprocessor : PreCAD
2026 cad_t *cleanc = NULL; // preprocessed cad
2027 dcad_t *cleandc = NULL; // preprocessed dcad
2028 precad_session_t *pcs = precad_session_new(ctx);
2029 // Give both dcad and cad to precad
2030 precad_data_set_dcad(pcs, dcad);
2031 precad_data_set_cad(pcs, c);
2033 cadsurf_session_t *css = cadsurf_session_new(ctx);
2035 // an object that correctly deletes all cadsurf objects at destruction
2036 BLSURF_Cleaner cleaner( ctx,css,c,dcad,cleanc,cleandc );
2038 MESSAGE("BEGIN SetParameters");
2039 bool use_precad = false;
2040 SetParameters(_hypothesis, css, pcs, aShape, &use_precad);
2041 MESSAGE("END SetParameters");
2043 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2045 haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
2046 helper.SetIsQuadratic( haveQuadraticSubMesh );
2048 // To remove as soon as quadratic mesh is allowed - BEGIN
2049 // GDD: Viscous layer is not allowed with quadratic mesh
2050 if (_haveViscousLayers && haveQuadraticSubMesh ) {
2051 quadraticSubMeshAndViscousLayer = true;
2052 _haveViscousLayers = !haveQuadraticSubMesh;
2053 _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
2054 error(COMPERR_WARNING, _comment);
2056 // To remove as soon as quadratic mesh is allowed - END
2058 // needed to prevent the opencascade memory managmement from freeing things
2059 vector<Handle(Geom2d_Curve)> curves;
2060 vector<Handle(Geom_Surface)> surfaces;
2064 FaceId2PythonSmp.clear();
2065 EdgeId2PythonSmp.clear();
2066 VertexId2PythonSmp.clear();
2068 /****************************************************************************************
2070 *****************************************************************************************/
2072 string bad_end = "return";
2074 TopTools_IndexedMapOfShape _map;
2075 TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
2076 int ienf = _map.Extent();
2078 assert(Py_IsInitialized());
2079 PyGILState_STATE gstate;
2081 string theSizeMapStr;
2083 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
2085 TopoDS_Face f = TopoDS::Face(face_iter.Current());
2087 SMESH_subMesh* fSM = aMesh.GetSubMesh( f );
2088 if ( !fSM->IsEmpty() ) continue; // skip already meshed FACE with viscous layers
2090 // make INTERNAL face oriented FORWARD (issue 0020993)
2091 if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
2092 f.Orientation(TopAbs_FORWARD);
2094 iface = fmap.Add(f);
2095 // std::string aFileName = "fmap_face_";
2096 // aFileName.append(val_to_string(iface));
2097 // aFileName.append(".brep");
2098 // BRepTools::Write(f,aFileName.c_str());
2100 surfaces.push_back(BRep_Tool::Surface(f));
2102 /* create an object representing the face for cadsurf */
2103 /* where face_id is an integer identifying the face.
2104 * surf_function is the function that defines the surface
2105 * (For this face, it will be called by cadsurf with your_face_object_ptr
2106 * as last parameter.
2108 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
2110 /* by default a face has no tag (color).
2111 The following call sets it to the same value as the Geom module ID : */
2112 const int faceTag = meshDS->ShapeToIndex(f);
2113 cad_face_set_tag(fce, faceTag);
2115 /* Set face orientation (optional if you want a well oriented output mesh)*/
2116 if(f.Orientation() != TopAbs_FORWARD)
2117 cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
2119 cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
2121 if (HasSizeMapOnFace /*&& !use_precad*/) //22903: use_precad seems not to interfere
2123 // -----------------
2125 // -----------------
2126 faceKey = FacesWithSizeMap.FindIndex(f);
2129 if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()) {
2130 MESSAGE("A size map is defined on face :"<<faceKey);
2131 theSizeMapStr = FaceId2SizeMap[faceKey];
2132 // check if function ends with "return"
2133 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2135 // Expr To Python function, verification is performed at validation in GUI
2136 gstate = PyGILState_Ensure();
2137 PyObject * obj = NULL;
2138 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2140 PyObject * func = NULL;
2141 func = PyObject_GetAttrString(main_mod, "f");
2142 FaceId2PythonSmp[iface]=func;
2143 FaceId2SizeMap.erase(faceKey);
2144 PyGILState_Release(gstate);
2147 // Specific size map = Attractor
2148 std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
2150 for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
2151 if (attractor_iter->first == faceKey) {
2152 MESSAGE("Face indice: " << iface);
2153 MESSAGE("Adding attractor");
2155 double xyzCoords[3] = {attractor_iter->second[2],
2156 attractor_iter->second[3],
2157 attractor_iter->second[4]};
2159 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2160 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2161 BRepClass_FaceClassifier scl(f,P,1e-7);
2162 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2163 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2164 // OCC 6.5.2: scl.Perform() is not bugged anymore
2165 scl.Perform(f, P, 1e-7);
2166 TopAbs_State result = scl.State();
2167 MESSAGE("Position of point on face: "<<result);
2168 if ( result == TopAbs_OUT )
2169 MESSAGE("Point is out of face: node is not created");
2170 if ( result == TopAbs_UNKNOWN )
2171 MESSAGE("Point position on face is unknown: node is not created");
2172 if ( result == TopAbs_ON )
2173 MESSAGE("Point is on border of face: node is not created");
2174 if ( result == TopAbs_IN )
2176 // Point is inside face and not on border
2177 MESSAGE("Point is in face: node is created");
2178 double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
2180 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2181 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2182 cad_point_set_tag(point_p, ienf);
2184 FaceId2AttractorCoords.erase(faceKey);
2188 // -----------------
2190 // -----------------
2191 TId2ClsAttractorVec::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
2192 if (clAttractor_iter != FaceId2ClassAttractor.end()){
2193 MESSAGE("Face indice: " << iface);
2194 MESSAGE("Adding attractor");
2195 std::vector< BLSURFPlugin_Attractor* > & attVec = clAttractor_iter->second;
2196 for ( size_t i = 0; i < attVec.size(); ++i )
2197 if ( !attVec[i]->IsMapBuilt() ) {
2198 std::cout<<"Compute " << theNbAttractors-- << "-th attractor" <<std::endl;
2199 attVec[i]->BuildMap();
2201 FaceIndex2ClassAttractor[iface].swap( attVec );
2202 FaceId2ClassAttractor.erase(clAttractor_iter);
2204 } // if (HasSizeMapOnFace && !use_precad)
2206 // ------------------
2207 // Enforced Vertices
2208 // ------------------
2209 faceKey = FacesWithEnforcedVertices.FindIndex(f);
2210 std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
2211 if (evmIt != FaceId2EnforcedVertexCoords.end()) {
2212 MESSAGE("Some enforced vertices are defined");
2213 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
2214 MESSAGE("Face indice: " << iface);
2215 MESSAGE("Adding enforced vertices");
2216 evl = evmIt->second;
2217 MESSAGE("Number of vertices to add: "<< evl.size());
2218 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
2219 for (; evlIt != evl.end(); ++evlIt) {
2220 BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
2221 xyzCoords.push_back(evlIt->at(2));
2222 xyzCoords.push_back(evlIt->at(3));
2223 xyzCoords.push_back(evlIt->at(4));
2224 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2225 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2226 BRepClass_FaceClassifier scl(f,P,1e-7);
2227 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2228 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2229 // OCC 6.5.2: scl.Perform() is not bugged anymore
2230 scl.Perform(f, P, 1e-7);
2231 TopAbs_State result = scl.State();
2232 MESSAGE("Position of point on face: "<<result);
2233 if ( result == TopAbs_OUT ) {
2234 MESSAGE("Point is out of face: node is not created");
2235 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2236 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2237 // isssue 22783. Do not erase as this point can be IN other face of a group
2238 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2241 if ( result == TopAbs_UNKNOWN ) {
2242 MESSAGE("Point position on face is unknown: node is not created");
2243 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2244 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2245 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2248 if ( result == TopAbs_ON ) {
2249 MESSAGE("Point is on border of face: node is not created");
2250 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2251 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2252 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2255 if ( result == TopAbs_IN )
2257 // Point is inside face and not on border
2258 MESSAGE("Point is in face: node is created");
2259 double uvCoords[2] = {evlIt->at(0),evlIt->at(1)};
2261 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2262 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2264 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
2265 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
2266 !enfCoordsIt->second.empty() )
2268 // to merge nodes of an INTERNAL vertex belonging to several faces
2269 TopoDS_Vertex v = (*enfCoordsIt->second.begin())->vertex;
2270 if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
2271 if ( !v.IsNull() ) {
2272 tag = pmap.Add( v );
2273 SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
2274 vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2275 mergeSubmeshes.insert( vSM->GetSubMeshDS() );
2276 // //if ( tag != pmap.Extent() )
2277 // needMerge = true;
2280 if ( tag == 0 ) tag = ienf;
2281 cad_point_set_tag(point_p, tag);
2284 FaceId2EnforcedVertexCoords.erase(faceKey);
2288 /****************************************************************************************
2290 now create the edges associated to this face
2291 *****************************************************************************************/
2293 for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next())
2295 TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
2296 int ic = emap.FindIndex(e);
2300 // std::string aFileName = "fmap_edge_";
2301 // aFileName.append(val_to_string(ic));
2302 // aFileName.append(".brep");
2303 // BRepTools::Write(e,aFileName.c_str());
2306 curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
2308 if (HasSizeMapOnEdge){
2309 edgeKey = EdgesWithSizeMap.FindIndex(e);
2310 if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
2311 MESSAGE("Sizemap defined on edge with index " << edgeKey);
2312 theSizeMapStr = EdgeId2SizeMap[edgeKey];
2313 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2315 // Expr To Python function, verification is performed at validation in GUI
2316 gstate = PyGILState_Ensure();
2317 PyObject * obj = NULL;
2318 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2320 PyObject * func = NULL;
2321 func = PyObject_GetAttrString(main_mod, "f");
2322 EdgeId2PythonSmp[ic]=func;
2323 EdgeId2SizeMap.erase(edgeKey);
2324 PyGILState_Release(gstate);
2327 /* data of nodes existing on the edge */
2328 StdMeshers_FaceSidePtr nodeData;
2329 SMESH_subMesh* sm = aMesh.GetSubMesh( e );
2330 if ( !sm->IsEmpty() )
2332 // SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
2333 // /*complexFirst=*/false);
2334 // while ( subsmIt->more() )
2335 // edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
2336 edgeSubmeshes.insert( sm->GetSubMeshDS() );
2338 nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
2339 /*ignoreMedium=*/haveQuadraticSubMesh));
2340 if ( nodeData->MissVertexNode() )
2341 return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
2343 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2344 if ( !nodeDataVec.empty() )
2346 if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
2348 nodeData->Reverse();
2349 nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
2351 // tmin and tmax can change in case of viscous layer on an adjacent edge
2352 tmin = nodeDataVec.front().param;
2353 tmax = nodeDataVec.back().param;
2357 cout << "---------------- Invalid nodeData" << endl;
2362 /* attach the edge to the current cadsurf face */
2363 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
2365 /* by default an edge has no tag (color).
2366 The following call sets it to the same value as the edge_id : */
2367 cad_edge_set_tag(edg, ic);
2369 /* by default, an edge does not necessalry appear in the resulting mesh,
2370 unless the following property is set :
2372 cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2374 /* by default an edge is a boundary edge */
2375 if (e.Orientation() == TopAbs_INTERNAL)
2376 cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2378 // pass existing nodes of sub-meshes to MG-CADSurf
2381 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2382 const int nbNodes = nodeDataVec.size();
2384 dcad_edge_discretization_t *dedge;
2385 dcad_get_edge_discretization(dcad, edg, &dedge);
2386 dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2388 // cout << endl << " EDGE " << ic << endl;
2389 // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2390 for ( int iN = 0; iN < nbNodes; ++iN )
2392 const UVPtStruct& nData = nodeDataVec[ iN ];
2393 double t = nData.param;
2394 real uv[2] = { nData.u, nData.v };
2395 SMESH_TNodeXYZ nXYZ( nData.node );
2396 // cout << "\tt = " << t
2397 // << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2398 // << "\t u = " << nData.param
2399 // << "\t ID = " << nData.node->GetID() << endl;
2400 dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ._xyz );
2402 dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2405 /****************************************************************************************
2407 *****************************************************************************************/
2411 gp_Pnt2d e0 = curves.back()->Value(tmin);
2412 gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
2413 Standard_Real d1=0,d2=0;
2416 for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
2417 TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
2421 d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2424 d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2426 *ip = pmap.FindIndex(v);
2429 // SMESH_subMesh* sm = aMesh.GetSubMesh(v);
2430 // if ( sm->IsMeshComputed() )
2431 // edgeSubmeshes.insert( sm->GetSubMeshDS() );
2434 // std::string aFileName = "fmap_vertex_";
2435 // aFileName.append(val_to_string(*ip));
2436 // aFileName.append(".brep");
2437 // BRepTools::Write(v,aFileName.c_str());
2439 if (HasSizeMapOnVertex){
2440 vertexKey = VerticesWithSizeMap.FindIndex(v);
2441 if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
2442 theSizeMapStr = VertexId2SizeMap[vertexKey];
2443 //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
2444 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2446 // Expr To Python function, verification is performed at validation in GUI
2447 gstate = PyGILState_Ensure();
2448 PyObject * obj = NULL;
2449 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2451 PyObject * func = NULL;
2452 func = PyObject_GetAttrString(main_mod, "f");
2453 VertexId2PythonSmp[*ip]=func;
2454 VertexId2SizeMap.erase(vertexKey); // do not erase if using a vector
2455 PyGILState_Release(gstate);
2460 // should not happen
2461 MESSAGE("An edge does not have 2 extremities.");
2464 // This defines the curves extremity connectivity
2465 cad_edge_set_extremities(edg, ip1, ip2);
2466 /* set the tag (color) to the same value as the extremity id : */
2467 cad_edge_set_extremities_tag(edg, ip1, ip2);
2470 cad_edge_set_extremities(edg, ip2, ip1);
2471 cad_edge_set_extremities_tag(edg, ip2, ip1);
2477 // Clear mesh from already meshed edges if possible else
2478 // remember that merge is needed
2479 TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2480 for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2482 SMESHDS_SubMesh* smDS = *smIt;
2483 if ( !smDS ) continue;
2484 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2487 const SMDS_MeshNode* n = nIt->next();
2488 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2490 needMerge = true; // to correctly sew with viscous mesh
2491 // add existing medium nodes to helper
2492 if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2494 SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2495 while ( edgeIt->more() )
2496 helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2501 if ( allowSubMeshClearing )
2503 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2504 while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), 0 );
2505 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2506 while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), 0 );
2515 ///////////////////////
2517 ///////////////////////
2519 MESSAGE("BEFORE PERIODICITY");
2520 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2521 if (! _preCadFacesIDsPeriodicityVector.empty()) {
2522 MESSAGE("INTO PRECAD FACES PERIODICITY");
2523 for (std::size_t i=0; i < _preCadFacesIDsPeriodicityVector.size(); i++){
2524 std::vector<int> theFace1_ids = _preCadFacesIDsPeriodicityVector[i].shape1IDs;
2525 std::vector<int> theFace2_ids = _preCadFacesIDsPeriodicityVector[i].shape2IDs;
2526 int* theFace1_ids_c = &theFace1_ids[0];
2527 int* theFace2_ids_c = &theFace2_ids[0];
2528 std::ostringstream o;
2529 o << "_preCadFacesIDsPeriodicityVector[" << i << "] = [";
2530 for (std::size_t j=0; j < theFace1_ids.size(); j++)
2531 o << theFace1_ids[j] << ", ";
2533 for (std::size_t j=0; j < theFace2_ids.size(); j++)
2534 o << theFace2_ids[j] << ", ";
2537 MESSAGE("theFace1_ids.size(): " << theFace1_ids.size());
2538 MESSAGE("theFace2_ids.size(): " << theFace2_ids.size());
2539 if (_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2541 // If no source points, call peridoicity without transformation function
2542 MESSAGE("periodicity without transformation function");
2543 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2544 status = cad_add_face_multiple_periodicity_with_transformation_function(c, theFace1_ids_c, theFace1_ids.size(),
2545 theFace2_ids_c, theFace2_ids.size(), periodicity_transformation, NULL);
2546 if(status != STATUS_OK)
2547 cout << "cad_add_face_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2551 // get the transformation vertices
2552 MESSAGE("periodicity with transformation vertices");
2553 double* theSourceVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2554 double* theTargetVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2555 int nbSourceVertices = _preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2556 int nbTargetVertices = _preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2558 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2560 status = cad_add_face_multiple_periodicity_with_transformation_function_by_points(c, theFace1_ids_c, theFace1_ids.size(),
2561 theFace2_ids_c, theFace2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2562 if(status != STATUS_OK)
2563 cout << "cad_add_face_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2567 MESSAGE("END PRECAD FACES PERIODICITY");
2570 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
2571 if (! _preCadEdgesIDsPeriodicityVector.empty()) {
2572 MESSAGE("INTO PRECAD EDGES PERIODICITY");
2573 for (std::size_t i=0; i < _preCadEdgesIDsPeriodicityVector.size(); i++){
2574 std::vector<int> theEdge1_ids = _preCadEdgesIDsPeriodicityVector[i].shape1IDs;
2575 std::vector<int> theEdge2_ids = _preCadEdgesIDsPeriodicityVector[i].shape2IDs;
2576 // Use the address of the first element of the vector to initialise the array
2577 int* theEdge1_ids_c = &theEdge1_ids[0];
2578 int* theEdge2_ids_c = &theEdge2_ids[0];
2580 std::ostringstream o;
2581 o << "_preCadEdgesIDsPeriodicityVector[" << i << "] = [";
2582 for (std::size_t j=0; j < theEdge1_ids.size(); j++)
2583 o << theEdge1_ids[j] << ", ";
2585 for (std::size_t j=0; j < theEdge2_ids.size(); j++)
2586 o << theEdge2_ids[j] << ", ";
2589 MESSAGE("theEdge1_ids.size(): " << theEdge1_ids.size());
2590 MESSAGE("theEdge2_ids.size(): " << theEdge2_ids.size());
2592 if (_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2594 // If no source points, call peridoicity without transformation function
2595 MESSAGE("periodicity without transformation function");
2596 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2597 status = cad_add_edge_multiple_periodicity_with_transformation_function(c, theEdge1_ids_c, theEdge1_ids.size(),
2598 theEdge2_ids_c, theEdge2_ids.size(), periodicity_transformation, NULL);
2599 if(status != STATUS_OK)
2600 cout << "cad_add_edge_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2604 // get the transformation vertices
2605 MESSAGE("periodicity with transformation vertices");
2606 double* theSourceVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2607 double* theTargetVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2608 int nbSourceVertices = _preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2609 int nbTargetVertices = _preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2611 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2613 status = cad_add_edge_multiple_periodicity_with_transformation_function_by_points(c, theEdge1_ids_c, theEdge1_ids.size(),
2614 theEdge2_ids_c, theEdge2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2615 if(status != STATUS_OK)
2616 cout << "cad_add_edge_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2618 MESSAGE("cad_add_edge_multiple_periodicity_with_transformation_function_by_points succeeded.\n");
2622 MESSAGE("END PRECAD EDGES PERIODICITY");
2625 if (! _facesIDsPeriodicityVector.empty()){
2626 MESSAGE("INTO FACE PERIODICITY");
2627 for (std::size_t i=0; i < _facesIDsPeriodicityVector.size(); i++){
2628 int theFace1 = _facesIDsPeriodicityVector[i].first;
2629 int theFace2 = _facesIDsPeriodicityVector[i].second;
2630 MESSAGE("_facesIDsPeriodicityVector[" << i << "] = (" << theFace1 << ", " << theFace2 << ")");
2631 status = cad_add_face_periodicity(c, theFace1, theFace2);
2632 if(status != STATUS_OK){
2633 cout << "cad_add_face_periodicity failed with error code " << status << "\n";
2636 MESSAGE("END FACE PERIODICITY");
2640 if (! _edgesIDsPeriodicityVector.empty()){
2641 MESSAGE("INTO EDGE PERIODICITY");
2642 for (std::size_t i=0; i < _edgesIDsPeriodicityVector.size(); i++){
2643 int theFace1 = _edgesIDsPeriodicityVector[i].theFace1ID;
2644 int theEdge1 = _edgesIDsPeriodicityVector[i].theEdge1ID;
2645 int theFace2 = _edgesIDsPeriodicityVector[i].theFace2ID;
2646 int theEdge2 = _edgesIDsPeriodicityVector[i].theEdge2ID;
2647 int edge_orientation = _edgesIDsPeriodicityVector[i].edge_orientation;
2648 MESSAGE("_edgesIDsPeriodicityVector[" << i << "] = (" << theFace1 << ", " << theEdge1 << ", " << theFace2 << ", " << theEdge2 << ", " << edge_orientation << ")");
2649 status = cad_add_edge_periodicity(c, theFace1, theEdge1, theFace2, theEdge2, edge_orientation);
2650 if(status != STATUS_OK){
2651 cout << "cad_add_edge_periodicity failed with error code " << status << "\n";
2654 MESSAGE("END EDGE PERIODICITY");
2657 if (! _verticesIDsPeriodicityVector.empty()){
2658 MESSAGE("INTO VERTEX PERIODICITY");
2659 for (std::size_t i=0; i < _verticesIDsPeriodicityVector.size(); i++){
2660 int theEdge1 = _verticesIDsPeriodicityVector[i].theEdge1ID;
2661 int theVertex1 = _verticesIDsPeriodicityVector[i].theVertex1ID;
2662 int theEdge2 = _verticesIDsPeriodicityVector[i].theEdge2ID;
2663 int theVertex2 = _verticesIDsPeriodicityVector[i].theVertex2ID;
2664 MESSAGE("_verticesIDsPeriodicityVector[" << i << "] = (" << theEdge1 << ", " << theVertex1 << ", " << theEdge2 << ", " << theVertex2 << ")");
2665 status = cad_add_point_periodicity(c, theEdge1, theVertex1, theEdge2, theVertex2);
2666 if(status != STATUS_OK){
2667 cout << "cad_add_vertex_periodicity failed with error code " << status << "\n";
2670 MESSAGE("END VERTEX PERIODICITY");
2676 MESSAGE("use_precad");
2677 /* Now launch the PreCAD process */
2678 status = precad_process(pcs);
2679 if(status != STATUS_OK){
2680 // TODO: raise an error if status < 0.
2681 cout << "================ WARNING =================== \n";
2683 msg << "PreCAD processing failed with error code " << status << "\n";
2684 msg << *mcud._error;
2686 cout << "============================================ \n";
2687 // the text of _comment is set in message_cb by mcud->_error
2688 // => No need to append msg to _comment
2691 // TODO: fix the SIGSEGV of COMPERR_WARNING with 2 launches
2692 error(COMPERR_WARNING, _comment);
2700 // retrieve the pre-processed CAD object
2703 cleandc = precad_new_dcad(pcs);
2705 cout << "Unable to retrieve PreCAD result on dcad \n";
2708 cout << "PreCAD processing successfull on dcad \n";
2711 cleanc = precad_new_cad(pcs);
2713 cout << "Unable to retrieve PreCAD result on cad \n";
2716 cout << "PreCAD processing successfull on cad \n";
2718 // #if BLSURF_VERSION_LONG >= "3.1.1"
2719 // /* We can now get the updated sizemaps (if any) */
2720 // // if(geo_sizemap_e)
2721 // // clean_geo_sizemap_e = precad_new_sizemap(pcs, geo_sizemap_e);
2723 // // if(geo_sizemap_f)
2724 // // clean_geo_sizemap_f = precad_new_sizemap(pcs, geo_sizemap_f);
2726 // if(iso_sizemap_p)
2727 // clean_iso_sizemap_p = precad_new_sizemap(pcs, iso_sizemap_p);
2729 // if(iso_sizemap_e)
2730 // clean_iso_sizemap_e = precad_new_sizemap(pcs, iso_sizemap_e);
2732 // if(iso_sizemap_f)
2733 // clean_iso_sizemap_f = precad_new_sizemap(pcs, iso_sizemap_f);
2736 // Now we can delete the PreCAD session
2737 precad_session_delete(pcs);
2741 cout << "Give the pre-processed dcad object to the current MG-CADSurf session \n";
2742 cadsurf_data_set_dcad(css, cleandc);
2745 // Use the original one
2746 cadsurf_data_set_dcad(css, dcad);
2750 // Give the pre-processed CAD object to the current MG-CADSurf session
2751 cout << "Give the pre-processed CAD object to the current MG-CADSurf session \n";
2752 cadsurf_data_set_cad(css, cleanc);
2755 // Use the original one
2756 cadsurf_data_set_cad(css, c);
2759 std::cout << std::endl;
2760 std::cout << "Beginning of Surface Mesh generation" << std::endl;
2761 std::cout << std::endl;
2766 status = cadsurf_compute_mesh(css);
2769 catch ( std::exception& exc ) {
2770 _comment += exc.what();
2772 catch (Standard_Failure& ex) {
2773 _comment += ex.DynamicType()->Name();
2774 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2776 _comment += ex.GetMessageString();
2780 if ( _comment.empty() )
2781 _comment = "Exception in cadsurf_compute_mesh()";
2784 std::cout << std::endl;
2785 std::cout << "End of Surface Mesh generation" << std::endl;
2786 std::cout << std::endl;
2789 cadsurf_data_get_mesh(css, &msh);
2791 /* release the mesh object */
2792 cadsurf_data_regain_mesh(css, msh);
2793 return error(_comment);
2796 std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2798 GMFFileName = _hypothesis->GetGMFFile();
2799 if (GMFFileName != "") {
2800 bool asciiFound = (GMFFileName.find(".mesh", GMFFileName.length()-5) != std::string::npos);
2801 bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2802 if (!asciiFound && !binaryFound)
2803 GMFFileName.append(".mesh");
2804 mesh_write_mesh(msh, GMFFileName.c_str());
2807 /* retrieve mesh data (see meshgems/mesh.h) */
2808 integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2809 integer *evedg, *evtri, *evquad, *tags_buff, type;
2812 mesh_get_vertex_count(msh, &nv);
2813 mesh_get_edge_count(msh, &ne);
2814 mesh_get_triangle_count(msh, &nt);
2815 mesh_get_quadrangle_count(msh, &nq);
2817 evedg = (integer *)mesh_calloc_generic_buffer(msh);
2818 evtri = (integer *)mesh_calloc_generic_buffer(msh);
2819 evquad = (integer *)mesh_calloc_generic_buffer(msh);
2820 tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
2822 std::vector<const SMDS_MeshNode*> nodes(nv+1);
2823 std::vector<bool> tags(nv+1);
2825 /* enumerated vertices */
2826 for(int iv=1;iv<=nv;iv++) {
2827 mesh_get_vertex_coordinates(msh, iv, xyz);
2828 mesh_get_vertex_tag(msh, iv, &tag);
2829 // Issue 0020656. Use vertex coordinates
2831 if ( tag > 0 && tag <= pmap.Extent() ) {
2832 TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2833 double tol = BRep_Tool::Tolerance( v );
2834 gp_Pnt p = BRep_Tool::Pnt( v );
2835 if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
2836 xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2838 tag = 0; // enforced or attracted vertex
2839 nodes[iv] = SMESH_Algo::VertexNode( v, meshDS );
2842 nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2844 // Create group of enforced vertices if requested
2845 BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2847 projVertex.push_back((double)xyz[0]);
2848 projVertex.push_back((double)xyz[1]);
2849 projVertex.push_back((double)xyz[2]);
2850 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
2851 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
2852 MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
2853 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
2854 BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
2855 for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
2856 currentEnfVertex = (*enfListIt);
2857 if (currentEnfVertex->grpName != "") {
2858 bool groupDone = false;
2859 SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
2860 MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
2861 MESSAGE("Parsing the groups of the mesh");
2862 while (grIt->more()) {
2863 SMESH_Group * group = grIt->next();
2864 if ( !group ) continue;
2865 MESSAGE("Group: " << group->GetName());
2866 SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2867 if ( !groupDS ) continue;
2868 MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
2869 MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
2870 MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
2871 if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
2872 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
2873 aGroupDS->SMDSGroup().Add(nodes[iv]);
2874 MESSAGE("Node ID: " << nodes[iv]->GetID());
2875 // How can I inform the hypothesis ?
2876 // _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
2878 MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
2885 SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
2886 aGroup->SetName( currentEnfVertex->grpName.c_str() );
2887 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2888 aGroupDS->SMDSGroup().Add(nodes[iv]);
2889 MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
2893 throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
2896 MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
2900 // internal points are tagged to zero
2901 if(tag > 0 && tag <= pmap.Extent() ){
2902 meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2909 /* enumerate edges */
2910 for(int it=1;it<=ne;it++) {
2912 mesh_get_edge_vertices(msh, it, vtx);
2913 mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2914 mesh_get_edge_tag(msh, it, &tag);
2916 // If PreCAD performed some cleaning operations (remove tiny edges,
2917 // merge edges ...) an output tag can indeed represent several original tags.
2918 // Get the initial tags corresponding to the output tag and redefine the tag as
2919 // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2920 mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2922 tag=tags_buff[nb_tag-1];
2923 if ( tag > emap.Extent() )
2925 std::cerr << "MG-CADSurf BUG:::: Edge tag " << tag
2926 << " more than nb CAD egdes (" << emap.Extent() << ")" << std::endl;
2930 Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2931 tags[vtx[0]] = false;
2934 Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2935 tags[vtx[1]] = false;
2937 if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2939 if (tags[evedg[0]]) {
2940 Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2941 tags[evedg[0]] = false;
2943 edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2946 edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2948 meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2951 /* enumerate triangles */
2952 for(int it=1;it<=nt;it++) {
2954 mesh_get_triangle_vertices(msh, it, vtx);
2955 mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2956 mesh_get_triangle_tag(msh, it, &tag);
2958 meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2959 tags[vtx[0]] = false;
2962 meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2963 tags[vtx[1]] = false;
2966 meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2967 tags[vtx[2]] = false;
2969 if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2970 // QUADRATIC TRIANGLE
2971 if (tags[evtri[0]]) {
2972 meshDS->SetNodeOnFace(nodes[evtri[0]], tag);
2973 tags[evtri[0]] = false;
2975 if (tags[evtri[1]]) {
2976 meshDS->SetNodeOnFace(nodes[evtri[1]], tag);
2977 tags[evtri[1]] = false;
2979 if (tags[evtri[2]]) {
2980 meshDS->SetNodeOnFace(nodes[evtri[2]], tag);
2981 tags[evtri[2]] = false;
2983 tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2984 nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2987 tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2989 meshDS->SetMeshElementOnShape(tri, tag);
2992 /* enumerate quadrangles */
2993 for(int it=1;it<=nq;it++) {
2994 SMDS_MeshFace* quad;
2995 mesh_get_quadrangle_vertices(msh, it, vtx);
2996 mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2997 mesh_get_quadrangle_tag(msh, it, &tag);
2999 meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
3000 tags[vtx[0]] = false;
3003 meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
3004 tags[vtx[1]] = false;
3007 meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
3008 tags[vtx[2]] = false;
3011 meshDS->SetNodeOnFace(nodes[vtx[3]], tag);
3012 tags[vtx[3]] = false;
3014 if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
3015 // QUADRATIC QUADRANGLE
3016 std::cout << "This is a quadratic quadrangle" << std::endl;
3017 if (tags[evquad[0]]) {
3018 meshDS->SetNodeOnFace(nodes[evquad[0]], tag);
3019 tags[evquad[0]] = false;
3021 if (tags[evquad[1]]) {
3022 meshDS->SetNodeOnFace(nodes[evquad[1]], tag);
3023 tags[evquad[1]] = false;
3025 if (tags[evquad[2]]) {
3026 meshDS->SetNodeOnFace(nodes[evquad[2]], tag);
3027 tags[evquad[2]] = false;
3029 if (tags[evquad[3]]) {
3030 meshDS->SetNodeOnFace(nodes[evquad[3]], tag);
3031 tags[evquad[3]] = false;
3033 if (tags[evquad[4]]) {
3034 meshDS->SetNodeOnFace(nodes[evquad[4]], tag);
3035 tags[evquad[4]] = false;
3037 quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
3038 nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
3042 quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
3044 meshDS->SetMeshElementOnShape(quad, tag);
3047 /* release the mesh object, the rest is released by cleaner */
3048 cadsurf_data_regain_mesh(css, msh);
3050 if ( needMerge ) // sew mesh computed by MG-CADSurf with pre-existing mesh
3052 SMESH_MeshEditor editor( &aMesh );
3053 SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
3054 TIDSortedElemSet segementsOnEdge;
3055 TSubMeshSet::iterator smIt;
3056 SMESHDS_SubMesh* smDS;
3058 // merge nodes on EDGE's with ones computed by MG-CADSurf
3059 for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
3061 if (! (smDS = *smIt) ) continue;
3062 getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
3064 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
3065 while ( segIt->more() )
3066 segementsOnEdge.insert( segIt->next() );
3069 editor.MergeNodes( nodeGroupsToMerge );
3072 SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
3073 editor.FindEqualElements( segementsOnEdge, equalSegments );
3074 editor.MergeElements( equalSegments );
3076 // remove excess segments created on the boundary of viscous layers
3077 const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
3078 for ( int i = 1; i <= emap.Extent(); ++i )
3080 if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
3082 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
3083 while ( segIt->more() )
3085 const SMDS_MeshElement* seg = segIt->next();
3086 if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
3087 seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
3088 meshDS->RemoveFreeElement( seg, smDS );
3094 // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
3095 TopLoc_Location loc; double f,l;
3096 for (int i = 1; i <= emap.Extent(); i++)
3097 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
3098 sm->SetIsAlwaysComputed( true );
3099 for (int i = 1; i <= pmap.Extent(); i++)
3100 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
3101 if ( !sm->IsMeshComputed() )
3102 sm->SetIsAlwaysComputed( true );
3104 // Set error to FACE's w/o elements
3105 SMESH_ComputeErrorName err = COMPERR_ALGO_FAILED;
3106 if ( _comment.empty() && status == STATUS_OK )
3108 err = COMPERR_WARNING;
3109 _comment = "No mesh elements assigned to a face";
3111 bool badFaceFound = false;
3112 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
3114 TopoDS_Face f = TopoDS::Face(face_iter.Current());
3115 SMESH_subMesh* sm = aMesh.GetSubMesh( f );
3116 if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
3118 sm->GetComputeError().reset( new SMESH_ComputeError( err, _comment, this ));
3119 badFaceFound = true;
3122 if ( err == COMPERR_WARNING )
3126 if ( status != STATUS_OK && !badFaceFound ) {
3130 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
3132 if ( oldFEFlags > 0 )
3133 feenableexcept( oldFEFlags );
3134 feclearexcept( FE_ALL_EXCEPT );
3138 std::cout << "FacesWithSizeMap" << std::endl;
3139 FacesWithSizeMap.Statistics(std::cout);
3140 std::cout << "EdgesWithSizeMap" << std::endl;
3141 EdgesWithSizeMap.Statistics(std::cout);
3142 std::cout << "VerticesWithSizeMap" << std::endl;
3143 VerticesWithSizeMap.Statistics(std::cout);
3144 std::cout << "FacesWithEnforcedVertices" << std::endl;
3145 FacesWithEnforcedVertices.Statistics(std::cout);
3148 MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
3149 return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
3152 //================================================================================
3154 * \brief Terminates computation
3156 //================================================================================
3158 void BLSURFPlugin_BLSURF::CancelCompute()
3160 _compute_canceled = true;
3163 //=============================================================================
3167 //=============================================================================
3169 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, const SMDS_MeshNode* node, const TopoDS_Shape& ed) {
3170 const TopoDS_Edge edge = TopoDS::Edge(ed);
3172 gp_Pnt pnt(node->X(), node->Y(), node->Z());
3174 Standard_Real p0 = 0.0;
3175 Standard_Real p1 = 1.0;
3176 TopLoc_Location loc;
3177 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
3178 if ( curve.IsNull() )
3180 // issue 22499. Node at a sphere apex
3181 meshDS->SetNodeOnEdge(node, edge, p0);
3185 if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
3186 GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
3189 if ( proj.NbPoints() > 0 )
3191 pa = (double)proj.LowerDistanceParameter();
3192 // Issue 0020656. Move node if it is too far from edge
3193 gp_Pnt curve_pnt = curve->Value( pa );
3194 double dist2 = pnt.SquareDistance( curve_pnt );
3195 double tol = BRep_Tool::Tolerance( edge );
3196 if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
3198 curve_pnt.Transform( loc );
3199 meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
3203 meshDS->SetNodeOnEdge(node, edge, pa);
3206 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
3208 * NOTE : if when your CAD systems evaluates second
3209 * order derivatives it also computes first order derivatives and
3210 * function evaluation, you can optimize this example by making only
3211 * one CAD call and filling the necessary uv, dt, dtt arrays.
3213 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
3215 /* t is given. It contains the t (time) 1D parametric coordintaes
3216 of the point PreCAD/MG-CADSurf is querying on the curve */
3218 /* user_data identifies the edge PreCAD/MG-CADSurf is querying
3219 * (see cad_edge_new later in this example) */
3220 const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
3223 /* MG-CADSurf is querying the function evaluation */
3226 uv[0]=P.X(); uv[1]=P.Y();
3230 /* query for the first order derivatives */
3233 dt[0]=V1.X(); dt[1]=V1.Y();
3237 /* query for the second order derivatives */
3240 dtt[0]=V2.X(); dtt[1]=V2.Y();
3246 /* Surface definition function.
3247 * See cad_surf_t in file meshgems/cad.h for more information.
3248 * NOTE : if when your CAD systems evaluates second order derivatives it also
3249 * computes first order derivatives and function evaluation, you can optimize
3250 * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
3253 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
3254 real *duu, real *duv, real *dvv, void *user_data)
3256 /* uv[2] is given. It contains the u,v coordinates of the point
3257 * PreCAD/MG-CADSurf is querying on the surface */
3259 /* user_data identifies the face PreCAD/MG-CADSurf is querying (see
3260 * cad_face_new later in this example)*/
3261 const Geom_Surface* geometry = (const Geom_Surface*) user_data;
3265 P=geometry->Value(uv[0],uv[1]); // S.D0(U,V,P);
3266 xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
3273 geometry->D1(uv[0],uv[1],P,D1U,D1V);
3274 du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
3275 dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
3278 if(duu && duv && dvv){
3282 gp_Vec D2U,D2V,D2UV;
3284 geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
3285 duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
3286 duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
3287 dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
3294 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
3296 TId2ClsAttractorVec::iterator f2attVec;
3297 if (FaceId2PythonSmp.count(face_id) != 0){
3298 assert(Py_IsInitialized());
3299 PyGILState_STATE gstate;
3300 gstate = PyGILState_Ensure();
3301 PyObject* pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
3303 if ( pyresult != NULL) {
3304 result = PyFloat_AsDouble(pyresult);
3305 Py_DECREF(pyresult);
3310 string err_description="";
3311 PyObject* new_stderr = newPyStdOut(err_description);
3312 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3313 Py_INCREF(old_stderr);
3314 PySys_SetObject((char*)"stderr", new_stderr);
3316 PySys_SetObject((char*)"stderr", old_stderr);
3317 Py_DECREF(new_stderr);
3318 MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
3319 result = *((real*)user_data);
3322 PyGILState_Release(gstate);
3324 else if (( f2attVec = FaceIndex2ClassAttractor.find(face_id)) != FaceIndex2ClassAttractor.end() && !f2attVec->second.empty()){
3325 // MESSAGE("attractor used on face :"<<face_id)
3326 // MESSAGE("List of attractor is not empty")
3327 // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
3330 std::vector< BLSURFPlugin_Attractor* > & attVec = f2attVec->second;
3331 for ( size_t i = 0; i < attVec.size(); ++i )
3333 //result += attVec[i]->GetSize(uv[0],uv[1]);
3334 result = Min( result, attVec[i]->GetSize(uv[0],uv[1]));
3336 //*size = result / attVec.size(); // mean of sizes defined by all attractors
3340 // MESSAGE("List of attractor is empty !!!")
3341 *size = *((real*)user_data);
3343 // std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
3347 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
3349 if (EdgeId2PythonSmp.count(edge_id) != 0){
3350 assert(Py_IsInitialized());
3351 PyGILState_STATE gstate;
3352 gstate = PyGILState_Ensure();
3353 PyObject* pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
3355 if ( pyresult != NULL) {
3356 result = PyFloat_AsDouble(pyresult);
3357 Py_DECREF(pyresult);
3362 string err_description="";
3363 PyObject* new_stderr = newPyStdOut(err_description);
3364 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3365 Py_INCREF(old_stderr);
3366 PySys_SetObject((char*)"stderr", new_stderr);
3368 PySys_SetObject((char*)"stderr", old_stderr);
3369 Py_DECREF(new_stderr);
3370 MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
3371 result = *((real*)user_data);
3374 PyGILState_Release(gstate);
3377 *size = *((real*)user_data);
3382 status_t size_on_vertex(integer point_id, real *size, void *user_data)
3384 if (VertexId2PythonSmp.count(point_id) != 0){
3385 assert(Py_IsInitialized());
3386 PyGILState_STATE gstate;
3387 gstate = PyGILState_Ensure();
3388 PyObject* pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
3390 if ( pyresult != NULL) {
3391 result = PyFloat_AsDouble(pyresult);
3392 Py_DECREF(pyresult);
3397 string err_description="";
3398 PyObject* new_stderr = newPyStdOut(err_description);
3399 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3400 Py_INCREF(old_stderr);
3401 PySys_SetObject((char*)"stderr", new_stderr);
3403 PySys_SetObject((char*)"stderr", old_stderr);
3404 Py_DECREF(new_stderr);
3405 MESSAGE("Can't evaluate f()" << " error is " << err_description);
3406 result = *((real*)user_data);
3409 PyGILState_Release(gstate);
3412 *size = *((real*)user_data);
3418 * The following function will be called for PreCAD/MG-CADSurf message
3419 * printing. See context_set_message_callback (later in this
3420 * template) for how to set user_data.
3422 status_t message_cb(message_t *msg, void *user_data)
3424 integer errnumber = 0;
3426 message_get_number(msg, &errnumber);
3427 message_get_description(msg, &desc);
3429 message_cb_user_data * mcud = (message_cb_user_data*)user_data;
3430 // Get all the error message and some warning messages related to license and periodicity
3431 if ( errnumber < 0 ||
3432 err.find("license" ) != string::npos ||
3433 err.find("periodicity") != string::npos )
3435 // remove ^A from the tail
3436 int len = strlen( desc );
3437 while (len > 0 && desc[len-1] != '\n')
3439 mcud->_error->append( desc, len );
3442 if ( errnumber == 3009001 )
3443 * mcud->_progress = atof( desc + 11 ) / 100.;
3444 if ( mcud->_verbosity > 0 )
3445 std::cout << desc << std::endl;
3450 /* This is the interrupt callback. PreCAD/MG-CADSurf will call this
3451 * function regularily. See the file meshgems/interrupt.h
3453 status_t interrupt_cb(integer *interrupt_status, void *user_data)
3455 integer you_want_to_continue = 1;
3456 BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
3457 you_want_to_continue = !tmp->computeCanceled();
3459 if(you_want_to_continue)
3461 *interrupt_status = INTERRUPT_CONTINUE;
3464 else /* you want to stop MG-CADSurf */
3466 *interrupt_status = INTERRUPT_STOP;
3467 return STATUS_ERROR;
3471 //=============================================================================
3475 //=============================================================================
3476 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
3477 const TopoDS_Shape& aShape,
3478 MapShapeNbElems& aResMap)
3480 double diagonal = aMesh.GetShapeDiagonalSize();
3481 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
3482 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
3483 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
3484 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
3485 //int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
3486 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
3487 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
3489 _physicalMesh = (int) _hypothesis->GetPhysicalMesh();
3490 _phySizeRel = _hypothesis->IsPhySizeRel();
3491 if ( _hypothesis->GetPhySize() > 0)
3492 _phySize = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
3493 //_geometricMesh = (int) hyp->GetGeometricMesh();
3494 if (_hypothesis->GetAngleMesh() > 0)
3495 _angleMesh = _hypothesis->GetAngleMesh();
3496 _quadAllowed = _hypothesis->GetQuadAllowed();
3498 //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
3499 // GetDefaultPhySize() sometimes leads to computation failure
3500 _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
3501 MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
3504 bool IsQuadratic = _quadraticMesh;
3509 TopTools_DataMapOfShapeInteger EdgesMap;
3510 double fullLen = 0.0;
3511 double fullNbSeg = 0;
3512 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
3513 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3514 if( EdgesMap.IsBound(E) )
3516 SMESH_subMesh *sm = aMesh.GetSubMesh(E);
3517 double aLen = SMESH_Algo::EdgeLength(E);
3520 if(_physicalMesh==1) {
3521 nb1d = (int)( aLen/_phySize + 1 );
3526 Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
3527 double fullAng = 0.0;
3528 double dp = (l-f)/200;
3533 for(int j=2; j<=200; j++) {
3536 fullAng += fabs(V1.Angle(V2));
3540 nb1d = (int)( fullAng/_angleMesh + 1 );
3543 std::vector<int> aVec(SMDSEntity_Last);
3544 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3545 if( IsQuadratic > 0 ) {
3546 aVec[SMDSEntity_Node] = 2*nb1d - 1;
3547 aVec[SMDSEntity_Quad_Edge] = nb1d;
3550 aVec[SMDSEntity_Node] = nb1d - 1;
3551 aVec[SMDSEntity_Edge] = nb1d;
3553 aResMap.insert(std::make_pair(sm,aVec));
3554 EdgesMap.Bind(E,nb1d);
3556 double ELen = fullLen/fullNbSeg;
3560 // try to evaluate as in MEFISTO
3561 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
3562 TopoDS_Face F = TopoDS::Face( exp.Current() );
3563 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
3565 BRepGProp::SurfaceProperties(F,G);
3566 double anArea = G.Mass();
3568 std::vector<int> nb1dVec;
3569 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
3570 int nbSeg = EdgesMap.Find(exp1.Current());
3572 nb1dVec.push_back( nbSeg );
3575 int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
3576 int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
3579 if ( nb1dVec.size() == 4 ) // quadrangle geom face
3581 int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
3583 nbNodes = (n1 + 1) * (n2 + 1);
3588 nbTria = nbQuad = nbTria / 3 + 1;
3591 std::vector<int> aVec(SMDSEntity_Last,0);
3593 int nb1d_in = (nbTria*3 - nb1d) / 2;
3594 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3595 aVec[SMDSEntity_Quad_Triangle] = nbTria;
3596 aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3599 aVec[SMDSEntity_Node] = nbNodes;
3600 aVec[SMDSEntity_Triangle] = nbTria;
3601 aVec[SMDSEntity_Quadrangle] = nbQuad;
3603 aResMap.insert(std::make_pair(sm,aVec));
3610 BRepGProp::VolumeProperties(aShape,G);
3611 double aVolume = G.Mass();
3612 double tetrVol = 0.1179*ELen*ELen*ELen;
3613 int nbVols = int(aVolume/tetrVol);
3614 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3615 std::vector<int> aVec(SMDSEntity_Last);
3616 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3618 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3619 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3622 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3623 aVec[SMDSEntity_Tetra] = nbVols;
3625 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3626 aResMap.insert(std::make_pair(sm,aVec));