1 // Copyright (C) 2007-2024 CEA, EDF
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"
29 #include "BLSURFPlugin_Attractor.hxx"
30 #include "BLSURFPlugin_EnforcedMesh1D.hxx"
31 #include "BLSURFPlugin_Hypothesis.hxx"
34 #include <meshgems/meshgems.h>
35 #include <meshgems/cadsurf.h>
38 #include <SMDS_EdgePosition.hxx>
39 #include <SMESHDS_Group.hxx>
40 #include <SMESH_File.hxx>
41 #include <SMESH_Gen.hxx>
42 #include <SMESH_Group.hxx>
43 #include <SMESH_MGLicenseKeyGen.hxx>
44 #include <SMESH_Mesh.hxx>
45 #include <SMESH_MeshEditor.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <StdMeshers_FaceSide.hxx>
48 #include <StdMeshers_ProjectionUtils.hxx>
49 #include <StdMeshers_ViscousLayers2D.hxx>
51 #include <Basics_Utils.hxx>
52 #include <utilities.h>
60 #include <structmember.h> // python
62 // OPENCASCADE includes
63 #include <BRepBndLib.hxx>
64 #include <BRepBuilderAPI_MakeFace.hxx>
65 #include <BRepBuilderAPI_MakePolygon.hxx>
66 #include <BRepBuilderAPI_MakeWire.hxx>
67 #include <BRepGProp.hxx>
68 #include <BRepTools.hxx>
69 #include <BRep_Builder.hxx>
70 #include <BRep_Tool.hxx>
71 #include <GProp_GProps.hxx>
72 #include <Geom2d_Curve.hxx>
73 #include <Geom2d_Line.hxx>
74 #include <GeomAPI_ProjectPointOnCurve.hxx>
75 #include <GeomAPI_ProjectPointOnSurf.hxx>
76 #include <Geom_Curve.hxx>
77 #include <Geom_Surface.hxx>
78 #include <NCollection_DataMap.hxx>
79 #include <NCollection_Map.hxx>
80 #include <Standard_ErrorHandler.hxx>
82 #include <TopExp_Explorer.hxx>
83 #include <TopTools_DataMapOfShapeInteger.hxx>
84 #include <TopTools_IndexedMapOfShape.hxx>
85 #include <TopTools_MapOfShape.hxx>
87 #include <TopoDS_Compound.hxx>
88 #include <TopoDS_Edge.hxx>
89 #include <TopoDS_Face.hxx>
90 #include <TopoDS_Shape.hxx>
91 #include <TopoDS_Vertex.hxx>
92 #include <TopoDS_Wire.hxx>
94 #include <gp_Pnt2d.hxx>
101 #include <functional>
105 /* ==================================
106 * =========== PYTHON ==============
107 * ==================================*/
118 PyStdOut_dealloc(PyStdOut *self)
124 PyStdOut_write(PyStdOut *self, PyObject *args)
128 if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
131 *(self->out)=*(self->out)+c;
137 static PyMethodDef PyStdOut_methods[] = {
138 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
139 PyDoc_STR("write(string) -> None")},
140 {0, 0, 0, 0} /* sentinel */
143 static PyMemberDef PyStdOut_memberlist[] = {
144 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
145 (char*)"flag indicating that a space needs to be printed; used by print"},
146 {0, 0, 0, 0, 0} /* Sentinel */
149 static PyTypeObject PyStdOut_Type = {
150 /* The ob_type field must be initialized in the module init function
151 * to be portable to Windows without using C++. */
152 PyVarObject_HEAD_INIT(NULL, 0)
154 sizeof(PyStdOut), /*tp_basicsize*/
157 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
164 0, /*tp_as_sequence*/
169 PyObject_GenericGetAttr, /*tp_getattro*/
170 /* softspace is writable: we must supply tp_setattro */
171 PyObject_GenericSetAttr, /* tp_setattro */
173 Py_TPFLAGS_DEFAULT, /*tp_flags*/
177 0, /*tp_richcompare*/
178 0, /*tp_weaklistoffset*/
181 PyStdOut_methods, /*tp_methods*/
182 PyStdOut_memberlist, /*tp_members*/
200 0, /*tp_version_tag*/
204 PyObject * newPyStdOut( std::string& out )
206 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
211 return (PyObject*)self;
216 ////////////////////////END PYTHON///////////////////////////
218 //////////////////MY MAPS////////////////////////////////////////
220 TopTools_IndexedMapOfShape FacesWithSizeMap;
221 std::map<int,string> FaceId2SizeMap;
222 TopTools_IndexedMapOfShape EdgesWithSizeMap;
223 std::map<int,string> EdgeId2SizeMap;
224 TopTools_IndexedMapOfShape VerticesWithSizeMap;
225 std::map<int,string> VertexId2SizeMap;
227 std::map<int,PyObject*> FaceId2PythonSmp;
228 std::map<int,PyObject*> EdgeId2PythonSmp;
229 std::map<int,PyObject*> VertexId2PythonSmp;
231 typedef std::map<int, std::vector< BLSURFPlugin_Attractor* > > TId2ClsAttractorVec;
232 TId2ClsAttractorVec FaceId2ClassAttractor;
233 TId2ClsAttractorVec FaceIndex2ClassAttractor;
234 std::map<int,std::vector<double> > FaceId2AttractorCoords;
237 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
238 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
239 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
240 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
241 SMESH_MesherHelper* theHelper;
243 bool HasSizeMapOnFace=false;
244 bool HasSizeMapOnEdge=false;
245 bool HasSizeMapOnVertex=false;
246 //bool HasAttractorOnFace=false;
248 //=============================================================================
252 //=============================================================================
254 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId,
257 : SMESH_2D_Algo(hypId, gen)
259 _name = theHasGEOM ? "MG-CADSurf" : "MG-CADSurf_NOGEOM";//"BLSURF";
260 _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
261 _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType(theHasGEOM));
263 _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
264 _requireDiscreteBoundary = false;
265 _onlyUnaryInput = false;
267 _supportSubmeshes = true;
268 _requireShape = theHasGEOM;
270 /* Initialize the Python interpreter */
271 assert(Py_IsInitialized());
272 PyGILState_STATE gstate;
273 gstate = PyGILState_Ensure();
276 main_mod = PyImport_AddModule("__main__");
279 main_dict = PyModule_GetDict(main_mod);
281 PyRun_SimpleString("from math import *");
282 PyGILState_Release(gstate);
284 FacesWithSizeMap.Clear();
285 FaceId2SizeMap.clear();
286 EdgesWithSizeMap.Clear();
287 EdgeId2SizeMap.clear();
288 VerticesWithSizeMap.Clear();
289 VertexId2SizeMap.clear();
290 FaceId2PythonSmp.clear();
291 EdgeId2PythonSmp.clear();
292 VertexId2PythonSmp.clear();
293 FaceId2AttractorCoords.clear();
294 FaceId2ClassAttractor.clear();
295 FaceIndex2ClassAttractor.clear();
296 FacesWithEnforcedVertices.Clear();
297 FaceId2EnforcedVertexCoords.clear();
298 EnfVertexCoords2ProjVertex.clear();
299 EnfVertexCoords2EnfVertexList.clear();
301 _compute_canceled = false;
304 //=============================================================================
308 //=============================================================================
310 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
315 //=============================================================================
319 //=============================================================================
321 bool BLSURFPlugin_BLSURF::CheckHypothesis
323 const TopoDS_Shape& aShape,
324 SMESH_Hypothesis::Hypothesis_Status& aStatus)
327 _haveViscousLayers = false;
329 list<const SMESHDS_Hypothesis*>::const_iterator itl;
330 const SMESHDS_Hypothesis* theHyp;
332 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape,
333 /*ignoreAuxiliary=*/false);
334 aStatus = SMESH_Hypothesis::HYP_OK;
337 return true; // can work with no hypothesis
340 for ( itl = hyps.begin(); itl != hyps.end() && ( aStatus == HYP_OK ); ++itl )
343 string hypName = theHyp->GetName();
344 if ( hypName == BLSURFPlugin_Hypothesis::GetHypType(true) ||
345 hypName == BLSURFPlugin_Hypothesis::GetHypType(false) )
347 _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
349 if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
350 _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
351 // hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
352 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
354 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
356 if ( !_haveViscousLayers )
358 if ( error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus )))
359 _haveViscousLayers = true;
364 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
367 return aStatus == SMESH_Hypothesis::HYP_OK;
370 //=============================================================================
372 * Pass parameters to MG-CADSurf
374 //=============================================================================
376 inline std::string val_to_string(double d)
378 std::ostringstream o;
383 inline std::string val_to_string_rel(double d)
385 std::ostringstream o;
391 inline std::string val_to_string(int i)
393 std::ostringstream o;
398 inline std::string val_to_string_rel(int i)
400 std::ostringstream o;
406 double _smp_phy_size;
407 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
408 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
409 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
411 /////////////////////////////////////////////////////////
413 BLSURFPlugin_BLSURF::projectionPoint
414 BLSURFPlugin_BLSURF::getProjectionPoint(TopoDS_Face& theFace,
415 const gp_Pnt& thePoint,
416 const bool theAllowStateON)
418 projectionPoint myPoint;
420 if ( theFace.IsNull() )
422 TopoDS_Shape foundFace, myShape = theHelper->GetSubShape();
423 TopTools_MapOfShape checkedFaces;
424 std::map< double, std::pair< TopoDS_Face, gp_Pnt2d > > dist2face;
426 for ( TopExp_Explorer exp ( myShape, TopAbs_FACE ); exp.More(); exp.Next())
428 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
429 if ( !checkedFaces.Add( face )) continue;
431 // check distance to face
432 Handle(ShapeAnalysis_Surface) surface = theHelper->GetSurface( face );
433 gp_Pnt2d uv = surface->ValueOfUV( thePoint, Precision::Confusion());
434 double distance = surface->Gap();
435 if ( distance > Precision::Confusion() )
437 // the face is far, store for future analysis
438 dist2face.insert( std::make_pair( distance, std::make_pair( face, uv )));
442 // check location on the face
443 BRepClass_FaceClassifier FC( face, uv, BRep_Tool::Tolerance( face ));
444 if (( FC.State() == TopAbs_IN ) ||
445 ( FC.State() == TopAbs_ON && theAllowStateON ))
447 if ( !foundFace.IsNull() && !theAllowStateON )
448 return myPoint; // thePoint seems to be TopAbs_ON
450 myPoint.uv = uv.XY();
451 myPoint.xyz = surface->Value( uv ).XYZ();
452 myPoint.state = FC.State();
455 if ( FC.State() == TopAbs_ON && !theAllowStateON )
459 if ( foundFace.IsNull() )
461 // find the closest face
462 std::map< double, std::pair< TopoDS_Face, gp_Pnt2d > >::iterator d2f = dist2face.begin();
463 for ( ; d2f != dist2face.end(); ++d2f )
465 const TopoDS_Face& face = d2f->second.first;
466 const gp_Pnt2d & uv = d2f->second.second;
467 BRepClass_FaceClassifier FC( face, uv, Precision::Confusion());
468 if (( FC.State() == TopAbs_IN ) ||
469 ( FC.State() == TopAbs_ON && theAllowStateON ))
472 myPoint.uv = uv.XY();
473 myPoint.xyz = theHelper->GetSurface( face )->Value( uv ).XYZ();
474 myPoint.state = FC.State();
475 if ( FC.State() == TopAbs_IN )
480 // set the resultShape
481 // if ( foundFace.IsNull() )
482 // throw SMESH_ComputeError(COMPERR_BAD_PARMETERS,
483 // "getProjectionPoint: can't find a face by a vertex");
484 theFace = TopoDS::Face( foundFace );
486 else // !theFace.IsNull()
488 Handle(Geom_Surface) surface = BRep_Tool::Surface( theFace );
489 GeomAPI_ProjectPointOnSurf projector( thePoint, surface );
490 if ( !projector.IsDone() || projector.NbPoints()==0 )
491 throw SMESH_ComputeError(COMPERR_BAD_PARMETERS,
492 "getProjectionPoint: can't project a vertex to a face");
495 projector.LowerDistanceParameters(u,v);
496 myPoint.uv = gp_XY(u,v);
497 myPoint.xyz = projector.NearestPoint().XYZ();
499 BRepClass_FaceClassifier FC( theFace, myPoint.uv, Precision::Confusion());
500 myPoint.state = FC.State();
502 if (( FC.State() != TopAbs_IN ) &&
503 ( FC.State() != TopAbs_ON || !theAllowStateON ))
510 /////////////////////////////////////////////////////////
511 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
513 GEOM::GEOM_Object_var aGeomObj = SMESH_Gen_i::GetSMESHGen()->GetGeomObjectByEntry( entry );
514 TopoDS_Shape S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj );
518 // Check if a point is already on the shape.
519 // if faceShape is defined, we use it
520 // else we use the sub-shape of the mesh
521 bool _doVertexAlreadyExists(const TopoDS_Face& faceShape,
524 // If the point is already on the shape, no need to add it
526 TopoDS_Shape shapeToCheckVertices(faceShape);
527 bool alreadyExists(false);
528 if (faceShape.IsNull())
529 shapeToCheckVertices = theHelper->GetSubShape();
530 for (ex.Init(shapeToCheckVertices, TopAbs_VERTEX); ex.More(); ex.Next())
532 TopoDS_Vertex vertex = TopoDS::Vertex(ex.Current());
533 double tol = BRep_Tool::Tolerance( vertex );
534 gp_Pnt p = BRep_Tool::Pnt(vertex);
535 if ( p.IsEqual( aPnt, tol))
537 MESSAGE("The enforced vertex is already on the shape => No need to add it.");
538 alreadyExists = true;
542 return alreadyExists;
545 void _createEnforcedVertexOnFace(TopoDS_Face faceShape,
547 BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex,
548 bool checkVertexAlreadyExists=true)
550 BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
552 // checkVertexAlreadyExists only for non internal vertices.
553 // For them we set checkVertexAlreadyExists=false as we do have to add them
554 if (checkVertexAlreadyExists && _doVertexAlreadyExists(faceShape, aPnt))
557 // Find the face and get the (u,v) values of the enforced vertex on the face
558 BLSURFPlugin_BLSURF::projectionPoint projPnt =
559 BLSURFPlugin_BLSURF::getProjectionPoint( faceShape, aPnt, /*allowStateON=*/true );
560 if ( faceShape.IsNull() )
563 enf_coords.push_back(aPnt.X());
564 enf_coords.push_back(aPnt.Y());
565 enf_coords.push_back(aPnt.Z());
567 coords.push_back(projPnt.uv.X());
568 coords.push_back(projPnt.uv.Y());
569 coords.push_back(projPnt.xyz.X());
570 coords.push_back(projPnt.xyz.Y());
571 coords.push_back(projPnt.xyz.Z());
572 coords.push_back(projPnt.state == TopAbs_ON);
574 s_coords.push_back(projPnt.xyz.X());
575 s_coords.push_back(projPnt.xyz.Y());
576 s_coords.push_back(projPnt.xyz.Z());
578 // Save pair projected vertex / enf vertex
579 EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
580 pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
581 BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
582 ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
583 if (ret.second == false) {
585 (*it)->grpName = enfVertex->grpName;
588 int key = FacesWithEnforcedVertices.Add( faceShape );
590 // If a node is already created by an attractor, do not create enforced vertex
591 int attractorKey = FacesWithSizeMap.FindIndex( faceShape );
592 bool sameAttractor = false;
593 if (attractorKey >= 0)
594 if (FaceId2AttractorCoords.count(attractorKey) > 0)
595 if (FaceId2AttractorCoords[attractorKey] == coords)
596 sameAttractor = true;
598 if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
600 FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redundant coords here (see std::set management)
603 if (! sameAttractor) {
604 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
606 FaceId2EnforcedVertexCoords[key] = ens;
611 /////////////////////////////////////////////////////////
612 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
615 for( BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex : enfVertexList )
617 // Case of manual coords
618 if (enfVertex->coords.size() != 0) {
619 aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
620 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
623 // Case of geom vertex coords
624 if (enfVertex->geomEntry != "") {
625 TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
626 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
627 if (GeomType == TopAbs_VERTEX)
629 enfVertex->vertex = TopoDS::Vertex( GeomShape );
630 aPnt = BRep_Tool::Pnt( enfVertex->vertex );
631 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
634 if (GeomType == TopAbs_COMPOUND)
636 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next())
637 if (it.Value().ShapeType() == TopAbs_VERTEX)
639 enfVertex->vertex = TopoDS::Vertex( it.Value() );
640 aPnt = BRep_Tool::Pnt( enfVertex->vertex );
641 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
648 /////////////////////////////////////////////////////////
649 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction, double defaultSize)
651 double xa=0., ya=0., za=0.; // Coordinates of attractor point
652 double a, b; // Attractor parameter
654 bool createNode=false; // To create a node on attractor projection
656 const char *sep = ";";
657 // atIt->second has the following pattern:
658 // ATTRACTOR(xa;ya;za;a;b;True|False;d)
660 // xa;ya;za : coordinates of attractor
661 // a : desired size on attractor
662 // b : distance of influence of attractor
663 // d : distance until which the size remains constant
665 // We search the parameters in the string
667 pos1 = AttractorFunction.find(sep);
668 if (pos1!=string::npos)
669 xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
671 pos2 = AttractorFunction.find(sep, pos1+1);
672 if (pos2!=string::npos) {
673 ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
677 pos2 = AttractorFunction.find(sep, pos1+1);
678 if (pos2!=string::npos) {
679 za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
683 pos2 = AttractorFunction.find(sep, pos1+1);
684 if (pos2!=string::npos) {
685 a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
689 pos2 = AttractorFunction.find(sep, pos1+1);
690 if (pos2!=string::npos) {
691 b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
695 pos2 = AttractorFunction.find(sep, pos1+1);
696 if (pos2!=string::npos) {
697 string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
698 createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
702 pos2 = AttractorFunction.find(")");
703 if (pos2!=string::npos) {
704 d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
707 // Get the (u,v) values of the attractor on the face
708 BLSURFPlugin_BLSURF::projectionPoint projPnt =
709 BLSURFPlugin_BLSURF::getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
710 gp_XY uvPoint = projPnt.uv;
711 gp_XYZ xyzPoint = projPnt.xyz;
712 Standard_Real u0 = uvPoint.X();
713 Standard_Real v0 = uvPoint.Y();
714 Standard_Real x0 = xyzPoint.X();
715 Standard_Real y0 = xyzPoint.Y();
716 Standard_Real z0 = xyzPoint.Z();
717 std::vector<double> coords;
718 coords.push_back(u0);
719 coords.push_back(v0);
720 coords.push_back(x0);
721 coords.push_back(y0);
722 coords.push_back(z0);
723 // We construct the python function
724 ostringstream attractorFunctionStream;
725 attractorFunctionStream << "def f(u,v): return ";
726 attractorFunctionStream << defaultSize << "-(" << defaultSize <<"-" << a << ")";
727 //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
728 // rnc: make possible to keep the size constant until
729 // a defined distance. Distance is expressed as the positiv part
730 // of r-d where r is the distance to (u0,v0)
731 attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
734 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
735 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
738 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
740 FaceId2SizeMap[key] =attractorFunctionStream.str();
742 FaceId2AttractorCoords[key] = coords;
744 // // Test for new attractors
745 // gp_Pnt myP(xyzPoint);
746 // TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
747 // BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
748 // myAttractor.SetParameters(a, defaultSize, b, d);
749 // myAttractor.SetType(1);
750 // FaceId2ClassAttractor[key] = myAttractor;
751 // if(FaceId2ClassAttractor[key].GetFace().IsNull()){
755 // One sub-shape to get ids from
756 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(const TopoDS_Shape& theMainShape,
757 const TopoDS_Shape& theSubShape,
758 TopAbs_ShapeEnum theShapeType)
760 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
762 TopTools_MapOfShape subShapes;
763 TopTools_IndexedMapOfShape anIndices;
764 TopExp::MapShapes(theMainShape, theShapeType, anIndices);
766 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
768 if ( subShapes.Add( face_iter.Current() )) // issue 23416
770 int face_id = anIndices.FindIndex( face_iter.Current() );
772 throw SALOME_Exception( "Periodicity: sub_shape not found in main_shape");
773 face_ids.push_back( face_id );
779 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(SMESH_Mesh* theMesh,
780 TopoDS_Shape theSubShape,
781 TopAbs_ShapeEnum theShapeType)
783 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
785 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
787 int face_id = theMesh->GetMeshDS()->ShapeToIndex(face_iter.Current());
789 throw SALOME_Exception ( "Periodicity: sub_shape not found in main_shape");
790 face_ids.push_back(face_id);
796 void BLSURFPlugin_BLSURF::addCoordsFromVertices(const std::vector<std::string> &theVerticesEntries, std::vector<double> &theVerticesCoords)
798 for (std::vector<std::string>::const_iterator it = theVerticesEntries.begin(); it != theVerticesEntries.end(); it++)
800 BLSURFPlugin_Hypothesis::TEntry theVertexEntry = *it;
801 addCoordsFromVertex(theVertexEntry, theVerticesCoords);
806 void BLSURFPlugin_BLSURF::addCoordsFromVertex(BLSURFPlugin_Hypothesis::TEntry theVertexEntry, std::vector<double> &theVerticesCoords)
808 if (theVertexEntry!="")
810 TopoDS_Shape aShape = entryToShape(theVertexEntry);
812 gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex( aShape ) );
813 double theX, theY, theZ;
818 theVerticesCoords.push_back(theX);
819 theVerticesCoords.push_back(theY);
820 theVerticesCoords.push_back(theZ);
824 /////////////////////////////////////////////////////////
825 void BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
827 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
828 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
830 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_FACE);
831 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_FACE);
833 TPreCadPeriodicityIDs preCadFacesPeriodicityIDs;
834 preCadFacesPeriodicityIDs.shape1IDs = theFace1_ids;
835 preCadFacesPeriodicityIDs.shape2IDs = theFace2_ids;
837 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadFacesPeriodicityIDs.theSourceVerticesCoords);
838 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadFacesPeriodicityIDs.theTargetVerticesCoords);
840 _preCadFacesIDsPeriodicityVector.push_back(preCadFacesPeriodicityIDs);
843 /////////////////////////////////////////////////////////
844 void BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
846 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
847 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
849 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_EDGE);
850 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_EDGE);
852 TPreCadPeriodicityIDs preCadEdgesPeriodicityIDs;
853 preCadEdgesPeriodicityIDs.shape1IDs = theEdge1_ids;
854 preCadEdgesPeriodicityIDs.shape2IDs = theEdge2_ids;
856 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadEdgesPeriodicityIDs.theSourceVerticesCoords);
857 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadEdgesPeriodicityIDs.theTargetVerticesCoords);
859 _preCadEdgesIDsPeriodicityVector.push_back(preCadEdgesPeriodicityIDs);
863 /////////////////////////////////////////////////////////
865 void BLSURFPlugin_BLSURF::SetParameters(const BLSURFPlugin_Hypothesis* hyp,
866 cadsurf_session_t * css,
867 const TopoDS_Shape& theGeomShape)
870 // Clear map so that it is not stored in the algorithm with old enforced vertices in it
871 FacesWithSizeMap.Clear();
872 FaceId2SizeMap.clear();
873 EdgesWithSizeMap.Clear();
874 EdgeId2SizeMap.clear();
875 VerticesWithSizeMap.Clear();
876 VertexId2SizeMap.clear();
877 FaceId2PythonSmp.clear();
878 EdgeId2PythonSmp.clear();
879 VertexId2PythonSmp.clear();
880 FaceId2AttractorCoords.clear();
881 FaceId2ClassAttractor.clear();
882 FaceIndex2ClassAttractor.clear();
883 FacesWithEnforcedVertices.Clear();
884 FaceId2EnforcedVertexCoords.clear();
885 EnfVertexCoords2ProjVertex.clear();
886 EnfVertexCoords2EnfVertexList.clear();
888 double diagonal = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
889 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
890 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
891 int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
892 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
893 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
894 double _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
895 bool _minSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
896 double _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
897 bool _maxSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
898 double _use_gradation = BLSURFPlugin_Hypothesis::GetDefaultUseGradation();
899 double _gradation = BLSURFPlugin_Hypothesis::GetDefaultGradation();
900 double _use_volume_gradation = BLSURFPlugin_Hypothesis::GetDefaultUseVolumeGradation();
901 double _volume_gradation = BLSURFPlugin_Hypothesis::GetDefaultVolumeGradation();
902 BLSURFPlugin_Hypothesis::ElementType _elementType = BLSURFPlugin_Hypothesis::GetDefaultElementType();
903 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
904 double _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
905 bool _anisotropic = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
906 double _anisotropicRatio = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
907 bool _removeTinyEdges = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
908 double _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
909 bool _optimiseTinyEdges = BLSURFPlugin_Hypothesis::GetDefaultOptimiseTinyEdges();
910 double _tinyEdgeOptimisLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeOptimisationLength(diagonal);
911 bool _correctSurfaceIntersec= BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersection();
912 double _corrSurfaceIntersCost = BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersectionMaxCost();
913 bool _badElementRemoval = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
914 double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
915 bool _optimizeMesh = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
916 bool _quadraticMesh = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
917 int _verb = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
918 //int _topology = BLSURFPlugin_Hypothesis::GetDefaultTopology();
919 bool _useSurfaceProximity = BLSURFPlugin_Hypothesis::GetDefaultUseSurfaceProximity ();
920 int _nbSurfaceProximityLayers = BLSURFPlugin_Hypothesis::GetDefaultNbSurfaceProximityLayers();
921 double _surfaceProximityRatio = BLSURFPlugin_Hypothesis::GetDefaultSurfaceProximityRatio ();
922 bool _useVolumeProximity = BLSURFPlugin_Hypothesis::GetDefaultUseVolumeProximity ();
923 int _nbVolumeProximityLayers = BLSURFPlugin_Hypothesis::GetDefaultNbVolumeProximityLayers ();
924 double _volumeProximityRatio = BLSURFPlugin_Hypothesis::GetDefaultVolumeProximityRatio ();
927 //int _precadMergeEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
928 //int _precadRemoveDuplicateCADFaces = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveDuplicateCADFaces();
929 //int _precadProcess3DTopology = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
930 //int _precadDiscardInput = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
932 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadFacesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadFacesPeriodicityVector(hyp);
935 _physicalMesh = (int) hyp->GetPhysicalMesh();
936 _geometricMesh = (int) hyp->GetGeometricMesh();
937 if (hyp->GetPhySize() > 0) {
938 _phySize = hyp->GetPhySize();
939 // if user size is not explicitly specified, "relative" flag is ignored
940 _phySizeRel = hyp->IsPhySizeRel();
942 if (hyp->GetMinSize() > 0) {
943 _minSize = hyp->GetMinSize();
944 // if min size is not explicitly specified, "relative" flag is ignored
945 _minSizeRel = hyp->IsMinSizeRel();
947 if (hyp->GetMaxSize() > 0) {
948 _maxSize = hyp->GetMaxSize();
949 // if max size is not explicitly specified, "relative" flag is ignored
950 _maxSizeRel = hyp->IsMaxSizeRel();
952 _use_gradation = hyp->GetUseGradation();
953 if (hyp->GetGradation() > 0 && _use_gradation)
954 _gradation = hyp->GetGradation();
955 _use_volume_gradation = hyp->GetUseVolumeGradation();
956 if (hyp->GetVolumeGradation() > 0 && _use_volume_gradation )
957 _volume_gradation = hyp->GetVolumeGradation();
958 _elementType = hyp->GetElementType();
959 if (hyp->GetAngleMesh() > 0)
960 _angleMesh = hyp->GetAngleMesh();
961 if (hyp->GetChordalError() > 0)
962 _chordalError = hyp->GetChordalError();
963 _anisotropic = hyp->GetAnisotropic();
964 if (hyp->GetAnisotropicRatio() >= 0)
965 _anisotropicRatio = hyp->GetAnisotropicRatio();
966 _removeTinyEdges = hyp->GetRemoveTinyEdges();
967 if (hyp->GetTinyEdgeLength() > 0)
968 _tinyEdgeLength = hyp->GetTinyEdgeLength();
969 _optimiseTinyEdges = hyp->GetOptimiseTinyEdges();
970 if (hyp->GetTinyEdgeOptimisationLength() > 0)
971 _tinyEdgeOptimisLength = hyp->GetTinyEdgeOptimisationLength();
972 _correctSurfaceIntersec = hyp->GetCorrectSurfaceIntersection();
973 if (hyp->GetCorrectSurfaceIntersectionMaxCost() > 0)
974 _corrSurfaceIntersCost = hyp->GetCorrectSurfaceIntersectionMaxCost();
975 _badElementRemoval = hyp->GetBadElementRemoval();
976 if (hyp->GetBadElementAspectRatio() >= 0)
977 _badElementAspectRatio = hyp->GetBadElementAspectRatio();
978 _optimizeMesh = hyp->GetOptimizeMesh();
979 _quadraticMesh = hyp->GetQuadraticMesh();
980 _verb = hyp->GetVerbosity();
981 //_topology = (int) hyp->GetTopology();
983 //_precadMergeEdges = hyp->GetPreCADMergeEdges();
984 //_precadRemoveDuplicateCADFaces = hyp->GetPreCADRemoveDuplicateCADFaces();
985 //_precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
986 //_precadDiscardInput = hyp->GetPreCADDiscardInput();
987 _useSurfaceProximity = hyp->GetUseSurfaceProximity ();
988 _nbSurfaceProximityLayers = hyp->GetNbSurfaceProximityLayers();
989 _surfaceProximityRatio = hyp->GetSurfaceProximityRatio ();
990 _useVolumeProximity = hyp->GetUseVolumeProximity ();
991 _nbVolumeProximityLayers = hyp->GetNbVolumeProximityLayers ();
992 _volumeProximityRatio = hyp->GetVolumeProximityRatio ();
995 const BLSURFPlugin_Hypothesis::TOptionValues& opts = hyp->GetOptionValues();
996 BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
997 for ( opIt = opts.begin(); opIt != opts.end(); ++opIt ){
998 MESSAGE("OptionValue: " << opIt->first.c_str() << ", value: " << opIt->second.c_str());
999 if ( !opIt->second.empty() ) {
1000 // With MeshGems 2.4-5, there are issues with periodicity and multithread
1001 // => As a temporary workaround, we enforce to use only one thread if periodicity is used.
1002 if (opIt->first == "max_number_of_threads" && opIt->second != "1" && ! preCadFacesPeriodicityVector.empty()){
1003 std::cout << "INFO: Disabling multithread to avoid periodicity issues" << std::endl;
1004 set_param(css, opIt->first.c_str(), "1");
1007 set_param(css, opIt->first.c_str(), opIt->second.c_str());
1011 const BLSURFPlugin_Hypothesis::TOptionValues& custom_opts = hyp->GetCustomOptionValues();
1012 for ( opIt = custom_opts.begin(); opIt != custom_opts.end(); ++opIt )
1013 if ( !opIt->second.empty() ) {
1014 set_param(css, opIt->first.c_str(), opIt->second.c_str());
1017 const BLSURFPlugin_Hypothesis::TOptionValues& preCADopts = hyp->GetPreCADOptionValues();
1018 for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
1019 if ( !opIt->second.empty() ) {
1020 set_param(css, opIt->first.c_str(), opIt->second.c_str());
1023 if ( hyp->GetHyperPatches().size() < hyp->GetHyperPatchEntries().size() )
1025 std::map< std::string, TopoDS_Shape > entryToShape;
1026 FillEntryToShape( hyp, entryToShape );
1027 const_cast<BLSURFPlugin_Hypothesis*>( hyp )->SetHyperPatchIDsByEntry( theGeomShape,
1032 if ( BLSURFPlugin_Hypothesis::HasPreCADOptions( hyp ))
1034 cadsurf_set_param(css, "use_precad", "yes" ); // for old versions
1036 // PreProcessor (formerly PreCAD) -- commented params are preCADoptions (since 0023307)
1037 //set_param(css, "merge_edges", _precadMergeEdges ? "yes" : "no");
1038 //set_param(css, "remove_duplicate_cad_faces", _precadRemoveDuplicateCADFaces ? "yes" : "no");
1039 //set_param(css, "process_3d_topology", _precadProcess3DTopology ? "1" : "0");
1040 //set_param(css, "discard_input_topology", _precadDiscardInput ? "1" : "0");
1041 //set_param(css, "max_number_of_points_per_patch", "1000000");
1043 bool useGradation = false;
1044 switch (_physicalMesh)
1046 case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
1047 set_param(css, "physical_size_mode", "global");
1048 set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1049 //useGradation = true;
1051 case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
1052 set_param(css, "physical_size_mode", "local");
1053 set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1054 //useGradation = true;
1057 set_param(css, "physical_size_mode", "none");
1060 switch (_geometricMesh)
1062 case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
1063 set_param(css, "geometric_size_mode", "global");
1064 set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
1065 set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
1066 //useGradation = true;
1068 case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
1069 set_param(css, "geometric_size_mode", "local");
1070 set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
1071 set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
1072 //useGradation = true;
1075 set_param(css, "geometric_size_mode", "none");
1078 if ( hyp && hyp->GetPhySize() > 0 ) {
1079 // user size is explicitly specified via hypothesis parameters
1080 // min and max sizes should be compared with explicitly specified user size
1081 // - compute absolute min size
1082 double mins = _minSizeRel ? _minSize * diagonal : _minSize;
1083 // - min size should not be greater than user size
1084 if ( _phySize < mins )
1085 set_param(css, "min_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1087 set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
1088 // - compute absolute max size
1089 double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
1090 // - max size should not be less than user size
1091 if ( _phySize > maxs )
1092 set_param(css, "max_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1094 set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1097 // user size is not explicitly specified
1098 // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1099 set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
1100 // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1101 set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1103 useGradation = true; // bos #18758
1104 // anisotropic and quadrangle mesh requires disabling gradation
1105 if ( _anisotropic && _elementType != BLSURFPlugin_Hypothesis::Triangles )
1106 useGradation = false; // limitation of V1.3
1107 if ( useGradation && _use_gradation )
1108 set_param(css, "gradation", val_to_string(_gradation).c_str());
1109 if ( useGradation && _use_volume_gradation )
1110 set_param(css, "volume_gradation", val_to_string(_volume_gradation).c_str());
1112 // New since MeshGems 2.5: add full_quad
1113 const char * element_generation = "";
1114 switch ( _elementType )
1116 case BLSURFPlugin_Hypothesis::Triangles:
1117 element_generation = "triangle";
1119 case BLSURFPlugin_Hypothesis::QuadrangleDominant:
1120 element_generation = "quad_dominant";
1122 case BLSURFPlugin_Hypothesis::Quadrangles:
1123 element_generation = "full_quad";
1127 set_param(css, "element_generation", element_generation);
1130 set_param(css, "metric", _anisotropic ? "anisotropic" : "isotropic");
1132 set_param(css, "anisotropic_ratio", val_to_string(_anisotropicRatio).c_str());
1133 set_param(css, "remove_tiny_edges", _removeTinyEdges ? "1" : "0");
1134 if ( _removeTinyEdges )
1135 set_param(css, "tiny_edge_length", val_to_string(_tinyEdgeLength).c_str());
1136 set_param(css, "optimise_tiny_edges", _optimiseTinyEdges ? "1" : "0");
1137 if ( _optimiseTinyEdges )
1138 set_param(css, "tiny_edge_optimisation_length", val_to_string(_tinyEdgeOptimisLength).c_str());
1139 set_param(css, "correct_surface_intersections", _correctSurfaceIntersec ? "1" : "0");
1140 if ( _correctSurfaceIntersec )
1141 set_param(css, "surface_intersections_processing_max_cost", val_to_string(_corrSurfaceIntersCost ).c_str());
1142 set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
1143 if ( _badElementRemoval )
1144 set_param(css, "bad_surface_element_aspect_ratio", val_to_string(_badElementAspectRatio).c_str());
1145 set_param(css, "optimisation", _optimizeMesh ? "yes" : "no");
1146 set_param(css, "element_order", _quadraticMesh ? "quadratic" : "linear");
1147 set_param(css, "verbose", val_to_string(_verb).c_str());
1149 set_param(css, "use_surface_proximity", _useSurfaceProximity ? "yes" : "no" );
1150 if ( _useSurfaceProximity )
1152 set_param(css, "surface_proximity_layers", SMESH_Comment( _nbSurfaceProximityLayers ));
1153 set_param(css, "surface_proximity_ratio", SMESH_Comment( _surfaceProximityRatio ));
1155 set_param(css, "use_volume_proximity", _useVolumeProximity ? "yes" : "no" );
1156 if ( _useVolumeProximity )
1158 set_param(css, "volume_proximity_layers", SMESH_Comment( _nbVolumeProximityLayers ));
1159 set_param(css, "volume_proximity_ratio", SMESH_Comment( _volumeProximityRatio ));
1162 _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
1164 std::cout << "_smp_phy_size = " << _smp_phy_size << std::endl;
1166 if (_physicalMesh == BLSURFPlugin_Hypothesis::PhysicalLocalSize)
1168 TopoDS_Shape GeomShape;
1169 TopoDS_Shape AttShape;
1170 TopAbs_ShapeEnum GeomType;
1172 // Standard Size Maps
1174 const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
1175 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
1176 for ( ; smIt != sizeMaps.end(); ++smIt ) {
1177 if ( !smIt->second.empty() ) {
1178 GeomShape = entryToShape(smIt->first);
1179 GeomType = GeomShape.ShapeType();
1182 if (GeomType == TopAbs_COMPOUND) {
1183 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1185 if (it.Value().ShapeType() == TopAbs_FACE){
1186 HasSizeMapOnFace = true;
1187 if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
1188 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
1191 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
1193 FaceId2SizeMap[key] = smIt->second;
1196 if (it.Value().ShapeType() == TopAbs_EDGE){
1197 HasSizeMapOnEdge = true;
1198 HasSizeMapOnFace = true;
1199 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
1200 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
1203 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
1205 EdgeId2SizeMap[key] = smIt->second;
1207 // Group of vertices
1208 if (it.Value().ShapeType() == TopAbs_VERTEX){
1209 HasSizeMapOnVertex = true;
1210 HasSizeMapOnEdge = true;
1211 HasSizeMapOnFace = true;
1212 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
1213 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
1216 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
1218 VertexId2SizeMap[key] = smIt->second;
1223 if (GeomType == TopAbs_FACE){
1224 HasSizeMapOnFace = true;
1225 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
1226 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
1229 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1231 FaceId2SizeMap[key] = smIt->second;
1234 if (GeomType == TopAbs_EDGE){
1235 HasSizeMapOnEdge = true;
1236 HasSizeMapOnFace = true;
1237 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
1238 key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
1241 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
1243 EdgeId2SizeMap[key] = smIt->second;
1246 if (GeomType == TopAbs_VERTEX){
1247 HasSizeMapOnVertex = true;
1248 HasSizeMapOnEdge = true;
1249 HasSizeMapOnFace = true;
1250 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
1251 key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
1254 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
1256 VertexId2SizeMap[key] = smIt->second;
1264 // TODO appeler le constructeur des attracteurs directement ici
1265 // if ( !_phySizeRel ) {
1266 const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
1267 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
1268 for ( ; atIt != attractors.end(); ++atIt ) {
1269 if ( !atIt->second.empty() ) {
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;
1304 // temporary commented out for testing
1306 // - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
1307 // - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
1308 // - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
1310 // - Construct the attractors with an empty dist. map in the hypothesis
1311 // - 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()
1312 // -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap() OK
1314 theNbAttractors = 0;
1315 const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
1317 BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
1318 for ( ; AtIt != class_attractors.end(); ++AtIt ) {
1319 if ( !AtIt->second->Empty() ) {
1320 GeomShape = entryToShape(AtIt->first);
1321 if ( !SMESH_MesherHelper::IsSubShape( GeomShape, theGeomShape ))
1323 AttShape = AtIt->second->GetAttractorShape();
1324 GeomType = GeomShape.ShapeType();
1326 // if (GeomType == TopAbs_COMPOUND){
1327 // for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1328 // if (it.Value().ShapeType() == TopAbs_FACE){
1329 // HasAttractorOnFace = true;
1330 // myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
1335 if (GeomType == TopAbs_FACE
1336 && (AttShape.ShapeType() == TopAbs_VERTEX
1337 || AttShape.ShapeType() == TopAbs_EDGE
1338 || AttShape.ShapeType() == TopAbs_WIRE
1339 || AttShape.ShapeType() == TopAbs_COMPOUND) ){
1340 HasSizeMapOnFace = true;
1342 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
1344 FaceId2ClassAttractor[key].push_back( AtIt->second );
1348 MESSAGE("Wrong shape type !!");
1356 // Enforced Vertices
1358 const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
1359 BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
1360 for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
1361 if ( !enfIt->second.empty() ) {
1362 GeomShape = entryToShape(enfIt->first);
1363 if ( GeomShape.IsNull() )
1365 createEnforcedVertexOnFace( GeomShape, enfIt->second );
1368 else if ( GeomShape.ShapeType() == 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);
1377 else if ( GeomShape.ShapeType() == 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);
1390 TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
1391 for (; exp.More(); exp.Next()){
1392 TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
1393 for (; exp_face.More(); exp_face.Next())
1395 // Get coords of vertex
1396 // Check if current coords is already in enfVertexList
1397 // If coords not in enfVertexList, add new enfVertex
1398 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1399 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1400 enfVertex->coords.push_back(aPnt.X());
1401 enfVertex->coords.push_back(aPnt.Y());
1402 enfVertex->coords.push_back(aPnt.Z());
1403 enfVertex->name = "";
1404 enfVertex->faceEntries.clear();
1405 enfVertex->geomEntry = "";
1406 enfVertex->grpName = grpName;
1407 enfVertex->vertex = TopoDS::Vertex( exp_face.Current() );
1408 _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()), aPnt, enfVertex,
1409 /*checkVertexAlreadyExists*/false);
1410 HasSizeMapOnFace = true;
1415 cadsurf_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
1417 if (HasSizeMapOnEdge){
1418 cadsurf_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
1420 if (HasSizeMapOnVertex){
1421 cadsurf_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
1428 _preCadFacesIDsPeriodicityVector.clear();
1429 _preCadEdgesIDsPeriodicityVector.clear();
1431 for (std::size_t i = 0; i<preCadFacesPeriodicityVector.size(); i++){
1432 createPreCadFacesPeriodicity(theGeomShape, preCadFacesPeriodicityVector[i]);
1435 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadEdgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadEdgesPeriodicityVector(hyp);
1437 for (std::size_t i = 0; i<preCadEdgesPeriodicityVector.size(); i++){
1438 createPreCadEdgesPeriodicity(theGeomShape, preCadEdgesPeriodicityVector[i]);
1442 //================================================================================
1444 * \brief Throws an exception if a parameter name is wrong
1446 //================================================================================
1448 void BLSURFPlugin_BLSURF::set_param(cadsurf_session_t *css,
1449 const char * option_name,
1450 const char * option_value)
1452 status_t status = cadsurf_set_param(css, option_name, option_value );
1454 if ( _hypothesis && _hypothesis->GetVerbosity() > _hypothesis->GetDefaultVerbosity() )
1455 cout << option_name << " = " << option_value << endl;
1457 if ( status != MESHGEMS_STATUS_OK )
1459 if ( status == MESHGEMS_STATUS_UNKNOWN_PARAMETER ) {
1460 throw SALOME_Exception
1461 ( SMESH_Comment("Invalid name of CADSURF parameter: ") << option_name );
1463 else if ( status == MESHGEMS_STATUS_NOLICENSE )
1464 throw SALOME_Exception
1465 ( "No valid license available" );
1467 throw SALOME_Exception
1468 ( SMESH_Comment("Either wrong name or unacceptable value of CADSURF parameter '")
1469 << option_name << "': " << option_value);
1475 // --------------------------------------------------------------------------
1477 * \brief Class correctly terminating usage of MG-CADSurf library at destruction
1479 struct BLSURF_Cleaner
1482 cadsurf_session_t* _css;
1486 BLSURF_Cleaner(context_t * ctx,
1487 cadsurf_session_t* css=0,
1498 Clean( /*exceptContext=*/false );
1500 void Clean(const bool exceptContext)
1504 cadsurf_session_delete(_css); _css = 0;
1506 // #if BLSURF_VERSION_LONG >= "3.1.1"
1507 // // if(geo_sizemap_e)
1508 // // distene_sizemap_delete(geo_sizemap_e);
1509 // // if(geo_sizemap_f)
1510 // // distene_sizemap_delete(geo_sizemap_f);
1511 // if(iso_sizemap_p)
1512 // distene_sizemap_delete(iso_sizemap_p);
1513 // if(iso_sizemap_e)
1514 // distene_sizemap_delete(iso_sizemap_e);
1515 // if(iso_sizemap_f)
1516 // distene_sizemap_delete(iso_sizemap_f);
1518 // // if(clean_geo_sizemap_e)
1519 // // distene_sizemap_delete(clean_geo_sizemap_e);
1520 // // if(clean_geo_sizemap_f)
1521 // // distene_sizemap_delete(clean_geo_sizemap_f);
1522 // if(clean_iso_sizemap_p)
1523 // distene_sizemap_delete(clean_iso_sizemap_p);
1524 // if(clean_iso_sizemap_e)
1525 // distene_sizemap_delete(clean_iso_sizemap_e);
1526 // if(clean_iso_sizemap_f)
1527 // distene_sizemap_delete(clean_iso_sizemap_f);
1530 cad_delete(_cad); _cad = 0;
1531 dcad_delete(_dcad); _dcad = 0;
1532 if ( !exceptContext )
1534 context_delete(_ctx); _ctx = 0;
1540 // --------------------------------------------------------------------------
1541 // comparator to sort nodes and sub-meshes
1542 struct ShapeTypeCompare
1544 // sort nodes by position in the following order:
1545 // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
1546 bool operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
1548 // NEW ORDER: nodes earlier added to sub-mesh are considered "less"
1549 //return n1->getIdInShape() < n2->getIdInShape();
1550 return n1->GetID() < n2->GetID(); // earlier created nodes have less IDs
1552 // sort sub-meshes in order: EDGE, VERTEX
1553 bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
1555 int isVertex1 = ( s1 && s1->NbElements() == 0 );
1556 int isVertex2 = ( s2 && s2->NbElements() == 0 );
1557 if ( isVertex1 == isVertex2 )
1559 return isVertex1 < isVertex2;
1563 //================================================================================
1565 * \brief Fills groups of nodes to be merged
1567 //================================================================================
1569 void getNodeGroupsToMerge( const SMESHDS_SubMesh* smDS,
1570 const TopoDS_Shape& shape,
1571 SMESH_MeshEditor::TListOfListOfNodes& nodeGroupsToMerge)
1573 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1574 switch ( shape.ShapeType() )
1576 case TopAbs_VERTEX: {
1577 std::list< const SMDS_MeshNode* > nodes;
1578 while ( nIt->more() )
1579 nodes.push_back( nIt->next() );
1580 if ( nodes.size() > 1 )
1581 nodeGroupsToMerge.push_back( nodes );
1585 std::multimap< double, const SMDS_MeshNode* > u2node;
1586 while ( nIt->more() )
1588 const SMDS_MeshNode* n = nIt->next();
1589 if ( SMDS_EdgePositionPtr ePos = n->GetPosition() )
1590 u2node.insert( make_pair( ePos->GetUParameter(), n ));
1592 if ( u2node.size() < 2 ) return;
1594 //double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
1596 BRep_Tool::Range( TopoDS::Edge( shape ), f,l );
1597 double tol = (( l - f ) / 10.) / double( u2node.size() ); // 10. - adjusted for #17262
1599 std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
1600 for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
1602 if (( un2->first - un1->first ) <= tol )
1604 std::list< const SMDS_MeshNode* > nodes;
1605 nodes.push_back( un1->second );
1606 while (( un2->first - un1->first ) <= tol )
1608 nodes.push_back( un2->second );
1609 if ( ++un2 == u2node.end()) {
1614 // make nodes created on the boundary of viscous layer replace nodes created
1615 // by MG-CADSurf as their SMDS_Position is more correct
1616 nodes.sort( ShapeTypeCompare() );
1617 nodeGroupsToMerge.push_back( nodes );
1624 // SMESH_MeshEditor::TListOfListOfNodes::const_iterator nll = nodeGroupsToMerge.begin();
1625 // for ( ; nll != nodeGroupsToMerge.end(); ++nll )
1627 // cout << "Merge ";
1628 // const std::list< const SMDS_MeshNode* >& nl = *nll;
1629 // std::list< const SMDS_MeshNode* >::const_iterator nIt = nl.begin();
1630 // for ( ; nIt != nl.end(); ++nIt )
1631 // cout << (*nIt) << " ";
1637 //================================================================================
1639 * \brief A temporary mesh used to compute mesh on a proxy FACE
1641 //================================================================================
1643 struct TmpMesh: public SMESH_Mesh
1645 typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
1646 TN2NMap _tmp2origNN;
1647 TopoDS_Face _proxyFace;
1651 _meshDS = new SMESHDS_Mesh( _id, true );
1653 //--------------------------------------------------------------------------------
1655 * \brief Creates a FACE bound by viscous layers and mesh each its EDGE with 1 segment
1657 //--------------------------------------------------------------------------------
1659 const TopoDS_Face& makeProxyFace( SMESH_ProxyMesh::Ptr& viscousMesh,
1660 const TopoDS_Face& origFace)
1662 SMESH_Mesh* origMesh = viscousMesh->GetMesh();
1664 SMESH_MesherHelper helper( *origMesh );
1665 helper.SetSubShape( origFace );
1666 const bool hasSeam = helper.HasRealSeam();
1668 // get data of nodes on inner boundary of viscous layers
1670 TSideVector wireVec = StdMeshers_FaceSide::GetFaceWires(origFace, *origMesh,
1671 /*skipMediumNodes = */true,
1672 err, &helper, viscousMesh );
1673 if ( err && err->IsKO() )
1674 throw *err.get(); // it should be caught at SMESH_subMesh
1676 // proxy nodes and corresponding tmp VERTEXes
1677 std::vector<const SMDS_MeshNode*> origNodes;
1678 std::vector<TopoDS_Vertex> tmpVertex;
1680 // create a proxy FACE
1681 TopoDS_Face origFaceCopy = TopoDS::Face( origFace.EmptyCopied() );
1682 BRepBuilderAPI_MakeFace newFace( origFaceCopy );
1683 bool hasPCurves = false;
1684 for ( size_t iW = 0; iW != wireVec.size(); ++iW )
1686 StdMeshers_FaceSidePtr& wireData = wireVec[iW];
1687 const UVPtStructVec& wirePoints = wireData->GetUVPtStruct();
1688 if ( wirePoints.size() < 3 )
1691 BRepBuilderAPI_MakePolygon polygon;
1692 const size_t i0 = tmpVertex.size();
1693 for ( size_t iN = 0; iN < wirePoints.size(); ++iN )
1695 polygon.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
1696 origNodes.push_back( wirePoints[ iN ].node );
1697 tmpVertex.push_back( polygon.LastVertex() );
1699 // check presence of a pcurve
1700 checkPCurve( polygon, origFaceCopy, hasPCurves, &wirePoints[ iN-1 ] );
1702 tmpVertex[ i0 ] = polygon.FirstVertex(); // polygon.LastVertex()==NULL for 1 vertex in wire
1704 if ( !polygon.IsDone() )
1705 throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
1706 TopoDS_Wire wire = polygon;
1708 wire = updateSeam( wire, origNodes );
1709 newFace.Add( wire );
1711 _proxyFace = newFace;
1713 // set a new shape to mesh
1714 TopoDS_Compound auxCompoundToMesh;
1715 BRep_Builder shapeBuilder;
1716 shapeBuilder.MakeCompound( auxCompoundToMesh );
1717 shapeBuilder.Add( auxCompoundToMesh, _proxyFace );
1718 shapeBuilder.Add( auxCompoundToMesh, origMesh->GetShapeToMesh() );
1720 ShapeToMesh( auxCompoundToMesh );
1723 // Make input mesh for MG-CADSurf: segments on EDGE's of newFace
1725 // make nodes and fill in _tmp2origNN
1727 SMESHDS_Mesh* tmpMeshDS = GetMeshDS();
1728 for ( size_t i = 0; i < origNodes.size(); ++i )
1730 GetSubMesh( tmpVertex[i] )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1731 if ( const SMDS_MeshNode* tmpN = SMESH_Algo::VertexNode( tmpVertex[i], tmpMeshDS ))
1732 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( tmpN, origNodes[i] ));
1733 // else -- it can be a seam vertex replaced by updateSeam()
1734 // throw SALOME_Exception("BLSURFPlugin_BLSURF: a proxy vertex not meshed");
1738 TopoDS_Vertex v1, v2;
1739 for ( TopExp_Explorer edge( _proxyFace, TopAbs_EDGE ); edge.More(); edge.Next() )
1741 const TopoDS_Edge& E = TopoDS::Edge( edge.Current() );
1742 TopExp::Vertices( E, v1, v2 );
1743 const SMDS_MeshNode* n1 = SMESH_Algo::VertexNode( v1, tmpMeshDS );
1744 const SMDS_MeshNode* n2 = SMESH_Algo::VertexNode( v2, tmpMeshDS );
1746 if ( SMDS_MeshElement* seg = tmpMeshDS->AddEdge( n1, n2 ))
1747 tmpMeshDS->SetMeshElementOnShape( seg, E );
1753 //--------------------------------------------------------------------------------
1755 * \brief Add pcurve to the last edge of a wire
1757 //--------------------------------------------------------------------------------
1759 void checkPCurve( BRepBuilderAPI_MakePolygon& wire,
1760 const TopoDS_Face& face,
1762 const uvPtStruct * wirePoints )
1766 TopoDS_Edge edge = wire.Edge();
1767 if ( edge.IsNull() ) return;
1769 if ( BRep_Tool::CurveOnSurface(edge, face, f, l))
1774 gp_XY p1 = wirePoints[ 0 ].UV(), p2 = wirePoints[ 1 ].UV();
1775 Handle(Geom2d_Line) pcurve = new Geom2d_Line( p1, gp_Dir2d( p2 - p1 ));
1776 BRep_Builder().UpdateEdge( edge, Handle(Geom_Curve)(), Precision::Confusion() );
1777 BRep_Builder().UpdateEdge( edge, pcurve, face, Precision::Confusion() );
1778 BRep_Builder().Range( edge, 0, ( p2 - p1 ).Modulus() );
1779 // cout << "n1 = mesh.AddNode( " << p1.X()*10 << ", " << p1.Y() << ", 0 )" << endl
1780 // << "n2 = mesh.AddNode( " << p2.X()*10 << ", " << p2.Y() << ", 0 )" << endl
1781 // << "mesh.AddEdge( [ n1, n2 ] )" << endl;
1784 //--------------------------------------------------------------------------------
1786 * \brief Replace coincident EDGEs with reversed copies.
1788 //--------------------------------------------------------------------------------
1790 TopoDS_Wire updateSeam( const TopoDS_Wire& wire,
1791 const std::vector<const SMDS_MeshNode*>& nodesOfVertices )
1793 BRepBuilderAPI_MakeWire newWire;
1795 typedef NCollection_DataMap<SMESH_TLink, TopoDS_Edge, SMESH_TLinkHasher > TSeg2EdgeMap;
1796 TSeg2EdgeMap seg2EdgeMap;
1798 TopoDS_Iterator edgeIt( wire );
1799 for ( size_t iSeg = 1; edgeIt.More() && iSeg < nodesOfVertices.size(); edgeIt.Next(), ++iSeg )
1801 SMESH_TLink link( nodesOfVertices[ iSeg-1 ], nodesOfVertices[ iSeg ]);
1802 TopoDS_Edge edge( TopoDS::Edge( edgeIt.Value() ));
1804 TopoDS_Edge* edgeInMap = seg2EdgeMap.Bound( link, edge );
1805 bool isSeam = ( *edgeInMap != edge );
1808 edgeInMap->Reverse();
1811 newWire.Add( edge );
1816 //--------------------------------------------------------------------------------
1818 * \brief Fill in the origMesh with faces computed by MG-CADSurf in this tmp mesh
1820 //--------------------------------------------------------------------------------
1822 void FillInOrigMesh( SMESH_Mesh& origMesh,
1823 const TopoDS_Face& origFace )
1825 SMESH_MesherHelper helper( origMesh );
1826 helper.SetSubShape( origFace );
1827 helper.SetElementsOnShape( true );
1829 SMESH_MesherHelper tmpHelper( *this );
1830 tmpHelper.SetSubShape( _proxyFace );
1832 // iterate over tmp faces and copy them in origMesh
1833 const SMDS_MeshNode* nodes[27];
1834 const SMDS_MeshNode* nullNode = 0;
1836 SMDS_FaceIteratorPtr fIt = GetMeshDS()->facesIterator();
1837 while ( fIt->more() )
1839 const SMDS_MeshElement* f = fIt->next();
1840 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
1842 for ( ; nIt->more(); ++nbN )
1844 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
1845 TN2NMap::iterator n2nIt =
1846 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
1847 if ( !n2nIt->second ) {
1849 gp_XY uv = tmpHelper.GetNodeUV( _proxyFace, n );
1850 n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], /*id=*/0, uv.X(), uv.Y() );
1852 nodes[ nbN ] = n2nIt->second;
1855 case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
1856 // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
1857 // nodes[3], nodes[4], nodes[5]); break;
1858 case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
1859 // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1860 // nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
1861 // case 8: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1862 // nodes[4], nodes[5], nodes[6], nodes[7]); break;
1869 * \brief A structure holding an error description and a verbisity level
1871 struct message_cb_user_data
1873 std::string * _error;
1880 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1881 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1882 real *duu, real *duv, real *dvv, void *user_data);
1883 status_t message_cb(message_t *msg, void *user_data);
1884 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1886 //=============================================================================
1890 //=============================================================================
1892 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
1894 // Fix problem with locales
1895 Kernel_Utils::Localizer aLocalizer;
1897 this->SMESH_Algo::_progress = 1e-3; // prevent progress advancment while computing attractors
1899 bool viscousLayersMade =
1900 ( aShape.ShapeType() == TopAbs_FACE &&
1901 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( aShape ), aMesh ));
1903 if ( !viscousLayersMade )
1904 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1907 if ( _haveViscousLayers || viscousLayersMade )
1909 // Compute viscous layers
1911 TopTools_MapOfShape map;
1912 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1914 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1915 if ( !map.Add( F )) continue;
1916 SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1918 return false; // error in StdMeshers_ViscousLayers2D::Compute()
1920 // Compute MG-CADSurf mesh on viscous layers
1922 if ( viscousMesh->NbProxySubMeshes() > 0 )
1925 const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1926 if ( !compute( tmpMesh, proxyFace, /*allowSubMeshClearing=*/false ))
1928 tmpMesh.FillInOrigMesh( aMesh, F );
1932 // Re-compute MG-CADSurf mesh on the rest faces if the mesh was cleared
1934 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1936 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1937 SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1938 if ( fSM->IsMeshComputed() ) continue;
1940 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1948 //=============================================================================
1952 //=============================================================================
1954 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh& aMesh,
1955 const TopoDS_Shape& aShape,
1956 bool allowSubMeshClearing)
1958 /* create a distene context (generic object) */
1959 status_t status = STATUS_ERROR;
1961 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1962 SMESH_MesherHelper helper( aMesh ), helperWithShape( aMesh );
1963 theHelper = & helperWithShape;
1964 // do not call helper.IsQuadraticSubMesh() because sub-meshes
1965 // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1966 bool haveQuadraticSubMesh = helperWithShape.IsQuadraticSubMesh( aShape );
1967 haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis && _hypothesis->GetQuadraticMesh());
1968 helper.SetIsQuadratic( haveQuadraticSubMesh );
1969 helperWithShape.SetIsQuadratic( haveQuadraticSubMesh );
1971 bool quadraticSubMeshAndViscousLayer = false;
1972 bool needMerge = false;
1973 typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1974 TSubMeshSet edgeSubmeshes;
1975 TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1976 double existingPhySize = 0;
1978 TopTools_IndexedMapOfShape pmap, emap, fmap;
1980 TopTools_IndexedDataMapOfShapeListOfShape e2ffmap;
1981 TopExp::MapShapesAndAncestors( aShape, TopAbs_EDGE, TopAbs_FACE, e2ffmap );
1983 BLSURFPlugin_EnforcedMesh1D enforcedMesh( helperWithShape, _hypothesis );
1985 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1987 feclearexcept( FE_ALL_EXCEPT );
1988 int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1991 context_t *ctx = context_new();
1993 /* Set the message callback in the working context */
1994 message_cb_user_data mcud;
1995 mcud._error = & this->SMESH_Algo::_comment;
1996 mcud._progress = & this->SMESH_Algo::_progress;
1998 _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
1999 context_set_message_callback(ctx, message_cb, &mcud);
2001 /* set the interruption callback */
2002 _compute_canceled = false;
2003 context_set_interrupt_callback(ctx, interrupt_cb, this);
2005 /* create the CAD object we will work on. It is associated to the context ctx. */
2006 cad_t *c = cad_new(ctx);
2007 dcad_t *dcad = dcad_new(c);
2009 // To enable multithreading
2010 cad_set_thread_safety(c, 1);
2012 /* Now fill the CAD object with data from your CAD
2013 * environement. This is the most complex part of a successfull
2019 cadsurf_session_t *css = cadsurf_session_new(ctx);
2021 // an object that correctly deletes all cadsurf objects at destruction
2022 BLSURF_Cleaner cleaner( ctx,css,c,dcad );
2024 SetParameters(_hypothesis, css, aShape);
2026 // To remove as soon as quadratic mesh is allowed - BEGIN
2027 // GDD: Viscous layer is not allowed with quadratic mesh
2028 if (_haveViscousLayers && haveQuadraticSubMesh ) {
2029 quadraticSubMeshAndViscousLayer = true;
2030 _haveViscousLayers = !haveQuadraticSubMesh;
2031 _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
2032 error(COMPERR_WARNING, _comment);
2034 // To remove as soon as quadratic mesh is allowed - END
2036 // needed to prevent the opencascade memory managmement from freeing things
2037 vector<Handle(Geom2d_Curve)> curves;
2038 vector<Handle(Geom_Surface)> surfaces;
2042 FaceId2PythonSmp.clear();
2043 EdgeId2PythonSmp.clear();
2044 VertexId2PythonSmp.clear();
2046 /****************************************************************************************
2048 *****************************************************************************************/
2050 string bad_end = "return";
2052 TopTools_IndexedMapOfShape _map;
2053 TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
2054 int ienf = _map.Extent();
2056 assert(Py_IsInitialized());
2057 PyGILState_STATE gstate;
2059 string theSizeMapStr;
2061 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
2063 TopoDS_Face f = TopoDS::Face(face_iter.Current());
2065 //SMESH_subMesh* fSM = aMesh.GetSubMesh( f );
2066 //if ( !fSM->IsEmpty() ) continue; // skip already meshed FACE with viscous layers
2068 // make INTERNAL face oriented FORWARD (issue 0020993)
2069 if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
2070 f.Orientation(TopAbs_FORWARD);
2072 iface = fmap.Add(f);
2074 surfaces.push_back(BRep_Tool::Surface(f));
2076 /* create an object representing the face for cadsurf */
2077 /* where face_id is an integer identifying the face.
2078 * surf_function is the function that defines the surface
2079 * (For this face, it will be called by cadsurf with your_face_object_ptr
2080 * as last parameter.
2082 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back().get());
2084 /* by default a face has no tag (color).
2085 The following call sets it to the same value as the Geom module ID : */
2086 int faceTag = meshDS->ShapeToIndex(f);
2087 faceTag = BLSURFPlugin_Hypothesis::GetHyperPatchTag( faceTag, _hypothesis );
2088 cad_face_set_tag(fce, faceTag);
2090 /* Set face orientation (optional if you want a well oriented output mesh)*/
2091 if(f.Orientation() != TopAbs_FORWARD)
2092 cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
2094 cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
2096 if (HasSizeMapOnFace /*&& !use_precad*/) //22903: use_precad seems not to interfere
2098 // -----------------
2100 // -----------------
2101 faceKey = FacesWithSizeMap.FindIndex(f);
2104 if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end())
2106 theSizeMapStr = FaceId2SizeMap[faceKey];
2107 // check if function ends with "return"
2108 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2110 // Expr To Python function, verification is performed at validation in GUI
2111 gstate = PyGILState_Ensure();
2112 PyObject * obj = NULL;
2113 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2115 PyObject * func = NULL;
2116 func = PyObject_GetAttrString(main_mod, "f");
2117 FaceId2PythonSmp[iface]=func;
2118 FaceId2SizeMap.erase(faceKey);
2119 PyGILState_Release(gstate);
2122 // Specific size map = Attractor
2123 std::map<int,std::vector<double> >::iterator attractor_iter =
2124 FaceId2AttractorCoords.find( faceKey );
2125 if (attractor_iter != FaceId2AttractorCoords.end() )
2127 double * xyzCoords = & attractor_iter->second[2];
2128 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2129 BRepClass_FaceClassifier scl(f,P,1e-7);
2130 TopAbs_State result = scl.State();
2131 if ( result == TopAbs_OUT )
2132 MESSAGE("Point is out of face: node is not created");
2133 if ( result == TopAbs_UNKNOWN )
2134 MESSAGE("Point position on face is unknown: node is not created");
2135 if ( result == TopAbs_ON )
2136 MESSAGE("Point is on border of face: node is not created");
2137 if ( result == TopAbs_IN )
2139 // Point is inside face and not on border
2140 double * uvCoords = & attractor_iter->second[0];
2142 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2143 cad_point_set_tag(point_p, ienf);
2145 FaceId2AttractorCoords.erase(faceKey);
2148 // -----------------
2150 // -----------------
2151 TId2ClsAttractorVec::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
2152 if (clAttractor_iter != FaceId2ClassAttractor.end()){
2153 std::vector< BLSURFPlugin_Attractor* > & attVec = clAttractor_iter->second;
2154 for ( size_t i = 0; i < attVec.size(); ++i )
2155 if ( !attVec[i]->IsMapBuilt() ) {
2156 std::cout<<"Compute " << theNbAttractors-- << "-th attractor" <<std::endl;
2157 attVec[i]->BuildMap();
2159 FaceIndex2ClassAttractor[iface].swap( attVec );
2160 FaceId2ClassAttractor.erase(clAttractor_iter);
2162 } // if (HasSizeMapOnFace && !use_precad)
2164 // ------------------
2165 // Enforced Vertices
2166 // ------------------
2167 faceKey = FacesWithEnforcedVertices.FindIndex(f);
2168 std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
2169 if (evmIt != FaceId2EnforcedVertexCoords.end())
2171 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl = evmIt->second;
2172 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
2173 for (; evlIt != evl.end(); ++evlIt)
2175 BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords = { evlIt->at(2),
2178 bool isOnEdge = evlIt->at(5);
2181 enforcedMesh.AddVertexOnEdge( xyzCoords.data() );
2184 double uvCoords[2] = { evlIt->at(0), evlIt->at(1) };
2186 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2188 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
2189 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
2190 !enfCoordsIt->second.empty() )
2192 // to merge nodes of an INTERNAL vertex belonging to several faces
2193 TopoDS_Vertex v = (*enfCoordsIt->second.begin() )->vertex;
2194 if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
2195 if ( !v.IsNull() && meshDS->ShapeToIndex( v ) > 0 )
2197 tag = pmap.Add( v );
2198 SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
2199 vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2200 mergeSubmeshes.insert( vSM->GetSubMeshDS() );
2201 // //if ( tag != pmap.Extent() )
2202 // needMerge = true;
2205 if ( tag == 0 ) tag = ienf;
2206 cad_point_set_tag(point_p, tag);
2208 FaceId2EnforcedVertexCoords.erase(faceKey);
2212 /****************************************************************************************
2214 now create the edges associated to this face
2215 *****************************************************************************************/
2217 std::vector< TopoDS_Edge > edges;
2218 for ( TopExp_Explorer edge_iter( f, TopAbs_EDGE ); edge_iter.More(); edge_iter.Next() )
2220 const TopoDS_Edge& e = TopoDS::Edge( edge_iter.Current() );
2221 if ( !enforcedMesh.GetSplitsOfEdge( e, edges, emap ))
2222 edges.push_back( e );
2224 for ( const TopoDS_Edge& e : edges )
2226 int ic = emap.Add(e);
2229 curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
2231 if ( HasSizeMapOnEdge )
2233 int edgeKey = EdgesWithSizeMap.FindIndex(e);
2234 if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end())
2236 theSizeMapStr = EdgeId2SizeMap[edgeKey];
2237 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2239 // Expr To Python function, verification is performed at validation in GUI
2240 gstate = PyGILState_Ensure();
2241 PyObject * obj = NULL;
2242 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2244 PyObject * func = NULL;
2245 func = PyObject_GetAttrString(main_mod, "f");
2246 EdgeId2PythonSmp[ic]=func;
2247 EdgeId2SizeMap.erase(edgeKey);
2248 PyGILState_Release(gstate);
2251 /* data of nodes existing on the edge */
2252 StdMeshers_FaceSidePtr nodeData;
2253 SMESH_subMesh* sm = aMesh.GetSubMesh( e );
2254 if ( !sm->IsEmpty() )
2256 // SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
2257 // /*complexFirst=*/false);
2258 // while ( subsmIt->more() )
2259 // edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
2260 edgeSubmeshes.insert( sm->GetSubMeshDS() );
2262 nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
2263 /*ignoreMedium=*/haveQuadraticSubMesh));
2264 if ( nodeData->MissVertexNode() )
2265 return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
2267 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2268 if ( !nodeDataVec.empty() )
2270 if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
2272 nodeData->Reverse();
2273 nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
2275 // tmin and tmax can change in case of viscous layer on an adjacent edge
2276 tmin = nodeDataVec.front().param;
2277 tmax = nodeDataVec.back().param;
2279 existingPhySize += nodeData->Length() / double( nodeDataVec.size() - 1 );
2283 cout << "---------------- Invalid nodeData" << endl;
2288 /* attach the edge to the current cadsurf face */
2289 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back().get());
2291 /* by default an edge has no tag (color).
2292 The following call sets it to the same value as the edge_id : */
2293 // IMP23368. Do not set tag to an EDGE shared by FACEs of a hyper-patch
2294 bool isInHyperPatch = false;
2295 if ( e2ffmap.Contains( e )) // not there for a part of EDGE divided by enforced segments
2297 std::set< int > faceTags, faceIDs;
2298 TopTools_ListIteratorOfListOfShape fIt( e2ffmap.FindFromKey( e ));
2299 for ( ; fIt.More(); fIt.Next() )
2301 int faceTag = meshDS->ShapeToIndex( fIt.Value() );
2302 if ( !faceIDs.insert( faceTag ).second )
2303 continue; // a face encounters twice for a seam edge
2304 int hpTag = BLSURFPlugin_Hypothesis::GetHyperPatchTag( faceTag, _hypothesis );
2305 if ( !faceTags.insert( hpTag ).second )
2307 isInHyperPatch = true;
2312 if ( !isInHyperPatch )
2313 cad_edge_set_tag(edg, ic);
2315 /* by default, an edge does not necessarily appear in the resulting mesh,
2316 unless the following property is set :
2318 cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2320 /* by default an edge is a boundary edge */
2321 if (e.Orientation() == TopAbs_INTERNAL)
2322 cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2324 // pass existing nodes of sub-meshes to MG-CADSurf
2327 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2328 const int nbNodes = (int) nodeDataVec.size();
2330 dcad_edge_discretization_t *dedge;
2331 dcad_get_edge_discretization(dcad, edg, &dedge);
2332 dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2334 // cout << endl << " EDGE " << ic << endl;
2335 // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2336 for ( int iN = 0; iN < nbNodes; ++iN )
2338 const UVPtStruct& nData = nodeDataVec[ iN ];
2339 double t = nData.param;
2340 real uv[2] = { nData.u, nData.v };
2341 SMESH_TNodeXYZ nXYZ = nData.node;
2342 // cout << "\tt = " << t
2343 // << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2344 // << "\t u = " << nData.param
2345 // << "\t ID = " << nData.node->GetID() << endl;
2346 dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ.ChangeData() );
2348 TopoDS_Shape v = helper.GetSubShapeByNode( nodeDataVec[0].node, meshDS );
2349 if ( !v.IsNull() && v.ShapeType() == TopAbs_VERTEX )
2350 dcad_edge_discretization_set_vertex_tag( dedge, 1, pmap.Add( v ));
2352 v = helper.GetSubShapeByNode( nodeDataVec.back().node, meshDS );
2353 if ( !v.IsNull() && v.ShapeType() == TopAbs_VERTEX )
2354 dcad_edge_discretization_set_vertex_tag( dedge, nbNodes, pmap.Add( v ));
2356 dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2359 /****************************************************************************************
2361 *****************************************************************************************/
2366 gp_Pnt2d uv0 = curves.back()->Value(tmin);
2367 gp_Pnt p0 = surfaces.back()->Value( uv0.X(), uv0.Y() );
2369 for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next())
2371 const TopoDS_Vertex& v = TopoDS::Vertex(ex_edge.Current());
2372 ip[ npts ] = pmap.Add(v);
2373 d [ npts ] = p0.SquareDistance(BRep_Tool::Pnt(v));
2376 if (HasSizeMapOnVertex)
2378 int vertexKey = VerticesWithSizeMap.FindIndex(v);
2379 if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end())
2381 theSizeMapStr = VertexId2SizeMap[vertexKey];
2382 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2384 // Expr To Python function, verification is performed at validation in GUI
2385 gstate = PyGILState_Ensure();
2386 PyObject * obj = NULL;
2387 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2389 PyObject * func = NULL;
2390 func = PyObject_GetAttrString(main_mod, "f");
2391 VertexId2PythonSmp[*ip]=func;
2392 VertexId2SizeMap.erase(vertexKey); // do not erase if using a vector
2393 PyGILState_Release(gstate);
2396 } // loop on vertices
2398 if (npts != 2) { // should not happen
2399 MESSAGE("An edge does not have 2 extremities.");
2404 std::swap( ip[0], ip[1] );
2406 // This defines the curves extremity connectivity
2407 cad_edge_set_extremities (edg, ip[0], ip[1]);
2408 /* set the tag (color) to the same value as the extremity id : */
2409 cad_edge_set_extremities_tag(edg, ip[0], ip[1]);
2413 // ==============================
2414 // Add segments of enforced mesh
2415 // ==============================
2417 if ( enforcedMesh.HasSegmentsOnFace( f ))
2419 BLSURFPlugin_EnforcedMesh1D::Segmemnt seg;
2420 while ( enforcedMesh.NextSegment( seg, pmap ))
2422 curves.push_back( seg._pcurve );
2424 cad_edge_t *edg = cad_edge_new( fce, seg._tag, seg._u[0], seg._u[1],
2425 curv_fun,seg._pcurve.get());
2426 cad_edge_set_tag( edg, seg._tag );
2428 cad_edge_set_property( edg, EDGE_PROPERTY_SOFT_REQUIRED );
2429 cad_edge_set_property( edg, EDGE_PROPERTY_INTERNAL );
2431 cad_edge_set_extremities ( edg, seg._vTag[0], seg._vTag[1]);
2432 cad_edge_set_extremities_tag( edg, seg._vTag[0], seg._vTag[1]);
2434 dcad_edge_discretization_t *dedge;
2435 dcad_get_edge_discretization( dcad, edg, &dedge );
2436 dcad_edge_discretization_set_vertex_count( dedge, 2 );
2438 dcad_edge_discretization_set_vertex_coordinates( dedge, 1,
2440 &seg._uv[0].ChangeCoord(1),
2441 seg._xyz[0].ChangeData() );
2442 dcad_edge_discretization_set_vertex_coordinates( dedge, 2,
2444 &seg._uv[1].ChangeCoord(1),
2445 seg._xyz[1].ChangeData() );
2447 dcad_edge_discretization_set_vertex_tag( dedge, 1, seg._vTag[0] );
2448 dcad_edge_discretization_set_vertex_tag( dedge, 2, seg._vTag[1] );
2450 dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2457 ///////////////////////
2459 ///////////////////////
2461 if (! _preCadFacesIDsPeriodicityVector.empty())
2463 for (std::size_t i=0; i < _preCadFacesIDsPeriodicityVector.size(); i++){
2464 std::vector<int> theFace1_ids = _preCadFacesIDsPeriodicityVector[i].shape1IDs;
2465 std::vector<int> theFace2_ids = _preCadFacesIDsPeriodicityVector[i].shape2IDs;
2466 int* theFace1_ids_c = &theFace1_ids[0];
2467 int* theFace2_ids_c = &theFace2_ids[0];
2468 std::ostringstream o;
2469 o << "_preCadFacesIDsPeriodicityVector[" << i << "] = [";
2470 for (std::size_t j=0; j < theFace1_ids.size(); j++)
2471 o << theFace1_ids[j] << ", ";
2473 for (std::size_t j=0; j < theFace2_ids.size(); j++)
2474 o << theFace2_ids[j] << ", ";
2476 // if ( _hypothesis->GetVerbosity() > _hypothesis->GetDefaultVerbosity() )
2477 // cout << o.str() << endl;
2478 if (_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2480 // If no source points, call periodicity without transformation function
2481 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2482 status = cad_add_face_multiple_periodicity_with_transformation_function
2483 (c, theFace1_ids_c, (meshgems_integer) theFace1_ids.size(), theFace2_ids_c,
2484 (meshgems_integer) theFace2_ids.size(), periodicity_transformation, NULL);
2485 if(status != STATUS_OK)
2486 cout << "cad_add_face_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2490 // get the transformation vertices
2491 double* theSourceVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2492 double* theTargetVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2493 int nbSourceVertices = (int)_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2494 int nbTargetVertices = (int)_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2496 status = cad_add_face_multiple_periodicity_with_transformation_function_by_points
2497 (c, theFace1_ids_c, (meshgems_integer) theFace1_ids.size(), theFace2_ids_c,
2498 (meshgems_integer) theFace2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2499 if(status != STATUS_OK)
2500 cout << "cad_add_face_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2505 if (! _preCadEdgesIDsPeriodicityVector.empty())
2507 for (std::size_t i=0; i < _preCadEdgesIDsPeriodicityVector.size(); i++){
2508 std::vector<int> theEdge1_ids = _preCadEdgesIDsPeriodicityVector[i].shape1IDs;
2509 std::vector<int> theEdge2_ids = _preCadEdgesIDsPeriodicityVector[i].shape2IDs;
2510 // Use the address of the first element of the vector to initialize the array
2511 int* theEdge1_ids_c = &theEdge1_ids[0];
2512 int* theEdge2_ids_c = &theEdge2_ids[0];
2514 std::ostringstream o;
2515 o << "_preCadEdgesIDsPeriodicityVector[" << i << "] = [";
2516 for (std::size_t j=0; j < theEdge1_ids.size(); j++)
2517 o << theEdge1_ids[j] << ", ";
2519 for (std::size_t j=0; j < theEdge2_ids.size(); j++)
2520 o << theEdge2_ids[j] << ", ";
2522 // if ( _hypothesis->GetVerbosity() > _hypothesis->GetDefaultVerbosity() )
2523 // cout << o.str() << endl;
2525 if (_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2527 // If no source points, call periodicity without transformation function
2528 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2529 status = cad_add_edge_multiple_periodicity_with_transformation_function
2530 (c, theEdge1_ids_c, (meshgems_integer) theEdge1_ids.size(), theEdge2_ids_c,
2531 (meshgems_integer) theEdge2_ids.size(), periodicity_transformation, NULL);
2532 if(status != STATUS_OK)
2533 cout << "cad_add_edge_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2537 // get the transformation vertices
2538 double* theSourceVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2539 double* theTargetVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2540 int nbSourceVertices = (int) _preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2541 int nbTargetVertices = (int) _preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2543 status = cad_add_edge_multiple_periodicity_with_transformation_function_by_points
2544 (c, theEdge1_ids_c, (meshgems_integer) theEdge1_ids.size(), theEdge2_ids_c,
2545 (meshgems_integer) theEdge2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2546 if(status != STATUS_OK)
2547 cout << "cad_add_edge_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2552 if ( !_hypothesis && !edgeSubmeshes.empty() && existingPhySize != 0 )
2554 // prevent failure due to the default PhySize incompatible with size of existing 1D mesh
2555 // and with face size
2556 // double minFaceSize = existingPhySize / edgeSubmeshes.size();
2557 // for ( int iF = 1; iF <= fmap.Extent(); ++iF )
2560 // BRepBndLib::Add( fmap( iF ), box );
2561 // gp_XYZ delta = box.CornerMax().XYZ() - box.CornerMin().XYZ();
2562 // std::sort( delta.ChangeData(), delta.ChangeData() + 3 );
2563 // minFaceSize = Min( minFaceSize, delta.Coord(2) );
2565 // set_param(css, "global_physical_size", val_to_string( minFaceSize * 0.5 ).c_str());
2566 // set_param(css, "max_size", val_to_string( minFaceSize * 5 ).c_str());
2568 std::string errorTxt;
2569 if ( !SMESHUtils_MGLicenseKeyGen::SignCAD( c, errorTxt ))
2570 return error( "Problem with library SalomeMeshGemsKeyGenerator: " + errorTxt );
2572 // Use the original dcad
2573 cadsurf_set_dcad(css, dcad);
2575 // Use the original cad
2576 cadsurf_set_cad(css, c);
2578 std::cout << std::endl;
2579 std::cout << "Beginning of Surface Mesh generation" << std::endl;
2580 std::cout << std::endl;
2585 status = cadsurf_compute_mesh(css);
2588 catch ( std::exception& exc ) {
2589 _comment += exc.what();
2591 catch (Standard_Failure& ex) {
2592 _comment += ex.DynamicType()->Name();
2593 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2595 _comment += ex.GetMessageString();
2599 if ( _comment.empty() )
2600 _comment = "Exception in cadsurf_compute_mesh()";
2603 std::cout << std::endl;
2604 std::cout << "End of Surface Mesh generation" << std::endl;
2605 std::cout << std::endl;
2608 cadsurf_get_mesh(css, &msh);
2609 if ( !msh || STATUS_IS_ERROR( status ))
2611 /* release the mesh object */
2612 cadsurf_regain_mesh(css, msh);
2613 return error(_comment);
2616 // Clear mesh from already meshed edges if possible else
2617 // remember that merge is needed
2618 TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2619 for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2621 SMESHDS_SubMesh* smDS = *smIt;
2622 if ( !smDS ) continue;
2623 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2626 const SMDS_MeshNode* n = nIt->next();
2627 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2629 needMerge = true; // to correctly sew with viscous mesh
2630 // add existing medium nodes to helper
2631 if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2633 SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2634 while ( edgeIt->more() )
2635 helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2640 if ( allowSubMeshClearing )
2642 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2643 while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), 0 );
2644 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2645 while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), 0 );
2654 std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2656 GMFFileName = _hypothesis->GetGMFFile();
2657 if (GMFFileName != "")
2659 bool asciiFound = (GMFFileName.find(".mesh", GMFFileName.length()-5) != std::string::npos);
2660 bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2661 if (!asciiFound && !binaryFound)
2662 GMFFileName.append(".mesh");
2663 mesh_write_mesh(msh, GMFFileName.c_str());
2666 /* retrieve mesh data (see meshgems/mesh.h) */
2667 integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2671 mesh_get_vertex_count (msh, &nv);
2672 mesh_get_edge_count (msh, &ne);
2673 mesh_get_triangle_count (msh, &nt);
2674 mesh_get_quadrangle_count(msh, &nq);
2676 using deleted_unique_ptr = std::unique_ptr<integer,std::function<void(integer*)>>;
2678 deleted_unique_ptr evedg_var((integer *)mesh_calloc_generic_buffer(msh), [](integer *ptr) { free(ptr); });
2679 deleted_unique_ptr evtri_var((integer *)mesh_calloc_generic_buffer(msh), [](integer *ptr) { free(ptr); });
2680 deleted_unique_ptr evquad_var((integer *)mesh_calloc_generic_buffer(msh), [](integer *ptr) { free(ptr); });
2681 deleted_unique_ptr tags_buff_var((integer*)mesh_calloc_generic_buffer(msh), [](integer *ptr) { free(ptr); });
2683 integer *evedg(evedg_var.get()),*evtri(evtri_var.get()),*evquad(evquad_var.get()),*tags_buff(tags_buff_var.get());
2685 std::vector<const SMDS_MeshNode*> nodes(nv+1);
2686 std::vector<bool> tags(nv+1);
2688 BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2690 /* enumerated vertices */
2691 for ( int iv = 1; iv <= nv; iv++ )
2693 mesh_get_vertex_coordinates(msh, iv, xyz);
2694 mesh_get_vertex_tag(msh, iv, &tag);
2695 // Issue 0020656. Use vertex coordinates
2697 bool isEnforcedNode = false;
2700 if ( tag <= pmap.Extent() )
2702 TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2703 double tol = BRep_Tool::Tolerance( v );
2704 gp_Pnt p = BRep_Tool::Pnt( v );
2705 if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 1e3*tol))
2706 xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2708 tag = 0; // enforced or attracted vertex
2709 nodes[iv] = SMESH_Algo::VertexNode( v, meshDS );
2712 isEnforcedNode = ( nodes[iv] = enforcedMesh.GetNodeByTag( tag, pmap ));
2715 nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2717 // Create group of enforced vertices if requested
2718 projVertex.assign( xyz, xyz + 3 );
2719 auto enfCoordsIt = EnfVertexCoords2EnfVertexList.find( projVertex );
2720 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end())
2722 for ( BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex : enfCoordsIt->second )
2723 if (currentEnfVertex->grpName != "")
2725 SMDS_MeshGroup* groupDS = nullptr;
2726 for ( SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups(); grIt->more() && !groupDS; )
2728 SMESH_Group * group = grIt->next();
2729 SMESHDS_Group * grp = dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() );
2731 grp->GetType() == SMDSAbs_Node &&
2732 currentEnfVertex->grpName == group->GetName() )
2733 groupDS = &grp->SMDSGroup();
2737 SMESH_Group * group = aMesh.AddGroup( SMDSAbs_Node, currentEnfVertex->grpName.c_str() );
2738 SMESHDS_Group * grp = static_cast< SMESHDS_Group* >( group->GetGroupDS() );
2739 groupDS = &grp->SMDSGroup();
2741 groupDS->Add( nodes[iv] );
2744 if ( isEnforcedNode )
2747 // internal points are tagged to zero
2748 if ( tag > 0 && tag <= pmap.Extent() )
2750 meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2759 /* enumerate edges */
2760 for ( int it = 1; it <= ne; it++ )
2763 mesh_get_edge_vertices(msh, it, vtx);
2764 mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2765 mesh_get_edge_tag(msh, it, &tag);
2767 // If PreCAD performed some cleaning operations (remove tiny edges,
2768 // merge edges ...) an output tag can indeed represent several original tags.
2769 // Get the initial tags corresponding to the output tag and redefine the tag as
2770 // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2771 mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2773 tag = tags_buff[ nb_tag-1 ];
2774 if ( tag < 1 || tag > emap.Extent() )
2776 if ( !enforcedMesh.IsSegmentTag( tag )) // it's a false INTERNAL EDGE of enforced mesh
2778 std::cerr << "MG-CADSurf BUG:::: Edge tag " << tag
2779 << " does not point to a CAD edge (nb edges " << emap.Extent() << ")"
2784 if ( meshDS->ShapeToIndex( emap( tag )) == 0 )
2785 tag = enforcedMesh.GetTagOfSplitEdge( tag );
2788 Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2789 tags[vtx[0]] = false;
2792 Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2793 tags[vtx[1]] = false;
2795 if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2797 if (tags[evedg[0]]) {
2798 Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2799 tags[evedg[0]] = false;
2801 edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2804 edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2806 meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2809 std::vector<meshgems_real> uvEntries(4*2);
2810 meshgems_integer uid;
2812 /* enumerate triangles */
2813 for(int it=1;it<=nt;it++) {
2815 meshgems_integer computedMap;
2816 mesh_get_triangle_vertices(msh, it, vtx);
2817 mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2818 mesh_get_triangle_tag(msh, it, &tag);
2819 meshgems_cadsurf_get_triangle_location_on_face( css, it, &computedMap, &uid, &uvEntries[0], &uvEntries[2], &uvEntries[4] );
2823 meshDS->SetNodeOnFace(nodes[vtx[0]], tag, uvEntries[0], uvEntries[1] );
2825 meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2826 tags[vtx[0]] = false;
2830 meshDS->SetNodeOnFace(nodes[vtx[1]], tag, uvEntries[2], uvEntries[3] );
2832 meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2833 tags[vtx[1]] = false;
2837 meshDS->SetNodeOnFace(nodes[vtx[2]], tag, uvEntries[4], uvEntries[5] );
2839 meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2841 tags[vtx[2]] = false;
2843 if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2844 // QUADRATIC TRIANGLE
2845 if (tags[evtri[0]]) {
2846 meshDS->SetNodeOnFace(nodes[evtri[0]], tag);
2847 tags[evtri[0]] = false;
2849 if (tags[evtri[1]]) {
2850 meshDS->SetNodeOnFace(nodes[evtri[1]], tag);
2851 tags[evtri[1]] = false;
2853 if (tags[evtri[2]]) {
2854 meshDS->SetNodeOnFace(nodes[evtri[2]], tag);
2855 tags[evtri[2]] = false;
2857 tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2858 nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2861 if ( helper.GetIsQuadratic() )
2862 helper.SetSubShape( tag );
2863 tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2865 meshDS->SetMeshElementOnShape(tri, tag);
2868 /* enumerate quadrangles */
2869 for(int it=1;it<=nq;it++) {
2870 SMDS_MeshFace* quad;
2871 meshgems_integer computedMap;
2872 mesh_get_quadrangle_vertices(msh, it, vtx);
2873 mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2874 mesh_get_quadrangle_tag(msh, it, &tag);
2875 meshgems_cadsurf_get_quadrilateral_location_on_face( css, it, &computedMap, &uid, &uvEntries[0], &uvEntries[2], &uvEntries[4], &uvEntries[6] );
2879 meshDS->SetNodeOnFace(nodes[vtx[0]], tag, uvEntries[0], uvEntries[1]);
2881 meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2882 tags[vtx[0]] = false;
2886 meshDS->SetNodeOnFace(nodes[vtx[1]], tag, uvEntries[2], uvEntries[3]);
2888 meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2889 tags[vtx[1]] = false;
2893 meshDS->SetNodeOnFace(nodes[vtx[2]], tag, uvEntries[4], uvEntries[5]);
2895 meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2896 tags[vtx[2]] = false;
2900 meshDS->SetNodeOnFace(nodes[vtx[3]], tag, uvEntries[6], uvEntries[7]);
2902 meshDS->SetNodeOnFace(nodes[vtx[3]], tag);
2903 tags[vtx[3]] = false;
2905 if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
2906 // QUADRATIC QUADRANGLE
2907 if (tags[evquad[0]]) {
2908 meshDS->SetNodeOnFace(nodes[evquad[0]], tag);
2909 tags[evquad[0]] = false;
2911 if (tags[evquad[1]]) {
2912 meshDS->SetNodeOnFace(nodes[evquad[1]], tag);
2913 tags[evquad[1]] = false;
2915 if (tags[evquad[2]]) {
2916 meshDS->SetNodeOnFace(nodes[evquad[2]], tag);
2917 tags[evquad[2]] = false;
2919 if (tags[evquad[3]]) {
2920 meshDS->SetNodeOnFace(nodes[evquad[3]], tag);
2921 tags[evquad[3]] = false;
2923 if (tags[evquad[4]]) {
2924 meshDS->SetNodeOnFace(nodes[evquad[4]], tag);
2925 tags[evquad[4]] = false;
2927 quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
2928 nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
2932 quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
2934 meshDS->SetMeshElementOnShape(quad, tag);
2937 /* release the mesh object, the rest is released by cleaner */
2938 cadsurf_regain_mesh(css, msh);
2941 // Remove free nodes that can appear e.g. if "remove tiny edges"(IPAL53235)
2942 for(int iv=1;iv<=nv;iv++)
2943 if ( nodes[iv] && nodes[iv]->NbInverseElements() == 0 )
2944 meshDS->RemoveFreeNode( nodes[iv], 0, /*fromGroups=*/false );
2947 if ( needMerge ) // sew mesh computed by MG-CADSurf with pre-existing mesh
2949 SMESH_MeshEditor editor( &aMesh );
2950 SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
2951 TIDSortedElemSet segementsOnEdge;
2952 TSubMeshSet::iterator smIt;
2953 SMESHDS_SubMesh* smDS;
2955 // merge nodes on EDGE's with ones computed by MG-CADSurf
2956 for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
2958 if (! (smDS = *smIt) ) continue;
2959 getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
2961 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2962 while ( segIt->more() )
2963 segementsOnEdge.insert( segIt->next() );
2966 editor.MergeNodes( nodeGroupsToMerge );
2969 SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
2970 editor.FindEqualElements( segementsOnEdge, equalSegments );
2971 editor.MergeElements( equalSegments );
2973 // remove excess segments created on the boundary of viscous layers
2974 const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
2975 for ( int i = 1; i <= emap.Extent(); ++i )
2977 if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
2979 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2980 while ( segIt->more() )
2982 const SMDS_MeshElement* seg = segIt->next();
2983 if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
2984 seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
2985 meshDS->RemoveFreeElement( seg, smDS );
2992 // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
2993 for (int i = 1; i <= emap.Extent(); i++)
2994 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
2995 sm->SetIsAlwaysComputed( true );
2996 for (int i = 1; i <= pmap.Extent(); i++)
2997 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
2998 if ( !sm->IsMeshComputed() )
2999 sm->SetIsAlwaysComputed( true );
3001 // Set error to FACE's w/o elements
3002 SMESH_ComputeErrorName err = COMPERR_ALGO_FAILED;
3003 if ( _comment.empty() && status == STATUS_OK )
3005 err = COMPERR_WARNING;
3006 _comment = "No mesh elements assigned to a face";
3008 bool badFaceFound = false;
3009 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
3011 TopoDS_Face f = TopoDS::Face(face_iter.Current());
3012 SMESH_subMesh* sm = aMesh.GetSubMesh( f );
3013 if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
3015 int faceTag = sm->GetId();
3016 if ( faceTag != BLSURFPlugin_Hypothesis::GetHyperPatchTag( faceTag, _hypothesis ))
3018 // triangles are assigned to the first face of hyper-patch
3019 sm->SetIsAlwaysComputed( true );
3023 sm->GetComputeError().reset( new SMESH_ComputeError( err, _comment, this ));
3024 badFaceFound = true;
3028 if ( err == COMPERR_WARNING )
3032 if ( status != STATUS_OK && !badFaceFound ) {
3036 // Set event listeners
3038 for ( int iF = 1; iF <= fmap.Size(); ++iF )
3040 const TopoDS_Shape& face = fmap( iF );
3041 SetEventListener( aMesh.GetSubMesh( face ));
3044 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
3046 if ( oldFEFlags > 0 )
3047 feenableexcept( oldFEFlags );
3048 feclearexcept( FE_ALL_EXCEPT );
3052 std::cout << "FacesWithSizeMap" << std::endl;
3053 FacesWithSizeMap.Statistics(std::cout);
3054 std::cout << "EdgesWithSizeMap" << std::endl;
3055 EdgesWithSizeMap.Statistics(std::cout);
3056 std::cout << "VerticesWithSizeMap" << std::endl;
3057 VerticesWithSizeMap.Statistics(std::cout);
3058 std::cout << "FacesWithEnforcedVertices" << std::endl;
3059 FacesWithEnforcedVertices.Statistics(std::cout);
3062 return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
3065 //================================================================================
3067 * \brief Compute a mesh basing on discrete CAD description
3069 //================================================================================
3071 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
3073 if ( aMesh.NbFaces() == 0 )
3074 return error( COMPERR_BAD_INPUT_MESH, "2D elements are missing" );
3076 context_t *ctx = context_new();
3077 if (!ctx) return error("Pb in context_new()");
3079 if ( aMesh.NbNodes() > std::numeric_limits< meshgems_integer >::max() ||
3080 aMesh.NbFaces() > std::numeric_limits< meshgems_integer >::max() )
3081 return error("Too large input mesh");
3083 BLSURF_Cleaner cleaner( ctx );
3085 message_cb_user_data mcud;
3086 mcud._error = & this->SMESH_Algo::_comment;
3087 mcud._progress = & this->SMESH_Algo::_progress;
3089 _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
3090 meshgems_status_t ret = context_set_message_callback(ctx, message_cb, &mcud);
3091 if (ret != STATUS_OK) return error("Pb. in context_set_message_callback() ");
3093 cadsurf_session_t * css = cadsurf_session_new(ctx);
3094 if(!css) return error( "Pb. in cadsurf_session_new() " );
3098 // Fill an input mesh
3100 mesh_t * msh = meshgems_mesh_new_in_memory( ctx );
3101 if ( !msh ) return error("Pb. in meshgems_mesh_new_in_memory()");
3103 // mark nodes used by 2D elements
3104 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
3105 SMDS_NodeIteratorPtr nodeIt = meshDS->nodesIterator();
3106 while ( nodeIt->more() )
3108 const SMDS_MeshNode* n = nodeIt->next();
3109 n->setIsMarked( n->NbInverseElements( SMDSAbs_Face ));
3111 meshgems_mesh_set_vertex_count( msh, (meshgems_integer) meshDS->NbNodes() );
3113 // set node coordinates
3114 if ( meshDS->NbNodes() != meshDS->MaxNodeID() )
3116 meshDS->CompactMesh();
3119 nodeIt = meshDS->nodesIterator();
3121 for ( i = 1; nodeIt->more(); ++i )
3123 nXYZ.Set( nodeIt->next() );
3124 meshgems_mesh_set_vertex_coordinates( msh, i, nXYZ.ChangeData() );
3127 // set nodes of faces
3128 meshgems_mesh_set_triangle_count ( msh, (meshgems_integer) meshDS->GetMeshInfo().NbTriangles() );
3129 meshgems_mesh_set_quadrangle_count( msh, (meshgems_integer) meshDS->GetMeshInfo().NbQuadrangles() );
3130 meshgems_integer nodeIDs[4];
3131 meshgems_integer iT = 1, iQ = 1;
3132 SMDS_FaceIteratorPtr faceIt = meshDS->facesIterator();
3133 while ( faceIt->more() )
3135 const SMDS_MeshElement* face = faceIt->next();
3136 meshgems_integer nbNodes = face->NbCornerNodes();
3137 if ( nbNodes > 4 || face->IsPoly() ) continue;
3139 for ( i = 0; i < nbNodes; ++i )
3140 nodeIDs[i] = (meshgems_integer) face->GetNode( i )->GetID();
3142 meshgems_mesh_set_triangle_vertices ( msh, iT++, nodeIDs );
3144 meshgems_mesh_set_quadrangle_vertices( msh, iQ++, nodeIDs );
3147 std::string errorTxt;
3149 if ( !SMESHUtils_MGLicenseKeyGen::SignMesh( msh, "cadsurf", errorTxt ))
3150 return error( "Problem with library SalomeMeshGemsKeyGenerator: " + errorTxt );
3152 ret = cadsurf_set_mesh(css, msh);
3153 if ( ret != STATUS_OK ) return error("Pb in cadsurf_set_mesh()");
3158 SetParameters(_hypothesis, css, aMesh.GetShapeToMesh() );
3160 ret = cadsurf_compute_mesh(css);
3161 if ( ret != STATUS_OK ) return false;
3164 cadsurf_get_mesh(css, &omsh);
3165 if ( !omsh ) return error( "Pb. in cadsurf_get_mesh()" );
3168 // Update SALOME mesh
3170 // remove quadrangles and triangles
3171 for ( faceIt = meshDS->facesIterator(); faceIt->more(); )
3173 const SMDS_MeshElement* face = faceIt->next();
3174 if ( !face->IsPoly() )
3175 meshDS->RemoveFreeElement( face, /*sm=*/0, /*fromGroups=*/true );
3177 // remove edges that bound the just removed faces
3178 for ( SMDS_EdgeIteratorPtr edgeIt = meshDS->edgesIterator(); edgeIt->more(); )
3180 const SMDS_MeshElement* edge = edgeIt->next();
3181 const SMDS_MeshNode* n0 = edge->GetNode(0);
3182 const SMDS_MeshNode* n1 = edge->GetNode(1);
3183 if ( n0->isMarked() &&
3185 n0->NbInverseElements( SMDSAbs_Volume ) == 0 &&
3186 n1->NbInverseElements( SMDSAbs_Volume ) == 0 )
3187 meshDS->RemoveFreeElement( edge, /*sm=*/0, /*fromGroups=*/true );
3189 // remove nodes that just became free
3190 for ( nodeIt = meshDS->nodesIterator(); nodeIt->more(); )
3192 const SMDS_MeshNode* n = nodeIt->next();
3193 if ( n->isMarked() && n->NbInverseElements() == 0 )
3194 meshDS->RemoveFreeNode( n, /*sm=*/0, /*fromGroups=*/true );
3198 meshgems_integer nbvtx = 0, nodeID;
3199 meshgems_mesh_get_vertex_count( omsh, &nbvtx );
3200 meshgems_real xyz[3];
3201 for ( i = 1; i <= nbvtx; ++i )
3203 meshgems_mesh_get_vertex_coordinates( omsh, i, xyz );
3204 SMDS_MeshNode* n = meshDS->AddNode( xyz[0], xyz[1], xyz[2] );
3205 nodeID = (meshgems_integer) n->GetID();
3206 meshgems_mesh_set_vertex_tag( omsh, i, &nodeID ); // save mapping of IDs in MG and SALOME meshes
3210 meshgems_integer nbtri = 0;
3211 meshgems_mesh_get_triangle_count( omsh, &nbtri );
3212 const SMDS_MeshNode* nodes[4];
3213 for ( i = 1; i <= nbtri; ++i )
3215 meshgems_mesh_get_triangle_vertices( omsh, i, nodeIDs );
3216 for ( int j = 0; j < 3; ++j )
3218 meshgems_mesh_get_vertex_tag( omsh, nodeIDs[j], &nodeID );
3219 nodes[j] = meshDS->FindNode( nodeID );
3221 meshDS->AddFace( nodes[0], nodes[1], nodes[2] );
3225 meshgems_integer nbquad = 0;
3226 meshgems_mesh_get_quadrangle_count( omsh, &nbquad );
3227 for ( i = 1; i <= nbquad; ++i )
3229 meshgems_mesh_get_quadrangle_vertices( omsh, i, nodeIDs );
3230 for ( int j = 0; j < 4; ++j )
3232 meshgems_mesh_get_vertex_tag( omsh, nodeIDs[j], &nodeID );
3233 nodes[j] = meshDS->FindNode( nodeID );
3235 meshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
3240 std::string GMFFileName = _hypothesis->GetGMFFile();
3241 if ( !GMFFileName.empty() )
3243 bool asciiFound = (GMFFileName.find(".mesh", GMFFileName.size()-5) != std::string::npos);
3244 bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.size()-6) != std::string::npos);
3245 if ( !asciiFound && !binaryFound )
3246 GMFFileName.append(".mesh");
3247 mesh_write_mesh(msh, GMFFileName.c_str());
3251 cadsurf_regain_mesh(css, omsh);
3253 // as we don't assign the new triangles to a shape (the pseudo-shape),
3254 // we mark the shape as always computed to avoid the error messages
3255 // that no elements assigned to the shape
3256 aMesh.GetSubMesh( aHelper->GetSubShape() )->SetIsAlwaysComputed( true );
3261 //================================================================================
3263 * \brief Terminates computation
3265 //================================================================================
3267 void BLSURFPlugin_BLSURF::CancelCompute()
3269 _compute_canceled = true;
3272 //=============================================================================
3276 //=============================================================================
3278 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS,
3279 const SMDS_MeshNode* node,
3280 const TopoDS_Shape& ed)
3282 const TopoDS_Edge edge = TopoDS::Edge(ed);
3284 gp_Pnt pnt(node->X(), node->Y(), node->Z());
3286 Standard_Real p0 = 0.0;
3287 Standard_Real p1 = 1.0;
3288 TopLoc_Location loc;
3289 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
3290 if ( curve.IsNull() )
3292 // issue 22499. Node at a sphere apex
3293 meshDS->SetNodeOnEdge(node, edge, p0);
3297 if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
3298 GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
3301 if ( proj.NbPoints() > 0 )
3303 pa = (double)proj.LowerDistanceParameter();
3304 // Issue 0020656. Move node if it is too far from edge
3305 gp_Pnt curve_pnt = curve->Value( pa );
3306 double dist2 = pnt.SquareDistance( curve_pnt );
3307 double tol = BRep_Tool::Tolerance( edge );
3308 if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
3310 curve_pnt.Transform( loc );
3311 meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
3315 meshDS->SetNodeOnEdge(node, edge, pa);
3318 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
3320 * NOTE : if when your CAD systems evaluates second
3321 * order derivatives it also computes first order derivatives and
3322 * function evaluation, you can optimize this example by making only
3323 * one CAD call and filling the necessary uv, dt, dtt arrays.
3325 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
3327 /* t is given. It contains the 1D parametric coordintaes
3328 of the point MG-CADSurf is querying on the curve */
3330 /* user_data identifies the edge MG-CADSurf is querying */
3331 const Geom2d_Curve* pargeo = (const Geom2d_Curve*) user_data;
3334 /* MG-CADSurf is querying the function evaluation */
3335 gp_Pnt2d P = pargeo->Value(t);
3336 uv[0]=P.X(); uv[1]=P.Y();
3340 /* query for the first order derivatives */
3341 gp_Vec2d V1 = pargeo->DN(t,1);
3342 dt[0]=V1.X(); dt[1]=V1.Y();
3346 /* query for the second order derivatives */
3347 gp_Vec2d V2 = pargeo->DN(t,2);
3348 dtt[0]=V2.X(); dtt[1]=V2.Y();
3354 /* Surface definition function.
3355 * See cad_surf_t in file meshgems/cad.h for more information.
3356 * NOTE : if when your CAD systems evaluates second order derivatives it also
3357 * computes first order derivatives and function evaluation, you can optimize
3358 * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
3361 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
3362 real *duu, real *duv, real *dvv, void *user_data)
3364 /* uv[2] is given. It contains the u,v coordinates of the point
3365 * PreCAD/MG-CADSurf is querying on the surface */
3367 /* user_data identifies the face PreCAD/MG-CADSurf is querying (see
3368 * cad_face_new later in this example)*/
3369 const Geom_Surface* geometry = (const Geom_Surface*) user_data;
3373 P=geometry->Value(uv[0],uv[1]); // S.D0(U,V,P);
3374 xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
3381 geometry->D1(uv[0],uv[1],P,D1U,D1V);
3382 du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
3383 dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
3386 if(duu && duv && dvv){
3390 gp_Vec D2U,D2V,D2UV;
3392 geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
3393 duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
3394 duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
3395 dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
3402 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
3404 TId2ClsAttractorVec::iterator f2attVec;
3405 if (FaceId2PythonSmp.count(face_id) != 0) {
3406 assert(Py_IsInitialized());
3407 PyGILState_STATE gstate;
3408 gstate = PyGILState_Ensure();
3409 PyObject* pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
3411 if ( pyresult != NULL) {
3412 result = PyFloat_AsDouble(pyresult);
3413 Py_DECREF(pyresult);
3418 string err_description="";
3419 PyObject* new_stderr = newPyStdOut(err_description);
3420 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3421 Py_INCREF(old_stderr);
3422 PySys_SetObject((char*)"stderr", new_stderr);
3424 PySys_SetObject((char*)"stderr", old_stderr);
3425 Py_DECREF(new_stderr);
3426 MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
3427 result = *((real*)user_data);
3430 PyGILState_Release(gstate);
3432 else if (( f2attVec = FaceIndex2ClassAttractor.find(face_id)) != FaceIndex2ClassAttractor.end() && !f2attVec->second.empty())
3436 std::vector< BLSURFPlugin_Attractor* > & attVec = f2attVec->second;
3437 for ( size_t i = 0; i < attVec.size(); ++i )
3439 //result += attVec[i]->GetSize(uv[0],uv[1]);
3440 result = Min( result, attVec[i]->GetSize(uv[0],uv[1]));
3442 //*size = result / attVec.size(); // mean of sizes defined by all attractors
3446 *size = *((real*)user_data);
3448 // std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
3452 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
3454 if (EdgeId2PythonSmp.count(edge_id) != 0){
3455 assert(Py_IsInitialized());
3456 PyGILState_STATE gstate;
3457 gstate = PyGILState_Ensure();
3458 PyObject* pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
3460 if ( pyresult != NULL) {
3461 result = PyFloat_AsDouble(pyresult);
3462 Py_DECREF(pyresult);
3467 string err_description="";
3468 PyObject* new_stderr = newPyStdOut(err_description);
3469 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3470 Py_INCREF(old_stderr);
3471 PySys_SetObject((char*)"stderr", new_stderr);
3473 PySys_SetObject((char*)"stderr", old_stderr);
3474 Py_DECREF(new_stderr);
3475 MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
3476 result = *((real*)user_data);
3479 PyGILState_Release(gstate);
3482 *size = *((real*)user_data);
3487 status_t size_on_vertex(integer point_id, real *size, void *user_data)
3489 if (VertexId2PythonSmp.count(point_id) != 0){
3490 assert(Py_IsInitialized());
3491 PyGILState_STATE gstate;
3492 gstate = PyGILState_Ensure();
3493 PyObject* pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
3495 if ( pyresult != NULL) {
3496 result = PyFloat_AsDouble(pyresult);
3497 Py_DECREF(pyresult);
3502 string err_description="";
3503 PyObject* new_stderr = newPyStdOut(err_description);
3504 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3505 Py_INCREF(old_stderr);
3506 PySys_SetObject((char*)"stderr", new_stderr);
3508 PySys_SetObject((char*)"stderr", old_stderr);
3509 Py_DECREF(new_stderr);
3510 MESSAGE("Can't evaluate f()" << " error is " << err_description);
3511 result = *((real*)user_data);
3514 PyGILState_Release(gstate);
3517 *size = *((real*)user_data);
3523 * The following function will be called for PreCAD/MG-CADSurf message
3524 * printing. See context_set_message_callback (later in this
3525 * template) for how to set user_data.
3527 status_t message_cb(message_t *msg, void *user_data)
3529 integer errnumber = 0;
3531 message_get_number(msg, &errnumber);
3532 message_get_description(msg, &desc);
3534 message_cb_user_data * mcud = (message_cb_user_data*)user_data;
3535 // Get all the error message and some warning messages related to license and periodicity
3536 if ( errnumber < 0 ||
3537 err.find("license" ) != string::npos ||
3538 err.find("periodicity") != string::npos )
3540 // remove ^A from the tail
3541 size_t len = strlen( desc );
3542 while (len > 0 && desc[len-1] != '\n')
3544 mcud->_error->append( desc, len );
3547 if ( errnumber == 3009001 )
3548 * mcud->_progress = atof( desc + 11 ) / 100.;
3549 if ( mcud->_verbosity > 0 )
3550 std::cout << desc << std::endl;
3555 /* This is the interrupt callback. PreCAD/MG-CADSurf will call this
3556 * function regularily. See the file meshgems/interrupt.h
3558 status_t interrupt_cb(integer *interrupt_status, void *user_data)
3560 integer you_want_to_continue = 1;
3561 BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
3562 you_want_to_continue = !tmp->computeCanceled();
3564 if(you_want_to_continue)
3566 *interrupt_status = INTERRUPT_CONTINUE;
3569 else /* you want to stop MG-CADSurf */
3571 *interrupt_status = INTERRUPT_STOP;
3576 //=============================================================================
3580 //=============================================================================
3581 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
3582 const TopoDS_Shape& aShape,
3583 MapShapeNbElems& aResMap)
3585 double diagonal = aMesh.GetShapeDiagonalSize();
3586 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
3587 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
3588 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
3589 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
3590 //int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
3591 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
3592 BLSURFPlugin_Hypothesis::ElementType _elementType = BLSURFPlugin_Hypothesis::GetDefaultElementType();
3594 _physicalMesh = (int) _hypothesis->GetPhysicalMesh();
3595 _phySizeRel = _hypothesis->IsPhySizeRel();
3596 if ( _hypothesis->GetPhySize() > 0)
3597 _phySize = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
3598 //_geometricMesh = (int) hyp->GetGeometricMesh();
3599 if (_hypothesis->GetAngleMesh() > 0)
3600 _angleMesh = _hypothesis->GetAngleMesh();
3601 _elementType = _hypothesis->GetElementType();
3603 //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
3604 // GetDefaultPhySize() sometimes leads to computation failure
3605 _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
3608 bool IsQuadratic = _quadraticMesh;
3613 TopTools_DataMapOfShapeInteger EdgesMap;
3614 double fullLen = 0.0;
3615 double fullNbSeg = 0;
3616 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
3617 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3618 if( EdgesMap.IsBound(E) )
3620 SMESH_subMesh *sm = aMesh.GetSubMesh(E);
3621 double aLen = SMESH_Algo::EdgeLength(E);
3624 if(_physicalMesh==1) {
3625 nb1d = (int)( aLen/_phySize + 1 );
3630 Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
3631 double fullAng = 0.0;
3632 double dp = (l-f)/200;
3637 for(int j=2; j<=200; j++) {
3640 fullAng += fabs(V1.Angle(V2));
3644 nb1d = (int)( fullAng/_angleMesh + 1 );
3647 std::vector<smIdType> aVec(SMDSEntity_Last);
3648 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3649 if( IsQuadratic > 0 ) {
3650 aVec[SMDSEntity_Node] = 2*nb1d - 1;
3651 aVec[SMDSEntity_Quad_Edge] = nb1d;
3654 aVec[SMDSEntity_Node] = nb1d - 1;
3655 aVec[SMDSEntity_Edge] = nb1d;
3657 aResMap.insert(std::make_pair(sm,aVec));
3658 EdgesMap.Bind(E,nb1d);
3660 double ELen = fullLen/fullNbSeg;
3664 // try to evaluate as in MEFISTO
3665 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
3666 TopoDS_Face F = TopoDS::Face( exp.Current() );
3667 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
3669 BRepGProp::SurfaceProperties(F,G);
3670 double anArea = G.Mass();
3672 std::vector<int> nb1dVec;
3673 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
3674 int nbSeg = EdgesMap.Find(exp1.Current());
3676 nb1dVec.push_back( nbSeg );
3679 int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
3680 int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
3681 if ( _elementType != BLSURFPlugin_Hypothesis::Quadrangles )
3683 if ( nb1dVec.size() == 4 ) // quadrangle geom face
3685 int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
3687 nbNodes = (n1 + 1) * (n2 + 1);
3692 nbTria = nbQuad = nbTria / 3 + 1;
3695 std::vector<smIdType> aVec(SMDSEntity_Last,0);
3697 int nb1d_in = (nbTria*3 - nb1d) / 2;
3698 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3699 aVec[SMDSEntity_Quad_Triangle] = nbTria;
3700 aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3703 aVec[SMDSEntity_Node] = nbNodes;
3704 aVec[SMDSEntity_Triangle] = nbTria;
3705 aVec[SMDSEntity_Quadrangle] = nbQuad;
3707 aResMap.insert(std::make_pair(sm,aVec));
3714 BRepGProp::VolumeProperties(aShape,G);
3715 double aVolume = G.Mass();
3716 double tetrVol = 0.1179*ELen*ELen*ELen;
3717 int nbVols = int(aVolume/tetrVol);
3718 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3719 std::vector<smIdType> aVec(SMDSEntity_Last);
3720 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3722 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3723 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3726 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3727 aVec[SMDSEntity_Tetra] = nbVols;
3729 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3730 aResMap.insert(std::make_pair(sm,aVec));
3735 //================================================================================
3737 * \brief Find TopoDS_Shape for each hyper-patch study entry in a hypothesis
3739 //================================================================================
3741 void BLSURFPlugin_BLSURF::FillEntryToShape( const BLSURFPlugin_Hypothesis* hyp,
3742 std::map< std::string, TopoDS_Shape > & entryToShape )
3744 SMESH_Gen_i* smeshGen = SMESH_Gen_i::GetSMESHGen();
3745 for ( const ::BLSURFPlugin_Hypothesis::THyperPatchEntries& entries : hyp->GetHyperPatchEntries() )
3746 for ( const std::string& entry : entries )
3748 GEOM::GEOM_Object_var go = smeshGen->GetGeomObjectByEntry( entry );
3749 TopoDS_Shape shape = smeshGen->GeomObjectToShape( go );
3750 if ( !shape.IsNull() )
3751 entryToShape.insert({ entry, shape });
3755 //================================================================================
3757 * \brief Sets event listener to submeshes if enforced mesh is defined
3758 * \param subMesh - submesh where algo is set
3760 * This method is called when a submesh gets HYP_OK algo_state.
3761 * After being set, event listener is notified on each event of a submesh.
3762 * By default none listener is set
3764 //================================================================================
3766 void BLSURFPlugin_BLSURF::SetEventListener(SMESH_subMesh* faceSubMesh)
3771 for ( const BLSURFPlugin_Hypothesis::EnforcedMesh& enfMesh : _hypothesis->GetEnforcedMeshes() )
3774 _hypothesis->GetEnforcedSegments( enfMesh, mesh1D );
3778 TopExp_Explorer edgeExp( mesh1D->GetShapeToMesh(), TopAbs_EDGE );
3779 if ( edgeExp.More() )
3780 StdMeshers_ProjectionUtils::SetEventListener( faceSubMesh,
3783 // StdMeshers_ProjectionUtils::SetEventListener( faceSubMesh,
3784 // mesh1D->GetShapeToMesh(),
3790 //================================================================================
3792 * \brief Allow algo to do something after persistent restoration
3793 * \param subMesh - restored submesh
3795 * This method is called only if a submesh has HYP_OK algo_state.
3797 //================================================================================
3799 void BLSURFPlugin_BLSURF::SubmeshRestored(SMESH_subMesh* subMesh)
3801 SetEventListener( subMesh );