1 // Copyright (C) 2004-2022 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
20 //=============================================================================
21 // File : GHS3DPlugin_GHS3D.cxx
23 // Author : Edward AGAPOV, modified by Lioka RAZAFINDRAZAKA (CEA) 09/02/2007
25 //=============================================================================
27 #include "GHS3DPlugin_GHS3D.hxx"
28 #include "GHS3DPlugin_Hypothesis.hxx"
29 #include "MG_Tetra_API.hxx"
31 #include <SMDS_FaceOfNodes.hxx>
32 #include <SMDS_LinearEdge.hxx>
33 #include <SMDS_MeshElement.hxx>
34 #include <SMDS_MeshNode.hxx>
35 #include <SMDS_VolumeOfNodes.hxx>
36 #include <SMESHDS_Group.hxx>
37 #include <SMESHDS_Mesh.hxx>
38 #include <SMESH_Comment.hxx>
39 #include <SMESH_File.hxx>
40 #include <SMESH_Group.hxx>
41 #include <SMESH_HypoFilter.hxx>
42 #include <SMESH_Mesh.hxx>
43 #include <SMESH_MeshAlgos.hxx>
44 #include <SMESH_MeshEditor.hxx>
45 #include <SMESH_MesherHelper.hxx>
46 #include <SMESH_OctreeNode.hxx>
47 #include <SMESH_subMeshEventListener.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers.hxx>
51 #include <BRepAdaptor_Surface.hxx>
52 #include <BRepBndLib.hxx>
53 #include <BRepBuilderAPI_MakeVertex.hxx>
54 #include <BRepClass3d.hxx>
55 #include <BRepClass3d_SolidClassifier.hxx>
56 #include <BRepExtrema_DistShapeShape.hxx>
57 #include <BRepGProp.hxx>
58 #include <BRepTools.hxx>
59 #include <BRep_Tool.hxx>
60 #include <Bnd_Box.hxx>
61 #include <GProp_GProps.hxx>
62 #include <GeomAPI_ProjectPointOnSurf.hxx>
63 #include <Precision.hxx>
64 #include <Standard_ErrorHandler.hxx>
65 #include <Standard_Failure.hxx>
66 #include <Standard_ProgramError.hxx>
68 #include <TopExp_Explorer.hxx>
69 #include <TopTools_IndexedMapOfShape.hxx>
70 #include <TopTools_ListIteratorOfListOfShape.hxx>
71 #include <TopTools_MapOfShape.hxx>
73 #include <TopoDS_Shell.hxx>
74 #include <TopoDS_Solid.hxx>
76 #include <Basics_Utils.hxx>
77 #include <utilities.h>
86 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
92 // flags returning state of enforced entities, returned from writeGMFFile
93 enum InvalidEnforcedFlags { FLAG_BAD_ENF_VERT = 1,
94 FLAG_BAD_ENF_NODE = 2,
95 FLAG_BAD_ENF_EDGE = 4,
98 static std::string flagsToErrorStr( int anInvalidEnforcedFlags )
101 if ( anInvalidEnforcedFlags != 0 )
103 if ( anInvalidEnforcedFlags & FLAG_BAD_ENF_VERT )
104 str = "There are enforced vertices incorrectly defined.\n";
105 if ( anInvalidEnforcedFlags & FLAG_BAD_ENF_NODE )
106 str += "There are enforced nodes incorrectly defined.\n";
107 if ( anInvalidEnforcedFlags & FLAG_BAD_ENF_EDGE )
108 str += "There are enforced edge incorrectly defined.\n";
109 if ( anInvalidEnforcedFlags & FLAG_BAD_ENF_TRIA )
110 str += "There are enforced triangles incorrectly defined.\n";
115 typedef const list<const SMDS_MeshFace*> TTriaList;
117 static const char theDomainGroupNamePrefix[] = "Domain_";
119 static void removeFile( const TCollection_AsciiString& fileName )
122 SMESH_File( fileName.ToCString() ).remove();
125 MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
129 //=============================================================================
133 //=============================================================================
135 GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D(int hypId, SMESH_Gen* gen)
136 : SMESH_3D_Algo(hypId, gen), _isLibUsed( false )
139 _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
140 _onlyUnaryInput = false; // Compute() will be called on a compound of solids
143 _compatibleHypothesis.push_back( GHS3DPlugin_Hypothesis::GetHypType());
144 _compatibleHypothesis.push_back( StdMeshers_ViscousLayers::GetHypType() );
145 _requireShape = false; // can work without shape
147 _computeCanceled = false;
148 _progressAdvance = 1e-4;
151 //=============================================================================
155 //=============================================================================
157 GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D()
161 //=============================================================================
165 //=============================================================================
167 bool GHS3DPlugin_GHS3D::CheckHypothesis ( SMESH_Mesh& aMesh,
168 const TopoDS_Shape& aShape,
169 Hypothesis_Status& aStatus )
171 aStatus = SMESH_Hypothesis::HYP_OK;
174 _viscousLayersHyp = 0;
176 _removeLogOnSuccess = true;
177 _logInStandardOutput = false;
179 const list <const SMESHDS_Hypothesis * >& hyps =
180 GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
181 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
182 for ( ; h != hyps.end(); ++h )
185 _hyp = dynamic_cast< const GHS3DPlugin_Hypothesis*> ( *h );
186 if ( !_viscousLayersHyp )
187 _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
191 _keepFiles = _hyp->GetKeepFiles();
192 _removeLogOnSuccess = _hyp->GetRemoveLogOnSuccess();
193 _logInStandardOutput = _hyp->GetStandardOutputLog();
196 if ( _viscousLayersHyp )
197 error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
199 return aStatus == HYP_OK;
203 //=======================================================================
204 //function : entryToShape
206 //=======================================================================
208 TopoDS_Shape GHS3DPlugin_GHS3D::entryToShape(std::string entry)
210 if ( SMESH_Gen_i::GetSMESHGen()->getStudyServant()->_is_nil() )
211 throw SALOME_Exception("MG-Tetra plugin can't work w/o publishing in the study");
213 GEOM::GEOM_Object_var aGeomObj;
214 TopoDS_Shape S = TopoDS_Shape();
215 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
216 if (!aSObj->_is_nil() ) {
217 CORBA::Object_var obj = aSObj->GetObject();
218 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
221 if ( !aGeomObj->_is_nil() )
222 S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj.in() );
226 //================================================================================
228 * \brief returns id of a solid if a triangle defined by the nodes is a temporary face
229 * either on a side facet of pyramid or a top of pentahedron and defines sub-domian
230 * outside the volume; else returns HOLE_ID
232 //================================================================================
234 static int checkTmpFace(const SMDS_MeshNode* node1,
235 const SMDS_MeshNode* node2,
236 const SMDS_MeshNode* node3)
238 // find a pyramid sharing the 3 nodes
239 SMDS_ElemIteratorPtr vIt1 = node1->GetInverseElementIterator(SMDSAbs_Volume);
240 while ( vIt1->more() )
242 const SMDS_MeshElement* vol = vIt1->next();
243 const int nbNodes = vol->NbCornerNodes();
244 if ( nbNodes != 5 && nbNodes != 6 ) continue;
246 if ( (i2 = vol->GetNodeIndex( node2 )) >= 0 &&
247 (i3 = vol->GetNodeIndex( node3 )) >= 0 )
251 // Triangle defines sub-domian inside the pyramid if it's
252 // normal points out of the vol
254 // make i2 and i3 hold indices of base nodes of the vol while
255 // keeping the nodes order in the triangle
258 i2 = i3, i3 = vol->GetNodeIndex( node1 );
259 else if ( i3 == iApex )
260 i3 = i2, i2 = vol->GetNodeIndex( node1 );
262 int i3base = (i2+1) % 4; // next index after i2 within the pyramid base
263 bool isDomainInPyramid = ( i3base != i3 );
264 return isDomainInPyramid ? HOLE_ID : vol->getshapeId();
268 int i1 = vol->GetNodeIndex( node1 );
269 if (( i1 == 5 && i2 == 4 && i3 == 3 ) ||
270 ( i1 == 4 && i2 == 3 && i3 == 5 ) ||
271 ( i1 == 3 && i2 == 5 && i3 == 4 ))
274 return vol->getshapeId(); // triangle is a prism top
281 //=======================================================================
282 //function : findShapeID
283 //purpose : find the solid corresponding to MG-Tetra sub-domain following
284 // the technique proposed in MG-Tetra manual (available within
285 // MG-Tetra installation) in chapter "B.4 Subdomain (sub-region) assignment".
286 // In brief: normal of the triangle defined by the given nodes
287 // points out of the domain it is associated to
288 //=======================================================================
290 static int findShapeID(SMESH_Mesh& mesh,
291 const SMDS_MeshNode* node1,
292 const SMDS_MeshNode* node2,
293 const SMDS_MeshNode* node3,
294 const bool toMeshHoles)
296 const int invalidID = 0;
297 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
299 // face the nodes belong to
300 vector<const SMDS_MeshNode *> nodes(3);
304 const SMDS_MeshElement * face = meshDS->FindElement( nodes, SMDSAbs_Face, /*noMedium=*/true);
306 return checkTmpFace(node1, node2, node3);
308 std::cout << "bnd face " << face->GetID() << " - ";
310 // geom face the face assigned to
311 SMESH_MeshEditor editor(&mesh);
312 int geomFaceID = editor.FindShape( face );
314 return checkTmpFace(node1, node2, node3);
315 TopoDS_Shape shape = meshDS->IndexToShape( geomFaceID );
316 if ( shape.IsNull() || shape.ShapeType() != TopAbs_FACE )
318 TopoDS_Face geomFace = TopoDS::Face( shape );
320 // solids bounded by geom face
321 TopTools_IndexedMapOfShape solids, shells;
322 TopTools_ListIteratorOfListOfShape ansIt = mesh.GetAncestors(geomFace);
323 for ( ; ansIt.More(); ansIt.Next() ) {
324 switch ( ansIt.Value().ShapeType() ) {
326 solids.Add( ansIt.Value() ); break;
328 shells.Add( ansIt.Value() ); break;
332 // analyse found solids
333 if ( solids.Extent() == 0 || shells.Extent() == 0)
336 const TopoDS_Solid& solid1 = TopoDS::Solid( solids(1) );
337 if ( solids.Extent() == 1 )
340 return meshDS->ShapeToIndex( solid1 );
342 // - Are we at a hole boundary face?
343 if ( shells(1).IsSame( BRepClass3d::OuterShell( solid1 )) )
344 { // - No, but maybe a hole is bound by two shapes? Does shells(1) touch another shell?
346 TopExp_Explorer eExp( shells(1), TopAbs_EDGE );
347 // check if any edge of shells(1) belongs to another shell
348 for ( ; eExp.More() && !touch; eExp.Next() ) {
349 ansIt = mesh.GetAncestors( eExp.Current() );
350 for ( ; ansIt.More() && !touch; ansIt.Next() ) {
351 if ( ansIt.Value().ShapeType() == TopAbs_SHELL )
352 touch = ( !ansIt.Value().IsSame( shells(1) ));
356 return meshDS->ShapeToIndex( solid1 );
359 // find orientation of geom face within the first solid
360 TopExp_Explorer fExp( solid1, TopAbs_FACE );
361 for ( ; fExp.More(); fExp.Next() )
362 if ( geomFace.IsSame( fExp.Current() )) {
363 geomFace = TopoDS::Face( fExp.Current() );
367 return invalidID; // face not found
369 // normale to triangle
370 gp_Pnt node1Pnt ( node1->X(), node1->Y(), node1->Z() );
371 gp_Pnt node2Pnt ( node2->X(), node2->Y(), node2->Z() );
372 gp_Pnt node3Pnt ( node3->X(), node3->Y(), node3->Z() );
373 gp_Vec vec12( node1Pnt, node2Pnt );
374 gp_Vec vec13( node1Pnt, node3Pnt );
375 gp_Vec meshNormal = vec12 ^ vec13;
376 if ( meshNormal.SquareMagnitude() < DBL_MIN )
379 // get normale to geomFace at any node
380 bool geomNormalOK = false;
382 SMESH_MesherHelper helper( mesh ); helper.SetSubShape( geomFace );
383 for ( int i = 0; !geomNormalOK && i < 3; ++i )
385 // find UV of i-th node on geomFace
386 const SMDS_MeshNode* nNotOnSeamEdge = 0;
387 if ( helper.IsSeamShape( nodes[i]->getshapeId() )) {
388 if ( helper.IsSeamShape( nodes[(i+1)%3]->getshapeId() ))
389 nNotOnSeamEdge = nodes[(i+2)%3];
391 nNotOnSeamEdge = nodes[(i+1)%3];
394 gp_XY uv = helper.GetNodeUV( geomFace, nodes[i], nNotOnSeamEdge, &uvOK );
395 // check that uv is correct
398 TopoDS_Shape nodeShape = helper.GetSubShapeByNode( nodes[i], meshDS );
399 if ( !nodeShape.IsNull() )
400 switch ( nodeShape.ShapeType() )
402 case TopAbs_FACE: tol = BRep_Tool::Tolerance( TopoDS::Face( nodeShape )); break;
403 case TopAbs_EDGE: tol = BRep_Tool::Tolerance( TopoDS::Edge( nodeShape )); break;
404 case TopAbs_VERTEX: tol = BRep_Tool::Tolerance( TopoDS::Vertex( nodeShape )); break;
407 gp_Pnt nodePnt ( nodes[i]->X(), nodes[i]->Y(), nodes[i]->Z() );
408 BRepAdaptor_Surface surface( geomFace );
409 uvOK = ( nodePnt.Distance( surface.Value( uv.X(), uv.Y() )) < 2 * tol );
411 // normale to geomFace at UV
413 surface.D1( uv.X(), uv.Y(), nodePnt, du, dv );
414 geomNormal = du ^ dv;
415 if ( geomFace.Orientation() == TopAbs_REVERSED )
416 geomNormal.Reverse();
417 geomNormalOK = ( geomNormal.SquareMagnitude() > DBL_MIN * 1e3 );
425 bool isReverse = ( meshNormal * geomNormal ) < 0;
427 return meshDS->ShapeToIndex( solid1 );
429 if ( solids.Extent() == 1 )
430 return HOLE_ID; // we are inside a hole
432 return meshDS->ShapeToIndex( solids(2) );
435 //=======================================================================
436 //function : addElemInMeshGroup
437 //purpose : Update or create groups in mesh
438 //=======================================================================
440 static void addElemInMeshGroup(SMESH_Mesh* theMesh,
441 const SMDS_MeshElement* anElem,
442 std::string& groupName,
443 std::set<std::string>& /*groupsToRemove*/)
445 if ( !anElem ) return; // issue 0021776
447 bool groupDone = false;
448 SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
449 while (grIt->more()) {
450 SMESH_Group * group = grIt->next();
451 if ( !group ) continue;
452 SMESHDS_GroupBase* groupDS = group->GetGroupDS();
453 if ( !groupDS ) continue;
454 if ( groupDS->GetType()==anElem->GetType() &&groupName.compare(group->GetName())==0) {
455 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
456 aGroupDS->SMDSGroup().Add(anElem);
464 SMESH_Group* aGroup = theMesh->AddGroup(anElem->GetType(), groupName.c_str());
465 aGroup->SetName( groupName.c_str() );
466 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
467 aGroupDS->SMDSGroup().Add(anElem);
471 throw SALOME_Exception(LOCALIZED("A given element was not added to a group"));
475 //=======================================================================
476 //function : updateMeshGroups
477 //purpose : Update or create groups in mesh
478 //=======================================================================
480 static void updateMeshGroups(SMESH_Mesh* theMesh, std::set<std::string> groupsToRemove)
482 SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
483 while (grIt->more()) {
484 SMESH_Group * group = grIt->next();
485 if ( !group ) continue;
486 SMESHDS_GroupBase* groupDS = group->GetGroupDS();
487 if ( !groupDS ) continue;
488 std::string currentGroupName = (string)group->GetName();
489 if (groupDS->IsEmpty() && groupsToRemove.find(currentGroupName) != groupsToRemove.end()) {
490 // Previous group created by enforced elements
491 theMesh->RemoveGroup(groupDS->GetID());
496 //=======================================================================
497 //function : removeEmptyGroupsOfDomains
498 //purpose : remove empty groups named "Domain_nb" created due to
499 // "To make groups of domains" option.
500 //=======================================================================
502 static void removeEmptyGroupsOfDomains(SMESH_Mesh* mesh,
503 bool notEmptyAsWell = false)
505 const char* refName = theDomainGroupNamePrefix;
506 const size_t refLen = strlen( theDomainGroupNamePrefix );
508 std::list<int> groupIDs = mesh->GetGroupIds();
509 std::list<int>::const_iterator id = groupIDs.begin();
510 for ( ; id != groupIDs.end(); ++id )
512 SMESH_Group* group = mesh->GetGroup( *id );
513 if ( !group || ( !group->GetGroupDS()->IsEmpty() && !notEmptyAsWell ))
515 const char* name = group->GetName();
518 if ( strncmp( name, refName, refLen ) == 0 && // starts from refName;
519 isdigit( *( name + refLen )) && // refName is followed by a digit;
520 strtol( name + refLen, &end, 10) >= 0 && // there are only digits ...
521 *end == '\0') // ... till a string end.
523 mesh->RemoveGroup( *id );
528 //================================================================================
530 * \brief Create the groups corresponding to domains
532 //================================================================================
534 static void makeDomainGroups( std::vector< std::vector< const SMDS_MeshElement* > >& elemsOfDomain,
535 SMESH_MesherHelper* theHelper)
537 // int nbDomains = 0;
538 // for ( size_t i = 0; i < elemsOfDomain.size(); ++i )
539 // nbDomains += ( elemsOfDomain[i].size() > 0 );
541 // if ( nbDomains > 1 )
542 for ( size_t iDomain = 0; iDomain < elemsOfDomain.size(); ++iDomain )
544 std::vector< const SMDS_MeshElement* > & elems = elemsOfDomain[ iDomain ];
545 if ( elems.empty() ) continue;
547 // find existing groups
548 std::vector< SMESH_Group* > groupOfType( SMDSAbs_NbElementTypes, (SMESH_Group*)NULL );
549 const std::string domainName = ( SMESH_Comment( theDomainGroupNamePrefix ) << iDomain );
550 SMESH_Mesh::GroupIteratorPtr groupIt = theHelper->GetMesh()->GetGroups();
551 while ( groupIt->more() )
553 SMESH_Group* group = groupIt->next();
554 if ( domainName == group->GetName() &&
555 dynamic_cast< SMESHDS_Group* >( group->GetGroupDS()) )
556 groupOfType[ group->GetGroupDS()->GetType() ] = group;
558 // create and fill the groups
562 SMESH_Group* group = groupOfType[ elems[ iElem ]->GetType() ];
564 group = theHelper->GetMesh()->AddGroup( elems[ iElem ]->GetType(),
565 domainName.c_str() );
566 SMDS_MeshGroup& groupDS =
567 static_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
569 while ( iElem < elems.size() && groupDS.Add( elems[iElem] ))
572 } while ( iElem < elems.size() );
576 //=======================================================================
577 //function : readGMFFile
578 //purpose : read GMF file w/o geometry associated to mesh
579 //=======================================================================
581 static bool readGMFFile(MG_Tetra_API* MGOutput,
583 GHS3DPlugin_GHS3D* theAlgo,
584 SMESH_MesherHelper* theHelper,
585 std::vector <const SMDS_MeshNode*> & theNodeByGhs3dId,
586 std::vector <const SMDS_MeshElement*> & theFaceByGhs3dId,
587 map<const SMDS_MeshNode*,int> & /*theNodeToGhs3dIdMap*/,
588 std::vector<std::string> & aNodeGroupByGhs3dId,
589 std::vector<std::string> & anEdgeGroupByGhs3dId,
590 std::vector<std::string> & aFaceGroupByGhs3dId,
591 std::set<std::string> & groupsToRemove,
592 bool toMakeGroupsOfDomains=false,
593 bool toMeshHoles=true)
596 SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
597 const bool hasGeom = ( theHelper->GetMesh()->HasShapeToMesh() );
599 int nbInitialNodes = (int) theNodeByGhs3dId.size();
602 const bool isQuadMesh =
603 theHelper->GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
604 theHelper->GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
605 theHelper->GetMesh()->NbVolumes( ORDER_QUADRATIC );
606 std::cout << "theNodeByGhs3dId.size(): " << nbInitialNodes << std::endl;
607 std::cout << "theHelper->GetMesh()->NbNodes(): " << theMeshDS->NbNodes() << std::endl;
608 std::cout << "isQuadMesh: " << isQuadMesh << std::endl;
611 // ---------------------------------
612 // Read generated elements and nodes
613 // ---------------------------------
615 int nbElem = 0, nbRef = 0;
617 std::vector< const SMDS_MeshNode*> GMFNode;
619 std::map<int, std::set<int> > subdomainId2tetraId;
621 std::map <GmfKwdCod,int> tabRef;
622 const bool force3d = !hasGeom;
625 tabRef[GmfVertices] = 3; // for new nodes and enforced nodes
626 tabRef[GmfCorners] = 1;
627 tabRef[GmfEdges] = 2; // for enforced edges
628 tabRef[GmfRidges] = 1;
629 tabRef[GmfTriangles] = 3; // for enforced faces
630 tabRef[GmfQuadrilaterals] = 4;
631 tabRef[GmfTetrahedra] = 4; // for new tetras
632 tabRef[GmfHexahedra] = 8;
635 int InpMsh = MGOutput->GmfOpenMesh( theFile, GmfRead, &ver, &dim);
639 // Read ids of domains
640 vector< int > solidIDByDomain;
643 int solid1; // id used in case of 1 domain or some reading failure
644 if ( theHelper->GetSubShape().ShapeType() == TopAbs_SOLID )
645 solid1 = theHelper->GetSubShapeID();
647 solid1 = theMeshDS->ShapeToIndex
648 ( TopExp_Explorer( theHelper->GetSubShape(), TopAbs_SOLID ).Current() );
650 int nbDomains = MGOutput->GmfStatKwd( InpMsh, GmfSubDomainFromGeom );
653 solidIDByDomain.resize( nbDomains+1, theHelper->GetSubShapeID() );
654 int faceNbNodes, faceIndex, orientation, domainNb;
655 MGOutput->GmfGotoKwd( InpMsh, GmfSubDomainFromGeom );
656 for ( int i = 0; i < nbDomains; ++i )
659 MGOutput->GmfGetLin( InpMsh, GmfSubDomainFromGeom,
660 &faceNbNodes, &faceIndex, &orientation, &domainNb, i);
661 solidIDByDomain[ domainNb ] = 1;
662 if ( 0 < faceIndex && faceIndex-1 < (int)theFaceByGhs3dId.size() )
664 const SMDS_MeshElement* face = theFaceByGhs3dId[ faceIndex-1 ];
665 const SMDS_MeshNode* nn[3] = { face->GetNode(0),
668 if ( orientation < 0 )
669 std::swap( nn[1], nn[2] );
670 solidIDByDomain[ domainNb ] =
671 findShapeID( *theHelper->GetMesh(), nn[0], nn[1], nn[2], toMeshHoles );
672 if ( solidIDByDomain[ domainNb ] > 0 )
675 std::cout << "solid " << solidIDByDomain[ domainNb ] << std::endl;
677 const TopoDS_Shape& foundShape = theMeshDS->IndexToShape( solidIDByDomain[ domainNb ] );
678 if ( ! theHelper->IsSubShape( foundShape, theHelper->GetSubShape() ))
679 solidIDByDomain[ domainNb ] = HOLE_ID;
684 if ( solidIDByDomain.size() < 2 )
685 solidIDByDomain.resize( 2, solid1 );
688 // Issue 0020682. Avoid creating nodes and tetras at place where
689 // volumic elements already exist
690 SMESH_ElementSearcher* elemSearcher = 0;
691 std::vector< const SMDS_MeshElement* > foundVolumes;
692 if ( !hasGeom && theHelper->GetMesh()->NbVolumes() > 0 )
693 elemSearcher = SMESH_MeshAlgos::GetElementSearcher( *theMeshDS );
694 unique_ptr< SMESH_ElementSearcher > elemSearcherDeleter( elemSearcher );
696 // IMP 0022172: [CEA 790] create the groups corresponding to domains
697 std::vector< std::vector< const SMDS_MeshElement* > > elemsOfDomain;
699 int nbVertices = MGOutput->GmfStatKwd( InpMsh, GmfVertices ) - nbInitialNodes;
700 if ( nbVertices < 0 )
702 GMFNode.resize( nbVertices + 1 );
704 std::map <GmfKwdCod,int>::const_iterator it = tabRef.begin();
705 for ( ; it != tabRef.end() ; ++it)
707 if(theAlgo->computeCanceled()) {
711 GmfKwdCod token = it->first;
714 nbElem = MGOutput->GmfStatKwd( InpMsh, token);
716 MGOutput->GmfGotoKwd( InpMsh, token);
717 std::cout << "Read " << nbElem;
722 std::vector<int> id (nbElem*tabRef[token]); // node ids
723 std::vector<int> domainID( nbElem ); // domain
725 if (token == GmfVertices) {
726 (nbElem <= 1) ? tmpStr = " vertex" : tmpStr = " vertices";
727 // std::cout << nbInitialNodes << " from input mesh " << std::endl;
729 // Remove orphan nodes from previous enforced mesh which was cleared
730 // if ( nbElem < nbMeshNodes ) {
731 // const SMDS_MeshNode* node;
732 // SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
733 // while ( nodeIt->more() )
735 // node = nodeIt->next();
736 // if (theNodeToGhs3dIdMap.find(node) != theNodeToGhs3dIdMap.end())
737 // theMeshDS->RemoveNode(node);
746 const SMDS_MeshNode * aGMFNode;
748 for ( int iElem = 0; iElem < nbElem; iElem++ ) {
749 if(theAlgo->computeCanceled()) {
752 if (ver == GmfFloat) {
753 MGOutput->GmfGetLin( InpMsh, token, &VerTab_f[0], &VerTab_f[1], &VerTab_f[2], &dummy);
759 MGOutput->GmfGetLin( InpMsh, token, &x, &y, &z, &dummy);
761 if (iElem >= nbInitialNodes) {
763 elemSearcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_Volume, foundVolumes))
766 aGMFNode = theHelper->AddNode(x, y, z);
768 aGMFID = iElem -nbInitialNodes +1;
769 GMFNode[ aGMFID ] = aGMFNode;
770 if (aGMFID-1 < (int)aNodeGroupByGhs3dId.size() && !aNodeGroupByGhs3dId.at(aGMFID-1).empty())
771 addElemInMeshGroup(theHelper->GetMesh(), aGMFNode, aNodeGroupByGhs3dId.at(aGMFID-1), groupsToRemove);
775 else if (token == GmfCorners && nbElem > 0) {
776 (nbElem <= 1) ? tmpStr = " corner" : tmpStr = " corners";
777 for ( int iElem = 0; iElem < nbElem; iElem++ )
778 MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]]);
780 else if (token == GmfRidges && nbElem > 0) {
781 (nbElem <= 1) ? tmpStr = " ridge" : tmpStr = " ridges";
782 for ( int iElem = 0; iElem < nbElem; iElem++ )
783 MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]]);
785 else if (token == GmfEdges && nbElem > 0) {
786 (nbElem <= 1) ? tmpStr = " edge" : tmpStr = " edges";
787 for ( int iElem = 0; iElem < nbElem; iElem++ )
788 MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &domainID[iElem]);
790 else if (token == GmfTriangles && nbElem > 0) {
791 (nbElem <= 1) ? tmpStr = " triangle" : tmpStr = " triangles";
792 for ( int iElem = 0; iElem < nbElem; iElem++ )
793 MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &domainID[iElem]);
795 else if (token == GmfQuadrilaterals && nbElem > 0) {
796 (nbElem <= 1) ? tmpStr = " Quadrilateral" : tmpStr = " Quadrilaterals";
797 for ( int iElem = 0; iElem < nbElem; iElem++ )
798 MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
800 else if (token == GmfTetrahedra && nbElem > 0) {
801 (nbElem <= 1) ? tmpStr = " Tetrahedron" : tmpStr = " Tetrahedra";
802 for ( int iElem = 0; iElem < nbElem; iElem++ ) {
803 MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
805 subdomainId2tetraId[dummy].insert(iElem+1);
809 else if (token == GmfHexahedra && nbElem > 0) {
810 (nbElem <= 1) ? tmpStr = " Hexahedron" : tmpStr = " Hexahedra";
811 for ( int iElem = 0; iElem < nbElem; iElem++ )
812 MGOutput->GmfGetLin( InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
813 &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &id[iElem*tabRef[token]+6], &id[iElem*tabRef[token]+7], &domainID[iElem]);
815 std::cout << tmpStr << std::endl;
816 std::cout << std::endl;
823 case GmfQuadrilaterals:
827 std::vector< const SMDS_MeshNode* > node( nbRef );
828 std::vector< int > nodeID( nbRef );
829 std::vector< SMDS_MeshNode* > enfNode( nbRef );
830 const SMDS_MeshElement* aCreatedElem;
832 for ( int iElem = 0; iElem < nbElem; iElem++ )
834 if(theAlgo->computeCanceled()) {
837 // Check if elem is already in input mesh. If yes => skip
838 bool fullyCreatedElement = false; // if at least one of the nodes was created
839 for ( int iRef = 0; iRef < nbRef; iRef++ )
841 aGMFNodeID = id[iElem*tabRef[token]+iRef]; // read nbRef aGMFNodeID
842 if (aGMFNodeID <= nbInitialNodes) // input nodes
845 node[ iRef ] = theNodeByGhs3dId[aGMFNodeID];
849 fullyCreatedElement = true;
850 aGMFNodeID -= nbInitialNodes;
851 nodeID[ iRef ] = aGMFNodeID ;
852 node [ iRef ] = GMFNode[ aGMFNodeID ];
859 if (fullyCreatedElement) {
860 aCreatedElem = theHelper->AddEdge( node[0], node[1], noID, force3d );
861 if (anEdgeGroupByGhs3dId.size() && !anEdgeGroupByGhs3dId[iElem].empty())
862 addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, anEdgeGroupByGhs3dId[iElem], groupsToRemove);
866 if (fullyCreatedElement) {
867 aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], noID, force3d );
868 if (aFaceGroupByGhs3dId.size() && !aFaceGroupByGhs3dId[iElem].empty())
869 addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, aFaceGroupByGhs3dId[iElem], groupsToRemove);
872 case GmfQuadrilaterals:
873 if (fullyCreatedElement) {
874 aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], node[3], noID, force3d );
880 solidID = solidIDByDomain[ domainID[iElem]];
881 if ( solidID != HOLE_ID )
883 aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
885 theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
886 for ( int iN = 0; iN < 4; ++iN )
887 if ( node[iN]->getshapeId() < 1 )
888 theMeshDS->SetNodeInVolume( node[iN], solidID );
893 if ( elemSearcher ) {
894 // Issue 0020682. Avoid creating nodes and tetras at place where
895 // volumic elements already exist
896 if ( !node[1] || !node[0] || !node[2] || !node[3] )
898 if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
899 SMESH_TNodeXYZ(node[1]) +
900 SMESH_TNodeXYZ(node[2]) +
901 SMESH_TNodeXYZ(node[3]) ) / 4.,
902 SMDSAbs_Volume, foundVolumes ))
905 aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
912 solidID = solidIDByDomain[ domainID[iElem]];
913 if ( solidID != HOLE_ID )
915 aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
916 node[4], node[7], node[6], node[5],
918 theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
919 for ( int iN = 0; iN < 8; ++iN )
920 if ( node[iN]->getshapeId() < 1 )
921 theMeshDS->SetNodeInVolume( node[iN], solidID );
926 if ( elemSearcher ) {
927 // Issue 0020682. Avoid creating nodes and tetras at place where
928 // volumic elements already exist
929 if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] || !node[6] || !node[7])
931 if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
932 SMESH_TNodeXYZ(node[1]) +
933 SMESH_TNodeXYZ(node[2]) +
934 SMESH_TNodeXYZ(node[3]) +
935 SMESH_TNodeXYZ(node[4]) +
936 SMESH_TNodeXYZ(node[5]) +
937 SMESH_TNodeXYZ(node[6]) +
938 SMESH_TNodeXYZ(node[7])) / 8.,
939 SMDSAbs_Volume, foundVolumes ))
942 aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
943 node[4], node[7], node[6], node[5],
950 // care about medium nodes
952 aCreatedElem->IsQuadratic() &&
953 ( solidID = aCreatedElem->getshapeId() ) > 0 )
955 int iN = aCreatedElem->NbCornerNodes(), nbN = aCreatedElem->NbNodes();
956 for ( ; iN < nbN; ++iN )
958 const SMDS_MeshNode* n = aCreatedElem->GetNode(iN);
959 if ( n->getshapeId() < 1 )
960 theMeshDS->SetNodeInVolume( n, solidID );
964 if ( aCreatedElem && toMakeGroupsOfDomains )
966 if ( domainID[iElem] >= (int) elemsOfDomain.size() )
967 elemsOfDomain.resize( domainID[iElem] + 1 );
968 elemsOfDomain[ domainID[iElem] ].push_back( aCreatedElem );
970 } // loop on elements of one type
977 // remove nodes in holes
980 for ( int i = 1; i <= nbVertices; ++i )
981 if ( GMFNode[i]->NbInverseElements() == 0 )
982 theMeshDS->RemoveFreeNode( GMFNode[i], /*sm=*/0, /*fromGroups=*/false );
985 MGOutput->GmfCloseMesh( InpMsh);
987 // 0022172: [CEA 790] create the groups corresponding to domains
988 if ( toMakeGroupsOfDomains )
989 makeDomainGroups( elemsOfDomain, theHelper );
992 std::map<int, std::set<int> >::const_iterator subdomainIt = subdomainId2tetraId.begin();
993 TCollection_AsciiString aSubdomainFileName = theFile;
994 aSubdomainFileName = aSubdomainFileName + ".subdomain";
995 ofstream aSubdomainFile ( aSubdomainFileName.ToCString() , ios::out);
997 aSubdomainFile << "Nb subdomains " << subdomainId2tetraId.size() << std::endl;
998 for(;subdomainIt != subdomainId2tetraId.end() ; ++subdomainIt) {
999 int subdomainId = subdomainIt->first;
1000 std::set<int> tetraIds = subdomainIt->second;
1001 std::set<int>::const_iterator tetraIdsIt = tetraIds.begin();
1002 aSubdomainFile << subdomainId << std::endl;
1003 for(;tetraIdsIt != tetraIds.end() ; ++tetraIdsIt) {
1004 aSubdomainFile << (*tetraIdsIt) << " ";
1006 aSubdomainFile << std::endl;
1008 aSubdomainFile.close();
1015 static bool writeGMFFile(MG_Tetra_API* MGInput,
1016 const char* theMeshFileName,
1017 const char* theRequiredFileName,
1018 const char* theSolFileName,
1019 const SMESH_ProxyMesh& theProxyMesh,
1020 SMESH_MesherHelper& theHelper,
1021 std::vector <const SMDS_MeshNode*> & theNodeByGhs3dId,
1022 std::vector <const SMDS_MeshElement*> & theFaceByGhs3dId,
1023 std::map<const SMDS_MeshNode*,int> & aNodeToGhs3dIdMap,
1024 std::vector<std::string> & aNodeGroupByGhs3dId,
1025 std::vector<std::string> & anEdgeGroupByGhs3dId,
1026 std::vector<std::string> & aFaceGroupByGhs3dId,
1027 GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap & theEnforcedNodes,
1028 GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
1029 GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles,
1030 std::map<std::vector<double>, std::string> & enfVerticesWithGroup,
1031 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues & theEnforcedVertices,
1032 int & theInvalidEnforcedFlags)
1035 int idx, idxRequired = 0, idxSol = 0;
1036 const int dummyint = 0;
1037 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues::const_iterator vertexIt;
1038 std::vector<double> enfVertexSizes;
1039 const SMDS_MeshElement* elem;
1040 TIDSortedElemSet anElemSet, theKeptEnforcedEdges, theKeptEnforcedTriangles;
1041 SMDS_ElemIteratorPtr nodeIt;
1042 std::vector <const SMDS_MeshNode*> theEnforcedNodeByGhs3dId;
1043 map<const SMDS_MeshNode*,int> anEnforcedNodeToGhs3dIdMap, anExistingEnforcedNodeToGhs3dIdMap;
1044 std::vector< const SMDS_MeshElement* > foundElems;
1045 map<const SMDS_MeshNode*,TopAbs_State> aNodeToTopAbs_StateMap;
1047 GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap::iterator elemIt;
1048 TIDSortedElemSet::iterator elemSetIt;
1050 SMESH_Mesh* theMesh = theHelper.GetMesh();
1051 const bool hasGeom = theMesh->HasShapeToMesh();
1052 SMESHUtils::Deleter< SMESH_ElementSearcher > pntCls
1053 ( SMESH_MeshAlgos::GetElementSearcher(*theMesh->GetMeshDS()));
1055 int nbEnforcedVertices = (int) theEnforcedVertices.size();
1056 theInvalidEnforcedFlags = 0;
1059 smIdType nbFaces = theProxyMesh.NbFaces();
1061 theFaceByGhs3dId.reserve( nbFaces );
1063 // groups management
1064 int usedEnforcedNodes = 0;
1065 std::string gn = "";
1070 idx = MGInput->GmfOpenMesh( theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1074 /* ========================== FACES ========================== */
1075 /* TRIANGLES ========================== */
1076 SMDS_ElemIteratorPtr eIt =
1077 hasGeom ? theProxyMesh.GetFaces( theHelper.GetSubShape()) : theProxyMesh.GetFaces();
1078 while ( eIt->more() )
1081 anElemSet.insert(elem);
1082 nodeIt = elem->nodesIterator();
1083 nbNodes = elem->NbCornerNodes();
1084 while ( nodeIt->more() && nbNodes--)
1087 const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1088 int newId = (int) aNodeToGhs3dIdMap.size() + 1; // MG-Tetra ids count from 1
1089 aNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1092 if ( !anElemSet.empty() &&
1093 (*anElemSet.begin())->IsQuadratic() &&
1094 theProxyMesh.NbProxySubMeshes() > 0 )
1096 // add medium nodes of proxy triangles to theHelper (#16843)
1097 for ( elemSetIt = anElemSet.begin(); elemSetIt != anElemSet.end(); ++elemSetIt )
1098 theHelper.AddTLinks( static_cast< const SMDS_MeshFace* >( *elemSetIt ));
1101 /* EDGES ========================== */
1103 // Iterate over the enforced edges
1104 for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
1105 elem = elemIt->first;
1107 nodeIt = elem->nodesIterator();
1109 while ( nodeIt->more() && nbNodes-- ) {
1111 const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1112 // Test if point is inside shape to mesh
1113 gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1114 TopAbs_State result = pntCls->GetPointState( myPoint );
1115 if ( result == TopAbs_OUT ) {
1117 theInvalidEnforcedFlags |= FLAG_BAD_ENF_EDGE;
1120 aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1123 nodeIt = elem->nodesIterator();
1126 while ( nodeIt->more() && nbNodes-- ) {
1128 const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1129 gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1130 nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1132 std::cout << "Node at "<<node->X()<<", "<<node->Y()<<", "<<node->Z()<<std::endl;
1133 std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1135 if (nbFoundElems ==0) {
1136 if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1137 newId = int( aNodeToGhs3dIdMap.size() + anEnforcedNodeToGhs3dIdMap.size() + 1 ); // MG-Tetra ids count from 1
1138 anEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1141 else if (nbFoundElems ==1) {
1142 const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1143 newId = (*aNodeToGhs3dIdMap.find(existingNode)).second;
1144 anExistingEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1149 std::cout << "MG-Tetra node ID: "<<newId<<std::endl;
1153 theKeptEnforcedEdges.insert(elem);
1155 theInvalidEnforcedFlags |= FLAG_BAD_ENF_EDGE;
1159 /* ENFORCED TRIANGLES ========================== */
1161 // Iterate over the enforced triangles
1162 for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
1163 elem = elemIt->first;
1165 nodeIt = elem->nodesIterator();
1167 while ( nodeIt->more() && nbNodes--) {
1169 const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1170 // Test if point is inside shape to mesh
1171 gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1172 TopAbs_State result = pntCls->GetPointState( myPoint );
1173 if ( result == TopAbs_OUT ) {
1175 theInvalidEnforcedFlags |= FLAG_BAD_ENF_TRIA;
1178 aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1181 nodeIt = elem->nodesIterator();
1184 while ( nodeIt->more() && nbNodes--) {
1186 const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1187 gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1188 nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1190 std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1192 if (nbFoundElems ==0) {
1193 if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1194 newId = int( aNodeToGhs3dIdMap.size() + anEnforcedNodeToGhs3dIdMap.size() + 1 ); // MG-Tetra ids count from 1
1195 anEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1198 else if (nbFoundElems ==1) {
1199 const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1200 newId = (*aNodeToGhs3dIdMap.find(existingNode)).second;
1201 anExistingEnforcedNodeToGhs3dIdMap.insert( make_pair( node, newId ));
1206 std::cout << "MG-Tetra node ID: "<<newId<<std::endl;
1210 theKeptEnforcedTriangles.insert(elem);
1212 theInvalidEnforcedFlags |= FLAG_BAD_ENF_TRIA;
1216 // put nodes to theNodeByGhs3dId vector
1218 std::cout << "aNodeToGhs3dIdMap.size(): "<<aNodeToGhs3dIdMap.size()<<std::endl;
1220 theNodeByGhs3dId.resize( aNodeToGhs3dIdMap.size() );
1221 map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToGhs3dIdMap.begin();
1222 for ( ; n2id != aNodeToGhs3dIdMap.end(); ++ n2id)
1224 // std::cout << "n2id->first: "<<n2id->first<<std::endl;
1225 theNodeByGhs3dId[ n2id->second - 1 ] = n2id->first; // MG-Tetra ids count from 1
1228 // put nodes to anEnforcedNodeToGhs3dIdMap vector
1230 std::cout << "anEnforcedNodeToGhs3dIdMap.size(): "<<anEnforcedNodeToGhs3dIdMap.size()<<std::endl;
1232 theEnforcedNodeByGhs3dId.resize( anEnforcedNodeToGhs3dIdMap.size());
1233 n2id = anEnforcedNodeToGhs3dIdMap.begin();
1234 for ( ; n2id != anEnforcedNodeToGhs3dIdMap.end(); ++ n2id)
1236 if (n2id->second > (int)aNodeToGhs3dIdMap.size()) {
1237 theEnforcedNodeByGhs3dId[ n2id->second - aNodeToGhs3dIdMap.size() - 1 ] = n2id->first; // MG-Tetra ids count from 1
1242 /* ========================== NODES ========================== */
1243 vector<const SMDS_MeshNode*> theOrderedNodes, theRequiredNodes;
1244 std::set< std::vector<double> > nodesCoords;
1245 vector<const SMDS_MeshNode*>::const_iterator ghs3dNodeIt = theNodeByGhs3dId.begin();
1246 vector<const SMDS_MeshNode*>::const_iterator after = theNodeByGhs3dId.end();
1248 (theNodeByGhs3dId.size() <= 1) ? tmpStr = " node" : " nodes";
1249 std::cout << theNodeByGhs3dId.size() << tmpStr << " from mesh ..." << std::endl;
1250 for ( ; ghs3dNodeIt != after; ++ghs3dNodeIt )
1252 const SMDS_MeshNode* node = *ghs3dNodeIt;
1253 std::vector<double> coords;
1254 coords.push_back(node->X());
1255 coords.push_back(node->Y());
1256 coords.push_back(node->Z());
1257 nodesCoords.insert(coords);
1258 theOrderedNodes.push_back(node);
1261 // Iterate over the enforced nodes given by enforced elements
1262 ghs3dNodeIt = theEnforcedNodeByGhs3dId.begin();
1263 after = theEnforcedNodeByGhs3dId.end();
1264 (theEnforcedNodeByGhs3dId.size() <= 1) ? tmpStr = " node" : " nodes";
1265 std::cout << theEnforcedNodeByGhs3dId.size() << tmpStr << " from enforced elements ..." << std::endl;
1266 for ( ; ghs3dNodeIt != after; ++ghs3dNodeIt )
1268 const SMDS_MeshNode* node = *ghs3dNodeIt;
1269 std::vector<double> coords;
1270 coords.push_back(node->X());
1271 coords.push_back(node->Y());
1272 coords.push_back(node->Z());
1274 std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1277 if (nodesCoords.find(coords) != nodesCoords.end()) {
1278 // node already exists in original mesh
1280 std::cout << " found" << std::endl;
1285 if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1286 // node already exists in enforced vertices
1288 std::cout << " found" << std::endl;
1293 // gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1294 // nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1295 // if (nbFoundElems ==0) {
1296 // std::cout << " not found" << std::endl;
1297 // if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1298 // nodesCoords.insert(coords);
1299 // theOrderedNodes.push_back(node);
1303 // std::cout << " found in initial mesh" << std::endl;
1304 // const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1305 // nodesCoords.insert(coords);
1306 // theOrderedNodes.push_back(existingNode);
1310 std::cout << " not found" << std::endl;
1313 nodesCoords.insert(coords);
1314 theOrderedNodes.push_back(node);
1315 // theRequiredNodes.push_back(node);
1319 // Iterate over the enforced nodes
1320 GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt;
1321 (theEnforcedNodes.size() <= 1) ? tmpStr = " node" : " nodes";
1322 std::cout << theEnforcedNodes.size() << tmpStr << " from enforced nodes ..." << std::endl;
1323 for(enfNodeIt = theEnforcedNodes.begin() ; enfNodeIt != theEnforcedNodes.end() ; ++enfNodeIt)
1325 const SMDS_MeshNode* node = enfNodeIt->first;
1326 std::vector<double> coords;
1327 coords.push_back(node->X());
1328 coords.push_back(node->Y());
1329 coords.push_back(node->Z());
1331 std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1334 // Test if point is inside shape to mesh
1335 gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1336 TopAbs_State result = pntCls->GetPointState( myPoint );
1337 if ( result == TopAbs_OUT ) {
1339 std::cout << " out of volume" << std::endl;
1341 theInvalidEnforcedFlags |= FLAG_BAD_ENF_NODE;
1345 if (nodesCoords.find(coords) != nodesCoords.end()) {
1347 std::cout << " found in nodesCoords" << std::endl;
1349 // theRequiredNodes.push_back(node);
1353 if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1355 std::cout << " found in theEnforcedVertices" << std::endl;
1360 // nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1361 // if (nbFoundElems ==0) {
1362 // std::cout << " not found" << std::endl;
1363 // if (result == TopAbs_IN) {
1364 // nodesCoords.insert(coords);
1365 // theRequiredNodes.push_back(node);
1369 // std::cout << " found in initial mesh" << std::endl;
1370 // const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1371 // // nodesCoords.insert(coords);
1372 // theRequiredNodes.push_back(existingNode);
1377 // if (pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems) == 0)
1380 // if ( result != TopAbs_IN )
1384 std::cout << " not found" << std::endl;
1386 nodesCoords.insert(coords);
1387 // theOrderedNodes.push_back(node);
1388 theRequiredNodes.push_back(node);
1390 int requiredNodes = (int) theRequiredNodes.size();
1393 std::vector<std::vector<double> > ReqVerTab;
1394 if (nbEnforcedVertices) {
1395 // ReqVerTab.clear();
1396 (nbEnforcedVertices <= 1) ? tmpStr = " node" : " nodes";
1397 std::cout << nbEnforcedVertices << tmpStr << " from enforced vertices ..." << std::endl;
1398 // Iterate over the enforced vertices
1399 for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
1400 double x = vertexIt->first[0];
1401 double y = vertexIt->first[1];
1402 double z = vertexIt->first[2];
1403 // Test if point is inside shape to mesh
1404 gp_Pnt myPoint(x,y,z);
1405 TopAbs_State result = pntCls->GetPointState( myPoint );
1406 if ( result == TopAbs_OUT )
1408 std::cout << "Warning: enforced vertex at ( " << x << "," << y << "," << z << " ) is out of the meshed domain!!!" << std::endl;
1409 theInvalidEnforcedFlags |= FLAG_BAD_ENF_VERT;
1412 std::vector<double> coords;
1413 coords.push_back(x);
1414 coords.push_back(y);
1415 coords.push_back(z);
1416 ReqVerTab.push_back(coords);
1417 enfVertexSizes.push_back(vertexIt->second);
1424 std::cout << "Begin writting required nodes in GmfVertices" << std::endl;
1425 std::cout << "Nb vertices: " << theOrderedNodes.size() << std::endl;
1426 MGInput->GmfSetKwd( idx, GmfVertices, int( theOrderedNodes.size()/*+solSize*/));
1427 for (ghs3dNodeIt = theOrderedNodes.begin();ghs3dNodeIt != theOrderedNodes.end();++ghs3dNodeIt) {
1428 MGInput->GmfSetLin( idx, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
1431 std::cout << "End writting required nodes in GmfVertices" << std::endl;
1433 if (requiredNodes + solSize) {
1434 std::cout << "Begin writting in req and sol file" << std::endl;
1435 aNodeGroupByGhs3dId.resize( requiredNodes + solSize );
1436 idxRequired = MGInput->GmfOpenMesh( theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1440 idxSol = MGInput->GmfOpenMesh( theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1444 int TypTab[] = {GmfSca};
1445 double ValTab[] = {0.0};
1446 MGInput->GmfSetKwd( idxRequired, GmfVertices, requiredNodes + solSize);
1447 MGInput->GmfSetKwd( idxSol, GmfSolAtVertices, requiredNodes + solSize, 1, TypTab);
1448 // int usedEnforcedNodes = 0;
1449 // std::string gn = "";
1450 for (ghs3dNodeIt = theRequiredNodes.begin();ghs3dNodeIt != theRequiredNodes.end();++ghs3dNodeIt) {
1451 MGInput->GmfSetLin( idxRequired, GmfVertices, (*ghs3dNodeIt)->X(), (*ghs3dNodeIt)->Y(), (*ghs3dNodeIt)->Z(), dummyint);
1452 MGInput->GmfSetLin( idxSol, GmfSolAtVertices, ValTab);
1453 if (theEnforcedNodes.find((*ghs3dNodeIt)) != theEnforcedNodes.end())
1454 gn = theEnforcedNodes.find((*ghs3dNodeIt))->second;
1455 aNodeGroupByGhs3dId[usedEnforcedNodes] = gn;
1456 usedEnforcedNodes++;
1459 for (int i=0;i<solSize;i++) {
1460 std::cout << ReqVerTab[i][0] <<" "<< ReqVerTab[i][1] << " "<< ReqVerTab[i][2] << std::endl;
1462 std::cout << "enfVertexSizes.at("<<i<<"): " << enfVertexSizes.at(i) << std::endl;
1464 double solTab[] = {enfVertexSizes.at(i)};
1465 MGInput->GmfSetLin( idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint);
1466 MGInput->GmfSetLin( idxSol, GmfSolAtVertices, solTab);
1467 aNodeGroupByGhs3dId[usedEnforcedNodes] = enfVerticesWithGroup.find(ReqVerTab[i])->second;
1469 std::cout << "aNodeGroupByGhs3dId["<<usedEnforcedNodes<<"] = \""<<aNodeGroupByGhs3dId[usedEnforcedNodes]<<"\""<<std::endl;
1471 usedEnforcedNodes++;
1473 std::cout << "End writting in req and sol file" << std::endl;
1476 int nedge[2], ntri[3];
1479 int usedEnforcedEdges = 0;
1480 if (theKeptEnforcedEdges.size()) {
1481 anEdgeGroupByGhs3dId.resize( theKeptEnforcedEdges.size() );
1482 // idxRequired = MGInput->GmfOpenMesh( theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1483 // if (!idxRequired)
1485 MGInput->GmfSetKwd( idx, GmfEdges, (int) theKeptEnforcedEdges.size());
1486 // MGInput->GmfSetKwd( idxRequired, GmfEdges, theKeptEnforcedEdges.size());
1487 for(elemSetIt = theKeptEnforcedEdges.begin() ; elemSetIt != theKeptEnforcedEdges.end() ; ++elemSetIt) {
1488 elem = (*elemSetIt);
1489 nodeIt = elem->nodesIterator();
1491 while ( nodeIt->more() ) {
1493 const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1494 map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToGhs3dIdMap.find(node);
1495 if (it == anEnforcedNodeToGhs3dIdMap.end()) {
1496 it = anExistingEnforcedNodeToGhs3dIdMap.find(node);
1497 if (it == anEnforcedNodeToGhs3dIdMap.end())
1498 throw "Node not found";
1500 nedge[index] = it->second;
1503 MGInput->GmfSetLin( idx, GmfEdges, nedge[0], nedge[1], dummyint);
1504 anEdgeGroupByGhs3dId[usedEnforcedEdges] = theEnforcedEdges.find(elem)->second;
1505 // MGInput->GmfSetLin( idxRequired, GmfEdges, nedge[0], nedge[1], dummyint);
1506 usedEnforcedEdges++;
1511 if (usedEnforcedEdges) {
1512 MGInput->GmfSetKwd( idx, GmfRequiredEdges, usedEnforcedEdges);
1513 for (int enfID=1;enfID<=usedEnforcedEdges;enfID++) {
1514 MGInput->GmfSetLin( idx, GmfRequiredEdges, enfID);
1519 int usedEnforcedTriangles = 0;
1520 if (anElemSet.size()+theKeptEnforcedTriangles.size()) {
1521 aFaceGroupByGhs3dId.resize( anElemSet.size()+theKeptEnforcedTriangles.size() );
1522 MGInput->GmfSetKwd( idx, GmfTriangles, int( anElemSet.size()+theKeptEnforcedTriangles.size() ));
1524 for(elemSetIt = anElemSet.begin() ; elemSetIt != anElemSet.end() ; ++elemSetIt,++k) {
1525 elem = (*elemSetIt);
1526 theFaceByGhs3dId.push_back( elem );
1527 nodeIt = elem->nodesIterator();
1529 for ( int j = 0; j < 3; ++j ) {
1531 const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1532 map< const SMDS_MeshNode*,int >::iterator it = aNodeToGhs3dIdMap.find(node);
1533 if (it == aNodeToGhs3dIdMap.end())
1534 throw "Node not found";
1535 ntri[index] = it->second;
1538 MGInput->GmfSetLin( idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
1539 aFaceGroupByGhs3dId[k] = "";
1541 if ( !theHelper.GetMesh()->HasShapeToMesh() )
1542 SMESHUtils::FreeVector( theFaceByGhs3dId );
1543 if (theKeptEnforcedTriangles.size()) {
1544 for(elemSetIt = theKeptEnforcedTriangles.begin() ; elemSetIt != theKeptEnforcedTriangles.end() ; ++elemSetIt,++k) {
1545 elem = (*elemSetIt);
1546 nodeIt = elem->nodesIterator();
1548 for ( int j = 0; j < 3; ++j ) {
1550 const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1551 map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToGhs3dIdMap.find(node);
1552 if (it == anEnforcedNodeToGhs3dIdMap.end()) {
1553 it = anExistingEnforcedNodeToGhs3dIdMap.find(node);
1554 if (it == anEnforcedNodeToGhs3dIdMap.end())
1555 throw "Node not found";
1557 ntri[index] = it->second;
1560 MGInput->GmfSetLin( idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint);
1561 aFaceGroupByGhs3dId[k] = theEnforcedTriangles.find(elem)->second;
1562 usedEnforcedTriangles++;
1568 if (usedEnforcedTriangles) {
1569 MGInput->GmfSetKwd( idx, GmfRequiredTriangles, usedEnforcedTriangles);
1570 for (int enfID=1;enfID<=usedEnforcedTriangles;enfID++)
1571 MGInput->GmfSetLin( idx, GmfRequiredTriangles, int( anElemSet.size()+enfID ));
1574 MGInput->GmfCloseMesh(idx);
1576 MGInput->GmfCloseMesh(idxRequired);
1578 MGInput->GmfCloseMesh(idxSol);
1584 //=============================================================================
1586 *Here we are going to use the MG-Tetra mesher with geometry
1588 //=============================================================================
1589 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh& theMesh,
1590 const TopoDS_Shape& theShape)
1593 TopExp_Explorer expBox ( theShape, TopAbs_SOLID );
1595 // a unique working file name
1596 // to avoid access to the same files by eg different users
1597 _genericName = GHS3DPlugin_Hypothesis::GetFileName(_hyp);
1598 TCollection_AsciiString aGenericName((char*) _genericName.c_str() );
1599 TCollection_AsciiString aGenericNameRequired = aGenericName + "_required";
1601 TCollection_AsciiString aLogFileName = aGenericName + ".log"; // log
1602 TCollection_AsciiString aResultFileName;
1604 TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
1605 aGMFFileName = aGenericName + ".mesh"; // GMF mesh file
1606 aResultFileName = aGenericName + "Vol.mesh"; // GMF mesh file
1607 aResSolFileName = aGenericName + "Vol.sol"; // GMF mesh file
1608 aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
1609 aSolFileName = aGenericNameRequired + ".sol"; // GMF solution file
1611 std::map <int,int> aNodeId2NodeIndexMap, aSmdsToGhs3dIdMap, anEnforcedNodeIdToGhs3dIdMap;
1612 std::map <int, int> nodeID2nodeIndexMap;
1613 std::map<std::vector<double>, std::string> enfVerticesWithGroup;
1614 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues coordsSizeMap = GHS3DPlugin_Hypothesis::GetEnforcedVerticesCoordsSize(_hyp);
1615 GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = GHS3DPlugin_Hypothesis::GetEnforcedNodes(_hyp);
1616 GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = GHS3DPlugin_Hypothesis::GetEnforcedEdges(_hyp);
1617 GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = GHS3DPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
1618 GHS3DPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
1620 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList enfVertices = GHS3DPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1621 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
1622 std::vector<double> coords;
1624 for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
1626 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertex* enfVertex = (*enfVerIt);
1627 if (enfVertex->coords.size()) {
1628 coordsSizeMap.insert(make_pair(enfVertex->coords,enfVertex->size));
1629 enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
1632 TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
1633 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1635 if (it.Value().ShapeType() == TopAbs_VERTEX){
1636 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
1637 coords.push_back(aPnt.X());
1638 coords.push_back(aPnt.Y());
1639 coords.push_back(aPnt.Z());
1640 if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
1641 coordsSizeMap.insert(make_pair(coords,enfVertex->size));
1642 enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
1648 size_t nbEnforcedVertices = coordsSizeMap.size();
1649 size_t nbEnforcedNodes = enforcedNodes.size();
1652 (nbEnforcedNodes <= 1) ? tmpStr = "node" : "nodes";
1653 std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
1654 (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : "vertices";
1655 std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
1657 SMESH_MesherHelper helper( theMesh );
1658 helper.SetSubShape( theShape );
1660 std::vector <const SMDS_MeshNode*> aNodeByGhs3dId, anEnforcedNodeByGhs3dId;
1661 std::vector <const SMDS_MeshElement*> aFaceByGhs3dId;
1662 std::map<const SMDS_MeshNode*,int> aNodeToGhs3dIdMap;
1663 std::vector<std::string> aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId;
1665 MG_Tetra_API mgTetra( _computeCanceled, _progress );
1667 _isLibUsed = mgTetra.IsLibrary();
1668 if ( theMesh.NbQuadrangles() > 0 )
1669 _progressAdvance /= 10;
1670 if ( _viscousLayersHyp )
1671 _progressAdvance /= 10;
1673 // proxyMesh must live till readGMFFile() as a proxy face can be used by
1674 // MG-Tetra for domain indication
1675 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
1677 // make prisms on quadrangles and viscous layers
1678 if ( theMesh.NbQuadrangles() > 0 || _viscousLayersHyp )
1680 vector<SMESH_ProxyMesh::Ptr> components;
1681 for (expBox.ReInit(); expBox.More(); expBox.Next())
1683 if ( _viscousLayersHyp )
1685 proxyMesh = _viscousLayersHyp->Compute( theMesh, expBox.Current() );
1688 if ( theMesh.NbQuadrangles() == 0 )
1689 components.push_back( proxyMesh );
1691 if ( theMesh.NbQuadrangles() > 0 )
1693 StdMeshers_QuadToTriaAdaptor* q2t = new StdMeshers_QuadToTriaAdaptor;
1694 Ok = q2t->Compute( theMesh, expBox.Current(), proxyMesh.get() );
1695 components.push_back( SMESH_ProxyMesh::Ptr( q2t ));
1700 proxyMesh.reset( new SMESH_ProxyMesh( components ));
1702 // build viscous layers
1703 // else if ( _viscousLayersHyp )
1705 // proxyMesh = _viscousLayersHyp->Compute( theMesh, theShape );
1706 // if ( !proxyMesh )
1710 int anInvalidEnforcedFlags = 0;
1711 Ok = writeGMFFile(&mgTetra,
1712 aGMFFileName.ToCString(),
1713 aRequiredVerticesFileName.ToCString(),
1714 aSolFileName.ToCString(),
1716 aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
1717 aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
1718 enforcedNodes, enforcedEdges, enforcedTriangles,
1719 enfVerticesWithGroup, coordsSizeMap, anInvalidEnforcedFlags);
1721 // Write aSmdsToGhs3dIdMap to temp file
1722 TCollection_AsciiString aSmdsToGhs3dIdMapFileName;
1723 aSmdsToGhs3dIdMapFileName = aGenericName + ".ids"; // ids relation
1724 ofstream aIdsFile ( aSmdsToGhs3dIdMapFileName.ToCString() , ios::out);
1725 if ( !aIdsFile.rdbuf()->is_open() ) {
1726 INFOS( "Can't write into " << aSmdsToGhs3dIdMapFileName);
1727 //return error(SMESH_Comment("Can't write into ") << aSmdsToGhs3dIdMapFileName);
1731 INFOS( "Writing ids relation into " << aSmdsToGhs3dIdMapFileName);
1732 aIdsFile << "Smds MG-Tetra" << std::endl;
1733 map <int,int>::const_iterator myit;
1734 for (myit=aSmdsToGhs3dIdMap.begin() ; myit != aSmdsToGhs3dIdMap.end() ; ++myit) {
1735 aIdsFile << myit->first << " " << myit->second << std::endl;
1740 if ( !_keepFiles ) {
1741 removeFile( aGMFFileName );
1742 removeFile( aRequiredVerticesFileName );
1743 removeFile( aSolFileName );
1744 removeFile( aSmdsToGhs3dIdMapFileName );
1746 return error(COMPERR_BAD_INPUT_MESH);
1748 removeFile( aResultFileName ); // needed for boundary recovery module usage
1750 // -----------------
1751 // run MG-Tetra mesher
1752 // -----------------
1754 TCollection_AsciiString cmd = GHS3DPlugin_Hypothesis::CommandToRun( _hyp, true, mgTetra.IsExecutable() ).c_str();
1756 if ( mgTetra.IsExecutable() )
1758 cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
1759 if ( nbEnforcedVertices + nbEnforcedNodes)
1760 cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
1761 cmd += TCollection_AsciiString(" --out ") + aResultFileName;
1763 if ( !_logInStandardOutput )
1765 mgTetra.SetLogFile( aLogFileName.ToCString() );
1766 cmd += TCollection_AsciiString(" 1>" ) + aLogFileName; // dump into file
1770 BRIEF_INFOS("MG-Tetra execution...")
1773 _computeCanceled = false;
1776 Ok = mgTetra.Compute( cmd.ToCString(), errStr ); // run
1778 if ( _logInStandardOutput && mgTetra.IsLibrary() ) {
1780 BRIEF_INFOS(mgTetra.GetLog());
1785 BRIEF_INFOS("End of MG-Tetra execution !");
1793 GHS3DPlugin_Hypothesis::TSetStrings groupsToRemove = GHS3DPlugin_Hypothesis::GetGroupsToRemove(_hyp);
1795 _hyp ? _hyp->GetToMeshHoles(true) : GHS3DPlugin_Hypothesis::DefaultMeshHoles();
1796 const bool toMakeGroupsOfDomains = GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
1798 helper.IsQuadraticSubMesh( theShape );
1799 helper.SetElementsOnShape( false );
1801 Ok = readGMFFile(&mgTetra,
1802 aResultFileName.ToCString(),
1804 &helper, aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
1805 aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
1806 groupsToRemove, toMakeGroupsOfDomains, toMeshHoles);
1808 removeEmptyGroupsOfDomains( helper.GetMesh(), /*notEmptyAsWell =*/ !toMakeGroupsOfDomains );
1812 // ---------------------
1813 // remove working files
1814 // ---------------------
1818 if ( anInvalidEnforcedFlags )
1819 error( COMPERR_WARNING, flagsToErrorStr( anInvalidEnforcedFlags ));
1820 if ( _removeLogOnSuccess )
1821 removeFile( aLogFileName );
1822 // if ( _hyp && _hyp->GetToMakeGroupsOfDomains() )
1823 // error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since the mesh is on shape" );
1825 else if ( mgTetra.HasLog() )
1827 if( _computeCanceled )
1828 error( "interruption initiated by user" );
1831 // get problem description from the log file
1832 _Ghs2smdsConvertor conv( aNodeByGhs3dId, proxyMesh );
1833 error( getErrorDescription( _logInStandardOutput ? 0 : aLogFileName.ToCString(),
1834 mgTetra.GetLog(), conv ));
1837 else if ( !errStr.empty() )
1839 // the log file is empty
1840 removeFile( aLogFileName );
1841 INFOS( "MG-Tetra Error, " << errStr);
1842 error(COMPERR_ALGO_FAILED, errStr);
1845 if ( !_keepFiles ) {
1846 if (! Ok && _computeCanceled )
1847 removeFile( aLogFileName );
1848 removeFile( aGMFFileName );
1849 removeFile( aRequiredVerticesFileName );
1850 removeFile( aSolFileName );
1851 removeFile( aResSolFileName );
1852 removeFile( aResultFileName );
1853 removeFile( aSmdsToGhs3dIdMapFileName );
1855 if ( mgTetra.IsExecutable() )
1857 std::cout << "<" << aResultFileName.ToCString() << "> MG-Tetra output file ";
1859 std::cout << "not ";
1860 std::cout << "treated !" << std::endl;
1861 std::cout << std::endl;
1865 std::cout << "MG-Tetra " << ( Ok ? "succeeded" : "failed") << std::endl;
1870 //=============================================================================
1872 *Here we are going to use the MG-Tetra mesher w/o geometry
1874 //=============================================================================
1876 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh& theMesh,
1877 SMESH_MesherHelper* theHelper)
1879 theHelper->IsQuadraticSubMesh( theHelper->GetSubShape() );
1881 // a unique working file name
1882 // to avoid access to the same files by eg different users
1883 _genericName = GHS3DPlugin_Hypothesis::GetFileName(_hyp);
1884 TCollection_AsciiString aGenericName((char*) _genericName.c_str() );
1885 TCollection_AsciiString aGenericNameRequired = aGenericName + "_required";
1887 TCollection_AsciiString aLogFileName = aGenericName + ".log"; // log
1888 TCollection_AsciiString aResultFileName;
1891 TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
1892 aGMFFileName = aGenericName + ".mesh"; // GMF mesh file
1893 aResultFileName = aGenericName + "Vol.mesh"; // GMF mesh file
1894 aResSolFileName = aGenericName + "Vol.sol"; // GMF mesh file
1895 aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
1896 aSolFileName = aGenericNameRequired + ".sol"; // GMF solution file
1898 std::map <int, int> nodeID2nodeIndexMap;
1899 std::map<std::vector<double>, std::string> enfVerticesWithGroup;
1900 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexCoordsValues coordsSizeMap;
1901 TopoDS_Shape GeomShape;
1902 std::vector<double> coords;
1904 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertex* enfVertex;
1906 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList enfVertices = GHS3DPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1907 GHS3DPlugin_Hypothesis::TGHS3DEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
1909 for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
1911 enfVertex = (*enfVerIt);
1912 if (enfVertex->coords.size()) {
1913 coordsSizeMap.insert(make_pair(enfVertex->coords,enfVertex->size));
1914 enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
1917 GeomShape = entryToShape(enfVertex->geomEntry);
1918 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1920 if (it.Value().ShapeType() == TopAbs_VERTEX){
1921 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
1922 coords.push_back(aPnt.X());
1923 coords.push_back(aPnt.Y());
1924 coords.push_back(aPnt.Z());
1925 if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
1926 coordsSizeMap.insert(make_pair(coords,enfVertex->size));
1927 enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
1934 GHS3DPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = GHS3DPlugin_Hypothesis::GetEnforcedNodes(_hyp);
1935 GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = GHS3DPlugin_Hypothesis::GetEnforcedEdges(_hyp);
1936 GHS3DPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = GHS3DPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
1937 GHS3DPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = GHS3DPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
1941 size_t nbEnforcedVertices = coordsSizeMap.size();
1942 size_t nbEnforcedNodes = enforcedNodes.size();
1943 (nbEnforcedNodes <= 1) ? tmpStr = "node" : tmpStr = "nodes";
1944 std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
1945 (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : tmpStr = "vertices";
1946 std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
1948 std::vector <const SMDS_MeshNode*> aNodeByGhs3dId, anEnforcedNodeByGhs3dId;
1949 std::vector <const SMDS_MeshElement*> aFaceByGhs3dId;
1950 std::map<const SMDS_MeshNode*,int> aNodeToGhs3dIdMap;
1951 std::vector<std::string> aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId;
1954 MG_Tetra_API mgTetra( _computeCanceled, _progress );
1956 _isLibUsed = mgTetra.IsLibrary();
1957 if ( theMesh.NbQuadrangles() > 0 )
1958 _progressAdvance /= 10;
1960 // proxyMesh must live till readGMFFile() as a proxy face can be used by
1961 // MG-Tetra for domain indication
1962 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
1963 if ( theMesh.NbQuadrangles() > 0 )
1965 StdMeshers_QuadToTriaAdaptor* aQuad2Trias = new StdMeshers_QuadToTriaAdaptor;
1966 Ok = aQuad2Trias->Compute( theMesh );
1967 proxyMesh.reset( aQuad2Trias );
1972 int anInvalidEnforcedFlags = 0;
1973 Ok = writeGMFFile(&mgTetra,
1974 aGMFFileName.ToCString(), aRequiredVerticesFileName.ToCString(), aSolFileName.ToCString(),
1975 *proxyMesh, *theHelper,
1976 aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
1977 aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
1978 enforcedNodes, enforcedEdges, enforcedTriangles,
1979 enfVerticesWithGroup, coordsSizeMap, anInvalidEnforcedFlags);
1981 // -----------------
1982 // run MG-Tetra mesher
1983 // -----------------
1985 TCollection_AsciiString cmd = GHS3DPlugin_Hypothesis::CommandToRun( _hyp, false, mgTetra.IsExecutable() ).c_str();
1987 if ( mgTetra.IsExecutable() )
1989 cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
1990 if ( nbEnforcedVertices + nbEnforcedNodes)
1991 cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
1992 cmd += TCollection_AsciiString(" --out ") + aResultFileName;
1994 if ( !_logInStandardOutput )
1996 mgTetra.SetLogFile( aLogFileName.ToCString() );
1997 cmd += TCollection_AsciiString(" 1>" ) + aLogFileName; // dump into file
2001 BRIEF_INFOS("MG-Tetra execution...")
2004 _computeCanceled = false;
2007 Ok = mgTetra.Compute( cmd.ToCString(), errStr ); // run
2009 if ( _logInStandardOutput && mgTetra.IsLibrary() ) {
2011 BRIEF_INFOS(mgTetra.GetLog());
2016 BRIEF_INFOS("End of MG-Tetra execution !");
2023 GHS3DPlugin_Hypothesis::TSetStrings groupsToRemove = GHS3DPlugin_Hypothesis::GetGroupsToRemove(_hyp);
2024 const bool toMakeGroupsOfDomains = GHS3DPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
2026 Ok = Ok && readGMFFile(&mgTetra,
2027 aResultFileName.ToCString(),
2029 theHelper, aNodeByGhs3dId, aFaceByGhs3dId, aNodeToGhs3dIdMap,
2030 aNodeGroupByGhs3dId, anEdgeGroupByGhs3dId, aFaceGroupByGhs3dId,
2031 groupsToRemove, toMakeGroupsOfDomains);
2033 updateMeshGroups(theHelper->GetMesh(), groupsToRemove);
2034 removeEmptyGroupsOfDomains( theHelper->GetMesh(), /*notEmptyAsWell =*/ !toMakeGroupsOfDomains );
2037 GHS3DPlugin_Hypothesis* that = (GHS3DPlugin_Hypothesis*)this->_hyp;
2039 that->ClearGroupsToRemove();
2041 // ---------------------
2042 // remove working files
2043 // ---------------------
2047 if ( anInvalidEnforcedFlags )
2048 error( COMPERR_WARNING, flagsToErrorStr( anInvalidEnforcedFlags ));
2049 if ( _removeLogOnSuccess )
2050 removeFile( aLogFileName );
2052 //if ( !toMakeGroupsOfDomains && _hyp && _hyp->GetToMakeGroupsOfDomains() )
2053 //error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since 'toMeshHoles' is OFF." );
2055 else if ( mgTetra.HasLog() )
2057 if( _computeCanceled )
2058 error( "interruption initiated by user" );
2061 // get problem description from the log file
2062 _Ghs2smdsConvertor conv( aNodeByGhs3dId, proxyMesh );
2063 error( getErrorDescription( _logInStandardOutput ? 0 : aLogFileName.ToCString(),
2064 mgTetra.GetLog(), conv ));
2068 // the log file is empty
2069 removeFile( aLogFileName );
2070 INFOS( "MG-Tetra Error, " << errStr);
2071 error(COMPERR_ALGO_FAILED, errStr);
2076 if (! Ok && _computeCanceled)
2077 removeFile( aLogFileName );
2078 removeFile( aGMFFileName );
2079 removeFile( aResultFileName );
2080 removeFile( aRequiredVerticesFileName );
2081 removeFile( aSolFileName );
2082 removeFile( aResSolFileName );
2087 void GHS3DPlugin_GHS3D::CancelCompute()
2089 _computeCanceled = true;
2090 #if !defined WIN32 && !defined __APPLE__
2091 std::string cmd = "ps xo pid,args | grep " + _genericName;
2092 //cmd += " | grep -e \"^ *[0-9]\\+ \\+" + GHS3DPlugin_Hypothesis::GetExeName() + "\"";
2093 cmd += " | awk '{print $1}' | xargs kill -9 > /dev/null 2>&1";
2094 system( cmd.c_str() );
2098 //================================================================================
2100 * \brief Provide human readable text by error code reported by MG-Tetra
2102 //================================================================================
2104 static const char* translateError(const int errNum)
2108 return "The surface mesh includes a face of type other than edge, "
2109 "triangle or quadrilateral. This face type is not supported.";
2111 return "Not enough memory for the face table.";
2113 return "Not enough memory.";
2115 return "Not enough memory.";
2117 return "Face is ignored.";
2119 return "End of file. Some data are missing in the file.";
2121 return "Read error on the file. There are wrong data in the file.";
2123 return "the metric file is inadequate (dimension other than 3).";
2125 return "the metric file is inadequate (values not per vertices).";
2127 return "the metric file contains more than one field.";
2129 return "the number of values in the \".bb\" (metric file) is incompatible with the expected"
2130 "value of number of mesh vertices in the \".noboite\" file.";
2132 return "Too many sub-domains.";
2134 return "the number of vertices is negative or null.";
2136 return "the number of faces is negative or null.";
2138 return "A face has a null vertex.";
2140 return "incompatible data.";
2142 return "the number of vertices is negative or null.";
2144 return "the number of vertices is negative or null (in the \".mesh\" file).";
2146 return "the number of faces is negative or null.";
2148 return "A face appears more than once in the input surface mesh.";
2150 return "An edge appears more than once in the input surface mesh.";
2152 return "A face has a vertex negative or null.";
2154 return "NOT ENOUGH MEMORY.";
2156 return "Not enough available memory.";
2158 return "Some initial points cannot be inserted. The surface mesh is probably very bad "
2159 "in terms of quality or the input list of points is wrong.";
2161 return "Some vertices are too close to one another or coincident.";
2163 return "Some vertices are too close to one another or coincident.";
2165 return "A vertex cannot be inserted.";
2167 return "There are at least two points considered as coincident.";
2169 return "Some vertices are too close to one another or coincident.";
2171 return "The surface mesh regeneration step has failed.";
2173 return "Constrained edge cannot be enforced.";
2175 return "Constrained face cannot be enforced.";
2177 return "Missing faces.";
2179 return "No guess to start the definition of the connected component(s).";
2181 return "The surface mesh includes at least one hole. The domain is not well defined.";
2183 return "Impossible to define a component.";
2185 return "The surface edge intersects another surface edge.";
2187 return "The surface edge intersects the surface face.";
2189 return "One boundary point lies within a surface face.";
2191 return "One surface edge intersects a surface face.";
2193 return "One boundary point lies within a surface edge.";
2195 return "Insufficient memory ressources detected due to a bad quality surface mesh leading "
2196 "to too many swaps.";
2198 return "Edge is unique (i.e., bounds a hole in the surface).";
2200 return "Presumably, the surface mesh is not compatible with the domain being processed.";
2202 return "Too many components, too many sub-domain.";
2204 return "The surface mesh includes at least one hole. "
2205 "Therefore there is no domain properly defined.";
2207 return "Statistics.";
2209 return "Statistics.";
2211 return "Warning, it is dramatically tedious to enforce the boundary items.";
2213 return "Not enough memory at this time, nevertheless, the program continues. "
2214 "The expected mesh will be correct but not really as large as required.";
2216 return "see above error code, resulting quality may be poor.";
2218 return "Not enough memory at this time, nevertheless, the program continues (warning).";
2220 return "Unknown face type.";
2223 return "End of file. Some data are missing in the file.";
2225 return "A too small volume element is detected.";
2227 return "There exists at least a null or negative volume element.";
2229 return "There exist null or negative volume elements.";
2231 return "A too small volume element is detected. A face is considered being degenerated.";
2233 return "Some element is suspected to be very bad shaped or wrong.";
2235 return "A too bad quality face is detected. This face is considered degenerated.";
2237 return "A too bad quality face is detected. This face is degenerated.";
2239 return "Presumably, the surface mesh is not compatible with the domain being processed.";
2241 return "Abnormal error occured, contact hotline.";
2243 return "Not enough memory for the face table.";
2245 return "The algorithm cannot run further. "
2246 "The surface mesh is probably very bad in terms of quality.";
2248 return "Bad vertex number.";
2250 return "Cannot close mesh file NomFil.";
2252 return "There are wrong data.";
2254 return "The number of faces is negative or null.";
2256 return "The number of vertices is negative or null in the '.sol' file.";
2258 return "The number of tetrahedra is negative or null.";
2260 return "The number of vertices is negative or null.";
2262 return "A face has a vertex negative or null.";
2264 return "The field is not a size in file NomFil.";
2266 return "A count is wrong in the enclosing box in the .boite.mesh input "
2267 "file (option '--read_boite').";
2269 return "A tetrahedron has a vertex with a negative number.";
2271 return "the 'MeshVersionFormatted' is not 1 or 2 in the '.mesh' file or the '.sol'.";
2273 return "The number of values in the '.sol' (metric file) is incompatible with "
2274 "the expected value of number of mesh vertices in the '.mesh' file.";
2276 return "Not enough memory.";
2278 return "Not enough memory for the face table.";
2280 return "Insufficient memory ressources detected due to a bad quality "
2281 "surface mesh leading to too many swaps.";
2283 return "The surface coordinates of a vertex are differing from the "
2284 "volume coordinates, probably due to a precision problem.";
2286 return "Invalid dimension. Dimension 3 expected.";
2288 return "A point has a tag 0. This point is probably outside the domain which has been meshed.";
2290 return "The vertices of an element are too close to one another or coincident.";
2292 return "There are at least two points whose distance is very small, and considered as coincident.";
2294 return "Two vertices are too close to one another or coincident.";
2296 return "A vertex cannot be inserted.";
2298 return "Two vertices are too close to one another or coincident. Note : When "
2299 "this error occurs during the overconstrained processing phase, this is only "
2300 "a warning which means that it is difficult to break some overconstrained facets.";
2302 return "Two surface edges are intersecting.";
2304 return "A surface edge intersects a surface face.";
2306 return "A boundary point lies within a surface face.";
2308 return "A boundary point lies within a surface edge.";
2310 return "A surface mesh appears more than once in the input surface mesh.";
2312 return "An edge appears more than once in the input surface mesh.";
2314 return "Surface with unvalid triangles.";
2316 return "The metric in the '.sol' file contains more than one field.";
2318 return "The surface mesh includes at least one hole. The domain is not well defined.";
2320 return "Presumably, the surface mesh is not compatible with the domain being processed (warning).";
2322 return "Probable faces overlapping somewher.";
2324 return "The quadratic version does not work with prescribed free edges.";
2326 return "The quadratic version does not work with a volume mesh.";
2328 return "The metric in the '.sol' file is inadequate (values not per vertices).";
2330 return "The number of vertices in the '.sol' is different from the one in the "
2331 "'.mesh' file for the required vertices (option '--required_vertices').";
2333 return "More than one type in file NomFil. The type must be equal to 1 in the '.sol'"
2334 "for the required vertices (option '--required_vertices').";
2336 return "Bad vertex number.";
2338 return "No guess to start the definition of the connected component(s).";
2340 return "Some initial points cannot be inserted.";
2342 return "A too bad quality face is detected. This face is considered degenerated.";
2344 return "A too bad quality face is detected. This face is degenerated.";
2346 return "The algorithm cannot run further.";
2348 return "A too small volume element is detected.";
2350 return "A tetrahedra is suspected to be very bad shaped or wrong.";
2352 return "There is at least a null or negative volume element. The resulting mesh"
2353 "may be inappropriate.";
2355 return "There are some null or negative volume element. The resulting mesh may"
2356 "be inappropriate.";
2358 return "An edge is unique (i.e., bounds a hole in the surface).";
2360 return "Abnormal or internal error.";
2362 return "Too many components with respect to too many sub-domain.";
2364 return "An internal error has been encountered or a signal has been received. "
2365 "Current mesh will not be saved.";
2367 return "Impossible to define a component.";
2369 return "There are some overconstrained edges.";
2371 return "There are some overconstrained facets.";
2373 return "Give the number of missing faces (information given when regeneration phase failed).";
2375 return "A constrained face cannot be enforced (information given when regeneration phase failed).";
2377 return "A constrained edge cannot be enforced.";
2379 return "It is dramatically tedious to enforce the boundary items.";
2381 return "The surface mesh regeneration step has failed. A .boite.mesh and .boite.map files are created.";
2383 return "Invalid resulting mesh.";
2385 return "P2 correction not successful.";
2387 return "Program has received an interruption or a termination signal sent by the "
2388 "user or the system administrator. Current mesh will not be saved.";
2393 //================================================================================
2395 * \brief Retrieve from a string given number of integers
2397 //================================================================================
2399 static char* getIds( char* ptr, int nbIds, vector<int>& ids )
2402 ids.reserve( nbIds );
2405 while ( !isdigit( *ptr )) ++ptr;
2406 if ( ptr[-1] == '-' ) --ptr;
2407 ids.push_back((int) strtol( ptr, &ptr, 10 ));
2413 //================================================================================
2415 * \brief Retrieve problem description form a log file
2416 * \retval bool - always false
2418 //================================================================================
2420 SMESH_ComputeErrorPtr
2421 GHS3DPlugin_GHS3D::getErrorDescription(const char* logFile,
2422 const std::string& log,
2423 const _Ghs2smdsConvertor & toSmdsConvertor,
2424 const bool isOk/* = false*/ )
2426 SMESH_BadInputElements* badElemsErr =
2427 new SMESH_BadInputElements( toSmdsConvertor.getMesh(), COMPERR_ALGO_FAILED );
2428 SMESH_ComputeErrorPtr err( badElemsErr );
2430 char* ptr = const_cast<char*>( log.c_str() );
2431 char* buf = ptr, * bufEnd = ptr + log.size();
2434 SMESH_Comment errDescription;
2436 enum { NODE = 1, EDGE, TRIA, VOL, SKIP_ID = 1 };
2438 // look for MeshGems version
2439 // Since "MG-TETRA -- MeshGems 1.1-3 (January, 2013)" error codes change.
2440 // To discriminate old codes from new ones we add 1000000 to the new codes.
2441 // This way value of the new codes is same as absolute value of codes printed
2442 // in the log after "MGMESSAGE" string.
2443 int versionAddition = 0;
2446 while ( ++verPtr < bufEnd )
2448 if ( strncmp( verPtr, "MG-TETRA -- MeshGems ", 21 ) != 0 )
2450 if ( strcmp( verPtr, "MG-TETRA -- MeshGems 1.1-3 " ) >= 0 )
2451 versionAddition = 1000000;
2457 // look for errors "ERR #"
2459 set<string> foundErrorStr; // to avoid reporting same error several times
2460 set<int> elemErrorNums; // not to report different types of errors with bad elements
2461 while ( ++ptr < bufEnd )
2463 if ( strncmp( ptr, "ERR ", 4 ) != 0 )
2466 list<const SMDS_MeshElement*>& badElems = badElemsErr->myBadElements;
2467 vector<int> nodeIds;
2471 int errNum = int( strtol(ptr, &ptr, 10) + versionAddition );
2472 // we treat errors enumerated in [SALOME platform 0019316] issue
2473 // and all errors from a new (Release 1.1) MeshGems User Manual
2475 case 0015: // The face number (numfac) with vertices (f 1, f 2, f 3) has a null vertex.
2476 case 1005620 : // a too bad quality face is detected. This face is considered degenerated.
2477 ptr = getIds(ptr, SKIP_ID, nodeIds);
2478 ptr = getIds(ptr, TRIA, nodeIds);
2479 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2481 case 1005621 : // a too bad quality face is detected. This face is degenerated.
2482 // hence the is degenerated it is invisible, add its edges in addition
2483 ptr = getIds(ptr, SKIP_ID, nodeIds);
2484 ptr = getIds(ptr, TRIA, nodeIds);
2485 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2487 vector<int> edgeNodes( nodeIds.begin(), --nodeIds.end() ); // 01
2488 badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2489 edgeNodes[1] = nodeIds[2]; // 02
2490 badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2491 edgeNodes[0] = nodeIds[1]; // 12
2494 case 1000: // Face (f 1, f 2, f 3) appears more than once in the input surface mesh.
2496 case 1002: // Face (f 1, f 2, f 3) has a vertex negative or null
2497 case 3019: // Constrained face (f 1, f 2, f 3) cannot be enforced
2498 case 1002211: // a face has a vertex negative or null.
2499 case 1005200 : // a surface mesh appears more than once in the input surface mesh.
2500 case 1008423 : // a constrained face cannot be enforced (regeneration phase failed).
2501 ptr = getIds(ptr, TRIA, nodeIds);
2502 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2504 case 1001: // Edge (e1, e2) appears more than once in the input surface mesh
2505 case 3009: // Constrained edge (e1, e2) cannot be enforced (warning).
2506 // ERR 3109 : EDGE 5 6 UNIQUE
2507 case 3109: // Edge (e1, e2) is unique (i.e., bounds a hole in the surface)
2508 case 1005210 : // an edge appears more than once in the input surface mesh.
2509 case 1005820 : // an edge is unique (i.e., bounds a hole in the surface).
2510 case 1008441 : // a constrained edge cannot be enforced.
2511 ptr = getIds(ptr, EDGE, nodeIds);
2512 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2514 case 2004: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
2515 case 2014: // at least two points whose distance is dist, i.e., considered as coincident
2516 case 2103: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
2517 // ERR 2103 : 16 WITH 3
2518 case 1005105 : // two vertices are too close to one another or coincident.
2519 case 1005107: // Two vertices are too close to one another or coincident.
2520 ptr = getIds(ptr, NODE, nodeIds);
2521 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2522 ptr = getIds(ptr, NODE, nodeIds);
2523 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2525 case 2012: // Vertex v1 cannot be inserted (warning).
2526 case 1005106 : // a vertex cannot be inserted.
2527 ptr = getIds(ptr, NODE, nodeIds);
2528 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2530 case 3103: // The surface edge (e1, e2) intersects another surface edge (e3, e4)
2531 case 1005110 : // two surface edges are intersecting.
2532 // ERR 3103 : 1 2 WITH 7 3
2533 ptr = getIds(ptr, EDGE, nodeIds);
2534 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2535 ptr = getIds(ptr, EDGE, nodeIds);
2536 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2538 case 3104: // The surface edge (e1, e2) intersects the surface face (f 1, f 2, f 3)
2539 // ERR 3104 : 9 10 WITH 1 2 3
2540 case 3106: // One surface edge (say e1, e2) intersects a surface face (f 1, f 2, f 3)
2541 case 1005120 : // a surface edge intersects a surface face.
2542 ptr = getIds(ptr, EDGE, nodeIds);
2543 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2544 ptr = getIds(ptr, TRIA, nodeIds);
2545 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2547 case 3105: // One boundary point (say p1) lies within a surface face (f 1, f 2, f 3)
2548 // ERR 3105 : 8 IN 2 3 5
2549 case 1005150 : // a boundary point lies within a surface face.
2550 ptr = getIds(ptr, NODE, nodeIds);
2551 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2552 ptr = getIds(ptr, TRIA, nodeIds);
2553 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2555 case 3107: // One boundary point (say p1) lies within a surface edge (e1, e2) (stop).
2556 // ERR 3107 : 2 IN 4 1
2557 case 1005160 : // a boundary point lies within a surface edge.
2558 ptr = getIds(ptr, NODE, nodeIds);
2559 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2560 ptr = getIds(ptr, EDGE, nodeIds);
2561 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2563 case 9000: // ERR 9000
2564 // ELEMENT 261 WITH VERTICES : 7 396 -8 242
2565 // VOLUME : -1.11325045E+11 W.R.T. EPSILON 0.
2566 // A too small volume element is detected. Are reported the index of the element,
2567 // its four vertex indices, its volume and the tolerance threshold value
2568 ptr = getIds(ptr, SKIP_ID, nodeIds);
2569 ptr = getIds(ptr, VOL, nodeIds);
2570 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2571 // even if all nodes found, volume it most probably invisible,
2572 // add its faces to demonstrate it anyhow
2574 vector<int> faceNodes( nodeIds.begin(), --nodeIds.end() ); // 012
2575 badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2576 faceNodes[2] = nodeIds[3]; // 013
2577 badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2578 faceNodes[1] = nodeIds[2]; // 023
2579 badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2580 faceNodes[0] = nodeIds[1]; // 123
2581 badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2584 case 9001: // ERR 9001
2585 // %% NUMBER OF NEGATIVE VOLUME TETS : 1
2586 // %% THE LARGEST NEGATIVE TET : 1.75376581E+11
2587 // %% NUMBER OF NULL VOLUME TETS : 0
2588 // There exists at least a null or negative volume element
2591 // There exist n null or negative volume elements
2594 // A too small volume element is detected
2597 // A too bad quality face is detected. This face is considered degenerated,
2598 // its index, its three vertex indices together with its quality value are reported
2599 break; // same as next
2600 case 9112: // ERR 9112
2601 // FACE 2 WITH VERTICES : 4 2 5
2602 // SMALL INRADIUS : 0.
2603 // A too bad quality face is detected. This face is degenerated,
2604 // its index, its three vertex indices together with its inradius are reported
2605 ptr = getIds(ptr, SKIP_ID, nodeIds);
2606 ptr = getIds(ptr, TRIA, nodeIds);
2607 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2608 // add triangle edges as it most probably has zero area and hence invisible
2610 vector<int> edgeNodes(2);
2611 edgeNodes[0] = nodeIds[0]; edgeNodes[1] = nodeIds[1]; // 0-1
2612 badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2613 edgeNodes[1] = nodeIds[2]; // 0-2
2614 badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2615 edgeNodes[0] = nodeIds[1]; // 1-2
2616 badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2619 case 1005103 : // the vertices of an element are too close to one another or coincident.
2620 ptr = getIds(ptr, TRIA, nodeIds);
2621 if ( nodeIds.back() == 0 ) // index of the third vertex of the element (0 for an edge)
2622 nodeIds.resize( EDGE );
2623 badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2627 bool isNewError = foundErrorStr.insert( string( errBeg, ptr )).second;
2629 continue; // not to report same error several times
2631 // const SMDS_MeshElement* nullElem = 0;
2632 // bool allElemsOk = ( find( badElems.begin(), badElems.end(), nullElem) == badElems.end());
2634 // if ( allElemsOk && !badElems.empty() && !elemErrorNums.empty() ) {
2635 // bool oneMoreErrorType = elemErrorNums.insert( errNum ).second;
2636 // if ( oneMoreErrorType )
2637 // continue; // not to report different types of errors with bad elements
2641 string text = translateError( errNum );
2642 if ( errDescription.find( text ) == text.npos ) {
2643 if ( !errDescription.empty() )
2644 errDescription << "\n";
2645 errDescription << text;
2650 if ( errDescription.empty() ) { // no errors found
2651 char msgLic1[] = "connection to server failed";
2652 char msgLic2[] = " Dlim ";
2653 char msgLic3[] = "license is not valid";
2654 if ( search( &buf[0], bufEnd, msgLic1, msgLic1 + strlen(msgLic1)) != bufEnd ||
2655 search( &buf[0], bufEnd, msgLic2, msgLic2 + strlen(msgLic2)) != bufEnd )
2656 errDescription << "Network license problem.";
2657 else if ( search( &buf[0], bufEnd, msgLic3, msgLic3 + strlen(msgLic3)) != bufEnd )
2658 errDescription << "License is not valid.";
2661 char msg2[] = "SEGMENTATION FAULT";
2662 if ( search( &buf[0], bufEnd, msg2, msg2 + strlen(msg2)) != bufEnd )
2663 errDescription << "MG-Tetra: SEGMENTATION FAULT. ";
2667 if ( !isOk && logFile && logFile[0] )
2669 if ( errDescription.empty() )
2670 errDescription << "See " << logFile << " for problem description";
2672 errDescription << "\nSee " << logFile << " for more information";
2675 err->myComment = errDescription;
2677 if ( err->myComment.empty() && !err->HasBadElems() )
2678 err = SMESH_ComputeError::New(); // OK
2683 //================================================================================
2685 * \brief Creates _Ghs2smdsConvertor
2687 //================================================================================
2689 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const map <int,const SMDS_MeshNode*> & ghs2NodeMap,
2690 SMESH_ProxyMesh::Ptr mesh)
2691 :_ghs2NodeMap( & ghs2NodeMap ), _nodeByGhsId( 0 ), _mesh( mesh )
2695 //================================================================================
2697 * \brief Creates _Ghs2smdsConvertor
2699 //================================================================================
2701 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const vector <const SMDS_MeshNode*> & nodeByGhsId,
2702 SMESH_ProxyMesh::Ptr mesh)
2703 : _ghs2NodeMap( 0 ), _nodeByGhsId( &nodeByGhsId ), _mesh( mesh )
2707 //================================================================================
2709 * \brief Return SMDS element by ids of MG-Tetra nodes
2711 //================================================================================
2713 const SMDS_MeshElement* _Ghs2smdsConvertor::getElement(const vector<int>& ghsNodes) const
2715 size_t nbNodes = ghsNodes.size();
2716 vector<const SMDS_MeshNode*> nodes( nbNodes, 0 );
2717 for ( size_t i = 0; i < nbNodes; ++i ) {
2718 int ghsNode = ghsNodes[ i ];
2719 if ( _ghs2NodeMap ) {
2720 map <int,const SMDS_MeshNode*>::const_iterator in = _ghs2NodeMap->find( ghsNode);
2721 if ( in == _ghs2NodeMap->end() )
2723 nodes[ i ] = in->second;
2726 if ( ghsNode < 1 || ghsNode > (int)_nodeByGhsId->size() )
2728 nodes[ i ] = (*_nodeByGhsId)[ ghsNode-1 ];
2734 if ( nbNodes == 2 ) {
2735 const SMDS_MeshElement* edge= SMDS_Mesh::FindEdge( nodes[0], nodes[1] );
2736 if ( !edge || edge->GetID() < 1 || _mesh->IsTemporary( edge ))
2737 edge = new SMDS_LinearEdge( nodes[0], nodes[1] );
2740 if ( nbNodes == 3 ) {
2741 const SMDS_MeshElement* face = SMDS_Mesh::FindFace( nodes );
2742 if ( !face || face->GetID() < 1 || _mesh->IsTemporary( face ))
2743 face = new SMDS_FaceOfNodes( nodes[0], nodes[1], nodes[2] );
2747 return new SMDS_VolumeOfNodes( nodes[0], nodes[1], nodes[2], nodes[3] );
2752 //================================================================================
2754 * \brief Return a mesh
2756 //================================================================================
2758 const SMDS_Mesh* _Ghs2smdsConvertor::getMesh() const
2760 return _mesh->GetMeshDS();
2763 //=============================================================================
2767 //=============================================================================
2768 bool GHS3DPlugin_GHS3D::Evaluate(SMESH_Mesh& aMesh,
2769 const TopoDS_Shape& aShape,
2770 MapShapeNbElems& aResMap)
2772 smIdType nbtri = 0, nbqua = 0;
2773 double fullArea = 0.0;
2774 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
2775 TopoDS_Face F = TopoDS::Face( exp.Current() );
2776 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
2777 MapShapeNbElemsItr anIt = aResMap.find(sm);
2778 if( anIt==aResMap.end() ) {
2779 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2780 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
2781 "Submesh can not be evaluated",this));
2784 std::vector<smIdType> aVec = (*anIt).second;
2785 nbtri += std::max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
2786 nbqua += std::max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2788 BRepGProp::SurfaceProperties(F,G);
2789 double anArea = G.Mass();
2793 // collect info from edges
2794 smIdType nb0d_e = 0, nb1d_e = 0;
2795 bool IsQuadratic = false;
2796 bool IsFirst = true;
2797 TopTools_MapOfShape tmpMap;
2798 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
2799 TopoDS_Edge E = TopoDS::Edge(exp.Current());
2800 if( tmpMap.Contains(E) )
2803 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
2804 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
2805 std::vector<smIdType> aVec = (*anIt).second;
2806 nb0d_e += aVec[SMDSEntity_Node];
2807 nb1d_e += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
2809 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
2815 double ELen = sqrt(2.* ( fullArea/double(nbtri+nbqua*2) ) / sqrt(3.0) );
2818 BRepGProp::VolumeProperties(aShape,G);
2819 double aVolume = G.Mass();
2820 double tetrVol = 0.1179*ELen*ELen*ELen;
2821 double CoeffQuality = 0.9;
2822 smIdType nbVols = smIdType(aVolume/tetrVol/CoeffQuality);
2823 smIdType nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
2824 smIdType nb1d_in = (smIdType) ( nbVols*6 - nb1d_e - nb1d_f ) / 5;
2825 std::vector<smIdType> aVec(SMDSEntity_Last);
2826 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2828 aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
2829 aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
2830 aVec[SMDSEntity_Quad_Pyramid] = nbqua;
2833 aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
2834 aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
2835 aVec[SMDSEntity_Pyramid] = nbqua;
2837 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
2838 aResMap.insert(std::make_pair(sm,aVec));
2843 bool GHS3DPlugin_GHS3D::importGMFMesh(const char* theGMFFileName, SMESH_Mesh& theMesh)
2845 SMESH_ComputeErrorPtr err = theMesh.GMFToMesh( theGMFFileName, /*makeRequiredGroups =*/ true );
2847 theMesh.GetMeshDS()->Modified();
2849 return ( !err || err->IsOK());
2854 //================================================================================
2856 * \brief Sub-mesh event listener setting enforced elements as soon as an enforced
2859 struct _EnforcedMeshRestorer : public SMESH_subMeshEventListener
2861 _EnforcedMeshRestorer():
2862 SMESH_subMeshEventListener( /*isDeletable = */true, Name() )
2865 //================================================================================
2867 * \brief Returns an ID of listener
2869 static const char* Name() { return "GHS3DPlugin_GHS3D::_EnforcedMeshRestorer"; }
2871 //================================================================================
2873 * \brief Treat events of the subMesh
2875 void ProcessEvent(const int event,
2876 const int eventType,
2877 SMESH_subMesh* /*subMesh*/,
2878 SMESH_subMeshEventListenerData* data,
2879 const SMESH_Hypothesis* /*hyp*/)
2881 if ( SMESH_subMesh::SUBMESH_LOADED == event &&
2882 SMESH_subMesh::COMPUTE_EVENT == eventType &&
2884 !data->mySubMeshes.empty() )
2886 // An enforced mesh (subMesh->_father) has been loaded from hdf file
2887 if ( GHS3DPlugin_Hypothesis* hyp = GetGHSHypothesis( data->mySubMeshes.front() ))
2888 hyp->RestoreEnfElemsByMeshes();
2891 //================================================================================
2893 * \brief Returns GHS3DPlugin_Hypothesis used to compute a subMesh
2895 static GHS3DPlugin_Hypothesis* GetGHSHypothesis( SMESH_subMesh* subMesh )
2897 SMESH_HypoFilter ghsHypFilter
2898 ( SMESH_HypoFilter::HasName( GHS3DPlugin_Hypothesis::GetHypType() ));
2899 return (GHS3DPlugin_Hypothesis* )
2900 subMesh->GetFather()->GetHypothesis( subMesh->GetSubShape(),
2902 /*visitAncestors=*/true);
2906 //================================================================================
2908 * \brief Sub-mesh event listener removing empty groups created due to "To make
2909 * groups of domains".
2911 struct _GroupsOfDomainsRemover : public SMESH_subMeshEventListener
2913 _GroupsOfDomainsRemover():
2914 SMESH_subMeshEventListener( /*isDeletable = */true,
2915 "GHS3DPlugin_GHS3D::_GroupsOfDomainsRemover" ) {}
2917 * \brief Treat events of the subMesh
2919 void ProcessEvent(const int /*event*/,
2920 const int eventType,
2921 SMESH_subMesh* subMesh,
2922 SMESH_subMeshEventListenerData* /*data*/,
2923 const SMESH_Hypothesis* /*hyp*/)
2925 if (SMESH_subMesh::ALGO_EVENT == eventType &&
2926 !subMesh->GetAlgo() )
2928 removeEmptyGroupsOfDomains( subMesh->GetFather(), /*notEmptyAsWell=*/true );
2934 //================================================================================
2936 * \brief Set an event listener to set enforced elements as soon as an enforced
2939 //================================================================================
2941 void GHS3DPlugin_GHS3D::SubmeshRestored(SMESH_subMesh* subMesh)
2943 if ( GHS3DPlugin_Hypothesis* hyp = _EnforcedMeshRestorer::GetGHSHypothesis( subMesh ))
2945 GHS3DPlugin_Hypothesis::TGHS3DEnforcedMeshList enfMeshes = hyp->_GetEnforcedMeshes();
2946 GHS3DPlugin_Hypothesis::TGHS3DEnforcedMeshList::iterator it = enfMeshes.begin();
2947 for(;it != enfMeshes.end();++it) {
2948 GHS3DPlugin_Hypothesis::TGHS3DEnforcedMesh* enfMesh = *it;
2949 if ( SMESH_Mesh* mesh = GetMeshByPersistentID( enfMesh->persistID ))
2951 SMESH_subMesh* smToListen = mesh->GetSubMesh( mesh->GetShapeToMesh() );
2952 // a listener set to smToListen will care of hypothesis stored in SMESH_EventListenerData
2953 subMesh->SetEventListener( new _EnforcedMeshRestorer(),
2954 SMESH_subMeshEventListenerData::MakeData( subMesh ),
2961 //================================================================================
2963 * \brief Sets an event listener removing empty groups created due to "To make
2964 * groups of domains".
2965 * \param subMesh - submesh where algo is set
2967 * This method is called when a submesh gets HYP_OK algo_state.
2968 * After being set, event listener is notified on each event of a submesh.
2970 //================================================================================
2972 void GHS3DPlugin_GHS3D::SetEventListener(SMESH_subMesh* subMesh)
2974 subMesh->SetEventListener( new _GroupsOfDomainsRemover(), 0, subMesh );
2977 //================================================================================
2979 * \brief If possible, returns progress of computation [0.,1.]
2981 //================================================================================
2983 double GHS3DPlugin_GHS3D::GetProgress() const
2987 // this->_progress is advanced by MG_Tetra_API according to messages from MG library
2988 // but sharply. Advance it a bit to get smoother advancement.
2989 GHS3DPlugin_GHS3D* me = const_cast<GHS3DPlugin_GHS3D*>( this );
2990 if ( _progress < 0.1 ) // the first message is at 10%
2991 me->_progress = GetProgressByTic();
2992 else if ( _progress < 0.98 )
2993 me->_progress += _progressAdvance;