1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 // File : BLSURFPlugin_BLSURF.cxx
22 // Authors : Francis KLOSS (OCC) & Patrick LAUG (INRIA) & Lioka RAZAFINDRAZAKA (CEA)
23 // & Aurelien ALLEAUME (DISTENE)
24 // Size maps developement: Nicolas GEIMER (OCC) & Gilles DAVID (EURIWARE)
27 #include "BLSURFPlugin_BLSURF.hxx"
28 #include "BLSURFPlugin_Hypothesis.hxx"
29 #include "BLSURFPlugin_Attractor.hxx"
32 #include <meshgems/meshgems.h>
33 #include <meshgems/cadsurf.h>
36 #include <structmember.h>
39 #include <Basics_Utils.hxx>
40 #include <Basics_OCCTVersion.hxx>
42 #include <SMDS_EdgePosition.hxx>
43 #include <SMESHDS_Group.hxx>
44 #include <SMESH_Gen.hxx>
45 #include <SMESH_Group.hxx>
46 #include <SMESH_Mesh.hxx>
47 #include <SMESH_MeshEditor.hxx>
48 #include <SMESH_MesherHelper.hxx>
49 #include <StdMeshers_FaceSide.hxx>
50 #include <StdMeshers_ViscousLayers2D.hxx>
51 #include <SMESH_File.hxx>
53 #include <utilities.h>
61 // OPENCASCADE includes
62 #include <BRepBuilderAPI_MakeFace.hxx>
63 #include <BRepBuilderAPI_MakePolygon.hxx>
64 //#include <BRepBuilderAPI_MakeVertex.hxx>
65 #include <BRepGProp.hxx>
66 #include <BRepTools.hxx>
67 #include <BRep_Builder.hxx>
68 #include <BRep_Tool.hxx>
69 #include <GProp_GProps.hxx>
70 #include <Geom2d_Curve.hxx>
71 #include <GeomAPI_ProjectPointOnCurve.hxx>
72 #include <GeomAPI_ProjectPointOnSurf.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Surface.hxx>
75 #include <NCollection_Map.hxx>
76 #include <Standard_ErrorHandler.hxx>
78 #include <TopExp_Explorer.hxx>
79 #include <TopTools_DataMapOfShapeInteger.hxx>
80 #include <TopTools_IndexedMapOfShape.hxx>
81 #include <TopTools_MapOfShape.hxx>
83 #include <TopoDS_Compound.hxx>
84 #include <TopoDS_Edge.hxx>
85 #include <TopoDS_Face.hxx>
86 #include <TopoDS_Shape.hxx>
87 #include <TopoDS_Vertex.hxx>
88 #include <TopoDS_Wire.hxx>
90 #include <gp_Pnt2d.hxx>
100 /* ==================================
101 * =========== PYTHON ==============
102 * ==================================*/
113 PyStdOut_dealloc(PyStdOut *self)
119 PyStdOut_write(PyStdOut *self, PyObject *args)
123 if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
126 *(self->out)=*(self->out)+c;
132 static PyMethodDef PyStdOut_methods[] = {
133 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
134 PyDoc_STR("write(string) -> None")},
135 {NULL, NULL} /* sentinel */
138 static PyMemberDef PyStdOut_memberlist[] = {
139 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
140 (char*)"flag indicating that a space needs to be printed; used by print"},
141 {NULL} /* Sentinel */
144 static PyTypeObject PyStdOut_Type = {
145 /* The ob_type field must be initialized in the module init function
146 * to be portable to Windows without using C++. */
147 PyObject_HEAD_INIT(NULL)
150 sizeof(PyStdOut), /*tp_basicsize*/
153 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
160 0, /*tp_as_sequence*/
165 PyObject_GenericGetAttr, /*tp_getattro*/
166 /* softspace is writable: we must supply tp_setattro */
167 PyObject_GenericSetAttr, /* tp_setattro */
169 Py_TPFLAGS_DEFAULT, /*tp_flags*/
173 0, /*tp_richcompare*/
174 0, /*tp_weaklistoffset*/
177 PyStdOut_methods, /*tp_methods*/
178 PyStdOut_memberlist, /*tp_members*/
192 PyObject * newPyStdOut( std::string& out )
194 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
199 return (PyObject*)self;
204 ////////////////////////END PYTHON///////////////////////////
206 //////////////////MY MAPS////////////////////////////////////////
208 TopTools_IndexedMapOfShape FacesWithSizeMap;
209 std::map<int,string> FaceId2SizeMap;
210 TopTools_IndexedMapOfShape EdgesWithSizeMap;
211 std::map<int,string> EdgeId2SizeMap;
212 TopTools_IndexedMapOfShape VerticesWithSizeMap;
213 std::map<int,string> VertexId2SizeMap;
215 std::map<int,PyObject*> FaceId2PythonSmp;
216 std::map<int,PyObject*> EdgeId2PythonSmp;
217 std::map<int,PyObject*> VertexId2PythonSmp;
219 typedef std::map<int, std::vector< BLSURFPlugin_Attractor* > > TId2ClsAttractorVec;
220 TId2ClsAttractorVec FaceId2ClassAttractor;
221 TId2ClsAttractorVec FaceIndex2ClassAttractor;
222 std::map<int,std::vector<double> > FaceId2AttractorCoords;
225 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
226 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
227 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
228 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
230 bool HasSizeMapOnFace=false;
231 bool HasSizeMapOnEdge=false;
232 bool HasSizeMapOnVertex=false;
233 //bool HasAttractorOnFace=false;
235 //=============================================================================
239 //=============================================================================
241 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, SMESH_Gen* gen)
242 : SMESH_2D_Algo(hypId, gen)
244 MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
246 _name = "MG-CADSurf";//"BLSURF";
247 _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
248 _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
249 _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
250 _requireDiscreteBoundary = false;
251 _onlyUnaryInput = false;
253 _supportSubmeshes = true;
255 /* Initialize the Python interpreter */
256 assert(Py_IsInitialized());
257 PyGILState_STATE gstate;
258 gstate = PyGILState_Ensure();
261 main_mod = PyImport_AddModule("__main__");
264 main_dict = PyModule_GetDict(main_mod);
266 PyRun_SimpleString("from math import *");
267 PyGILState_Release(gstate);
269 FacesWithSizeMap.Clear();
270 FaceId2SizeMap.clear();
271 EdgesWithSizeMap.Clear();
272 EdgeId2SizeMap.clear();
273 VerticesWithSizeMap.Clear();
274 VertexId2SizeMap.clear();
275 FaceId2PythonSmp.clear();
276 EdgeId2PythonSmp.clear();
277 VertexId2PythonSmp.clear();
278 FaceId2AttractorCoords.clear();
279 FaceId2ClassAttractor.clear();
280 FaceIndex2ClassAttractor.clear();
281 FacesWithEnforcedVertices.Clear();
282 FaceId2EnforcedVertexCoords.clear();
283 EnfVertexCoords2ProjVertex.clear();
284 EnfVertexCoords2EnfVertexList.clear();
286 _compute_canceled = false;
289 //=============================================================================
293 //=============================================================================
295 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
297 MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
301 //=============================================================================
305 //=============================================================================
307 bool BLSURFPlugin_BLSURF::CheckHypothesis
309 const TopoDS_Shape& aShape,
310 SMESH_Hypothesis::Hypothesis_Status& aStatus)
313 _haveViscousLayers = false;
315 list<const SMESHDS_Hypothesis*>::const_iterator itl;
316 const SMESHDS_Hypothesis* theHyp;
318 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape,
319 /*ignoreAuxiliary=*/false);
320 aStatus = SMESH_Hypothesis::HYP_OK;
323 return true; // can work with no hypothesis
326 for ( itl = hyps.begin(); itl != hyps.end() && ( aStatus == HYP_OK ); ++itl )
329 string hypName = theHyp->GetName();
330 if ( hypName == BLSURFPlugin_Hypothesis::GetHypType() )
332 _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
334 if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
335 _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
336 // hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
337 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
339 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
341 if ( !_haveViscousLayers )
343 if ( error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus )))
344 _haveViscousLayers = true;
349 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
352 return aStatus == SMESH_Hypothesis::HYP_OK;
355 //=============================================================================
357 * Pass parameters to MG-CADSurf
359 //=============================================================================
361 inline std::string val_to_string(double d)
363 std::ostringstream o;
368 inline std::string val_to_string_rel(double d)
370 std::ostringstream o;
376 inline std::string val_to_string(int i)
378 std::ostringstream o;
383 inline std::string val_to_string_rel(int i)
385 std::ostringstream o;
391 double _smp_phy_size;
392 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
393 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
394 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
400 /////////////////////////////////////////////////////////
401 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_Pnt& point)
403 projectionPoint myPoint;
404 Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
405 GeomAPI_ProjectPointOnSurf projector( point, surface );
406 if ( !projector.IsDone() || projector.NbPoints()==0 )
407 throw "getProjectionPoint: Can't project";
409 Quantity_Parameter u,v;
410 projector.LowerDistanceParameters(u,v);
411 myPoint.uv = gp_XY(u,v);
412 gp_Pnt aPnt = projector.NearestPoint();
413 myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
417 /////////////////////////////////////////////////////////
419 /////////////////////////////////////////////////////////
420 double getT(const TopoDS_Edge& edge, const gp_Pnt& point)
423 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
424 GeomAPI_ProjectPointOnCurve projector( point, curve);
425 if ( projector.NbPoints() == 0 )
427 return projector.LowerDistanceParameter();
430 /////////////////////////////////////////////////////////
431 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
433 MESSAGE("BLSURFPlugin_BLSURF::entryToShape "<<entry );
434 GEOM::GEOM_Object_var aGeomObj;
435 TopoDS_Shape S = TopoDS_Shape();
436 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::getStudyServant()->FindObjectID( entry.c_str() );
437 if (!aSObj->_is_nil()) {
438 CORBA::Object_var obj = aSObj->GetObject();
439 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
442 if ( !aGeomObj->_is_nil() )
443 S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj.in() );
447 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
449 BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
454 // Get the (u,v) values of the enforced vertex on the face
455 projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
457 MESSAGE("Enforced Vertex: " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z());
458 MESSAGE("Projected Vertex: " << myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z());
459 MESSAGE("Parametric coordinates: " << myPoint.uv.X() << ", " << myPoint.uv.Y() );
461 enf_coords.push_back(aPnt.X());
462 enf_coords.push_back(aPnt.Y());
463 enf_coords.push_back(aPnt.Z());
465 coords.push_back(myPoint.uv.X());
466 coords.push_back(myPoint.uv.Y());
467 coords.push_back(myPoint.xyz.X());
468 coords.push_back(myPoint.xyz.Y());
469 coords.push_back(myPoint.xyz.Z());
471 s_coords.push_back(myPoint.xyz.X());
472 s_coords.push_back(myPoint.xyz.Y());
473 s_coords.push_back(myPoint.xyz.Z());
475 // Save pair projected vertex / enf vertex
476 MESSAGE("Storing pair projected vertex / enf vertex:");
477 MESSAGE("("<< myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z() <<") / (" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z()<<")");
478 EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
479 MESSAGE("Group name is: \"" << enfVertex->grpName << "\"");
480 pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
481 BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
482 ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
483 if (ret.second == false) {
485 (*it)->grpName = enfVertex->grpName;
489 if (! FacesWithEnforcedVertices.Contains(faceShape)) {
490 key = FacesWithEnforcedVertices.Add(faceShape);
493 key = FacesWithEnforcedVertices.FindIndex(faceShape);
496 // If a node is already created by an attractor, do not create enforced vertex
497 int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
498 bool sameAttractor = false;
499 if (attractorKey >= 0)
500 if (FaceId2AttractorCoords.count(attractorKey) > 0)
501 if (FaceId2AttractorCoords[attractorKey] == coords)
502 sameAttractor = true;
504 if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
505 MESSAGE("Map of enf. vertex has key " << key)
506 MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
508 FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
510 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
511 MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
514 MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
515 if (! sameAttractor) {
516 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
518 FaceId2EnforcedVertexCoords[key] = ens;
521 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
525 /////////////////////////////////////////////////////////
526 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
528 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
531 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
533 for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
534 enfVertex = *enfVertexListIt;
535 // Case of manual coords
536 if (enfVertex->coords.size() != 0) {
537 aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
538 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
541 // Case of geom vertex coords
542 if (enfVertex->geomEntry != "") {
543 TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
544 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
545 if (GeomType == TopAbs_VERTEX){
546 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
547 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
550 if (GeomType == TopAbs_COMPOUND){
551 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
552 if (it.Value().ShapeType() == TopAbs_VERTEX){
553 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
554 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
562 /////////////////////////////////////////////////////////
563 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction, double defaultSize)
565 MESSAGE("Attractor function: "<< AttractorFunction);
566 double xa, ya, za; // Coordinates of attractor point
567 double a, b; // Attractor parameter
569 bool createNode=false; // To create a node on attractor projection
571 const char *sep = ";";
572 // atIt->second has the following pattern:
573 // ATTRACTOR(xa;ya;za;a;b;True|False;d)
575 // xa;ya;za : coordinates of attractor
576 // a : desired size on attractor
577 // b : distance of influence of attractor
578 // d : distance until which the size remains constant
580 // We search the parameters in the string
582 pos1 = AttractorFunction.find(sep);
583 if (pos1!=string::npos)
584 xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
586 pos2 = AttractorFunction.find(sep, pos1+1);
587 if (pos2!=string::npos) {
588 ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
592 pos2 = AttractorFunction.find(sep, pos1+1);
593 if (pos2!=string::npos) {
594 za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
598 pos2 = AttractorFunction.find(sep, pos1+1);
599 if (pos2!=string::npos) {
600 a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
604 pos2 = AttractorFunction.find(sep, pos1+1);
605 if (pos2!=string::npos) {
606 b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
610 pos2 = AttractorFunction.find(sep, pos1+1);
611 if (pos2!=string::npos) {
612 string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
613 MESSAGE("createNode: " << createNodeStr);
614 createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
618 pos2 = AttractorFunction.find(")");
619 if (pos2!=string::npos) {
620 d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
623 // Get the (u,v) values of the attractor on the face
624 projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
625 gp_XY uvPoint = myPoint.uv;
626 gp_XYZ xyzPoint = myPoint.xyz;
627 Standard_Real u0 = uvPoint.X();
628 Standard_Real v0 = uvPoint.Y();
629 Standard_Real x0 = xyzPoint.X();
630 Standard_Real y0 = xyzPoint.Y();
631 Standard_Real z0 = xyzPoint.Z();
632 std::vector<double> coords;
633 coords.push_back(u0);
634 coords.push_back(v0);
635 coords.push_back(x0);
636 coords.push_back(y0);
637 coords.push_back(z0);
638 // We construct the python function
639 ostringstream attractorFunctionStream;
640 attractorFunctionStream << "def f(u,v): return ";
641 attractorFunctionStream << defaultSize << "-(" << defaultSize <<"-" << a << ")";
642 //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
643 // rnc: make possible to keep the size constant until
644 // a defined distance. Distance is expressed as the positiv part
645 // of r-d where r is the distance to (u0,v0)
646 attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
648 MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
651 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
652 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
655 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
657 FaceId2SizeMap[key] =attractorFunctionStream.str();
659 MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
660 FaceId2AttractorCoords[key] = coords;
662 // // Test for new attractors
663 // gp_Pnt myP(xyzPoint);
664 // TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
665 // BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
666 // myAttractor.SetParameters(a, defaultSize, b, d);
667 // myAttractor.SetType(1);
668 // FaceId2ClassAttractor[key] = myAttractor;
669 // if(FaceId2ClassAttractor[key].GetFace().IsNull()){
670 // MESSAGE("face nulle ");
673 // MESSAGE("face OK");
675 // if (FaceId2ClassAttractor[key].GetAttractorShape().IsNull()){
676 // MESSAGE("pas de point");
679 // MESSAGE("point OK");
682 // One sub-shape to get ids from
683 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(TopoDS_Shape theMainShape, TopoDS_Shape theSubShape,
684 TopAbs_ShapeEnum theShapeType)
686 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
687 TopTools_IndexedMapOfShape anIndices;
689 TopExp::MapShapes(theMainShape, theShapeType, anIndices);
691 // Standard_Boolean result = BRepTools::Write(theMainShape,"main_shape.brep");
693 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
695 int face_id = anIndices.FindIndex(face_iter.Current());
697 throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
698 face_ids.push_back(face_id);
699 // std::ostringstream o;
700 // o << "face_" << face_id << ".brep";
701 // std::string face_name = o.str();
702 // const TopoDS_Face& face = TopoDS::Face(face_iter.Current());
703 // Standard_Boolean result = BRepTools::Write(face,face_name.c_str());
709 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(SMESH_Mesh* theMesh,
710 TopoDS_Shape theSubShape,
711 TopAbs_ShapeEnum theShapeType)
713 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
715 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
717 int face_id = theMesh->GetMeshDS()->ShapeToIndex(face_iter.Current());
719 throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
720 face_ids.push_back(face_id);
726 void BLSURFPlugin_BLSURF::addCoordsFromVertices(const std::vector<std::string> &theVerticesEntries, std::vector<double> &theVerticesCoords)
728 for (std::vector<std::string>::const_iterator it = theVerticesEntries.begin(); it != theVerticesEntries.end(); it++)
730 BLSURFPlugin_Hypothesis::TEntry theVertexEntry = *it;
731 MESSAGE("Vertex entry " << theVertexEntry);
732 addCoordsFromVertex(theVertexEntry, theVerticesCoords);
737 void BLSURFPlugin_BLSURF::addCoordsFromVertex(BLSURFPlugin_Hypothesis::TEntry theVertexEntry, std::vector<double> &theVerticesCoords)
739 if (theVertexEntry!="")
741 TopoDS_Shape aShape = entryToShape(theVertexEntry);
743 gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex( aShape ) );
744 double theX, theY, theZ;
749 theVerticesCoords.push_back(theX);
750 theVerticesCoords.push_back(theY);
751 theVerticesCoords.push_back(theZ);
755 /////////////////////////////////////////////////////////
756 void BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
758 MESSAGE("BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity");
760 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
761 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
763 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_FACE);
764 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_FACE);
766 TPreCadPeriodicityIDs preCadFacesPeriodicityIDs;
767 preCadFacesPeriodicityIDs.shape1IDs = theFace1_ids;
768 preCadFacesPeriodicityIDs.shape2IDs = theFace2_ids;
770 MESSAGE("preCadPeriodicity.theSourceVerticesEntries.size(): " << preCadPeriodicity.theSourceVerticesEntries.size());
771 MESSAGE("preCadPeriodicity.theTargetVerticesEntries.size(): " << preCadPeriodicity.theTargetVerticesEntries.size());
773 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadFacesPeriodicityIDs.theSourceVerticesCoords);
774 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadFacesPeriodicityIDs.theTargetVerticesCoords);
776 MESSAGE("preCadFacesPeriodicityIDs.theSourceVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theSourceVerticesCoords.size());
777 MESSAGE("preCadFacesPeriodicityIDs.theTargetVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theTargetVerticesCoords.size());
779 _preCadFacesIDsPeriodicityVector.push_back(preCadFacesPeriodicityIDs);
780 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
781 MESSAGE("BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity END");
785 /////////////////////////////////////////////////////////
786 void BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
788 MESSAGE("BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity");
790 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
791 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
793 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_EDGE);
794 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_EDGE);
796 TPreCadPeriodicityIDs preCadEdgesPeriodicityIDs;
797 preCadEdgesPeriodicityIDs.shape1IDs = theEdge1_ids;
798 preCadEdgesPeriodicityIDs.shape2IDs = theEdge2_ids;
800 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadEdgesPeriodicityIDs.theSourceVerticesCoords);
801 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadEdgesPeriodicityIDs.theTargetVerticesCoords);
803 _preCadEdgesIDsPeriodicityVector.push_back(preCadEdgesPeriodicityIDs);
804 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
805 MESSAGE("BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity END");
810 /////////////////////////////////////////////////////////
812 void BLSURFPlugin_BLSURF::SetParameters(const BLSURFPlugin_Hypothesis* hyp,
813 cadsurf_session_t * css,
814 const TopoDS_Shape& theGeomShape
818 // Clear map so that it is not stored in the algorithm with old enforced vertices in it
819 EnfVertexCoords2EnfVertexList.clear();
821 double diagonal = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
822 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
823 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
824 int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
825 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
826 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
827 double _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
828 bool _minSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
829 double _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
830 bool _maxSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
831 double _use_gradation = BLSURFPlugin_Hypothesis::GetDefaultUseGradation();
832 double _gradation = BLSURFPlugin_Hypothesis::GetDefaultGradation();
833 double _use_volume_gradation = BLSURFPlugin_Hypothesis::GetDefaultUseVolumeGradation();
834 double _volume_gradation = BLSURFPlugin_Hypothesis::GetDefaultVolumeGradation();
835 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
836 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
837 double _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
838 bool _anisotropic = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
839 double _anisotropicRatio = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
840 bool _removeTinyEdges = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
841 double _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
842 bool _optimiseTinyEdges = BLSURFPlugin_Hypothesis::GetDefaultOptimiseTinyEdges();
843 double _tinyEdgeOptimisLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeOptimisationLength(diagonal);
844 bool _correctSurfaceIntersec= BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersection();
845 double _corrSurfaceIntersCost = BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersectionMaxCost();
846 bool _badElementRemoval = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
847 double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
848 bool _optimizeMesh = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
849 bool _quadraticMesh = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
850 int _verb = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
851 //int _topology = BLSURFPlugin_Hypothesis::GetDefaultTopology();
854 //int _precadMergeEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
855 int _precadRemoveTinyUVEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveTinyUVEdges();
856 //int _precadRemoveDuplicateCADFaces = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveDuplicateCADFaces();
857 //int _precadProcess3DTopology = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
858 //int _precadDiscardInput = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
862 MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
863 _physicalMesh = (int) hyp->GetPhysicalMesh();
864 _geometricMesh = (int) hyp->GetGeometricMesh();
865 if (hyp->GetPhySize() > 0) {
866 _phySize = hyp->GetPhySize();
867 // if user size is not explicitly specified, "relative" flag is ignored
868 _phySizeRel = hyp->IsPhySizeRel();
870 if (hyp->GetMinSize() > 0) {
871 _minSize = hyp->GetMinSize();
872 // if min size is not explicitly specified, "relative" flag is ignored
873 _minSizeRel = hyp->IsMinSizeRel();
875 if (hyp->GetMaxSize() > 0) {
876 _maxSize = hyp->GetMaxSize();
877 // if max size is not explicitly specified, "relative" flag is ignored
878 _maxSizeRel = hyp->IsMaxSizeRel();
880 _use_gradation = hyp->GetUseGradation();
881 if (hyp->GetGradation() > 0 && _use_gradation)
882 _gradation = hyp->GetGradation();
883 _use_volume_gradation = hyp->GetUseVolumeGradation();
884 if (hyp->GetVolumeGradation() > 0 && _use_volume_gradation )
885 _volume_gradation = hyp->GetVolumeGradation();
886 _quadAllowed = hyp->GetQuadAllowed();
887 if (hyp->GetAngleMesh() > 0)
888 _angleMesh = hyp->GetAngleMesh();
889 if (hyp->GetChordalError() > 0)
890 _chordalError = hyp->GetChordalError();
891 _anisotropic = hyp->GetAnisotropic();
892 if (hyp->GetAnisotropicRatio() >= 0)
893 _anisotropicRatio = hyp->GetAnisotropicRatio();
894 _removeTinyEdges = hyp->GetRemoveTinyEdges();
895 if (hyp->GetTinyEdgeLength() > 0)
896 _tinyEdgeLength = hyp->GetTinyEdgeLength();
897 _optimiseTinyEdges = hyp->GetOptimiseTinyEdges();
898 if (hyp->GetTinyEdgeOptimisationLength() > 0)
899 _tinyEdgeOptimisLength = hyp->GetTinyEdgeOptimisationLength();
900 _correctSurfaceIntersec = hyp->GetCorrectSurfaceIntersection();
901 if (hyp->GetCorrectSurfaceIntersectionMaxCost() > 0)
902 _corrSurfaceIntersCost = hyp->GetCorrectSurfaceIntersectionMaxCost();
903 _badElementRemoval = hyp->GetBadElementRemoval();
904 if (hyp->GetBadElementAspectRatio() >= 0)
905 _badElementAspectRatio = hyp->GetBadElementAspectRatio();
906 _optimizeMesh = hyp->GetOptimizeMesh();
907 _quadraticMesh = hyp->GetQuadraticMesh();
908 _verb = hyp->GetVerbosity();
909 //_topology = (int) hyp->GetTopology();
911 //_precadMergeEdges = hyp->GetPreCADMergeEdges();
912 _precadRemoveTinyUVEdges = hyp->GetPreCADRemoveTinyUVEdges();
913 //_precadRemoveDuplicateCADFaces = hyp->GetPreCADRemoveDuplicateCADFaces();
914 //_precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
915 //_precadDiscardInput = hyp->GetPreCADDiscardInput();
917 const BLSURFPlugin_Hypothesis::TOptionValues& opts = hyp->GetOptionValues();
918 BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
919 for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
920 if ( !opIt->second.empty() ) {
921 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
922 set_param(css, opIt->first.c_str(), opIt->second.c_str());
925 const BLSURFPlugin_Hypothesis::TOptionValues& custom_opts = hyp->GetCustomOptionValues();
926 for ( opIt = custom_opts.begin(); opIt != custom_opts.end(); ++opIt )
927 if ( !opIt->second.empty() ) {
928 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
929 set_param(css, opIt->first.c_str(), opIt->second.c_str());
932 const BLSURFPlugin_Hypothesis::TOptionValues& preCADopts = hyp->GetPreCADOptionValues();
933 for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
934 if ( !opIt->second.empty() ) {
935 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
936 set_param(css, opIt->first.c_str(), opIt->second.c_str());
940 if ( BLSURFPlugin_Hypothesis::HasPreCADOptions( hyp ))
942 cadsurf_set_param(css, "use_precad", "yes" ); // for old versions
944 // PreProcessor (formerly PreCAD) -- commented params are preCADoptions (since 0023307)
945 //set_param(css, "merge_edges", _precadMergeEdges ? "yes" : "no");
946 set_param(css, "remove_tiny_uv_edges", _precadRemoveTinyUVEdges ? "yes" : "no");
947 //set_param(css, "remove_duplicate_cad_faces", _precadRemoveDuplicateCADFaces ? "yes" : "no");
948 //set_param(css, "process_3d_topology", _precadProcess3DTopology ? "1" : "0");
949 //set_param(css, "discard_input_topology", _precadDiscardInput ? "1" : "0");
950 //set_param(css, "max_number_of_points_per_patch", "1000000");
952 bool useGradation = false;
953 switch (_physicalMesh)
955 case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
956 set_param(css, "physical_size_mode", "global");
957 set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
959 case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
960 set_param(css, "physical_size_mode", "local");
961 set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
965 set_param(css, "physical_size_mode", "none");
968 switch (_geometricMesh)
970 case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
971 set_param(css, "geometric_size_mode", "global");
972 set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
973 set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
976 case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
977 set_param(css, "geometric_size_mode", "local");
978 set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
979 set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
983 set_param(css, "geometric_size_mode", "none");
986 if ( hyp && hyp->GetPhySize() > 0 ) {
987 // user size is explicitly specified via hypothesis parameters
988 // min and max sizes should be compared with explicitly specified user size
989 // - compute absolute min size
990 double mins = _minSizeRel ? _minSize * diagonal : _minSize;
991 // - min size should not be greater than user size
992 if ( _phySize < mins )
993 set_param(css, "min_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
995 set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
996 // - compute absolute max size
997 double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
998 // - max size should not be less than user size
999 if ( _phySize > maxs )
1000 set_param(css, "max_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1002 set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1005 // user size is not explicitly specified
1006 // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1007 set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
1008 // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1009 set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1011 // anisotropic and quadrangle mesh requires disabling gradation
1012 if ( _anisotropic && _quadAllowed )
1013 useGradation = false; // limitation of V1.3
1014 if ( useGradation && _use_gradation )
1015 set_param(css, "gradation", val_to_string(_gradation).c_str());
1016 if ( useGradation && _use_volume_gradation )
1017 set_param(css, "volume_gradation", val_to_string(_volume_gradation).c_str());
1018 set_param(css, "element_generation", _quadAllowed ? "quad_dominant" : "triangle");
1021 set_param(css, "metric", _anisotropic ? "anisotropic" : "isotropic");
1023 set_param(css, "anisotropic_ratio", val_to_string(_anisotropicRatio).c_str());
1024 set_param(css, "remove_tiny_edges", _removeTinyEdges ? "1" : "0");
1025 if ( _removeTinyEdges )
1026 set_param(css, "tiny_edge_length", val_to_string(_tinyEdgeLength).c_str());
1027 set_param(css, "optimise_tiny_edges", _optimiseTinyEdges ? "1" : "0");
1028 if ( _optimiseTinyEdges )
1029 set_param(css, "tiny_edge_optimisation_length", val_to_string(_tinyEdgeOptimisLength).c_str());
1030 set_param(css, "correct_surface_intersections", _correctSurfaceIntersec ? "1" : "0");
1031 if ( _correctSurfaceIntersec )
1032 set_param(css, "surface_intersections_processing_max_cost", val_to_string(_corrSurfaceIntersCost ).c_str());
1033 set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
1034 if ( _badElementRemoval )
1035 set_param(css, "bad_surface_element_aspect_ratio", val_to_string(_badElementAspectRatio).c_str());
1036 set_param(css, "optimisation", _optimizeMesh ? "yes" : "no");
1037 set_param(css, "element_order", _quadraticMesh ? "quadratic" : "linear");
1038 set_param(css, "verbose", val_to_string(_verb).c_str());
1040 _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
1042 std::cout << "_smp_phy_size = " << _smp_phy_size << std::endl;
1044 if (_physicalMesh == BLSURFPlugin_Hypothesis::PhysicalLocalSize){
1045 TopoDS_Shape GeomShape;
1046 TopoDS_Shape AttShape;
1047 TopAbs_ShapeEnum GeomType;
1049 // Standard Size Maps
1051 MESSAGE("Setting a Size Map");
1052 const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
1053 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
1054 for ( ; smIt != sizeMaps.end(); ++smIt ) {
1055 if ( !smIt->second.empty() ) {
1056 MESSAGE("cadsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
1057 GeomShape = entryToShape(smIt->first);
1058 GeomType = GeomShape.ShapeType();
1059 MESSAGE("Geomtype is " << GeomType);
1062 if (GeomType == TopAbs_COMPOUND) {
1063 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1065 if (it.Value().ShapeType() == TopAbs_FACE){
1066 HasSizeMapOnFace = true;
1067 if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
1068 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
1071 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
1072 // MESSAGE("Face with key " << key << " already in map");
1074 FaceId2SizeMap[key] = smIt->second;
1077 if (it.Value().ShapeType() == TopAbs_EDGE){
1078 HasSizeMapOnEdge = true;
1079 HasSizeMapOnFace = true;
1080 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
1081 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
1084 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
1085 // MESSAGE("Edge with key " << key << " already in map");
1087 EdgeId2SizeMap[key] = smIt->second;
1089 // Group of vertices
1090 if (it.Value().ShapeType() == TopAbs_VERTEX){
1091 HasSizeMapOnVertex = true;
1092 HasSizeMapOnEdge = true;
1093 HasSizeMapOnFace = true;
1094 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
1095 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
1098 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
1099 MESSAGE("Group of vertices with key " << key << " already in map");
1101 MESSAGE("Group of vertices with key " << key << " has a size map: " << smIt->second);
1102 VertexId2SizeMap[key] = smIt->second;
1107 if (GeomType == TopAbs_FACE){
1108 HasSizeMapOnFace = true;
1109 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
1110 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
1113 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1114 // MESSAGE("Face with key " << key << " already in map");
1116 FaceId2SizeMap[key] = smIt->second;
1119 if (GeomType == TopAbs_EDGE){
1120 HasSizeMapOnEdge = true;
1121 HasSizeMapOnFace = true;
1122 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
1123 key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
1126 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
1127 // MESSAGE("Edge with key " << key << " already in map");
1129 EdgeId2SizeMap[key] = smIt->second;
1132 if (GeomType == TopAbs_VERTEX){
1133 HasSizeMapOnVertex = true;
1134 HasSizeMapOnEdge = true;
1135 HasSizeMapOnFace = true;
1136 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
1137 key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
1140 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
1141 MESSAGE("Vertex with key " << key << " already in map");
1143 MESSAGE("Vertex with key " << key << " has a size map: " << smIt->second);
1144 VertexId2SizeMap[key] = smIt->second;
1152 // TODO appeler le constructeur des attracteurs directement ici
1153 MESSAGE("Setting Attractors");
1154 // if ( !_phySizeRel ) {
1155 const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
1156 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
1157 for ( ; atIt != attractors.end(); ++atIt ) {
1158 if ( !atIt->second.empty() ) {
1159 MESSAGE("cadsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
1160 GeomShape = entryToShape(atIt->first);
1161 GeomType = GeomShape.ShapeType();
1163 if (GeomType == TopAbs_COMPOUND){
1164 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1165 if (it.Value().ShapeType() == TopAbs_FACE){
1166 HasSizeMapOnFace = true;
1167 createAttractorOnFace(it.Value(), atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1172 if (GeomType == TopAbs_FACE){
1173 HasSizeMapOnFace = true;
1174 createAttractorOnFace(GeomShape, atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1177 if (GeomType == TopAbs_EDGE){
1178 HasSizeMapOnEdge = true;
1179 HasSizeMapOnFace = true;
1180 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
1182 if (GeomType == TopAbs_VERTEX){
1183 HasSizeMapOnVertex = true;
1184 HasSizeMapOnEdge = true;
1185 HasSizeMapOnFace = true;
1186 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
1193 // MESSAGE("Impossible to create the attractors when the physical size is relative");
1196 // temporary commented out for testing
1198 // - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
1199 // - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
1200 // - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
1202 // - Construct the attractors with an empty dist. map in the hypothesis
1203 // - 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()
1204 // -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap() OK
1206 theNbAttractors = 0;
1207 const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
1209 BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
1210 for ( ; AtIt != class_attractors.end(); ++AtIt ) {
1211 if ( !AtIt->second->Empty() ) {
1212 // MESSAGE("cadsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
1213 GeomShape = entryToShape(AtIt->first);
1214 if ( !SMESH_MesherHelper::IsSubShape( GeomShape, theGeomShape ))
1216 AttShape = AtIt->second->GetAttractorShape();
1217 GeomType = GeomShape.ShapeType();
1219 // if (GeomType == TopAbs_COMPOUND){
1220 // for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1221 // if (it.Value().ShapeType() == TopAbs_FACE){
1222 // HasAttractorOnFace = true;
1223 // myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
1228 if (GeomType == TopAbs_FACE
1229 && (AttShape.ShapeType() == TopAbs_VERTEX
1230 || AttShape.ShapeType() == TopAbs_EDGE
1231 || AttShape.ShapeType() == TopAbs_WIRE
1232 || AttShape.ShapeType() == TopAbs_COMPOUND) ){
1233 HasSizeMapOnFace = true;
1235 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
1237 FaceId2ClassAttractor[key].push_back( AtIt->second );
1241 MESSAGE("Wrong shape type !!")
1249 // Enforced Vertices
1251 MESSAGE("Setting Enforced Vertices");
1252 const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
1253 BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
1254 for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
1255 if ( !enfIt->second.empty() ) {
1256 GeomShape = entryToShape(enfIt->first);
1257 GeomType = GeomShape.ShapeType();
1259 if (GeomType == TopAbs_COMPOUND){
1260 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1261 if (it.Value().ShapeType() == TopAbs_FACE){
1262 HasSizeMapOnFace = true;
1263 createEnforcedVertexOnFace(it.Value(), enfIt->second);
1268 if (GeomType == TopAbs_FACE){
1269 HasSizeMapOnFace = true;
1270 createEnforcedVertexOnFace(GeomShape, enfIt->second);
1275 // Internal vertices
1276 bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1277 if (useInternalVertexAllFaces) {
1278 std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1279 MESSAGE("Setting Internal Enforced Vertices");
1281 TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
1282 for (; exp.More(); exp.Next()){
1283 MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
1284 TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
1285 for (; exp_face.More(); exp_face.Next())
1287 // Get coords of vertex
1288 // Check if current coords is already in enfVertexList
1289 // If coords not in enfVertexList, add new enfVertex
1290 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1291 MESSAGE("Found vertex on face at " << aPnt.X() <<", "<<aPnt.Y()<<", "<<aPnt.Z());
1292 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1293 enfVertex->coords.push_back(aPnt.X());
1294 enfVertex->coords.push_back(aPnt.Y());
1295 enfVertex->coords.push_back(aPnt.Z());
1296 enfVertex->name = "";
1297 enfVertex->faceEntries.clear();
1298 enfVertex->geomEntry = "";
1299 enfVertex->grpName = grpName;
1300 enfVertex->vertex = TopoDS::Vertex( exp_face.Current() );
1301 _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()), aPnt, enfVertex);
1302 HasSizeMapOnFace = true;
1307 MESSAGE("Setting Size Map on FACES ");
1308 cadsurf_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
1310 if (HasSizeMapOnEdge){
1311 MESSAGE("Setting Size Map on EDGES ");
1312 cadsurf_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
1314 if (HasSizeMapOnVertex){
1315 MESSAGE("Setting Size Map on VERTICES ");
1316 cadsurf_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
1323 _preCadFacesIDsPeriodicityVector.clear();
1324 _preCadEdgesIDsPeriodicityVector.clear();
1326 MESSAGE("SetParameters preCadFacesPeriodicityVector");
1327 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadFacesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadFacesPeriodicityVector(hyp);
1329 for (std::size_t i = 0; i<preCadFacesPeriodicityVector.size(); i++){
1330 MESSAGE("SetParameters preCadFacesPeriodicityVector[" << i << "]");
1331 createPreCadFacesPeriodicity(theGeomShape, preCadFacesPeriodicityVector[i]);
1333 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
1335 MESSAGE("SetParameters preCadEdgesPeriodicityVector");
1336 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadEdgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadEdgesPeriodicityVector(hyp);
1338 for (std::size_t i = 0; i<preCadEdgesPeriodicityVector.size(); i++){
1339 MESSAGE("SetParameters preCadEdgesPeriodicityVector[" << i << "]");
1340 createPreCadEdgesPeriodicity(theGeomShape, preCadEdgesPeriodicityVector[i]);
1342 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
1346 //================================================================================
1348 * \brief Throws an exception if a parameter name is wrong
1350 //================================================================================
1352 void BLSURFPlugin_BLSURF::set_param(cadsurf_session_t *css,
1353 const char * option_name,
1354 const char * option_value)
1356 status_t status = cadsurf_set_param(css, option_name, option_value );
1358 if ( _hypothesis && _hypothesis->GetVerbosity() > _hypothesis->GetDefaultVerbosity() )
1359 cout << option_name << " = " << option_value << endl;
1361 if ( status != MESHGEMS_STATUS_OK )
1363 if ( status == MESHGEMS_STATUS_UNKNOWN_PARAMETER ) {
1364 throw SALOME_Exception
1365 ( SMESH_Comment("Invalid name of CADSURF parameter: ") << option_name );
1367 else if ( status == MESHGEMS_STATUS_NOLICENSE )
1368 throw SALOME_Exception
1369 ( "No valid license available" );
1371 throw SALOME_Exception
1372 ( SMESH_Comment("Either wrong name or unacceptable value of CADSURF parameter '")
1373 << option_name << "': " << option_value);
1379 // --------------------------------------------------------------------------
1381 * \brief Class correctly terminating usage of MG-CADSurf library at destruction
1383 class BLSURF_Cleaner
1386 cadsurf_session_t* _css;
1390 BLSURF_Cleaner(context_t * ctx,
1391 cadsurf_session_t* css,
1402 Clean( /*exceptContext=*/false );
1404 void Clean(const bool exceptContext)
1408 cadsurf_session_delete(_css); _css = 0;
1410 // #if BLSURF_VERSION_LONG >= "3.1.1"
1411 // // if(geo_sizemap_e)
1412 // // distene_sizemap_delete(geo_sizemap_e);
1413 // // if(geo_sizemap_f)
1414 // // distene_sizemap_delete(geo_sizemap_f);
1415 // if(iso_sizemap_p)
1416 // distene_sizemap_delete(iso_sizemap_p);
1417 // if(iso_sizemap_e)
1418 // distene_sizemap_delete(iso_sizemap_e);
1419 // if(iso_sizemap_f)
1420 // distene_sizemap_delete(iso_sizemap_f);
1422 // // if(clean_geo_sizemap_e)
1423 // // distene_sizemap_delete(clean_geo_sizemap_e);
1424 // // if(clean_geo_sizemap_f)
1425 // // distene_sizemap_delete(clean_geo_sizemap_f);
1426 // if(clean_iso_sizemap_p)
1427 // distene_sizemap_delete(clean_iso_sizemap_p);
1428 // if(clean_iso_sizemap_e)
1429 // distene_sizemap_delete(clean_iso_sizemap_e);
1430 // if(clean_iso_sizemap_f)
1431 // distene_sizemap_delete(clean_iso_sizemap_f);
1434 cad_delete(_cad); _cad = 0;
1435 dcad_delete(_dcad); _dcad = 0;
1436 if ( !exceptContext )
1438 context_delete(_ctx); _ctx = 0;
1444 // --------------------------------------------------------------------------
1445 // comparator to sort nodes and sub-meshes
1446 struct ShapeTypeCompare
1448 // sort nodes by position in the following order:
1449 // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
1450 bool operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
1452 // NEW ORDER: nodes earlier added to sub-mesh are considered "less"
1453 return n1->getIdInShape() < n2->getIdInShape();
1454 // SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
1455 // SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
1456 // if ( pos1 == pos2 ) return 0;
1457 // if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
1460 // sort sub-meshes in order: EDGE, VERTEX
1461 bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
1463 int isVertex1 = ( s1 && s1->NbElements() == 0 );
1464 int isVertex2 = ( s2 && s2->NbElements() == 0 );
1465 if ( isVertex1 == isVertex2 )
1467 return isVertex1 < isVertex2;
1471 //================================================================================
1473 * \brief Fills groups of nodes to be merged
1475 //================================================================================
1477 void getNodeGroupsToMerge( const SMESHDS_SubMesh* smDS,
1478 const TopoDS_Shape& shape,
1479 SMESH_MeshEditor::TListOfListOfNodes& nodeGroupsToMerge)
1481 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1482 switch ( shape.ShapeType() )
1484 case TopAbs_VERTEX: {
1485 std::list< const SMDS_MeshNode* > nodes;
1486 while ( nIt->more() )
1487 nodes.push_back( nIt->next() );
1488 if ( nodes.size() > 1 )
1489 nodeGroupsToMerge.push_back( nodes );
1493 std::multimap< double, const SMDS_MeshNode* > u2node;
1494 const SMDS_EdgePosition* ePos;
1495 while ( nIt->more() )
1497 const SMDS_MeshNode* n = nIt->next();
1498 if (( ePos = dynamic_cast< const SMDS_EdgePosition* >( n->GetPosition() )))
1499 u2node.insert( make_pair( ePos->GetUParameter(), n ));
1501 if ( u2node.size() < 2 ) return;
1503 //double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
1505 BRep_Tool::Range( TopoDS::Edge( shape ), f,l );
1506 double tol = (( l - f ) / 20.) / u2node.size();
1508 std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
1509 for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
1511 if (( un2->first - un1->first ) <= tol )
1513 std::list< const SMDS_MeshNode* > nodes;
1514 nodes.push_back( un1->second );
1515 while (( un2->first - un1->first ) <= tol )
1517 nodes.push_back( un2->second );
1518 if ( ++un2 == u2node.end()) {
1523 // make nodes created on the boundary of viscous layer replace nodes created
1524 // by MG-CADSurf as their SMDS_Position is more correct
1525 nodes.sort( ShapeTypeCompare() );
1526 nodeGroupsToMerge.push_back( nodes );
1533 // SMESH_MeshEditor::TListOfListOfNodes::const_iterator nll = nodeGroupsToMerge.begin();
1534 // for ( ; nll != nodeGroupsToMerge.end(); ++nll )
1536 // cout << "Merge ";
1537 // const std::list< const SMDS_MeshNode* >& nl = *nll;
1538 // std::list< const SMDS_MeshNode* >::const_iterator nIt = nl.begin();
1539 // for ( ; nIt != nl.end(); ++nIt )
1540 // cout << (*nIt) << " ";
1546 //================================================================================
1548 * \brief A temporary mesh used to compute mesh on a proxy FACE
1550 //================================================================================
1552 struct TmpMesh: public SMESH_Mesh
1554 typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
1555 TN2NMap _tmp2origNN;
1556 TopoDS_Face _proxyFace;
1560 _myMeshDS = new SMESHDS_Mesh( _id, true );
1562 //--------------------------------------------------------------------------------
1564 * \brief Creates a FACE bound by viscous layers and mesh each its EDGE with 1 segment
1566 //--------------------------------------------------------------------------------
1568 const TopoDS_Face& makeProxyFace( SMESH_ProxyMesh::Ptr& viscousMesh,
1569 const TopoDS_Face& origFace)
1571 // get data of nodes on inner boundary of viscous layers
1572 SMESH_Mesh* origMesh = viscousMesh->GetMesh();
1574 TSideVector wireVec = StdMeshers_FaceSide::GetFaceWires(origFace, *origMesh,
1575 /*skipMediumNodes = */true,
1577 if ( err && err->IsKO() )
1578 throw *err.get(); // it should be caught at SMESH_subMesh
1580 // proxy nodes and corresponding tmp VERTEXes
1581 std::vector<const SMDS_MeshNode*> origNodes;
1582 std::vector<TopoDS_Vertex> tmpVertex;
1584 // create a proxy FACE
1585 TopoDS_Shape origFaceCopy = origFace.EmptyCopied();
1586 BRepBuilderAPI_MakeFace newFace( TopoDS::Face( origFaceCopy ));
1587 for ( size_t iW = 0; iW != wireVec.size(); ++iW )
1589 StdMeshers_FaceSidePtr& wireData = wireVec[iW];
1590 const UVPtStructVec& wirePoints = wireData->GetUVPtStruct();
1591 if ( wirePoints.size() < 3 )
1594 BRepBuilderAPI_MakePolygon wire;
1595 const size_t i0 = tmpVertex.size();
1596 for ( size_t iN = 0; iN < wirePoints.size(); ++iN )
1598 wire.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
1599 origNodes.push_back( wirePoints[ iN ].node );
1600 tmpVertex.push_back( wire.LastVertex() );
1602 tmpVertex[ i0 ] = wire.FirstVertex(); // wire.LastVertex()==NULL for 1 vertex in wire
1604 if ( !wire.IsDone() )
1605 throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
1606 newFace.Add( wire );
1608 _proxyFace = newFace;
1610 // set a new shape to mesh
1611 TopoDS_Compound auxCompoundToMesh;
1612 BRep_Builder shapeBuilder;
1613 shapeBuilder.MakeCompound( auxCompoundToMesh );
1614 shapeBuilder.Add( auxCompoundToMesh, _proxyFace );
1615 shapeBuilder.Add( auxCompoundToMesh, origMesh->GetShapeToMesh() );
1617 ShapeToMesh( auxCompoundToMesh );
1619 //TopExp_Explorer fExp( auxCompoundToMesh, TopAbs_FACE );
1620 //_proxyFace = TopoDS::Face( fExp.Current() );
1623 // Make input mesh for MG-CADSurf: segments on EDGE's of newFace
1625 // make nodes and fill in _tmp2origNN
1627 SMESHDS_Mesh* tmpMeshDS = GetMeshDS();
1628 for ( size_t i = 0; i < origNodes.size(); ++i )
1630 GetSubMesh( tmpVertex[i] )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1631 if ( const SMDS_MeshNode* tmpN = SMESH_Algo::VertexNode( tmpVertex[i], tmpMeshDS ))
1632 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( tmpN, origNodes[i] ));
1634 throw SALOME_Exception("BLSURFPlugin_BLSURF: a proxy vertex not meshed");
1638 TopoDS_Vertex v1, v2;
1639 for ( TopExp_Explorer edge( _proxyFace, TopAbs_EDGE ); edge.More(); edge.Next() )
1641 const TopoDS_Edge& E = TopoDS::Edge( edge.Current() );
1642 TopExp::Vertices( E, v1, v2 );
1643 const SMDS_MeshNode* n1 = SMESH_Algo::VertexNode( v1, tmpMeshDS );
1644 const SMDS_MeshNode* n2 = SMESH_Algo::VertexNode( v2, tmpMeshDS );
1646 if ( SMDS_MeshElement* seg = tmpMeshDS->AddEdge( n1, n2 ))
1647 tmpMeshDS->SetMeshElementOnShape( seg, E );
1653 //--------------------------------------------------------------------------------
1655 * \brief Fill in the origMesh with faces computed by MG-CADSurf in this tmp mesh
1657 //--------------------------------------------------------------------------------
1659 void FillInOrigMesh( SMESH_Mesh& origMesh,
1660 const TopoDS_Face& origFace )
1662 SMESH_MesherHelper helper( origMesh );
1663 helper.SetSubShape( origFace );
1664 helper.SetElementsOnShape( true );
1666 SMESH_MesherHelper tmpHelper( *this );
1667 tmpHelper.SetSubShape( _proxyFace );
1669 // iterate over tmp faces and copy them in origMesh
1670 const SMDS_MeshNode* nodes[27];
1671 const SMDS_MeshNode* nullNode = 0;
1673 SMDS_FaceIteratorPtr fIt = GetMeshDS()->facesIterator(/*idInceasingOrder=*/true);
1674 while ( fIt->more() )
1676 const SMDS_MeshElement* f = fIt->next();
1677 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
1679 for ( ; nIt->more(); ++nbN )
1681 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
1682 TN2NMap::iterator n2nIt =
1683 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
1684 if ( !n2nIt->second ) {
1686 gp_XY uv = tmpHelper.GetNodeUV( _proxyFace, n );
1687 n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], uv.X(), uv.Y() );
1689 nodes[ nbN ] = n2nIt->second;
1692 case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
1693 // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
1694 // nodes[3], nodes[4], nodes[5]); break;
1695 case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
1696 // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1697 // nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
1698 // case 8: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1699 // nodes[4], nodes[5], nodes[6], nodes[7]); break;
1706 * \brief A structure holding an error description and a verbisity level
1708 struct message_cb_user_data
1710 std::string * _error;
1717 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1718 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1719 real *duu, real *duv, real *dvv, void *user_data);
1720 status_t message_cb(message_t *msg, void *user_data);
1721 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1723 //=============================================================================
1727 //=============================================================================
1729 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1731 MESSAGE("BLSURFPlugin_BLSURF::Compute");
1733 // Fix problem with locales
1734 Kernel_Utils::Localizer aLocalizer;
1736 this->SMESH_Algo::_progress = 1e-3; // prevent progress advancment while computing attractors
1738 bool viscousLayersMade =
1739 ( aShape.ShapeType() == TopAbs_FACE &&
1740 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( aShape ), aMesh ));
1742 if ( !viscousLayersMade )
1743 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1746 if ( _haveViscousLayers || viscousLayersMade )
1748 // Compute viscous layers
1750 TopTools_MapOfShape map;
1751 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1753 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1754 if ( !map.Add( F )) continue;
1755 SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1757 return false; // error in StdMeshers_ViscousLayers2D::Compute()
1759 // Compute MG-CADSurf mesh on viscous layers
1761 if ( viscousMesh->NbProxySubMeshes() > 0 )
1764 const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1765 if ( !compute( tmpMesh, proxyFace, /*allowSubMeshClearing=*/false ))
1767 tmpMesh.FillInOrigMesh( aMesh, F );
1771 // Re-compute MG-CADSurf mesh on the rest faces if the mesh was cleared
1773 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1775 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1776 SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1777 if ( fSM->IsMeshComputed() ) continue;
1779 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1787 //=============================================================================
1791 //=============================================================================
1793 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh& aMesh,
1794 const TopoDS_Shape& aShape,
1795 bool allowSubMeshClearing)
1797 /* create a distene context (generic object) */
1798 status_t status = STATUS_ERROR;
1801 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1802 SMESH_MesherHelper helper( aMesh );
1803 // do not call helper.IsQuadraticSubMesh() because sub-meshes
1804 // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1805 bool haveQuadraticSubMesh = SMESH_MesherHelper( aMesh ).IsQuadraticSubMesh( aShape );
1806 bool quadraticSubMeshAndViscousLayer = false;
1807 bool needMerge = false;
1808 typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1809 TSubMeshSet edgeSubmeshes;
1810 TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1812 TopTools_IndexedMapOfShape pmap, emap, fmap;
1814 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1816 feclearexcept( FE_ALL_EXCEPT );
1817 int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1820 context_t *ctx = context_new();
1822 /* Set the message callback in the working context */
1823 message_cb_user_data mcud;
1824 mcud._error = & this->SMESH_Algo::_comment;
1825 mcud._progress = & this->SMESH_Algo::_progress;
1827 _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
1828 context_set_message_callback(ctx, message_cb, &mcud);
1830 /* set the interruption callback */
1831 _compute_canceled = false;
1832 context_set_interrupt_callback(ctx, interrupt_cb, this);
1834 /* create the CAD object we will work on. It is associated to the context ctx. */
1835 cad_t *c = cad_new(ctx);
1836 dcad_t *dcad = dcad_new(c);
1838 FacesWithSizeMap.Clear();
1839 FaceId2SizeMap.clear();
1840 FaceId2ClassAttractor.clear();
1841 FaceIndex2ClassAttractor.clear();
1842 EdgesWithSizeMap.Clear();
1843 EdgeId2SizeMap.clear();
1844 VerticesWithSizeMap.Clear();
1845 VertexId2SizeMap.clear();
1847 /* Now fill the CAD object with data from your CAD
1848 * environement. This is the most complex part of a successfull
1854 cadsurf_session_t *css = cadsurf_session_new(ctx);
1856 // an object that correctly deletes all cadsurf objects at destruction
1857 BLSURF_Cleaner cleaner( ctx,css,c,dcad );
1859 MESSAGE("BEGIN SetParameters");
1860 SetParameters(_hypothesis, css, aShape);
1861 MESSAGE("END SetParameters");
1863 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
1865 haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
1866 helper.SetIsQuadratic( haveQuadraticSubMesh );
1868 // To remove as soon as quadratic mesh is allowed - BEGIN
1869 // GDD: Viscous layer is not allowed with quadratic mesh
1870 if (_haveViscousLayers && haveQuadraticSubMesh ) {
1871 quadraticSubMeshAndViscousLayer = true;
1872 _haveViscousLayers = !haveQuadraticSubMesh;
1873 _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
1874 error(COMPERR_WARNING, _comment);
1876 // To remove as soon as quadratic mesh is allowed - END
1878 // needed to prevent the opencascade memory managmement from freeing things
1879 vector<Handle(Geom2d_Curve)> curves;
1880 vector<Handle(Geom_Surface)> surfaces;
1884 FaceId2PythonSmp.clear();
1885 EdgeId2PythonSmp.clear();
1886 VertexId2PythonSmp.clear();
1888 /****************************************************************************************
1890 *****************************************************************************************/
1892 string bad_end = "return";
1894 TopTools_IndexedMapOfShape _map;
1895 TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
1896 int ienf = _map.Extent();
1898 assert(Py_IsInitialized());
1899 PyGILState_STATE gstate;
1901 string theSizeMapStr;
1903 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1905 TopoDS_Face f = TopoDS::Face(face_iter.Current());
1907 SMESH_subMesh* fSM = aMesh.GetSubMesh( f );
1908 if ( !fSM->IsEmpty() ) continue; // skip already meshed FACE with viscous layers
1910 // make INTERNAL face oriented FORWARD (issue 0020993)
1911 if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
1912 f.Orientation(TopAbs_FORWARD);
1914 iface = fmap.Add(f);
1915 // std::string aFileName = "fmap_face_";
1916 // aFileName.append(val_to_string(iface));
1917 // aFileName.append(".brep");
1918 // BRepTools::Write(f,aFileName.c_str());
1920 surfaces.push_back(BRep_Tool::Surface(f));
1922 /* create an object representing the face for cadsurf */
1923 /* where face_id is an integer identifying the face.
1924 * surf_function is the function that defines the surface
1925 * (For this face, it will be called by cadsurf with your_face_object_ptr
1926 * as last parameter.
1928 #if OCC_VERSION_MAJOR < 7
1929 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
1931 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back().get());
1934 /* by default a face has no tag (color).
1935 The following call sets it to the same value as the Geom module ID : */
1936 const int faceTag = meshDS->ShapeToIndex(f);
1937 cad_face_set_tag(fce, faceTag);
1939 /* Set face orientation (optional if you want a well oriented output mesh)*/
1940 if(f.Orientation() != TopAbs_FORWARD)
1941 cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
1943 cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
1945 if (HasSizeMapOnFace /*&& !use_precad*/) //22903: use_precad seems not to interfere
1947 // -----------------
1949 // -----------------
1950 faceKey = FacesWithSizeMap.FindIndex(f);
1953 if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()) {
1954 MESSAGE("A size map is defined on face :"<<faceKey);
1955 theSizeMapStr = FaceId2SizeMap[faceKey];
1956 // check if function ends with "return"
1957 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1959 // Expr To Python function, verification is performed at validation in GUI
1960 gstate = PyGILState_Ensure();
1961 PyObject * obj = NULL;
1962 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1964 PyObject * func = NULL;
1965 func = PyObject_GetAttrString(main_mod, "f");
1966 FaceId2PythonSmp[iface]=func;
1967 FaceId2SizeMap.erase(faceKey);
1968 PyGILState_Release(gstate);
1971 // Specific size map = Attractor
1972 std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
1974 for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
1975 if (attractor_iter->first == faceKey) {
1976 MESSAGE("Face indice: " << iface);
1977 MESSAGE("Adding attractor");
1979 double xyzCoords[3] = {attractor_iter->second[2],
1980 attractor_iter->second[3],
1981 attractor_iter->second[4]};
1983 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1984 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1985 BRepClass_FaceClassifier scl(f,P,1e-7);
1986 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
1987 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1988 // OCC 6.5.2: scl.Perform() is not bugged anymore
1989 scl.Perform(f, P, 1e-7);
1990 TopAbs_State result = scl.State();
1991 MESSAGE("Position of point on face: "<<result);
1992 if ( result == TopAbs_OUT )
1993 MESSAGE("Point is out of face: node is not created");
1994 if ( result == TopAbs_UNKNOWN )
1995 MESSAGE("Point position on face is unknown: node is not created");
1996 if ( result == TopAbs_ON )
1997 MESSAGE("Point is on border of face: node is not created");
1998 if ( result == TopAbs_IN )
2000 // Point is inside face and not on border
2001 MESSAGE("Point is in face: node is created");
2002 double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
2004 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2005 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2006 cad_point_set_tag(point_p, ienf);
2008 FaceId2AttractorCoords.erase(faceKey);
2012 // -----------------
2014 // -----------------
2015 TId2ClsAttractorVec::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
2016 if (clAttractor_iter != FaceId2ClassAttractor.end()){
2017 MESSAGE("Face indice: " << iface);
2018 MESSAGE("Adding attractor");
2019 std::vector< BLSURFPlugin_Attractor* > & attVec = clAttractor_iter->second;
2020 for ( size_t i = 0; i < attVec.size(); ++i )
2021 if ( !attVec[i]->IsMapBuilt() ) {
2022 std::cout<<"Compute " << theNbAttractors-- << "-th attractor" <<std::endl;
2023 attVec[i]->BuildMap();
2025 FaceIndex2ClassAttractor[iface].swap( attVec );
2026 FaceId2ClassAttractor.erase(clAttractor_iter);
2028 } // if (HasSizeMapOnFace && !use_precad)
2030 // ------------------
2031 // Enforced Vertices
2032 // ------------------
2033 faceKey = FacesWithEnforcedVertices.FindIndex(f);
2034 std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
2035 if (evmIt != FaceId2EnforcedVertexCoords.end()) {
2036 MESSAGE("Some enforced vertices are defined");
2037 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
2038 MESSAGE("Face indice: " << iface);
2039 MESSAGE("Adding enforced vertices");
2040 evl = evmIt->second;
2041 MESSAGE("Number of vertices to add: "<< evl.size());
2042 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
2043 for (; evlIt != evl.end(); ++evlIt) {
2044 BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
2045 xyzCoords.push_back(evlIt->at(2));
2046 xyzCoords.push_back(evlIt->at(3));
2047 xyzCoords.push_back(evlIt->at(4));
2048 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2049 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2050 BRepClass_FaceClassifier scl(f,P,1e-7);
2051 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2052 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2053 // OCC 6.5.2: scl.Perform() is not bugged anymore
2054 scl.Perform(f, P, 1e-7);
2055 TopAbs_State result = scl.State();
2056 MESSAGE("Position of point on face: "<<result);
2057 if ( result == TopAbs_OUT ) {
2058 MESSAGE("Point is out of face: node is not created");
2059 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2060 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2061 // isssue 22783. Do not erase as this point can be IN other face of a group
2062 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2065 if ( result == TopAbs_UNKNOWN ) {
2066 MESSAGE("Point position on face is unknown: node is not created");
2067 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2068 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2069 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2072 if ( result == TopAbs_ON ) {
2073 MESSAGE("Point is on border of face: node is not created");
2074 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2075 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2076 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2079 if ( result == TopAbs_IN )
2081 // Point is inside face and not on border
2082 MESSAGE("Point is in face: node is created");
2083 double uvCoords[2] = {evlIt->at(0),evlIt->at(1)};
2085 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2086 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2088 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
2089 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
2090 !enfCoordsIt->second.empty() )
2092 // to merge nodes of an INTERNAL vertex belonging to several faces
2093 TopoDS_Vertex v = (*enfCoordsIt->second.begin())->vertex;
2094 if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
2095 if ( !v.IsNull() ) {
2096 tag = pmap.Add( v );
2097 SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
2098 vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2099 mergeSubmeshes.insert( vSM->GetSubMeshDS() );
2100 // //if ( tag != pmap.Extent() )
2101 // needMerge = true;
2104 if ( tag == 0 ) tag = ienf;
2105 cad_point_set_tag(point_p, tag);
2108 FaceId2EnforcedVertexCoords.erase(faceKey);
2112 /****************************************************************************************
2114 now create the edges associated to this face
2115 *****************************************************************************************/
2117 for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next())
2119 TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
2120 int ic = emap.FindIndex(e);
2124 // std::string aFileName = "fmap_edge_";
2125 // aFileName.append(val_to_string(ic));
2126 // aFileName.append(".brep");
2127 // BRepTools::Write(e,aFileName.c_str());
2130 curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
2132 if (HasSizeMapOnEdge){
2133 edgeKey = EdgesWithSizeMap.FindIndex(e);
2134 if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
2135 MESSAGE("Sizemap defined on edge with index " << edgeKey);
2136 theSizeMapStr = EdgeId2SizeMap[edgeKey];
2137 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2139 // Expr To Python function, verification is performed at validation in GUI
2140 gstate = PyGILState_Ensure();
2141 PyObject * obj = NULL;
2142 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2144 PyObject * func = NULL;
2145 func = PyObject_GetAttrString(main_mod, "f");
2146 EdgeId2PythonSmp[ic]=func;
2147 EdgeId2SizeMap.erase(edgeKey);
2148 PyGILState_Release(gstate);
2151 /* data of nodes existing on the edge */
2152 StdMeshers_FaceSidePtr nodeData;
2153 SMESH_subMesh* sm = aMesh.GetSubMesh( e );
2154 if ( !sm->IsEmpty() )
2156 // SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
2157 // /*complexFirst=*/false);
2158 // while ( subsmIt->more() )
2159 // edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
2160 edgeSubmeshes.insert( sm->GetSubMeshDS() );
2162 nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
2163 /*ignoreMedium=*/haveQuadraticSubMesh));
2164 if ( nodeData->MissVertexNode() )
2165 return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
2167 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2168 if ( !nodeDataVec.empty() )
2170 if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
2172 nodeData->Reverse();
2173 nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
2175 // tmin and tmax can change in case of viscous layer on an adjacent edge
2176 tmin = nodeDataVec.front().param;
2177 tmax = nodeDataVec.back().param;
2181 cout << "---------------- Invalid nodeData" << endl;
2186 /* attach the edge to the current cadsurf face */
2187 #if OCC_VERSION_MAJOR < 7
2188 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
2190 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back().get());
2193 /* by default an edge has no tag (color).
2194 The following call sets it to the same value as the edge_id : */
2195 cad_edge_set_tag(edg, ic);
2197 /* by default, an edge does not necessalry appear in the resulting mesh,
2198 unless the following property is set :
2200 cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2202 /* by default an edge is a boundary edge */
2203 if (e.Orientation() == TopAbs_INTERNAL)
2204 cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2206 // pass existing nodes of sub-meshes to MG-CADSurf
2209 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2210 const int nbNodes = nodeDataVec.size();
2212 dcad_edge_discretization_t *dedge;
2213 dcad_get_edge_discretization(dcad, edg, &dedge);
2214 dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2216 // cout << endl << " EDGE " << ic << endl;
2217 // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2218 for ( int iN = 0; iN < nbNodes; ++iN )
2220 const UVPtStruct& nData = nodeDataVec[ iN ];
2221 double t = nData.param;
2222 real uv[2] = { nData.u, nData.v };
2223 SMESH_TNodeXYZ nXYZ( nData.node );
2224 // cout << "\tt = " << t
2225 // << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2226 // << "\t u = " << nData.param
2227 // << "\t ID = " << nData.node->GetID() << endl;
2228 dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ._xyz );
2230 dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2233 /****************************************************************************************
2235 *****************************************************************************************/
2239 gp_Pnt2d e0 = curves.back()->Value(tmin);
2240 gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
2241 Standard_Real d1=0,d2=0;
2244 for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
2245 TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
2249 d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2252 d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2254 *ip = pmap.FindIndex(v);
2257 // SMESH_subMesh* sm = aMesh.GetSubMesh(v);
2258 // if ( sm->IsMeshComputed() )
2259 // edgeSubmeshes.insert( sm->GetSubMeshDS() );
2262 // std::string aFileName = "fmap_vertex_";
2263 // aFileName.append(val_to_string(*ip));
2264 // aFileName.append(".brep");
2265 // BRepTools::Write(v,aFileName.c_str());
2267 if (HasSizeMapOnVertex){
2268 vertexKey = VerticesWithSizeMap.FindIndex(v);
2269 if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
2270 theSizeMapStr = VertexId2SizeMap[vertexKey];
2271 //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
2272 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2274 // Expr To Python function, verification is performed at validation in GUI
2275 gstate = PyGILState_Ensure();
2276 PyObject * obj = NULL;
2277 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2279 PyObject * func = NULL;
2280 func = PyObject_GetAttrString(main_mod, "f");
2281 VertexId2PythonSmp[*ip]=func;
2282 VertexId2SizeMap.erase(vertexKey); // do not erase if using a vector
2283 PyGILState_Release(gstate);
2288 // should not happen
2289 MESSAGE("An edge does not have 2 extremities.");
2292 // This defines the curves extremity connectivity
2293 cad_edge_set_extremities(edg, ip1, ip2);
2294 /* set the tag (color) to the same value as the extremity id : */
2295 cad_edge_set_extremities_tag(edg, ip1, ip2);
2298 cad_edge_set_extremities(edg, ip2, ip1);
2299 cad_edge_set_extremities_tag(edg, ip2, ip1);
2305 // Clear mesh from already meshed edges if possible else
2306 // remember that merge is needed
2307 TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2308 for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2310 SMESHDS_SubMesh* smDS = *smIt;
2311 if ( !smDS ) continue;
2312 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2315 const SMDS_MeshNode* n = nIt->next();
2316 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2318 needMerge = true; // to correctly sew with viscous mesh
2319 // add existing medium nodes to helper
2320 if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2322 SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2323 while ( edgeIt->more() )
2324 helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2329 if ( allowSubMeshClearing )
2331 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2332 while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), 0 );
2333 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2334 while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), 0 );
2343 ///////////////////////
2345 ///////////////////////
2347 MESSAGE("BEFORE PERIODICITY");
2348 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2349 if (! _preCadFacesIDsPeriodicityVector.empty()) {
2350 MESSAGE("INTO PRECAD FACES PERIODICITY");
2351 for (std::size_t i=0; i < _preCadFacesIDsPeriodicityVector.size(); i++){
2352 std::vector<int> theFace1_ids = _preCadFacesIDsPeriodicityVector[i].shape1IDs;
2353 std::vector<int> theFace2_ids = _preCadFacesIDsPeriodicityVector[i].shape2IDs;
2354 int* theFace1_ids_c = &theFace1_ids[0];
2355 int* theFace2_ids_c = &theFace2_ids[0];
2356 std::ostringstream o;
2357 o << "_preCadFacesIDsPeriodicityVector[" << i << "] = [";
2358 for (std::size_t j=0; j < theFace1_ids.size(); j++)
2359 o << theFace1_ids[j] << ", ";
2361 for (std::size_t j=0; j < theFace2_ids.size(); j++)
2362 o << theFace2_ids[j] << ", ";
2365 MESSAGE("theFace1_ids.size(): " << theFace1_ids.size());
2366 MESSAGE("theFace2_ids.size(): " << theFace2_ids.size());
2367 if (_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2369 // If no source points, call peridoicity without transformation function
2370 MESSAGE("periodicity without transformation function");
2371 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2372 status = cad_add_face_multiple_periodicity_with_transformation_function(c, theFace1_ids_c, theFace1_ids.size(),
2373 theFace2_ids_c, theFace2_ids.size(), periodicity_transformation, NULL);
2374 if(status != STATUS_OK)
2375 cout << "cad_add_face_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2379 // get the transformation vertices
2380 MESSAGE("periodicity with transformation vertices");
2381 double* theSourceVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2382 double* theTargetVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2383 int nbSourceVertices = _preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2384 int nbTargetVertices = _preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2386 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2388 status = cad_add_face_multiple_periodicity_with_transformation_function_by_points(c, theFace1_ids_c, theFace1_ids.size(),
2389 theFace2_ids_c, theFace2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2390 if(status != STATUS_OK)
2391 cout << "cad_add_face_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2395 MESSAGE("END PRECAD FACES PERIODICITY");
2398 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
2399 if (! _preCadEdgesIDsPeriodicityVector.empty()) {
2400 MESSAGE("INTO PRECAD EDGES PERIODICITY");
2401 for (std::size_t i=0; i < _preCadEdgesIDsPeriodicityVector.size(); i++){
2402 std::vector<int> theEdge1_ids = _preCadEdgesIDsPeriodicityVector[i].shape1IDs;
2403 std::vector<int> theEdge2_ids = _preCadEdgesIDsPeriodicityVector[i].shape2IDs;
2404 // Use the address of the first element of the vector to initialise the array
2405 int* theEdge1_ids_c = &theEdge1_ids[0];
2406 int* theEdge2_ids_c = &theEdge2_ids[0];
2408 std::ostringstream o;
2409 o << "_preCadEdgesIDsPeriodicityVector[" << i << "] = [";
2410 for (std::size_t j=0; j < theEdge1_ids.size(); j++)
2411 o << theEdge1_ids[j] << ", ";
2413 for (std::size_t j=0; j < theEdge2_ids.size(); j++)
2414 o << theEdge2_ids[j] << ", ";
2417 MESSAGE("theEdge1_ids.size(): " << theEdge1_ids.size());
2418 MESSAGE("theEdge2_ids.size(): " << theEdge2_ids.size());
2420 if (_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2422 // If no source points, call peridoicity without transformation function
2423 MESSAGE("periodicity without transformation function");
2424 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2425 status = cad_add_edge_multiple_periodicity_with_transformation_function(c, theEdge1_ids_c, theEdge1_ids.size(),
2426 theEdge2_ids_c, theEdge2_ids.size(), periodicity_transformation, NULL);
2427 if(status != STATUS_OK)
2428 cout << "cad_add_edge_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2432 // get the transformation vertices
2433 MESSAGE("periodicity with transformation vertices");
2434 double* theSourceVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2435 double* theTargetVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2436 int nbSourceVertices = _preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2437 int nbTargetVertices = _preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2439 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2441 status = cad_add_edge_multiple_periodicity_with_transformation_function_by_points(c, theEdge1_ids_c, theEdge1_ids.size(),
2442 theEdge2_ids_c, theEdge2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2443 if(status != STATUS_OK)
2444 cout << "cad_add_edge_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2446 MESSAGE("cad_add_edge_multiple_periodicity_with_transformation_function_by_points succeeded.\n");
2450 MESSAGE("END PRECAD EDGES PERIODICITY");
2454 // TODO: be able to use a mesh in input.
2455 // See imsh usage in Products/templates/mg-cadsurf_template_common.cpp
2456 // => cadsurf_set_mesh
2458 // Use the original dcad
2459 cadsurf_set_dcad(css, dcad);
2461 // Use the original cad
2462 cadsurf_set_cad(css, c);
2464 std::cout << std::endl;
2465 std::cout << "Beginning of Surface Mesh generation" << std::endl;
2466 std::cout << std::endl;
2471 status = cadsurf_compute_mesh(css);
2474 catch ( std::exception& exc ) {
2475 _comment += exc.what();
2477 catch (Standard_Failure& ex) {
2478 _comment += ex.DynamicType()->Name();
2479 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2481 _comment += ex.GetMessageString();
2485 if ( _comment.empty() )
2486 _comment = "Exception in cadsurf_compute_mesh()";
2489 std::cout << std::endl;
2490 std::cout << "End of Surface Mesh generation" << std::endl;
2491 std::cout << std::endl;
2494 cadsurf_get_mesh(css, &msh);
2496 /* release the mesh object */
2497 cadsurf_regain_mesh(css, msh);
2498 return error(_comment);
2501 std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2503 GMFFileName = _hypothesis->GetGMFFile();
2504 if (GMFFileName != "") {
2505 bool asciiFound = (GMFFileName.find(".mesh", GMFFileName.length()-5) != std::string::npos);
2506 bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2507 if (!asciiFound && !binaryFound)
2508 GMFFileName.append(".mesh");
2509 mesh_write_mesh(msh, GMFFileName.c_str());
2512 /* retrieve mesh data (see meshgems/mesh.h) */
2513 integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2514 integer *evedg, *evtri, *evquad, *tags_buff, type;
2517 mesh_get_vertex_count(msh, &nv);
2518 mesh_get_edge_count(msh, &ne);
2519 mesh_get_triangle_count(msh, &nt);
2520 mesh_get_quadrangle_count(msh, &nq);
2522 evedg = (integer *)mesh_calloc_generic_buffer(msh);
2523 evtri = (integer *)mesh_calloc_generic_buffer(msh);
2524 evquad = (integer *)mesh_calloc_generic_buffer(msh);
2525 tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
2527 std::vector<const SMDS_MeshNode*> nodes(nv+1);
2528 std::vector<bool> tags(nv+1);
2530 /* enumerated vertices */
2531 for(int iv=1;iv<=nv;iv++) {
2532 mesh_get_vertex_coordinates(msh, iv, xyz);
2533 mesh_get_vertex_tag(msh, iv, &tag);
2534 // Issue 0020656. Use vertex coordinates
2536 if ( tag > 0 && tag <= pmap.Extent() ) {
2537 TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2538 double tol = BRep_Tool::Tolerance( v );
2539 gp_Pnt p = BRep_Tool::Pnt( v );
2540 if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
2541 xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2543 tag = 0; // enforced or attracted vertex
2544 nodes[iv] = SMESH_Algo::VertexNode( v, meshDS );
2547 nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2549 // Create group of enforced vertices if requested
2550 BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2552 projVertex.push_back((double)xyz[0]);
2553 projVertex.push_back((double)xyz[1]);
2554 projVertex.push_back((double)xyz[2]);
2555 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
2556 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
2557 MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
2558 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
2559 BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
2560 for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
2561 currentEnfVertex = (*enfListIt);
2562 if (currentEnfVertex->grpName != "") {
2563 bool groupDone = false;
2564 SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
2565 MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
2566 MESSAGE("Parsing the groups of the mesh");
2567 while (grIt->more()) {
2568 SMESH_Group * group = grIt->next();
2569 if ( !group ) continue;
2570 MESSAGE("Group: " << group->GetName());
2571 SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2572 if ( !groupDS ) continue;
2573 MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
2574 MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
2575 MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
2576 if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
2577 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
2578 aGroupDS->SMDSGroup().Add(nodes[iv]);
2579 MESSAGE("Node ID: " << nodes[iv]->GetID());
2580 // How can I inform the hypothesis ?
2581 // _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
2583 MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
2590 SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
2591 aGroup->SetName( currentEnfVertex->grpName.c_str() );
2592 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2593 aGroupDS->SMDSGroup().Add(nodes[iv]);
2594 MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
2598 throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
2601 MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
2605 // internal points are tagged to zero
2606 if(tag > 0 && tag <= pmap.Extent() ){
2607 meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2614 /* enumerate edges */
2615 for(int it=1;it<=ne;it++) {
2617 mesh_get_edge_vertices(msh, it, vtx);
2618 mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2619 mesh_get_edge_tag(msh, it, &tag);
2621 // If PreCAD performed some cleaning operations (remove tiny edges,
2622 // merge edges ...) an output tag can indeed represent several original tags.
2623 // Get the initial tags corresponding to the output tag and redefine the tag as
2624 // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2625 mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2627 tag=tags_buff[nb_tag-1];
2628 if ( tag < 1 || tag > emap.Extent() )
2630 std::cerr << "MG-CADSurf BUG:::: Edge tag " << tag
2631 << " does not point to a CAD edge (nb edges " << emap.Extent() << ")" << std::endl;
2635 Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2636 tags[vtx[0]] = false;
2639 Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2640 tags[vtx[1]] = false;
2642 if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2644 if (tags[evedg[0]]) {
2645 Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2646 tags[evedg[0]] = false;
2648 edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2651 edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2653 meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2656 /* enumerate triangles */
2657 for(int it=1;it<=nt;it++) {
2659 mesh_get_triangle_vertices(msh, it, vtx);
2660 mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2661 mesh_get_triangle_tag(msh, it, &tag);
2663 meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2664 tags[vtx[0]] = false;
2667 meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2668 tags[vtx[1]] = false;
2671 meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2672 tags[vtx[2]] = false;
2674 if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2675 // QUADRATIC TRIANGLE
2676 if (tags[evtri[0]]) {
2677 meshDS->SetNodeOnFace(nodes[evtri[0]], tag);
2678 tags[evtri[0]] = false;
2680 if (tags[evtri[1]]) {
2681 meshDS->SetNodeOnFace(nodes[evtri[1]], tag);
2682 tags[evtri[1]] = false;
2684 if (tags[evtri[2]]) {
2685 meshDS->SetNodeOnFace(nodes[evtri[2]], tag);
2686 tags[evtri[2]] = false;
2688 tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2689 nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2692 tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2694 meshDS->SetMeshElementOnShape(tri, tag);
2697 /* enumerate quadrangles */
2698 for(int it=1;it<=nq;it++) {
2699 SMDS_MeshFace* quad;
2700 mesh_get_quadrangle_vertices(msh, it, vtx);
2701 mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2702 mesh_get_quadrangle_tag(msh, it, &tag);
2704 meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2705 tags[vtx[0]] = false;
2708 meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2709 tags[vtx[1]] = false;
2712 meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2713 tags[vtx[2]] = false;
2716 meshDS->SetNodeOnFace(nodes[vtx[3]], tag);
2717 tags[vtx[3]] = false;
2719 if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
2720 // QUADRATIC QUADRANGLE
2721 std::cout << "This is a quadratic quadrangle" << std::endl;
2722 if (tags[evquad[0]]) {
2723 meshDS->SetNodeOnFace(nodes[evquad[0]], tag);
2724 tags[evquad[0]] = false;
2726 if (tags[evquad[1]]) {
2727 meshDS->SetNodeOnFace(nodes[evquad[1]], tag);
2728 tags[evquad[1]] = false;
2730 if (tags[evquad[2]]) {
2731 meshDS->SetNodeOnFace(nodes[evquad[2]], tag);
2732 tags[evquad[2]] = false;
2734 if (tags[evquad[3]]) {
2735 meshDS->SetNodeOnFace(nodes[evquad[3]], tag);
2736 tags[evquad[3]] = false;
2738 if (tags[evquad[4]]) {
2739 meshDS->SetNodeOnFace(nodes[evquad[4]], tag);
2740 tags[evquad[4]] = false;
2742 quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
2743 nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
2747 quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
2749 meshDS->SetMeshElementOnShape(quad, tag);
2752 /* release the mesh object, the rest is released by cleaner */
2753 cadsurf_regain_mesh(css, msh);
2756 // Remove free nodes that can appear e.g. if "remove tiny edges"(IPAL53235)
2757 for(int iv=1;iv<=nv;iv++)
2758 if ( nodes[iv] && nodes[iv]->NbInverseElements() == 0 )
2759 meshDS->RemoveFreeNode( nodes[iv], 0, /*fromGroups=*/false );
2762 if ( needMerge ) // sew mesh computed by MG-CADSurf with pre-existing mesh
2764 SMESH_MeshEditor editor( &aMesh );
2765 SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
2766 TIDSortedElemSet segementsOnEdge;
2767 TSubMeshSet::iterator smIt;
2768 SMESHDS_SubMesh* smDS;
2770 // merge nodes on EDGE's with ones computed by MG-CADSurf
2771 for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
2773 if (! (smDS = *smIt) ) continue;
2774 getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
2776 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2777 while ( segIt->more() )
2778 segementsOnEdge.insert( segIt->next() );
2781 editor.MergeNodes( nodeGroupsToMerge );
2784 SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
2785 editor.FindEqualElements( segementsOnEdge, equalSegments );
2786 editor.MergeElements( equalSegments );
2788 // remove excess segments created on the boundary of viscous layers
2789 const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
2790 for ( int i = 1; i <= emap.Extent(); ++i )
2792 if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
2794 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2795 while ( segIt->more() )
2797 const SMDS_MeshElement* seg = segIt->next();
2798 if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
2799 seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
2800 meshDS->RemoveFreeElement( seg, smDS );
2807 // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
2808 for (int i = 1; i <= emap.Extent(); i++)
2809 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
2810 sm->SetIsAlwaysComputed( true );
2811 for (int i = 1; i <= pmap.Extent(); i++)
2812 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
2813 if ( !sm->IsMeshComputed() )
2814 sm->SetIsAlwaysComputed( true );
2816 // Set error to FACE's w/o elements
2817 SMESH_ComputeErrorName err = COMPERR_ALGO_FAILED;
2818 if ( _comment.empty() && status == STATUS_OK )
2820 err = COMPERR_WARNING;
2821 _comment = "No mesh elements assigned to a face";
2823 bool badFaceFound = false;
2824 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
2826 TopoDS_Face f = TopoDS::Face(face_iter.Current());
2827 SMESH_subMesh* sm = aMesh.GetSubMesh( f );
2828 if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
2830 sm->GetComputeError().reset( new SMESH_ComputeError( err, _comment, this ));
2831 badFaceFound = true;
2834 if ( err == COMPERR_WARNING )
2838 if ( status != STATUS_OK && !badFaceFound ) {
2842 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
2844 if ( oldFEFlags > 0 )
2845 feenableexcept( oldFEFlags );
2846 feclearexcept( FE_ALL_EXCEPT );
2850 std::cout << "FacesWithSizeMap" << std::endl;
2851 FacesWithSizeMap.Statistics(std::cout);
2852 std::cout << "EdgesWithSizeMap" << std::endl;
2853 EdgesWithSizeMap.Statistics(std::cout);
2854 std::cout << "VerticesWithSizeMap" << std::endl;
2855 VerticesWithSizeMap.Statistics(std::cout);
2856 std::cout << "FacesWithEnforcedVertices" << std::endl;
2857 FacesWithEnforcedVertices.Statistics(std::cout);
2860 MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
2861 return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
2864 //================================================================================
2866 * \brief Terminates computation
2868 //================================================================================
2870 void BLSURFPlugin_BLSURF::CancelCompute()
2872 _compute_canceled = true;
2875 //=============================================================================
2879 //=============================================================================
2881 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, const SMDS_MeshNode* node, const TopoDS_Shape& ed) {
2882 const TopoDS_Edge edge = TopoDS::Edge(ed);
2884 gp_Pnt pnt(node->X(), node->Y(), node->Z());
2886 Standard_Real p0 = 0.0;
2887 Standard_Real p1 = 1.0;
2888 TopLoc_Location loc;
2889 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
2890 if ( curve.IsNull() )
2892 // issue 22499. Node at a sphere apex
2893 meshDS->SetNodeOnEdge(node, edge, p0);
2897 if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
2898 GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
2901 if ( proj.NbPoints() > 0 )
2903 pa = (double)proj.LowerDistanceParameter();
2904 // Issue 0020656. Move node if it is too far from edge
2905 gp_Pnt curve_pnt = curve->Value( pa );
2906 double dist2 = pnt.SquareDistance( curve_pnt );
2907 double tol = BRep_Tool::Tolerance( edge );
2908 if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
2910 curve_pnt.Transform( loc );
2911 meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
2915 meshDS->SetNodeOnEdge(node, edge, pa);
2918 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
2920 * NOTE : if when your CAD systems evaluates second
2921 * order derivatives it also computes first order derivatives and
2922 * function evaluation, you can optimize this example by making only
2923 * one CAD call and filling the necessary uv, dt, dtt arrays.
2925 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
2927 /* t is given. It contains the t (time) 1D parametric coordintaes
2928 of the point PreCAD/MG-CADSurf is querying on the curve */
2930 /* user_data identifies the edge PreCAD/MG-CADSurf is querying
2931 * (see cad_edge_new later in this example) */
2932 const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
2935 /* MG-CADSurf is querying the function evaluation */
2938 uv[0]=P.X(); uv[1]=P.Y();
2942 /* query for the first order derivatives */
2945 dt[0]=V1.X(); dt[1]=V1.Y();
2949 /* query for the second order derivatives */
2952 dtt[0]=V2.X(); dtt[1]=V2.Y();
2958 /* Surface definition function.
2959 * See cad_surf_t in file meshgems/cad.h for more information.
2960 * NOTE : if when your CAD systems evaluates second order derivatives it also
2961 * computes first order derivatives and function evaluation, you can optimize
2962 * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
2965 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
2966 real *duu, real *duv, real *dvv, void *user_data)
2968 /* uv[2] is given. It contains the u,v coordinates of the point
2969 * PreCAD/MG-CADSurf is querying on the surface */
2971 /* user_data identifies the face PreCAD/MG-CADSurf is querying (see
2972 * cad_face_new later in this example)*/
2973 const Geom_Surface* geometry = (const Geom_Surface*) user_data;
2977 P=geometry->Value(uv[0],uv[1]); // S.D0(U,V,P);
2978 xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
2985 geometry->D1(uv[0],uv[1],P,D1U,D1V);
2986 du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
2987 dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
2990 if(duu && duv && dvv){
2994 gp_Vec D2U,D2V,D2UV;
2996 geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
2997 duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
2998 duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
2999 dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
3006 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
3008 TId2ClsAttractorVec::iterator f2attVec;
3009 if (FaceId2PythonSmp.count(face_id) != 0){
3010 assert(Py_IsInitialized());
3011 PyGILState_STATE gstate;
3012 gstate = PyGILState_Ensure();
3013 PyObject* pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
3015 if ( pyresult != NULL) {
3016 result = PyFloat_AsDouble(pyresult);
3017 Py_DECREF(pyresult);
3022 string err_description="";
3023 PyObject* new_stderr = newPyStdOut(err_description);
3024 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3025 Py_INCREF(old_stderr);
3026 PySys_SetObject((char*)"stderr", new_stderr);
3028 PySys_SetObject((char*)"stderr", old_stderr);
3029 Py_DECREF(new_stderr);
3030 MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
3031 result = *((real*)user_data);
3034 PyGILState_Release(gstate);
3036 else if (( f2attVec = FaceIndex2ClassAttractor.find(face_id)) != FaceIndex2ClassAttractor.end() && !f2attVec->second.empty()){
3037 // MESSAGE("attractor used on face :"<<face_id)
3038 // MESSAGE("List of attractor is not empty")
3039 // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
3042 std::vector< BLSURFPlugin_Attractor* > & attVec = f2attVec->second;
3043 for ( size_t i = 0; i < attVec.size(); ++i )
3045 //result += attVec[i]->GetSize(uv[0],uv[1]);
3046 result = Min( result, attVec[i]->GetSize(uv[0],uv[1]));
3048 //*size = result / attVec.size(); // mean of sizes defined by all attractors
3052 // MESSAGE("List of attractor is empty !!!")
3053 *size = *((real*)user_data);
3055 // std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
3059 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
3061 if (EdgeId2PythonSmp.count(edge_id) != 0){
3062 assert(Py_IsInitialized());
3063 PyGILState_STATE gstate;
3064 gstate = PyGILState_Ensure();
3065 PyObject* pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
3067 if ( pyresult != NULL) {
3068 result = PyFloat_AsDouble(pyresult);
3069 Py_DECREF(pyresult);
3074 string err_description="";
3075 PyObject* new_stderr = newPyStdOut(err_description);
3076 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3077 Py_INCREF(old_stderr);
3078 PySys_SetObject((char*)"stderr", new_stderr);
3080 PySys_SetObject((char*)"stderr", old_stderr);
3081 Py_DECREF(new_stderr);
3082 MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
3083 result = *((real*)user_data);
3086 PyGILState_Release(gstate);
3089 *size = *((real*)user_data);
3094 status_t size_on_vertex(integer point_id, real *size, void *user_data)
3096 if (VertexId2PythonSmp.count(point_id) != 0){
3097 assert(Py_IsInitialized());
3098 PyGILState_STATE gstate;
3099 gstate = PyGILState_Ensure();
3100 PyObject* pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
3102 if ( pyresult != NULL) {
3103 result = PyFloat_AsDouble(pyresult);
3104 Py_DECREF(pyresult);
3109 string err_description="";
3110 PyObject* new_stderr = newPyStdOut(err_description);
3111 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3112 Py_INCREF(old_stderr);
3113 PySys_SetObject((char*)"stderr", new_stderr);
3115 PySys_SetObject((char*)"stderr", old_stderr);
3116 Py_DECREF(new_stderr);
3117 MESSAGE("Can't evaluate f()" << " error is " << err_description);
3118 result = *((real*)user_data);
3121 PyGILState_Release(gstate);
3124 *size = *((real*)user_data);
3130 * The following function will be called for PreCAD/MG-CADSurf message
3131 * printing. See context_set_message_callback (later in this
3132 * template) for how to set user_data.
3134 status_t message_cb(message_t *msg, void *user_data)
3136 integer errnumber = 0;
3138 message_get_number(msg, &errnumber);
3139 message_get_description(msg, &desc);
3141 message_cb_user_data * mcud = (message_cb_user_data*)user_data;
3142 // Get all the error message and some warning messages related to license and periodicity
3143 if ( errnumber < 0 ||
3144 err.find("license" ) != string::npos ||
3145 err.find("periodicity") != string::npos )
3147 // remove ^A from the tail
3148 int len = strlen( desc );
3149 while (len > 0 && desc[len-1] != '\n')
3151 mcud->_error->append( desc, len );
3154 if ( errnumber == 3009001 )
3155 * mcud->_progress = atof( desc + 11 ) / 100.;
3156 if ( mcud->_verbosity > 0 )
3157 std::cout << desc << std::endl;
3162 /* This is the interrupt callback. PreCAD/MG-CADSurf will call this
3163 * function regularily. See the file meshgems/interrupt.h
3165 status_t interrupt_cb(integer *interrupt_status, void *user_data)
3167 integer you_want_to_continue = 1;
3168 BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
3169 you_want_to_continue = !tmp->computeCanceled();
3171 if(you_want_to_continue)
3173 *interrupt_status = INTERRUPT_CONTINUE;
3176 else /* you want to stop MG-CADSurf */
3178 *interrupt_status = INTERRUPT_STOP;
3179 return STATUS_ERROR;
3183 //=============================================================================
3187 //=============================================================================
3188 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
3189 const TopoDS_Shape& aShape,
3190 MapShapeNbElems& aResMap)
3192 double diagonal = aMesh.GetShapeDiagonalSize();
3193 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
3194 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
3195 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
3196 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
3197 //int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
3198 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
3199 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
3201 _physicalMesh = (int) _hypothesis->GetPhysicalMesh();
3202 _phySizeRel = _hypothesis->IsPhySizeRel();
3203 if ( _hypothesis->GetPhySize() > 0)
3204 _phySize = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
3205 //_geometricMesh = (int) hyp->GetGeometricMesh();
3206 if (_hypothesis->GetAngleMesh() > 0)
3207 _angleMesh = _hypothesis->GetAngleMesh();
3208 _quadAllowed = _hypothesis->GetQuadAllowed();
3210 //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
3211 // GetDefaultPhySize() sometimes leads to computation failure
3212 _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
3213 MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
3216 bool IsQuadratic = _quadraticMesh;
3221 TopTools_DataMapOfShapeInteger EdgesMap;
3222 double fullLen = 0.0;
3223 double fullNbSeg = 0;
3224 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
3225 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3226 if( EdgesMap.IsBound(E) )
3228 SMESH_subMesh *sm = aMesh.GetSubMesh(E);
3229 double aLen = SMESH_Algo::EdgeLength(E);
3232 if(_physicalMesh==1) {
3233 nb1d = (int)( aLen/_phySize + 1 );
3238 Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
3239 double fullAng = 0.0;
3240 double dp = (l-f)/200;
3245 for(int j=2; j<=200; j++) {
3248 fullAng += fabs(V1.Angle(V2));
3252 nb1d = (int)( fullAng/_angleMesh + 1 );
3255 std::vector<int> aVec(SMDSEntity_Last);
3256 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3257 if( IsQuadratic > 0 ) {
3258 aVec[SMDSEntity_Node] = 2*nb1d - 1;
3259 aVec[SMDSEntity_Quad_Edge] = nb1d;
3262 aVec[SMDSEntity_Node] = nb1d - 1;
3263 aVec[SMDSEntity_Edge] = nb1d;
3265 aResMap.insert(std::make_pair(sm,aVec));
3266 EdgesMap.Bind(E,nb1d);
3268 double ELen = fullLen/fullNbSeg;
3272 // try to evaluate as in MEFISTO
3273 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
3274 TopoDS_Face F = TopoDS::Face( exp.Current() );
3275 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
3277 BRepGProp::SurfaceProperties(F,G);
3278 double anArea = G.Mass();
3280 std::vector<int> nb1dVec;
3281 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
3282 int nbSeg = EdgesMap.Find(exp1.Current());
3284 nb1dVec.push_back( nbSeg );
3287 int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
3288 int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
3291 if ( nb1dVec.size() == 4 ) // quadrangle geom face
3293 int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
3295 nbNodes = (n1 + 1) * (n2 + 1);
3300 nbTria = nbQuad = nbTria / 3 + 1;
3303 std::vector<int> aVec(SMDSEntity_Last,0);
3305 int nb1d_in = (nbTria*3 - nb1d) / 2;
3306 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3307 aVec[SMDSEntity_Quad_Triangle] = nbTria;
3308 aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3311 aVec[SMDSEntity_Node] = nbNodes;
3312 aVec[SMDSEntity_Triangle] = nbTria;
3313 aVec[SMDSEntity_Quadrangle] = nbQuad;
3315 aResMap.insert(std::make_pair(sm,aVec));
3322 BRepGProp::VolumeProperties(aShape,G);
3323 double aVolume = G.Mass();
3324 double tetrVol = 0.1179*ELen*ELen*ELen;
3325 int nbVols = int(aVolume/tetrVol);
3326 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3327 std::vector<int> aVec(SMDSEntity_Last);
3328 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3330 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3331 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3334 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3335 aVec[SMDSEntity_Tetra] = nbVols;
3337 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3338 aResMap.insert(std::make_pair(sm,aVec));