1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 // File : HexoticPlugin_Hexotic.cxx
22 // Author : Lioka RAZAFINDRAZAKA (CEA)
25 #include "HexoticPlugin_Hexotic.hxx"
26 #include "HexoticPlugin_Hypothesis.hxx"
28 #include "utilities.h"
31 #include <sys/sysinfo.h>
44 #include <SMESHDS_Mesh.hxx>
45 #include <SMESHDS_GroupBase.hxx>
46 #include <SMESH_ComputeError.hxx>
47 #include <SMESH_File.hxx>
48 #include <SMESH_Gen.hxx>
49 #include <SMESH_HypoFilter.hxx>
50 #include <SMESH_MesherHelper.hxx>
51 #include <SMESH_subMesh.hxx>
57 #include <Standard_ProgramError.hxx>
59 #include <BRep_Tool.hxx>
60 #include <BRepBndLib.hxx>
61 #include <BRepClass3d_SolidClassifier.hxx>
62 #include <BRepBuilderAPI_MakeVertex.hxx>
63 #include <BRepExtrema_DistShapeShape.hxx>
64 #include <OSD_File.hxx>
65 #include <Precision.hxx>
66 #include <TopExp_Explorer.hxx>
67 #include <TopTools_MapOfShape.hxx>
71 #include <GCPnts_UniformAbscissa.hxx>
72 #include <IntCurvesFace_Intersector.hxx>
73 #include <BRepMesh_IncrementalMesh.hxx>
74 #include <Poly_Triangulation.hxx>
76 #include <GeomAdaptor_Curve.hxx>
78 #include <Basics_Utils.hxx>
79 #include "GEOMImpl_Types.hxx"
80 #include "GEOM_wrap.hxx"
82 static void removeFile( const TCollection_AsciiString& fileName )
85 OSD_File( fileName ).Remove();
87 catch ( Standard_ProgramError ) {
88 MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
92 //=============================================================================
96 //=============================================================================
98 HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, int studyId, SMESH_Gen* gen)
99 : SMESH_3D_Algo(hypId, studyId, gen)
101 MESSAGE("HexoticPlugin_Hexotic::HexoticPlugin_Hexotic");
103 _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
104 // _onlyUnaryInput = false;
105 _requireShape = false;
108 _hexoticFilesKept=false;
109 _compatibleHypothesis.push_back( HexoticPlugin_Hypothesis::GetHypType() );
110 #ifdef WITH_BLSURFPLUGIN
113 _compute_canceled = false;
115 // Copy of what is done in BLSURFPLugin TODO : share the code
116 smeshGen_i = SMESH_Gen_i::GetSMESHGen();
117 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
118 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
121 myStudy = aStudyMgr->GetStudyByID(_studyId);
123 MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
126 //=============================================================================
130 //=============================================================================
132 HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic()
134 MESSAGE("HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic");
138 #ifdef WITH_BLSURFPLUGIN
139 bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh& aMesh,
140 const TopoDS_Shape& aShape )
142 // MESSAGE("HexoticPlugin_Hexotic::CheckBLSURFHypothesis");
145 std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
146 const SMESHDS_Hypothesis* theHyp;
148 // If a BLSURF hypothesis is applied, get it
149 SMESH_HypoFilter blsurfFilter;
150 blsurfFilter.Init( blsurfFilter.HasName( BLSURFPlugin_Hypothesis::GetHypType() ));
151 std::list<const SMESHDS_Hypothesis *> appliedHyps;
152 aMesh.GetHypotheses( aShape, blsurfFilter, appliedHyps, false );
154 if ( appliedHyps.size() > 0 ) {
155 itl = appliedHyps.begin();
156 theHyp = (*itl); // use only the first hypothesis
157 std::string hypName = theHyp->GetName();
158 if (hypName == BLSURFPlugin_Hypothesis::GetHypType()) {
159 _blsurfHypo = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
168 //=============================================================================
172 //=============================================================================
174 bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh& aMesh,
175 const TopoDS_Shape& aShape,
176 SMESH_Hypothesis::Hypothesis_Status& aStatus )
178 // MESSAGE("HexoticPlugin_Hexotic::CheckHypothesis");
181 std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
182 const SMESHDS_Hypothesis* theHyp;
184 const std::list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
185 int nbHyp = hyps.size();
187 aStatus = SMESH_Hypothesis::HYP_OK;
188 return true; // can work with no hypothesis
192 theHyp = (*itl); // use only the first hypothesis
194 std::string hypName = theHyp->GetName();
195 if (hypName == HexoticPlugin_Hypothesis::GetHypType() ) {
196 _hypothesis = static_cast<const HexoticPlugin_Hypothesis*> (theHyp);
198 aStatus = SMESH_Hypothesis::HYP_OK;
201 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
203 #ifdef WITH_BLSURFPLUGIN
204 CheckBLSURFHypothesis(aMesh, aShape);
207 return aStatus == SMESH_Hypothesis::HYP_OK;
210 //=======================================================================
211 //function : findShape
213 //=======================================================================
215 static TopoDS_Shape findShape(SMDS_MeshNode** t_Node,
217 const TopoDS_Shape* t_Shape,
222 int iShape, nbNode = 8;
224 for ( int i=0; i<3; i++ ) {
226 for ( int j=0; j<nbNode; j++ ) {
227 if ( i == 0) pntCoor[i] += t_Node[j]->X();
228 if ( i == 1) pntCoor[i] += t_Node[j]->Y();
229 if ( i == 2) pntCoor[i] += t_Node[j]->Z();
231 pntCoor[i] /= nbNode;
233 gp_Pnt aPnt(pntCoor[0], pntCoor[1], pntCoor[2]);
235 if ( aShape.IsNull() ) aShape = t_Shape[0];
236 BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
237 if ( !(SC.State() == TopAbs_IN) ) {
239 for (iShape = 0; iShape < nShape && aShape.IsNull(); iShape++) {
240 if ( !( pntCoor[0] < t_Box[iShape][0] || t_Box[iShape][1] < pntCoor[0] ||
241 pntCoor[1] < t_Box[iShape][2] || t_Box[iShape][3] < pntCoor[1] ||
242 pntCoor[2] < t_Box[iShape][4] || t_Box[iShape][5] < pntCoor[2]) ) {
243 BRepClass3d_SolidClassifier SC (t_Shape[iShape], aPnt, Precision::Confusion());
244 if (SC.State() == TopAbs_IN)
245 aShape = t_Shape[iShape];
252 //=======================================================================
253 //function : getNbShape
255 //=======================================================================
257 static int getNbShape(std::string aFile, std::string aString, int defaultValue=0) {
258 int number = defaultValue;
260 std::ifstream file(aFile.c_str());
261 while ( !file.eof() ) {
262 getline( file, aLine);
263 if ( aLine == aString ) {
264 getline( file, aLine);
265 std::istringstream stringFlux( aLine );
266 stringFlux >> number;
267 number = ( number + defaultValue + std::abs(number - defaultValue) ) / 2;
275 //=======================================================================
276 //function : countShape
278 //=======================================================================
280 template < class Mesh, class Shape >
281 static int countShape( Mesh* mesh, Shape shape ) {
282 TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
283 TopTools_MapOfShape mapShape;
285 for ( ; expShape.More(); expShape.Next() ) {
286 if (mapShape.Add(expShape.Current())) {
293 //=======================================================================
294 //function : getShape
296 //=======================================================================
298 template < class Mesh, class Shape, class Tab >
299 void getShape(Mesh* mesh, Shape shape, Tab *t_Shape) {
300 TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
301 TopTools_MapOfShape mapShape;
302 for ( int i=0; expShape.More(); expShape.Next() ) {
303 if (mapShape.Add(expShape.Current())) {
304 t_Shape[i] = expShape.Current();
311 //=======================================================================
312 //function : printWarning
314 //=======================================================================
316 static void printWarning(const int nbExpected, std::string aString, const int nbFound) {
318 cout << "WARNING : " << nbExpected << " " << aString << " expected, MG-Hexa has found " << nbFound << std::endl;
319 cout << "=======" << std::endl;
324 //=======================================================================
325 //function : removeHexoticFiles
327 //=======================================================================
329 static void removeHexoticFiles(TCollection_AsciiString file_In, TCollection_AsciiString file_Out) {
330 removeFile( file_In );
331 removeFile( file_Out );
334 //=======================================================================
335 //function : splitQuads
336 //purpose : splits all quadrangles into triangles
337 //=======================================================================
339 static void splitQuads(SMESH_Mesh& aMesh)
341 SMESH_MeshEditor spliter( &aMesh );
343 TIDSortedElemSet elems;
344 SMDS_ElemIteratorPtr eIt = aMesh.GetMeshDS()->elementsIterator();
346 elems.insert( elems.end(), eIt->next() );
348 spliter.QuadToTri ( elems, /*the13Diag=*/true);
351 //=======================================================================
352 //function : readResult
353 //purpose : Read GMF file in case of a mesh with geometry
354 //=======================================================================
356 static bool readResult(std::string theFile,
357 HexoticPlugin_Hexotic* theAlgo,
358 SMESHDS_Mesh* theMesh,
360 const TopoDS_Shape* tabShape,
363 // ---------------------------------
364 // Read generated elements and nodes
365 // ---------------------------------
368 TopoDS_Vertex aVertex;
370 int EndOfFile = 0, nbElem = 0, nField = 9, nbRef = 0;
371 int aHexoticNodeID = 0, shapeID, hexoticShapeID;
372 const int IdShapeRef = 2;
373 int *tabID, *tabRef, *nodeAssigne;
374 bool *tabDummy, hasDummy = false;
375 double epsilon = Precision::Confusion();
376 std::map <std::string,int> mapField;
377 SMDS_MeshNode** HexoticNode;
378 TopoDS_Shape *tabCorner, *tabEdge;
380 const int nbDomains = countShape( theMesh, TopAbs_SHELL );
381 const int holeID = -1;
383 // tabID = new int[nbShape];
384 tabID = new int[nbDomains];
385 tabRef = new int[nField];
386 tabDummy = new bool[nField];
388 for (int i=0; i<nbDomains; i++)
390 if ( nbDomains == 1 )
391 tabID[0] = theMesh->ShapeToIndex( tabShape[0] );
393 mapField["MeshVersionFormatted"] = 0; tabRef[0] = 0; tabDummy[0] = false;
394 mapField["Dimension"] = 1; tabRef[1] = 0; tabDummy[1] = false;
395 mapField["Vertices"] = 2; tabRef[2] = 3; tabDummy[2] = true;
396 mapField["Corners"] = 3; tabRef[3] = 1; tabDummy[3] = false;
397 mapField["Edges"] = 4; tabRef[4] = 2; tabDummy[4] = true;
398 mapField["Ridges"] = 5; tabRef[5] = 1; tabDummy[5] = false;
399 mapField["Quadrilaterals"] = 6; tabRef[6] = 4; tabDummy[6] = true;
400 mapField["Hexahedra"] = 7; tabRef[7] = 8; tabDummy[7] = true;
401 mapField["End"] = 8; tabRef[8] = 0; tabDummy[0] = false;
403 SMDS_NodeIteratorPtr itOnHexoticInputNode = theMesh->nodesIterator();
404 while ( itOnHexoticInputNode->more() )
405 theMesh->RemoveNode( itOnHexoticInputNode->next() );
407 int nbVertices = getNbShape(theFile, "Vertices");
408 int nbCorners = getNbShape(theFile, "Corners", countShape( theMesh, TopAbs_VERTEX ));
409 int nbShapeEdge = countShape( theMesh, TopAbs_EDGE );
411 tabCorner = new TopoDS_Shape[ nbCorners ];
412 tabEdge = new TopoDS_Shape[ nbShapeEdge ];
413 nodeAssigne = new int[ nbVertices + 1 ];
414 HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
416 getShape(theMesh, TopAbs_VERTEX, tabCorner);
417 getShape(theMesh, TopAbs_EDGE, tabEdge);
419 MESSAGE("Read " << theFile << " file");
420 std::ifstream fileRes(theFile.c_str());
423 while ( EndOfFile == 0 ) {
427 if (mapField.count(token)) {
428 nField = mapField[token];
429 nbRef = tabRef[nField];
430 hasDummy = tabDummy[nField];
438 if ( nField < int(mapField.size() - 1) && nField >= 0 )
442 case 0: { // "MeshVersionFormatted"
443 MESSAGE(token << " " << nbElem);
446 case 1: { // "Dimension"
447 MESSAGE("Mesh dimension " << nbElem << "D");
450 case 2: { // "Vertices"
451 MESSAGE("Read " << nbElem << " " << token);
454 SMDS_MeshNode * aHexoticNode;
456 coord = new double[nbRef];
457 for ( int iElem = 0; iElem < nbElem; iElem++ ) {
458 if(theAlgo->computeCanceled())
462 aHexoticID = iElem + 1;
463 for ( int iCoord = 0; iCoord < 3; iCoord++ )
464 fileRes >> coord[ iCoord ];
466 aHexoticNode = theMesh->AddNode(coord[0], coord[1], coord[2]);
467 HexoticNode[ aHexoticID ] = aHexoticNode;
468 nodeAssigne[ aHexoticID ] = 0;
476 case 6: // "Quadrilaterals"
477 case 7: { // "Hexahedra"
478 MESSAGE("Read " << nbElem << " " << token);
479 SMDS_MeshNode** node;
480 int nodeDim, *nodeID;
481 SMDS_MeshElement * aHexoticElement = 0;
483 node = new SMDS_MeshNode*[ nbRef ];
484 nodeID = new int[ nbRef ];
485 for ( int iElem = 0; iElem < nbElem; iElem++ ) {
486 if(theAlgo->computeCanceled())
490 for ( int iRef = 0; iRef < nbRef; iRef++ ) {
491 fileRes >> aHexoticNodeID; // read nbRef aHexoticNodeID
492 node[ iRef ] = HexoticNode[ aHexoticNodeID ];
493 nodeID[ iRef ] = aHexoticNodeID;
498 case 3: { // "Corners"
500 gp_Pnt HexoticPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
501 for ( int i=0; i<nbElem; i++ ) {
502 aVertex = TopoDS::Vertex( tabCorner[i] );
503 gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
504 if ( aPnt.Distance( HexoticPnt ) < epsilon )
507 if ( nodeAssigne[ nodeID[0] ] != 0 ) { // because "Edges" go before "Corners"
508 theMesh->UnSetNodeOnShape( node[0] );
509 nodeAssigne[ nodeID[0] ] = 0;
515 aHexoticElement = theMesh->AddEdge( node[0], node[1] );
517 if ( nodeAssigne[ nodeID[0] ] == 0 || nodeAssigne[ nodeID[0] ] == 2 )
522 case 5: { // "Ridges"
525 case 6: { // "Quadrilaterals"
527 aHexoticElement = theMesh->AddFace( node[0], node[1], node[2], node[3] );
531 case 7: { // "Hexahedra"
533 if ( nbDomains > 1 ) {
534 hexoticShapeID = dummy - IdShapeRef;
535 if ( tabID[ hexoticShapeID ] == 0 ) {
536 aShape = findShape(node, aShape, tabShape, tabBox, nbShape);
537 shapeID = aShape.IsNull() ? holeID : theMesh->ShapeToIndex( aShape );
538 tabID[ hexoticShapeID ] = shapeID;
541 shapeID = tabID[ hexoticShapeID ];
542 if ( iElem == (nbElem - 1) ) {
543 int shapeAssociated = 0;
544 for ( int i=0; i<nbDomains; i++ ) {
546 shapeAssociated += 1;
548 if ( shapeAssociated != nbShape )
549 printWarning(nbShape, "domains", shapeAssociated);
555 if ( shapeID != holeID )
556 aHexoticElement = theMesh->AddVolume( node[0], node[3], node[2], node[1], node[4], node[7], node[6], node[5] );
561 if ( token != "Ridges" && ( shapeID > 0 || token == "Corners")) {
562 for ( int i=0; i<nbRef; i++ ) {
563 if ( nodeAssigne[ nodeID[i] ] == 0 ) {
564 if ( token == "Corners" ) theMesh->SetNodeOnVertex( node[0], aVertex );
565 else if ( token == "Edges" ) theMesh->SetNodeOnEdge( node[i], shapeID );
566 else if ( token == "Quadrilaterals" ) theMesh->SetNodeOnFace( node[i], shapeID );
567 else if ( token == "Hexahedra" ) theMesh->SetNodeInVolume( node[i], shapeID );
568 nodeAssigne[ nodeID[i] ] = nodeDim;
571 if ( token != "Corners" && aHexoticElement )
572 theMesh->SetMeshElementOnShape( aHexoticElement, shapeID );
581 MESSAGE("End of " << theFile << " file");
585 MESSAGE("Unknown Token: " << token);
591 // remove nodes in holes
594 SMESHDS_SubMesh* subMesh;
595 for ( int i = 1; i <= nbVertices; ++i )
596 if ( HexoticNode[i]->NbInverseElements() == 0 )
598 subMesh = HexoticNode[i]->getshapeId() > 0 ? theMesh->MeshElements(HexoticNode[i]->getshapeId() ) : 0;
599 theMesh->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
607 delete [] nodeAssigne;
608 delete [] HexoticNode;
613 //=======================================================================
614 //function : readResult
615 //purpose : Read GMF file in case of a mesh w/o geometry
616 //=======================================================================
618 static bool readResult(std::string theFile,
619 HexoticPlugin_Hexotic* theAlgo,
620 SMESH_MesherHelper* theHelper)
622 SMESHDS_Mesh* theMesh = theHelper->GetMeshDS();
624 // ---------------------------------
625 // Read generated elements and nodes
626 // ---------------------------------
629 const int nbField = 9;
630 int nField, EndOfFile = 0, nbElem = 0, nbRef = 0;
631 int aHexoticNodeID = 0, shapeID;
632 int tabRef[nbField], *nodeAssigne;
633 bool tabDummy[nbField], hasDummy = false;
634 std::map <std::string,int> mapField;
635 SMDS_MeshNode** HexoticNode;
637 mapField["MeshVersionFormatted"] = 0; tabRef[0] = 0; tabDummy[0] = false;
638 mapField["Dimension"] = 1; tabRef[1] = 0; tabDummy[1] = false;
639 mapField["Vertices"] = 2; tabRef[2] = 3; tabDummy[2] = true;
640 mapField["Corners"] = 3; tabRef[3] = 1; tabDummy[3] = false;
641 mapField["Edges"] = 4; tabRef[4] = 2; tabDummy[4] = true;
642 mapField["Ridges"] = 5; tabRef[5] = 1; tabDummy[5] = false;
643 mapField["Quadrilaterals"] = 6; tabRef[6] = 4; tabDummy[6] = true;
644 mapField["Hexahedra"] = 7; tabRef[7] = 8; tabDummy[7] = true;
645 mapField["End"] = 8; tabRef[8] = 0; tabDummy[8] = false;
648 // theMesh->Clear(); -- this does not remove imported mesh
649 SMDS_ElemIteratorPtr eIt = theMesh->elementsIterator();
651 theMesh->RemoveFreeElement( eIt->next(), /*sm=*/0 );
652 SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator();
653 while ( nIt->more() )
654 theMesh->RemoveFreeNode( nIt->next(), /*sm=*/0 );
657 int nbVertices = getNbShape(theFile, "Vertices");
658 HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
659 nodeAssigne = new int[ nbVertices + 1 ];
661 MESSAGE("Read " << theFile << " file");
662 std::ifstream fileRes(theFile.c_str());
670 if (mapField.count(token)) {
671 nField = mapField[token];
672 nbRef = tabRef[nField];
673 hasDummy = tabDummy[nField];
681 if ( nField < int(mapField.size() - 1) && nField >= 0 )
685 case 0: { // "MeshVersionFormatted"
686 MESSAGE(token << " " << nbElem);
689 case 1: { // "Dimension"
690 MESSAGE("Mesh dimension " << nbElem << "D");
693 case 2: { // "Vertices"
694 MESSAGE("Read " << nbElem << " " << token);
697 SMDS_MeshNode * aHexoticNode;
699 for ( int iElem = 0; iElem < nbElem; iElem++ ) {
700 if(theAlgo->computeCanceled())
704 aHexoticID = iElem + 1;
705 for ( int iCoord = 0; iCoord < 3; iCoord++ )
706 fileRes >> coord[ iCoord ];
708 aHexoticNode = theMesh->AddNode(coord[0], coord[1], coord[2]);
709 HexoticNode[ aHexoticID ] = aHexoticNode;
710 nodeAssigne[ aHexoticID ] = 0;
717 case 6: // "Quadrilaterals"
718 case 7: { // "Hexahedra"
719 MESSAGE("Read " << nbElem << " " << token);
720 std::vector< SMDS_MeshNode* > node( nbRef );
721 std::vector< int > nodeID( nbRef );
723 for ( int iElem = 0; iElem < nbElem; iElem++ )
725 if(theAlgo->computeCanceled())
729 for ( int iRef = 0; iRef < nbRef; iRef++ )
731 fileRes >> aHexoticNodeID; // read nbRef aHexoticNodeID
732 node [ iRef ] = HexoticNode[ aHexoticNodeID ];
733 nodeID[ iRef ] = aHexoticNodeID;
740 theHelper->AddEdge( node[0], node[1] ); break;
741 case 6: // "Quadrilaterals"
742 theMesh->AddFace( node[0], node[1], node[2], node[3] ); break;
743 case 7: // "Hexahedra"
744 theHelper->AddVolume( node[0], node[3], node[2], node[1],
745 node[4], node[7], node[6], node[5] ); break;
749 for ( int iRef = 0; iRef < nbRef; iRef++ )
750 nodeAssigne[ nodeID[ iRef ]] = 1;
756 MESSAGE("End of " << theFile << " file");
760 MESSAGE("Unknown Token: " << token);
766 shapeID = theHelper->GetSubShapeID();
767 for ( int i = 0; i < nbVertices; ++i )
768 if ( !nodeAssigne[ i+1 ])
769 theMesh->SetNodeInVolume( HexoticNode[ i+1 ], shapeID );
771 delete [] HexoticNode;
772 delete [] nodeAssigne;
776 //=============================================================================
778 * Pass parameters to MG-Hexa
780 //=============================================================================
782 void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp) {
784 MESSAGE("HexoticPlugin_Hexotic::SetParameters");
786 _hexesMinLevel = hyp->GetHexesMinLevel();
787 _hexesMaxLevel = hyp->GetHexesMaxLevel();
788 _hexesMinSize = hyp->GetMinSize();
789 _hexesMaxSize = hyp->GetMaxSize();
790 _hexoticIgnoreRidges = hyp->GetHexoticIgnoreRidges();
791 _hexoticInvalidElements = hyp->GetHexoticInvalidElements();
792 _hexoticSharpAngleThreshold = hyp->GetHexoticSharpAngleThreshold();
793 _hexoticNbProc = hyp->GetHexoticNbProc();
794 _hexoticWorkingDirectory = hyp->GetHexoticWorkingDirectory();
795 _hexoticVerbosity = hyp->GetHexoticVerbosity();
796 _hexoticMaxMemory = hyp->GetHexoticMaxMemory();
797 _hexoticSdMode = hyp->GetHexoticSdMode();
798 _textOptions = hyp->GetTextOptions();
799 _sizeMaps = hyp->GetSizeMaps();
800 _nbLayers = hyp->GetNbLayers();
801 _firstLayerSize = hyp->GetFirstLayerSize();
802 _direction = hyp->GetDirection();
803 _growth = hyp->GetGrowth();
804 _facesWithLayers = hyp->GetFacesWithLayers();
805 _imprintedFaces = hyp->GetImprintedFaces();
809 cout << "WARNING : The MG-Hexa default parameters are taken into account" << std::endl;
810 cout << "=======" << std::endl;
811 _hexesMinLevel = hyp->GetDefaultHexesMinLevel();
812 _hexesMaxLevel = hyp->GetDefaultHexesMaxLevel();
813 _hexesMinSize = hyp->GetDefaultMinSize();
814 _hexesMaxSize = hyp->GetDefaultMaxSize();
815 _hexoticIgnoreRidges = hyp->GetDefaultHexoticIgnoreRidges();
816 _hexoticInvalidElements = hyp->GetDefaultHexoticInvalidElements();
817 _hexoticSharpAngleThreshold = hyp->GetDefaultHexoticSharpAngleThreshold();
818 _hexoticNbProc = hyp->GetDefaultHexoticNbProc();
819 _hexoticWorkingDirectory = hyp->GetDefaultHexoticWorkingDirectory();
820 _hexoticVerbosity = hyp->GetDefaultHexoticVerbosity();
821 _hexoticMaxMemory = hyp->GetDefaultHexoticMaxMemory();
822 _hexoticSdMode = hyp->GetDefaultHexoticSdMode();
823 _textOptions = hyp->GetDefaultTextOptions();
824 _sizeMaps = hyp->GetDefaultHexoticSizeMaps();
825 _nbLayers = hyp->GetDefaultNbLayers();
826 _firstLayerSize = hyp->GetDefaultFirstLayerSize();
827 _direction = hyp->GetDefaultDirection();
828 _growth = hyp->GetDefaultGrowth();
829 _facesWithLayers = hyp->GetDefaultFacesWithLayers();
830 _imprintedFaces = hyp->GetDefaultImprintedFaces();
834 //=======================================================================
835 //function : getTmpDir
837 //=======================================================================
839 // static TCollection_AsciiString getTmpDir()
841 // TCollection_AsciiString aTmpDir;
843 // char *Tmp_dir = getenv("SALOME_TMP_DIR");
845 // if(Tmp_dir == NULL) {
846 // Tmp_dir = getenv("TEMP");
847 // if( Tmp_dir== NULL )
848 // Tmp_dir = getenv("TMP");
852 // if(Tmp_dir != NULL) {
853 // aTmpDir = Tmp_dir;
855 // if(aTmpDir.Value(aTmpDir.Length()) != '\\') aTmpDir+='\\';
857 // if(aTmpDir.Value(aTmpDir.Length()) != '/') aTmpDir+='/';
862 // aTmpDir = TCollection_AsciiString("C:\\");
864 // aTmpDir = TCollection_AsciiString("/tmp/");
870 //=======================================================================
871 //function : getSuffix
872 //purpose : Returns a suffix that will be unique for the current process
873 //=======================================================================
875 static TCollection_AsciiString getSuffix()
877 TCollection_AsciiString aSuffix = "";
880 aSuffix += getenv("USER");
882 aSuffix += getenv("USERNAME");
885 aSuffix += Kernel_Utils::GetHostname().c_str();
890 aSuffix += _getpid();
896 //================================================================================
898 * \brief Returns a command to run MG-Hexa mesher
900 //================================================================================
902 std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
903 const TCollection_AsciiString& Hexotic_Out,
904 const TCollection_AsciiString& Hexotic_SizeMap_Prefix) const
907 cout << "MG-Hexa execution..." << std::endl;
908 cout << _name << " parameters :" << std::endl;
909 cout << " " << _name << " Verbosity = " << _hexoticVerbosity << std::endl;
910 cout << " " << _name << " Max Memory = " << _hexoticMaxMemory << std::endl;
911 cout << " " << _name << " Segments Min Level = " << _hexesMinLevel << std::endl;
912 cout << " " << _name << " Segments Max Level = " << _hexesMaxLevel << std::endl;
913 cout << " " << _name << " Segments Min Size = " << _hexesMinSize << std::endl;
914 cout << " " << _name << " Segments Max Size = " << _hexesMaxSize << std::endl;
915 cout << " " << "MG-Hexa can ignore ridges : " << (_hexoticIgnoreRidges ? "yes":"no") << std::endl;
916 cout << " " << "MG-Hexa authorize invalide elements : " << ( _hexoticInvalidElements ? "yes":"no") << std::endl;
917 cout << " " << _name << " Sharp angle threshold = " << _hexoticSharpAngleThreshold << " degrees" << std::endl;
918 cout << " " << _name << " Number of threads = " << _hexoticNbProc << std::endl;
919 cout << " " << _name << " Working directory = \"" << _hexoticWorkingDirectory << "\"" << std::endl;
920 cout << " " << _name << " Sub. Dom mode = " << _hexoticSdMode << std::endl;
921 cout << " " << _name << " Text options = \"" << _textOptions << "\"" << std::endl;
922 cout << " " << _name << " Number of layers = " << _nbLayers << std::endl;
923 cout << " " << _name << " Size of the first layer = " << _firstLayerSize << std::endl;
924 cout << " " << _name << " Direction of the layers = " << ( _direction ? "Inward" : "Outward" ) << std::endl;
925 cout << " " << _name << " Growth = " << _growth << std::endl;
926 if (!_facesWithLayers.empty()) {
927 cout << " " << _name << " Faces with layers = ";
928 for (size_t i = 0; i < _facesWithLayers.size(); i++)
930 cout << _facesWithLayers.at(i);
931 if ((i + 1) != _facesWithLayers.size())
936 if (!_imprintedFaces.empty()) {
937 cout << " " << _name << " Imprinted faces = ";
938 for (size_t i = 0; i < _imprintedFaces.size(); i++)
940 cout << _imprintedFaces.at(i);
941 if ((i + 1) != _imprintedFaces.size())
947 TCollection_AsciiString run_Hexotic( "mg-hexa.exe" );
949 TCollection_AsciiString minl = " --min_level ", maxl = " --max_level ", angle = " --ridge_angle ";
950 TCollection_AsciiString mins = " --min_size ", maxs = " --max_size ";
951 TCollection_AsciiString in = " --in ", out = " --out ";
952 TCollection_AsciiString sizeMap = " --read_sizemap ";
953 TCollection_AsciiString ignoreRidges = " --compute_ridges no ", invalideElements = " --allow_invalid_elements yes ";
954 TCollection_AsciiString subdom = " --components ";
956 TCollection_AsciiString proc = " --max_number_of_threads ";
958 TCollection_AsciiString verb = " --verbose ";
959 TCollection_AsciiString maxmem = " --max_memory ";
961 TCollection_AsciiString comNbLayers = " --number_of_boundary_layers ";
962 TCollection_AsciiString comFirstLayerSize = " --height_of_the_first_layer ";
963 TCollection_AsciiString comDirection = " --boundary_layers_subdomain_direction ";
964 TCollection_AsciiString comGrowth = " --boundary_layers_geometric_progression ";
965 TCollection_AsciiString comFacesWithLayers = " --boundary_layers_surface_ids ";
966 TCollection_AsciiString comImptintedFaces = " --imprinted_surface_ids ";
968 TCollection_AsciiString minLevel, maxLevel, minSize, maxSize, sharpAngle, mode, nbproc, verbosity, maxMemory,
969 textOptions, nbLayers, firstLayerSize, direction, growth, facesWithLayers, imprintedFaces;
970 minLevel = _hexesMinLevel;
971 maxLevel = _hexesMaxLevel;
972 minSize = _hexesMinSize;
973 maxSize = _hexesMaxSize;
974 sharpAngle = _hexoticSharpAngleThreshold;
975 // Mode translation for mg-tetra 1.1
976 switch ( _hexoticSdMode )
979 mode = "outside_skin_only";
982 mode = "outside_components";
988 mode = "all --manifold_geometry no";
991 nbproc = _hexoticNbProc;
992 verbosity = _hexoticVerbosity;
993 maxMemory = _hexoticMaxMemory;
994 textOptions = (" " + _textOptions + " ").c_str();
995 nbLayers = _nbLayers;
996 firstLayerSize = _firstLayerSize;
997 direction = _direction ? "1" : "-1";
999 for (size_t i = 0; i < _facesWithLayers.size(); i++)
1001 facesWithLayers += _facesWithLayers[i];
1002 if ((i + 1) != _facesWithLayers.size())
1003 facesWithLayers += ",";
1005 for (size_t i = 0; i < _imprintedFaces.size(); i++)
1007 imprintedFaces += _imprintedFaces[i];
1008 if ((i + 1) != _imprintedFaces.size())
1009 imprintedFaces += ",";
1012 if (_hexoticIgnoreRidges)
1013 run_Hexotic += ignoreRidges;
1015 if (_hexoticInvalidElements)
1016 run_Hexotic += invalideElements;
1018 if (_hexesMinSize > 0)
1019 run_Hexotic += mins + minSize;
1021 if (_hexesMaxSize > 0)
1022 run_Hexotic += maxs + maxSize;
1024 if (_hexesMinLevel > 0)
1025 run_Hexotic += minl + minLevel;
1027 if (_hexesMaxLevel > 0)
1028 run_Hexotic += maxl + maxLevel;
1030 if (_hexoticSharpAngleThreshold > 0)
1031 run_Hexotic += angle + sharpAngle;
1033 if (_sizeMaps.begin() != _sizeMaps.end())
1034 run_Hexotic += sizeMap + Hexotic_SizeMap_Prefix;
1036 if (_nbLayers > 0 &&
1037 _firstLayerSize > 0 &&
1039 !_facesWithLayers.empty())
1041 run_Hexotic += comNbLayers + nbLayers;
1042 run_Hexotic += comFirstLayerSize + firstLayerSize;
1043 run_Hexotic += comDirection + direction;
1044 run_Hexotic += comGrowth + growth;
1045 run_Hexotic += comFacesWithLayers + facesWithLayers;
1046 if (!_imprintedFaces.empty())
1047 run_Hexotic += comImptintedFaces + imprintedFaces;
1049 run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
1050 run_Hexotic += subdom + mode;
1052 run_Hexotic += proc + nbproc;
1054 run_Hexotic += verb + verbosity;
1055 run_Hexotic += maxmem + maxMemory;
1057 if (!_textOptions.empty())
1058 run_Hexotic += textOptions;
1060 return run_Hexotic.ToCString();
1063 // TODO : this is a duplication of some code found in BLSURFPlugin_BLSURF find a proper
1065 TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
1067 MESSAGE("HexoticPlugin_Hexotic::entryToShape "<<entry );
1068 GEOM::GEOM_Object_var aGeomObj;
1069 TopoDS_Shape S = TopoDS_Shape();
1070 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
1071 if (!aSObj->_is_nil()) {
1072 CORBA::Object_var obj = aSObj->GetObject();
1073 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
1074 aSObj->UnRegister();
1076 if ( !aGeomObj->_is_nil() )
1077 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
1081 //================================================================================
1083 * \brief Produces a .mesh file with the size maps informations to give to Hexotic
1085 //================================================================================
1086 std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( std::string sizeMapPrefix )
1088 HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it ;
1090 // The GMF driver will be used to write the size map file
1091 DriverGMF_Write aWriter;
1092 aWriter.SetSizeMapPrefix( sizeMapPrefix );
1094 std::vector<Control_Pnt> points;
1095 // Iterate on the size maps
1096 for (it=_sizeMaps.begin(); it!=_sizeMaps.end(); it++)
1098 // Step 1 : Get the GEOM object entry and the size
1099 // from the _sizeMaps infos
1100 std::string anEntry = it->first;
1101 double aLocalSize = it->second;
1102 TopoDS_Shape aShape = entryToShape( anEntry );
1104 // Step 2 : Create the points
1105 createControlPoints( aShape, aLocalSize, points );
1107 // Write the .mesh size map file
1108 aWriter.PerformSizeMap(points);
1109 return aWriter.GetSizeMapFiles();
1112 //================================================================================
1114 * \brief Fills a vector of points from which a size map input file can be written
1116 //================================================================================
1117 void HexoticPlugin_Hexotic::createControlPoints( const TopoDS_Shape& aShape,
1118 const double& theSize,
1119 std::vector<Control_Pnt>& thePoints )
1121 if ( aShape.ShapeType() == TopAbs_VERTEX )
1123 gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex(aShape) );
1124 Control_Pnt aControl_Pnt( aPnt, theSize );
1125 thePoints.push_back( aControl_Pnt );
1127 if ( aShape.ShapeType() == TopAbs_EDGE )
1129 createPointsSampleFromEdge( aShape, theSize, thePoints );
1131 else if ( aShape.ShapeType() == TopAbs_WIRE )
1134 for (Ex.Init(aShape,TopAbs_EDGE); Ex.More(); Ex.Next())
1136 createPointsSampleFromEdge( Ex.Current(), theSize, thePoints );
1139 else if ( aShape.ShapeType() == TopAbs_FACE )
1141 createPointsSampleFromFace( aShape, theSize, thePoints );
1143 else if ( aShape.ShapeType() == TopAbs_SOLID )
1145 createPointsSampleFromSolid( aShape, theSize, thePoints );
1147 else if ( aShape.ShapeType() == TopAbs_COMPOUND )
1149 TopoDS_Iterator it( aShape );
1150 for(; it.More(); it.Next())
1152 createControlPoints( it.Value(), theSize, thePoints );
1157 //================================================================================
1159 * \brief Fills a vector of points with point samples approximately
1160 * \brief spaced with a given size
1162 //================================================================================
1163 void HexoticPlugin_Hexotic::createPointsSampleFromEdge( const TopoDS_Shape& aShape,
1164 const double& theSize,
1165 std::vector<Control_Pnt>& thePoints )
1167 double step = theSize;
1169 Handle( Geom_Curve ) aCurve = BRep_Tool::Curve( TopoDS::Edge( aShape ), first, last );
1170 GeomAdaptor_Curve C ( aCurve );
1171 GCPnts_UniformAbscissa DiscretisationAlgo(C, step , first, last, Precision::Confusion());
1172 int nbPoints = DiscretisationAlgo.NbPoints();
1174 for ( int i = 1; i <= nbPoints; i++ )
1176 double param = DiscretisationAlgo.Parameter( i );
1178 aCurve->D0( param, aPnt );
1179 aPnt.SetSize(theSize);
1180 thePoints.push_back( aPnt );
1184 //================================================================================
1186 * \brief Fills a vector of points with point samples approximately
1187 * \brief spaced with a given size
1189 //================================================================================
1190 void HexoticPlugin_Hexotic::createPointsSampleFromFace( const TopoDS_Shape& aShape,
1191 const double& theSize,
1192 std::vector<Control_Pnt>& thePoints )
1194 BRepMesh_IncrementalMesh M(aShape, 0.01, Standard_True);
1195 TopLoc_Location aLocation;
1196 TopoDS_Face aFace = TopoDS::Face(aShape);
1198 // Triangulate the face
1199 Handle(Poly_Triangulation) aTri = BRep_Tool::Triangulation (aFace, aLocation);
1201 // Get the transformation associated to the face location
1202 gp_Trsf aTrsf = aLocation.Transformation();
1205 int nbTriangles = aTri->NbTriangles();
1206 Poly_Array1OfTriangle triangles(1,nbTriangles);
1207 triangles=aTri->Triangles();
1210 int nbNodes = aTri->NbNodes();
1211 TColgp_Array1OfPnt nodes(1,nbNodes);
1212 nodes = aTri->Nodes();
1214 // Iterate on triangles and subdivide them
1215 for(int i=1; i<=nbTriangles; i++)
1217 Poly_Triangle aTriangle = triangles.Value(i);
1218 gp_Pnt p1 = nodes.Value(aTriangle.Value(1));
1219 gp_Pnt p2 = nodes.Value(aTriangle.Value(2));
1220 gp_Pnt p3 = nodes.Value(aTriangle.Value(3));
1222 p1.Transform(aTrsf);
1223 p2.Transform(aTrsf);
1224 p3.Transform(aTrsf);
1226 subdivideTriangle(p1, p2, p3, theSize, thePoints);
1230 //================================================================================
1232 * \brief Fills a vector of points with point samples approximately
1233 * \brief spaced with a given size
1235 //================================================================================
1236 void HexoticPlugin_Hexotic::createPointsSampleFromSolid( const TopoDS_Shape& aShape,
1237 const double& theSize,
1238 std::vector<Control_Pnt>& thePoints )
1240 // Compute the bounding box
1241 double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1243 BRepBndLib::Add(aShape, B);
1244 B.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1246 // Create the points
1247 double step = theSize;
1249 for ( double x=Xmin; x-Xmax<Precision::Confusion(); x=x+step )
1251 for ( double y=Ymin; y-Ymax<Precision::Confusion(); y=y+step )
1253 // Step1 : generate the Zmin -> Zmax line
1254 gp_Pnt startPnt(x, y, Zmin);
1255 gp_Pnt endPnt(x, y, Zmax);
1256 gp_Vec aVec(startPnt, endPnt);
1257 gp_Lin aLine(startPnt, aVec);
1258 double endParam = Zmax - Zmin;
1260 // Step2 : for each face of aShape:
1261 std::set<double> intersections;
1262 std::set<double>::iterator it = intersections.begin();
1265 for (Ex.Init(aShape,TopAbs_FACE); Ex.More(); Ex.Next())
1267 // check if there is an intersection
1268 IntCurvesFace_Intersector anIntersector(TopoDS::Face(Ex.Current()), Precision::Confusion());
1269 anIntersector.Perform(aLine, 0, endParam);
1271 // get the intersection's parameter and store it
1272 int nbPoints = anIntersector.NbPnt();
1273 for(int i = 0 ; i < nbPoints ; i++ )
1275 it = intersections.insert( it, anIntersector.WParameter(i+1) );
1278 // Step3 : go through the line chunk by chunk
1279 if ( intersections.begin() != intersections.end() )
1281 std::set<double>::iterator intersectionsIterator=intersections.begin();
1282 double first = *intersectionsIterator;
1283 intersectionsIterator++;
1284 bool innerPoints = true;
1285 for ( ; intersectionsIterator!=intersections.end() ; intersectionsIterator++ )
1287 double second = *intersectionsIterator;
1290 // If the last chunk was outside of the shape or this is the first chunk
1291 // add the points in the range [first, second] to the points vector
1292 double localStep = (second -first) / ceil( (second - first) / step );
1293 for ( double z = Zmin + first; z < Zmin + second; z = z + localStep )
1295 thePoints.push_back(Control_Pnt( x, y, z, theSize ));
1297 thePoints.push_back(Control_Pnt( x, y, Zmin + second, theSize ));
1300 innerPoints = !innerPoints;
1307 //================================================================================
1309 * \brief Subdivides a triangle until it reaches a certain size (recursive function)
1311 //================================================================================
1312 void HexoticPlugin_Hexotic::subdivideTriangle( const gp_Pnt& p1,
1315 const double& theSize,
1316 std::vector<Control_Pnt>& thePoints)
1318 // Size threshold to stop subdividing
1319 // This value ensures that two control points are distant no more than 2*theSize
1322 // The greater distance D of the mass center M to each Edge is 1/3 * Median
1323 // and Median < sqrt(3/4) * a where a is the greater side (by using Apollonius' thorem).
1324 // So D < 1/3 * sqrt(3/4) * a and if a < sqrt(3) * S then D < S/2
1325 // and the distance between two mass centers of two neighbouring triangles
1326 // sharing an edge is < 2 * 1/2 * S = S
1327 // If the traingles share a Vertex and no Edge the distance of the mass centers
1328 // to the Vertices is 2*D < S so the mass centers are distant of less than 2*S
1330 double threshold = sqrt( 3. ) * theSize;
1332 if ( (p1.Distance(p2) > threshold ||
1333 p2.Distance(p3) > threshold ||
1334 p3.Distance(p1) > threshold))
1336 std::vector<gp_Pnt> midPoints = computePointsForSplitting(p1, p2, p3);
1338 subdivideTriangle( midPoints[0], midPoints[1], midPoints[2], theSize, thePoints );
1339 subdivideTriangle( midPoints[0], p2, midPoints[1], theSize, thePoints );
1340 subdivideTriangle( midPoints[2], midPoints[1], p3, theSize, thePoints );
1341 subdivideTriangle( p1, midPoints[0], midPoints[2], theSize, thePoints );
1345 double x = (p1.X() + p2.X() + p3.X()) / 3 ;
1346 double y = (p1.Y() + p2.Y() + p3.Y()) / 3 ;
1347 double z = (p1.Z() + p2.Z() + p3.Z()) / 3 ;
1349 Control_Pnt massCenter( x ,y ,z, theSize );
1350 thePoints.push_back( massCenter );
1354 //================================================================================
1356 * \brief Returns the appropriate points for splitting a triangle
1357 * \brief the tangency points of the incircle are used in order to have mostly
1358 * \brief well-shaped sub-triangles
1360 //================================================================================
1361 std::vector<gp_Pnt> HexoticPlugin_Hexotic::computePointsForSplitting( const gp_Pnt& p1,
1365 std::vector<gp_Pnt> midPoints;
1366 //Change coordinates
1367 gp_Trsf Trsf_1; // Identity transformation
1368 gp_Ax3 reference_system(gp::Origin(), gp::DZ(), gp::DX()); // OXY
1371 gp_Vec Vaux(p1, p2);
1374 gp_Dir Dz = Dx.Crossed(Daux);
1375 gp_Ax3 current_system(p1, Dz, Dx);
1377 Trsf_1.SetTransformation( reference_system, current_system );
1379 gp_Pnt A = p1.Transformed(Trsf_1);
1380 gp_Pnt B = p2.Transformed(Trsf_1);
1381 gp_Pnt C = p3.Transformed(Trsf_1);
1383 double a = B.Distance(C) ;
1384 double b = A.Distance(C) ;
1385 double c = B.Distance(A) ;
1387 // Incenter coordinates
1388 // see http://mathworld.wolfram.com/Incenter.html
1389 double Xi = ( b*B.X() + c*C.X() ) / ( a + b + c );
1390 double Yi = ( b*B.Y() ) / ( a + b + c );
1391 gp_Pnt Center(Xi, Yi, 0);
1393 // Calculate the tangency points of the incircle
1394 gp_Pnt T1 = tangencyPoint( A, B, Center);
1395 gp_Pnt T2 = tangencyPoint( B, C, Center);
1396 gp_Pnt T3 = tangencyPoint( C, A, Center);
1398 gp_Pnt p1_2 = T1.Transformed(Trsf_1.Inverted());
1399 gp_Pnt p2_3 = T2.Transformed(Trsf_1.Inverted());
1400 gp_Pnt p3_1 = T3.Transformed(Trsf_1.Inverted());
1402 midPoints.push_back(p1_2);
1403 midPoints.push_back(p2_3);
1404 midPoints.push_back(p3_1);
1409 //================================================================================
1411 * \brief Computes the tangency points of the circle of center Center with
1412 * \brief the straight line (p1 p2)
1414 //================================================================================
1415 gp_Pnt HexoticPlugin_Hexotic::tangencyPoint(const gp_Pnt& p1,
1417 const gp_Pnt& Center)
1422 // The tangency point is the intersection of the straight line (p1 p2)
1423 // and the straight line (Center T) which is orthogonal to (p1 p2)
1424 if ( fabs(p1.X() - p2.X()) <= Precision::Confusion() )
1426 Xt=p1.X(); // T is on (p1 p2)
1427 Yt=Center.Y(); // (Center T) is orthogonal to (p1 p2)
1429 else if ( fabs(p1.Y() - p2.Y()) <= Precision::Confusion() )
1431 Yt=p1.Y(); // T is on (p1 p2)
1432 Xt=Center.X(); // (Center T) is orthogonal to (p1 p2)
1436 // First straight line coefficients (equation y=a*x+b)
1437 double a = (p2.Y() - p1.Y()) / (p2.X() - p1.X()) ;
1438 double b = p1.Y() - a*p1.X(); // p1 is on this straight line
1440 // Second straight line coefficients (equation y=c*x+d)
1441 double c = -1 / a; // The 2 lines are orthogonal
1442 double d = Center.Y() - c*Center.X(); // Center is on this straight line
1444 Xt = (d - b) / (a - c);
1448 return gp_Pnt( Xt, Yt, 0 );
1451 //=============================================================================
1453 * Here we are going to use the MG-Hexa mesher
1455 //=============================================================================
1457 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh& aMesh,
1458 const TopoDS_Shape& aShape)
1460 _compute_canceled = false;
1462 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1463 TCollection_AsciiString hexahedraMessage;
1465 if (_iShape == 0 && _nbShape == 0) {
1466 _nbShape = countShape( meshDS, TopAbs_SOLID ); // we count the number of shapes
1469 // to prevent from displaying error message after computing,
1470 // SetIsAlwaysComputed( true ) to empty sub-meshes
1471 std::vector< SMESH_subMesh* > subMeshesAlwaysComp;
1472 for ( int i = 0; i < _nbShape; ++i )
1473 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( aShape ))
1475 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true,
1476 /*complexShapeFirst=*/false);
1477 while ( smIt->more() )
1480 if ( !sm->IsMeshComputed() )
1482 sm->SetIsAlwaysComputed( true );
1483 subMeshesAlwaysComp.push_back( sm );
1490 if (_iShape == _nbShape ) {
1492 // create bounding box for each shape of the compound
1495 TopoDS_Shape *tabShape;
1498 tabShape = new TopoDS_Shape[_nbShape];
1499 tabBox = new double*[_nbShape];
1500 for (int i=0; i<_nbShape; i++)
1501 tabBox[i] = new double[6];
1502 double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1504 TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
1505 for (; expBox.More(); expBox.Next()) {
1506 tabShape[iShape] = expBox.Current();
1507 Bnd_Box BoundingBox;
1508 BRepBndLib::Add(expBox.Current(), BoundingBox);
1509 BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1510 tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1511 tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1512 tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1516 SetParameters(_hypothesis);
1518 // TCollection_AsciiString aTmpDir = getTmpDir();
1519 TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();
1521 if ( aTmpDir.Value(aTmpDir.Length()) != '\\' ) aTmpDir += '\\';
1523 if ( aTmpDir.Value(aTmpDir.Length()) != '/' ) aTmpDir += '/';
1525 TCollection_AsciiString Hexotic_In(""), Hexotic_Out, Hexotic_SizeMap_Prefix;
1526 TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " ); TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log"; // log
1528 std::map <int,int> aSmdsToHexoticIdMap;
1529 std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1531 Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1532 #ifdef WITH_BLSURFPLUGIN
1533 bool defaultInputFile = true;
1534 if (_blsurfHypo && !_blsurfHypo->GetQuadAllowed()) {
1535 Hexotic_In = _blsurfHypo->GetGMFFile().c_str();
1536 if ( !Hexotic_In.IsEmpty() &&
1537 SMESH_File( _blsurfHypo->GetGMFFile() ).exists() )
1538 defaultInputFile = false;
1540 if (defaultInputFile) {
1542 Hexotic_In = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1543 removeHexoticFiles(Hexotic_In, Hexotic_Out);
1544 splitQuads(aMesh); // quadrangles are no longer acceptable as input
1546 cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1547 aMesh.ExportGMF(Hexotic_In.ToCString(), meshDS, true);
1548 #ifdef WITH_BLSURFPLUGIN
1551 removeFile( Hexotic_Out );
1555 Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap" + getSuffix();
1556 std::vector<std::string> sizeMapFiles = writeSizeMapFile( Hexotic_SizeMap_Prefix.ToCString() );
1558 std::string run_Hexotic = getHexoticCommand(Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix);
1559 run_Hexotic += std::string(" 1> ") + aLogFileName.ToCString(); // dump into file
1561 cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1563 cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1566 modeFile_In += Hexotic_In;
1567 system( modeFile_In.ToCString() );
1569 aSmdsToHexoticIdMap.clear();
1570 aHexoticIdToNodeMap.clear();
1572 MESSAGE("HexoticPlugin_Hexotic::Compute");
1574 int status = system( run_Hexotic.data() );
1580 std::ifstream fileRes( Hexotic_Out.ToCString() );
1582 modeFile_Out += Hexotic_Out;
1583 system( modeFile_Out.ToCString() );
1585 if ( ! fileRes.fail() ) {
1586 Ok = readResult( Hexotic_Out.ToCString(),
1588 meshDS, _nbShape, tabShape, tabBox );
1590 /*********************
1591 // TODO: Detect and remove elements in holes in case of sd mode = 4
1592 // Remove previous nodes and elements
1593 SMDS_ElemIteratorPtr itElement = meshDS->elementsIterator();
1594 SMDS_NodeIteratorPtr itNode = meshDS->nodesIterator();
1596 while ( itElement->more() )
1597 meshDS->RemoveElement( itElement->next() );
1598 while ( itNode->more() )
1599 meshDS->RemoveNode( itNode->next() );
1601 SMESH_ComputeErrorPtr myError = aMesh.GMFToMesh(Hexotic_Out.ToCString());
1604 hexahedraMessage = "success";
1606 removeFile(Hexotic_Out);
1607 removeFile(Hexotic_In);
1608 //removeFile(aLogFileName);
1609 for( int i=0; i<sizeMapFiles.size(); i++)
1611 removeFile( TCollection_AsciiString( sizeMapFiles[i].c_str() ) );
1616 hexahedraMessage = "failed";
1620 hexahedraMessage = "failed";
1621 cout << "Problem with MG-Hexa output file " << Hexotic_Out.ToCString() << std::endl;
1624 SMESH_File logFile( aLogFileName.ToCString() );
1625 if ( !logFile.eof() )
1627 char msgLic[] = " Dlim ";
1628 const char* fileBeg = logFile.getPos(), *fileEnd = fileBeg + logFile.size();
1629 if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1630 error("Licence problems.");
1633 if ( status > 0 && WEXITSTATUS(status) == 127 )
1634 error("mg-hexa.exe: command not found");
1637 if ( status == 0 && err == ENOENT ) {
1638 error("mg-hexa.exe: command not found");
1642 cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1645 // restore "always computed" flag of sub-meshes (0022127)
1646 for ( size_t iSM = 0; iSM < subMeshesAlwaysComp.size(); ++iSM )
1647 subMeshesAlwaysComp[ iSM ]->SetIsAlwaysComputed( false );
1650 for (int i=0; i<_nbShape; i++)
1651 delete [] tabBox[i];
1656 if(_compute_canceled)
1657 return error(SMESH_Comment("interruption initiated by user"));
1661 //=============================================================================
1663 * \brief Computes mesh without geometry
1664 * \param aMesh - the mesh
1665 * \param aHelper - helper that must be used for adding elements to \aaMesh
1666 * \retval bool - is a success
1668 * The method is called if ( !aMesh->HasShapeToMesh() )
1670 //=============================================================================
1672 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
1674 _compute_canceled = false;
1676 SMESH_ComputeErrorPtr myError = SMESH_ComputeError::New();
1679 TCollection_AsciiString hexahedraMessage;
1681 SetParameters(_hypothesis);
1683 TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();//getTmpDir();
1684 TCollection_AsciiString Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix;
1685 TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1686 TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log"; // log
1688 std::map <int,int> aSmdsToHexoticIdMap;
1689 std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1691 Hexotic_In = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1692 Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1693 Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap";
1696 std::vector<std::string> sizeMapFiles = writeSizeMapFile( Hexotic_SizeMap_Prefix.ToCString() );
1698 std::string run_Hexotic = getHexoticCommand(Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix);
1699 run_Hexotic += std::string(" 1> ") + aLogFileName.ToCString(); // dump into file
1701 removeHexoticFiles(Hexotic_In, Hexotic_Out);
1703 splitQuads(aMesh); // quadrangles are no longer acceptable as input
1706 cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1707 cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1708 aMesh.ExportGMF(Hexotic_In.ToCString(), aHelper->GetMeshDS());
1710 modeFile_In += Hexotic_In;
1711 system( modeFile_In.ToCString() );
1713 aSmdsToHexoticIdMap.clear();
1714 aHexoticIdToNodeMap.clear();
1716 MESSAGE("HexoticPlugin_Hexotic::Compute");
1719 cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1720 system( run_Hexotic.data() );
1726 std::ifstream fileRes( Hexotic_Out.ToCString() );
1727 modeFile_Out += Hexotic_Out;
1728 system( modeFile_Out.ToCString() );
1729 if ( ! fileRes.fail() ) {
1730 Ok = readResult( Hexotic_Out.ToCString(),
1735 // Remove previous nodes and elements
1736 SMDS_ElemIteratorPtr itElement = aHelper->GetMeshDS()->elementsIterator();
1737 SMDS_NodeIteratorPtr itNode = aHelper->GetMeshDS()->nodesIterator();
1739 while ( itElement->more() )
1740 aHelper->GetMeshDS()->RemoveElement( itElement->next() );
1741 while ( itNode->more() )
1742 aHelper->GetMeshDS()->RemoveNode( itNode->next() );
1745 myError = aMesh.GMFToMesh(Hexotic_Out.ToCString());
1747 itElement = aHelper->GetMeshDS()->elementsIterator();
1748 itNode = aHelper->GetMeshDS()->nodesIterator();
1750 // Assign nodes and elements to the pseudo shape
1751 while ( itNode->more() )
1752 aHelper->GetMeshDS()->SetNodeInVolume(itNode->next(), 1);
1753 while ( itElement->more() )
1754 aHelper->GetMeshDS()->SetMeshElementOnShape(itElement->next(), 1);
1758 hexahedraMessage = "success";
1760 hexahedraMessage = "failed";
1764 myError->myName = COMPERR_EXCEPTION;
1766 hexahedraMessage = "failed";
1767 cout << "Problem with MG-Hexa output file " << Hexotic_Out << std::endl;
1769 SMESH_File logFile( aLogFileName.ToCString() );
1770 if ( !logFile.eof() )
1772 char msgLic[] = " Dlim ";
1773 const char* fileBeg = logFile.getPos(), *fileEnd = fileBeg + logFile.size();
1774 if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1775 return error("Licence problems.");
1777 return error(SMESH_Comment("Problem with MG-Hexa output file ")<<Hexotic_Out);
1779 cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1782 if(_compute_canceled)
1783 return error(SMESH_Comment("interruption initiated by user"));
1784 removeFile(Hexotic_Out);
1785 removeFile(Hexotic_In);
1786 removeFile(aLogFileName);
1787 for( size_t i=0; i<sizeMapFiles.size(); i++)
1789 removeFile( TCollection_AsciiString(sizeMapFiles[i].c_str()) );
1793 return myError->IsOK();
1797 //=============================================================================
1801 //=============================================================================
1803 bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh& aMesh,
1804 const TopoDS_Shape& aShape,
1805 MapShapeNbElems& aResMap)
1807 std::vector<int> aResVec(SMDSEntity_Last);
1808 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1809 SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
1810 aResMap.insert(std::make_pair(sm,aResVec));
1812 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1813 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Evaluation is not implemented",this));
1818 void HexoticPlugin_Hexotic::CancelCompute()
1820 _compute_canceled = true;
1823 TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str(); //getTmpDir();
1824 TCollection_AsciiString Hexotic_In = aTmpDir + "Hexotic_In.mesh";
1825 TCollection_AsciiString cmd = TCollection_AsciiString("ps ux | grep ") + Hexotic_In;
1826 cmd += TCollection_AsciiString(" | grep -v grep | awk '{print $2}' | xargs kill -9 > /dev/null 2>&1");
1827 system( cmd.ToCString() );